title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Check if a number is divisible by 41 or not - GeeksforGeeks
17 May, 2021 Given a number, the task is to quickly check if the number is divisible by 41 or not. Examples: Input : x = 123 Output : Yes Input : 104413920565933 Output : YES A solution to the problem is to extract the last digit and subtract 4 times of the last digit from the remaining number and repeat this process until a two-digit number is obtained. If the obtained two-digit number is divisible by 41, then the given number is divisible by 41.Approach: Extract the last digit of the number/truncated number every time Subtract 4*(last digit of the previous number) from the truncated number Repeat the above three steps as long as necessary. Illustrations: Illustration 1: 30873-->3087-4*3=3075-->307-4*5=287-->28-4*7=0 As the remainder is zero, 30873 is divisible by 41 Illustration 2: 104413920565933 --> 10441392056593 - 4*3= 10441392056581 10441392056581 --> 1044139205658 - 4*1 = 1044139205654 1044139205654 --> 104413920565 - 4*4 = 104413920549 104413920549 --> 10441392054 - 4*9 = 10441392018 10441392018 --> 1044139201 - 4*8 = 1044139169 1044139169 --> 104413916 - 4*9 = 104413880 104413880 --> 10441388 - 4*0 = 10441380 10441388 --> 1044138 - 4*8 = 1044106 1044106 --> 104410 - 4*6 = 104386 104386 --> 10438 - 4*6 = 10414 10414 --> 1041 - 4*4 = 1025 1025 --> 102 - 4*5 =82 Now, 82%41 = 0 --> 82 is divisible by 41 and hence, 104413920565933 is divisible by 41 Mathematical Proof : Let be any number such that =100a+10b+c . Now assume that is divisible by 41. Then 0 (mod 41) 100a+10b+c 0 (mod 41) 10(10a+b)+c 0 (mod 41) 10 +c 0 (mod 41)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of 1. In other words, we have to find an integer such that n such that 10n 1 mod 41. It can be observed that the smallest n which satisfies this property is -4 as -40 1 mod 41. Now we can multiply the original equation 10 +c 0 (mod 41) by -4 and simplify it: -40 -4c 0 (mod 41) -4c 0 (mod 41) We have found out that if 0 (mod 41) then, -4c 0 (mod 41). In other words, to check if a 3-digit number is divisible by 41, we can just remove the last digit, multiply it by 4, and then subtract it from the rest of the two digits. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to validate above logic#include <bits/stdc++.h>using namespace std; // Function to check if the number// is divisible by 41 or notbool isDivisible(long long int n){ while (n / 100) { // Extracting the last digit int d = n % 10; // Truncating the number n /= 10; // Subtracting the four times // the last digit from the // remaining number n -= d * 4; } // return true if number is divisible by 41 return (n % 41 == 0);} int main(){ long long int n = 104413920565933; if (isDivisible(n)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java program to validate above logic class GFG { // Function to check if the number// is divisible by 41 or not static boolean isDivisible(long n) { while (n / 100 != 0) {// Extracting the last digit int d = (int) (n % 10); // Truncating the number n /= 10; // Subtracting the four times// the last digit from the// remaining number n -= d * 4; } // return true if number// is divisible by 41 return (n % 41 == 0); } public static void main(String[] args) { long n = 104413920565933L; if (isDivisible(n)) { System.out.println("Yes"); } else { System.out.println("No"); } }}// This code is contributed by RAJPUT-JI # Python3 Program to validate above logic # Function to check if the number# is divisible by 41 or notdef isDivisible(n) : while n // 100 : # Extracting the last digit d = n % 10 # Truncating the number n //= 10 # Subtracting the four times # the last digit from the # remaining number n -= d * 4 # return true if number is divisible by 41 return n % 41 == 0 # Driver Codeif __name__ == "__main__" : n = 104413920565933 if isDivisible(n) : print("Yes") else : print("No") # This code is contributed by ANKITRAI1 // C# program to validate above logicusing System; class GFG{// Function to check if the number// is divisible by 41 or notstatic bool isDivisible(long n){ while (n / 100 != 0) { // Extracting the last digit int d = (int)(n % 10); // Truncating the number n /= 10; // Subtracting the four times // the last digit from the // remaining number n -= d * 4; } // return true if number // is divisible by 41 return (n % 41 == 0);} // Driver Codestatic public void Main (){ long n = 104413920565933; if (isDivisible(n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Raj <?php// PHP program to validate above logic // Function to check if the number// is divisible by 41 or notfunction isDivisible($n){ while ($n / 100) { // Extracting the last digit $d = $n % 10; // Truncating the number $n /= 10; // Subtracting the four times // the last digit from the // remaining number $n -= $d * 4; } // return true if number // is divisible by 41 return ($n % 41 == 0);} // Driver Code$n = 104413920565933;if (isDivisible($n)) echo "Yes"."\n";else echo "No"."\n"; // This code is contributed// by ChitraNayal?> <script> // JavaScript program to validate above logic // Function to check if the number// is divisible by 41 or not function isDivisible(n) { while (Math.floor(n / 100) != 0) {// Extracting the last digit let d = (n % 10); // Truncating the number n = Math.floor(n/10); // Subtracting the four times// the last digit from the// remaining number n -= d * 4; } // return true if number// is divisible by 41 return (n % 41 == 0); } let n = 104413920565933; if (isDivisible(n)) { document.write("Yes"); } else { document.write("No"); } // This code is contributed by avanitrachhadiya2155 </script> Yes Note that the above program may not make a lot of sense as could simply do n % 41 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. ankthon ukasp R_Raj Rajput-Ji abhirup45 avanitrachhadiya2155 divisibility Number Divisibility number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Program for Decimal to Binary Conversion Sieve of Eratosthenes Operators in C / C++ Euclidean algorithms (Basic and Extended)
[ { "code": null, "e": 25360, "s": 25332, "text": "\n17 May, 2021" }, { "code": null, "e": 25447, "s": 25360, "text": "Given a number, the task is to quickly check if the number is divisible by 41 or not. " }, { "code": null, "e": 25458, "s": 25447, "text": "Examples: " }, { "code": null, "e": 25526, "s": 25458, "text": "Input : x = 123\nOutput : Yes\n\nInput : 104413920565933\nOutput : YES" }, { "code": null, "e": 25813, "s": 25526, "text": "A solution to the problem is to extract the last digit and subtract 4 times of the last digit from the remaining number and repeat this process until a two-digit number is obtained. If the obtained two-digit number is divisible by 41, then the given number is divisible by 41.Approach: " }, { "code": null, "e": 25878, "s": 25813, "text": "Extract the last digit of the number/truncated number every time" }, { "code": null, "e": 25951, "s": 25878, "text": "Subtract 4*(last digit of the previous number) from the truncated number" }, { "code": null, "e": 26002, "s": 25951, "text": "Repeat the above three steps as long as necessary." }, { "code": null, "e": 26018, "s": 26002, "text": "Illustrations: " }, { "code": null, "e": 26731, "s": 26018, "text": "Illustration 1:\n30873-->3087-4*3=3075-->307-4*5=287-->28-4*7=0\nAs the remainder is zero, 30873 is divisible by 41\n\nIllustration 2:\n104413920565933 --> 10441392056593 - 4*3= 10441392056581\n10441392056581 --> 1044139205658 - 4*1 = 1044139205654\n1044139205654 --> 104413920565 - 4*4 = 104413920549\n104413920549 --> 10441392054 - 4*9 = 10441392018\n10441392018 --> 1044139201 - 4*8 = 1044139169\n1044139169 --> 104413916 - 4*9 = 104413880\n104413880 --> 10441388 - 4*0 = 10441380\n10441388 --> 1044138 - 4*8 = 1044106\n1044106 --> 104410 - 4*6 = 104386\n104386 --> 10438 - 4*6 = 10414\n10414 --> 1041 - 4*4 = 1025\n1025 --> 102 - 4*5 =82\nNow, 82%41 = 0 --> 82 is divisible by 41 and hence, 104413920565933 is divisible by 41" }, { "code": null, "e": 26757, "s": 26731, "text": "Mathematical Proof : Let " }, { "code": null, "e": 26784, "s": 26759, "text": "be any number such that " }, { "code": null, "e": 26817, "s": 26786, "text": "=100a+10b+c . Now assume that " }, { "code": null, "e": 26846, "s": 26819, "text": "is divisible by 41. Then " }, { "code": null, "e": 26870, "s": 26848, "text": "0 (mod 41) 100a+10b+c" }, { "code": null, "e": 26895, "s": 26872, "text": "0 (mod 41) 10(10a+b)+c" }, { "code": null, "e": 26911, "s": 26897, "text": "0 (mod 41) 10" }, { "code": null, "e": 26916, "s": 26913, "text": "+c" }, { "code": null, "e": 27045, "s": 26918, "text": "0 (mod 41)Now that we have separated the last digit from the number, we have to find a way to use it. Make the coefficient of " }, { "code": null, "e": 27119, "s": 27047, "text": "1. In other words, we have to find an integer such that n such that 10n" }, { "code": null, "e": 27213, "s": 27121, "text": "1 mod 41. It can be observed that the smallest n which satisfies this property is -4 as -40" }, { "code": null, "e": 27270, "s": 27215, "text": "1 mod 41. Now we can multiply the original equation 10" }, { "code": null, "e": 27275, "s": 27272, "text": "+c" }, { "code": null, "e": 27315, "s": 27277, "text": "0 (mod 41) by -4 and simplify it: -40" }, { "code": null, "e": 27321, "s": 27317, "text": "-4c" }, { "code": null, "e": 27336, "s": 27323, "text": "0 (mod 41) " }, { "code": null, "e": 27342, "s": 27338, "text": "-4c" }, { "code": null, "e": 27382, "s": 27344, "text": "0 (mod 41) We have found out that if " }, { "code": null, "e": 27403, "s": 27384, "text": "0 (mod 41) then, " }, { "code": null, "e": 27409, "s": 27405, "text": "-4c" }, { "code": null, "e": 27597, "s": 27411, "text": "0 (mod 41). In other words, to check if a 3-digit number is divisible by 41, we can just remove the last digit, multiply it by 4, and then subtract it from the rest of the two digits. " }, { "code": null, "e": 27646, "s": 27599, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 27650, "s": 27646, "text": "C++" }, { "code": null, "e": 27655, "s": 27650, "text": "Java" }, { "code": null, "e": 27663, "s": 27655, "text": "Python3" }, { "code": null, "e": 27666, "s": 27663, "text": "C#" }, { "code": null, "e": 27670, "s": 27666, "text": "PHP" }, { "code": null, "e": 27681, "s": 27670, "text": "Javascript" }, { "code": "// CPP program to validate above logic#include <bits/stdc++.h>using namespace std; // Function to check if the number// is divisible by 41 or notbool isDivisible(long long int n){ while (n / 100) { // Extracting the last digit int d = n % 10; // Truncating the number n /= 10; // Subtracting the four times // the last digit from the // remaining number n -= d * 4; } // return true if number is divisible by 41 return (n % 41 == 0);} int main(){ long long int n = 104413920565933; if (isDivisible(n)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 28344, "s": 27681, "text": null }, { "code": "// Java program to validate above logic class GFG { // Function to check if the number// is divisible by 41 or not static boolean isDivisible(long n) { while (n / 100 != 0) {// Extracting the last digit int d = (int) (n % 10); // Truncating the number n /= 10; // Subtracting the four times// the last digit from the// remaining number n -= d * 4; } // return true if number// is divisible by 41 return (n % 41 == 0); } public static void main(String[] args) { long n = 104413920565933L; if (isDivisible(n)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}// This code is contributed by RAJPUT-JI", "e": 29079, "s": 28344, "text": null }, { "code": "# Python3 Program to validate above logic # Function to check if the number# is divisible by 41 or notdef isDivisible(n) : while n // 100 : # Extracting the last digit d = n % 10 # Truncating the number n //= 10 # Subtracting the four times # the last digit from the # remaining number n -= d * 4 # return true if number is divisible by 41 return n % 41 == 0 # Driver Codeif __name__ == \"__main__\" : n = 104413920565933 if isDivisible(n) : print(\"Yes\") else : print(\"No\") # This code is contributed by ANKITRAI1", "e": 29710, "s": 29079, "text": null }, { "code": "// C# program to validate above logicusing System; class GFG{// Function to check if the number// is divisible by 41 or notstatic bool isDivisible(long n){ while (n / 100 != 0) { // Extracting the last digit int d = (int)(n % 10); // Truncating the number n /= 10; // Subtracting the four times // the last digit from the // remaining number n -= d * 4; } // return true if number // is divisible by 41 return (n % 41 == 0);} // Driver Codestatic public void Main (){ long n = 104413920565933; if (isDivisible(n)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Raj", "e": 30409, "s": 29710, "text": null }, { "code": "<?php// PHP program to validate above logic // Function to check if the number// is divisible by 41 or notfunction isDivisible($n){ while ($n / 100) { // Extracting the last digit $d = $n % 10; // Truncating the number $n /= 10; // Subtracting the four times // the last digit from the // remaining number $n -= $d * 4; } // return true if number // is divisible by 41 return ($n % 41 == 0);} // Driver Code$n = 104413920565933;if (isDivisible($n)) echo \"Yes\".\"\\n\";else echo \"No\".\"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 31025, "s": 30409, "text": null }, { "code": "<script> // JavaScript program to validate above logic // Function to check if the number// is divisible by 41 or not function isDivisible(n) { while (Math.floor(n / 100) != 0) {// Extracting the last digit let d = (n % 10); // Truncating the number n = Math.floor(n/10); // Subtracting the four times// the last digit from the// remaining number n -= d * 4; } // return true if number// is divisible by 41 return (n % 41 == 0); } let n = 104413920565933; if (isDivisible(n)) { document.write(\"Yes\"); } else { document.write(\"No\"); } // This code is contributed by avanitrachhadiya2155 </script>", "e": 31753, "s": 31025, "text": null }, { "code": null, "e": 31757, "s": 31753, "text": "Yes" }, { "code": null, "e": 32010, "s": 31759, "text": "Note that the above program may not make a lot of sense as could simply do n % 41 to check for divisibility. The idea of this program is to validate the concept. Also, this might be an efficient approach if input number is large and given as string. " }, { "code": null, "e": 32018, "s": 32010, "text": "ankthon" }, { "code": null, "e": 32024, "s": 32018, "text": "ukasp" }, { "code": null, "e": 32030, "s": 32024, "text": "R_Raj" }, { "code": null, "e": 32040, "s": 32030, "text": "Rajput-Ji" }, { "code": null, "e": 32050, "s": 32040, "text": "abhirup45" }, { "code": null, "e": 32071, "s": 32050, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32084, "s": 32071, "text": "divisibility" }, { "code": null, "e": 32104, "s": 32084, "text": "Number Divisibility" }, { "code": null, "e": 32118, "s": 32104, "text": "number-digits" }, { "code": null, "e": 32131, "s": 32118, "text": "Mathematical" }, { "code": null, "e": 32144, "s": 32131, "text": "Mathematical" }, { "code": null, "e": 32242, "s": 32144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32284, "s": 32242, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 32308, "s": 32284, "text": "Merge two sorted arrays" }, { "code": null, "e": 32351, "s": 32308, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32365, "s": 32351, "text": "Prime Numbers" }, { "code": null, "e": 32414, "s": 32365, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32448, "s": 32414, "text": "Program for factorial of a number" }, { "code": null, "e": 32489, "s": 32448, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 32511, "s": 32489, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32532, "s": 32511, "text": "Operators in C / C++" } ]
PL/SQL - Relational Operators
Relational operators compare two expressions or values and return a Boolean result. Following table shows all the relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable B holds 20, then − != <> ~= DECLARE a number (2) := 21; b number (2) := 10; BEGIN IF (a = b) then dbms_output.put_line('Line 1 - a is equal to b'); ELSE dbms_output.put_line('Line 1 - a is not equal to b'); END IF; IF (a < b) then dbms_output.put_line('Line 2 - a is less than b'); ELSE dbms_output.put_line('Line 2 - a is not less than b'); END IF; IF ( a > b ) THEN dbms_output.put_line('Line 3 - a is greater than b'); ELSE dbms_output.put_line('Line 3 - a is not greater than b'); END IF; -- Lets change value of a and b a := 5; b := 20; IF ( a <= b ) THEN dbms_output.put_line('Line 4 - a is either equal or less than b'); END IF; IF ( b >= a ) THEN dbms_output.put_line('Line 5 - b is either equal or greater than a'); END IF; IF ( a <> b ) THEN dbms_output.put_line('Line 6 - a is not equal to b'); ELSE dbms_output.put_line('Line 6 - a is equal to b'); END IF; END; / When the above code is executed at the SQL prompt, it produces the following result − Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b Line 4 - a is either equal or less than b Line 5 - b is either equal or greater than a Line 6 - a is not equal to b PL/SQL procedure successfully completed Print Add Notes Bookmark this page
[ { "code": null, "e": 2287, "s": 2065, "text": "Relational operators compare two expressions or values and return a Boolean result. Following table shows all the relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 2290, "s": 2287, "text": "!=" }, { "code": null, "e": 2293, "s": 2290, "text": "<>" }, { "code": null, "e": 2296, "s": 2293, "text": "~=" }, { "code": null, "e": 3309, "s": 2296, "text": "DECLARE \n a number (2) := 21; \n b number (2) := 10; \nBEGIN \n IF (a = b) then \n dbms_output.put_line('Line 1 - a is equal to b'); \n ELSE \n dbms_output.put_line('Line 1 - a is not equal to b'); \n END IF; \n IF (a < b) then \n dbms_output.put_line('Line 2 - a is less than b'); \n ELSE \n dbms_output.put_line('Line 2 - a is not less than b'); \n END IF; \n \n IF ( a > b ) THEN \n dbms_output.put_line('Line 3 - a is greater than b'); \n ELSE \n dbms_output.put_line('Line 3 - a is not greater than b'); \n END IF; \n -- Lets change value of a and b \n a := 5; \n b := 20; \n IF ( a <= b ) THEN \n dbms_output.put_line('Line 4 - a is either equal or less than b'); \n END IF; \n IF ( b >= a ) THEN \n dbms_output.put_line('Line 5 - b is either equal or greater than a'); \n END IF;\n IF ( a <> b ) THEN \n dbms_output.put_line('Line 6 - a is not equal to b'); \n ELSE \n dbms_output.put_line('Line 6 - a is equal to b'); \n END IF; \nEND; \n/ " }, { "code": null, "e": 3395, "s": 3309, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3649, "s": 3395, "text": "Line 1 - a is not equal to b \nLine 2 - a is not less than b \nLine 3 - a is greater than b \nLine 4 - a is either equal or less than b \nLine 5 - b is either equal or greater than a \nLine 6 - a is not equal to b \n\nPL/SQL procedure successfully completed \n" }, { "code": null, "e": 3656, "s": 3649, "text": " Print" }, { "code": null, "e": 3667, "s": 3656, "text": " Add Notes" } ]
How to filter data using where Clause and “AND” in Android sqlite?
Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc. This example demonstrates How to filter data using where Clause and “AND” in Android sqlite. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <EditText android:id = "@+id/salary" android:layout_width = "match_parent" android:inputType = "numberDecimal" android:hint = "Enter Salary" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"><Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button after insert values to update listview from cursor. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button save, refresh; EditText name, salary; private ListView listView; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); final DatabaseHelper helper = new DatabaseHelper(this); final ArrayList array_list = helper.getAllCotacts(); name = findViewById(R.id.name); salary = findViewById(R.id.salary); listView = findViewById(R.id.listView); final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { array_list.clear(); array_list.addAll(helper.getAllCotacts()); arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.insert(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); } } Step 4 − Add the following code to src/ DatabaseHelper.java package com.example.andy.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.IOException; import java.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "salaryDatabase3"; public static final String CONTACTS_TABLE_NAME = "SalaryDetails"; public DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,1); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL( "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text )" ); } catch (SQLiteException e) { try { throw new IOException(e); } catch (IOException e1) { e1.printStackTrace(); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME); onCreate(db); } public boolean insert(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", s); contentValues.put("salary", s1); db.insert(CONTACTS_TABLE_NAME, null, contentValues); return true; } public ArrayList getAllCotacts() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<String> array_list = new ArrayList<String>(); Cursor res = db.rawQuery( "select * from "+CONTACTS_TABLE_NAME+" WHERE name = 'Me'"+"AND salary = '1234567890'", null ); res.moveToFirst(); while(res.isAfterLast() = = false) { array_list.add(res.getString(res.getColumnIndex("name"))); res.moveToNext(); } return array_list; } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result it is showing “Me” in list view because we have given where cause and salary should be “1234567890” with select command so it is filtering name and salary. Click here to download the project code
[ { "code": null, "e": 1457, "s": 1062, "text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc." }, { "code": null, "e": 1550, "s": 1457, "text": "This example demonstrates How to filter data using where Clause and “AND” in Android sqlite." }, { "code": null, "e": 1679, "s": 1550, "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": 1744, "s": 1679, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3057, "s": 1744, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\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 android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <EditText\n android:id = \"@+id/salary\"\n android:layout_width = \"match_parent\"\n android:inputType = \"numberDecimal\"\n android:hint = \"Enter Salary\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"><Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 3273, "s": 3057, "text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button after insert values to update listview from cursor." }, { "code": null, "e": 3330, "s": 3273, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5460, "s": 3330, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5520, "s": 5460, "text": "Step 4 − Add the following code to src/ DatabaseHelper.java" }, { "code": null, "e": 7503, "s": 5520, "text": "package com.example.andy.myapplication;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport java.io.IOException;\nimport java.util.ArrayList;\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase3\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary text )\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.insert(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery( \"select * from \"+CONTACTS_TABLE_NAME+\" WHERE name = 'Me'\"+\"AND salary = '1234567890'\", null );\n res.moveToFirst();\n while(res.isAfterLast() = = false) {\n array_list.add(res.getString(res.getColumnIndex(\"name\")));\n res.moveToNext();\n }\n return array_list;\n }\n}" }, { "code": null, "e": 7850, "s": 7503, "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": 8026, "s": 7850, "text": "In the above result it is showing “Me” in list view because we have given where cause and salary should be “1234567890” with select command so it is filtering name and salary." }, { "code": null, "e": 8066, "s": 8026, "text": "Click here to download the project code" } ]
Short Circuit Logical Operators in Java with Examples - GeeksforGeeks
02 Dec, 2021 In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing. Below are the various types of Short circuits that occur in Java: In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned. Example: Short-circuiting using AND(&&) operator. Java // Java code to demonstrate the// short circuiting using && import java.io.*; class ShortCirAND { public static void main(String arg[]) { // Since first operand is false // and operator is &&, // Evaluation stops and // false is returned. if (false && true && true) { System.out.println("This output " + "will not " + "be printed"); } else { System.out.println("This output " + "got printed actually, " + " due to short circuit"); } // Whole expression will be evaluated, // as no false is encountered // before last condition // Therefore no Short circuit if (true && true && true) { System.out.println("This output " + "gets print" + " as there will be" + " no Short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } }} This output got printed actually, due to short circuit This output gets print as there will be no Short circuit In the case of OR, the expression is evaluated until we get one true result because the result will always be true, independent of the further conditions. If there is an expression with ||(logical OR), and the first operand itself is true, a short circuit occurs, evaluation stops, and true is returned. Example: Short-circuiting using OR( || ). Java // Java program to demonstrate the// short circuiting using OR class ShortCirOR { public static void main(String arg[]) { // Since first operand is true // and operator is ||, // Evaluation stops and // true is returned. if (true || false || false) { System.out.println("This output " + "got printed actually, " + " due to short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } // Whole expression will be evaluated, // as no true is encountered // before last condition // Therefore no Short circuit if (false || false || true) { System.out.println("This output " + "gets print" + " as there will be" + " no Short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } }} This output got printed actually, due to short circuit This output gets print as there will be no Short circuit jasonleake nishkarshgandhi Java-Operators Java Java-Operators Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n02 Dec, 2021" }, { "code": null, "e": 23925, "s": 23557, "text": "In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing." }, { "code": null, "e": 23991, "s": 23925, "text": "Below are the various types of Short circuits that occur in Java:" }, { "code": null, "e": 24329, "s": 23991, "text": "In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned." }, { "code": null, "e": 24379, "s": 24329, "text": "Example: Short-circuiting using AND(&&) operator." }, { "code": null, "e": 24384, "s": 24379, "text": "Java" }, { "code": "// Java code to demonstrate the// short circuiting using && import java.io.*; class ShortCirAND { public static void main(String arg[]) { // Since first operand is false // and operator is &&, // Evaluation stops and // false is returned. if (false && true && true) { System.out.println(\"This output \" + \"will not \" + \"be printed\"); } else { System.out.println(\"This output \" + \"got printed actually, \" + \" due to short circuit\"); } // Whole expression will be evaluated, // as no false is encountered // before last condition // Therefore no Short circuit if (true && true && true) { System.out.println(\"This output \" + \"gets print\" + \" as there will be\" + \" no Short circuit\"); } else { System.out.println(\"This output \" + \"will not \" + \"be printed\"); } }}", "e": 25588, "s": 24384, "text": null }, { "code": null, "e": 25701, "s": 25588, "text": "This output got printed actually, due to short circuit\nThis output gets print as there will be no Short circuit" }, { "code": null, "e": 26005, "s": 25701, "text": "In the case of OR, the expression is evaluated until we get one true result because the result will always be true, independent of the further conditions. If there is an expression with ||(logical OR), and the first operand itself is true, a short circuit occurs, evaluation stops, and true is returned." }, { "code": null, "e": 26047, "s": 26005, "text": "Example: Short-circuiting using OR( || )." }, { "code": null, "e": 26052, "s": 26047, "text": "Java" }, { "code": "// Java program to demonstrate the// short circuiting using OR class ShortCirOR { public static void main(String arg[]) { // Since first operand is true // and operator is ||, // Evaluation stops and // true is returned. if (true || false || false) { System.out.println(\"This output \" + \"got printed actually, \" + \" due to short circuit\"); } else { System.out.println(\"This output \" + \"will not \" + \"be printed\"); } // Whole expression will be evaluated, // as no true is encountered // before last condition // Therefore no Short circuit if (false || false || true) { System.out.println(\"This output \" + \"gets print\" + \" as there will be\" + \" no Short circuit\"); } else { System.out.println(\"This output \" + \"will not \" + \"be printed\"); } }}", "e": 27237, "s": 26052, "text": null }, { "code": null, "e": 27350, "s": 27237, "text": "This output got printed actually, due to short circuit\nThis output gets print as there will be no Short circuit" }, { "code": null, "e": 27361, "s": 27350, "text": "jasonleake" }, { "code": null, "e": 27377, "s": 27361, "text": "nishkarshgandhi" }, { "code": null, "e": 27392, "s": 27377, "text": "Java-Operators" }, { "code": null, "e": 27397, "s": 27392, "text": "Java" }, { "code": null, "e": 27412, "s": 27397, "text": "Java-Operators" }, { "code": null, "e": 27417, "s": 27412, "text": "Java" }, { "code": null, "e": 27515, "s": 27417, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27524, "s": 27515, "text": "Comments" }, { "code": null, "e": 27537, "s": 27524, "text": "Old Comments" }, { "code": null, "e": 27567, "s": 27537, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27582, "s": 27567, "text": "Stream In Java" }, { "code": null, "e": 27603, "s": 27582, "text": "Constructors in Java" }, { "code": null, "e": 27649, "s": 27603, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27668, "s": 27649, "text": "Exceptions in Java" }, { "code": null, "e": 27685, "s": 27668, "text": "Generics in Java" }, { "code": null, "e": 27728, "s": 27685, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27744, "s": 27728, "text": "Strings in Java" }, { "code": null, "e": 27793, "s": 27744, "text": "How to remove an element from ArrayList in Java?" } ]
Implementation of Basic NLP Techniques with spaCy | Towards Data Science
Natural Language Processing (NLP) is a very interesting technique because, with this technique, the computer can recognize our natural language and respond like an intelligent person. At first, when I came to know about the magic of NLP, it was amazing to me. [If you want to know about my journey to NLP as well as the basics of NLP, I will strongly recommend you to read out the article — A Complete Guideline to Natural Language Processing (NLP).] I believe practical experience is the best way to learn a technique, and only theoretical knowledge doesn’t help. Apple’s Siri, Microsoft’s Cortana, Google’s Voice Assistance, Amazon’s Alexa, etc., all of them are using NLP. How interesting their works are! And hopefully, we will also create some interesting projects. So, it’s time to make our hands dirty by having a hands-on experience of implementing tokenization, lemmatization, stemming, stop word, POS tagging, etc. We also learn which python library is best for practical use and why. Let’s get started......... Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data[1]. Both spaCy and NLTK are open-source Natural Language Processing libraries. ◉ spaCy spaCy first came into the spotlight in 2015 as an open source NLP library. It can perform most of the NLP tasks efficiently. spaCy mainly implements the most common efficient NLP techniques for performing the task. There is no option to select a specific algorithm to perform a task. For example, there is more than one technique for stemming, and you want to choose one of them. Unfortunately, spaCy does not provide us the flexibility; rather, it automatically selects the best commonly used algorithm to perform the task. If you want to know more about spaCy, please visit the official website of spaCy [2]. ◉ NLTK NLTK stands for Natural Language Toolkit, one of the oldest and popular Natural Language Processing Library. It was first released in 2001, which means it is much older than spaCy. It facilitates many NLP functionalities, but it is less efficient. You can select different algorithms in NLTK. You may have the official documentation of NLTK from here[3]. ➤ Comparative Analysis of NLTK and spaCy Both NLTK and spaCy are important libraries for NLP. Some tasks are efficient in spaCy, and some are efficient in NLTK. We need to use both libraries in different circumstances, and let’s see some comparisons. The above figure clearly indicates that spaCy is 20 times and 443 times faster than NLTK in the case of tokenization and tagging. We can not classify the libraries based on superiority; instead, both are needed in different cases. In general, spaCy works better than NLTK in comparison to the speed and implementation, but NLTK is also required. Throughout the article I will show you the basic implementation of NLP tasks like tokenization, stemming, lemmatization, POS tagging, text matching, etc. Let’s make our hands dirty with some code. First of all, I will show how to create the environment for spaCy. If you use Anaconda, you must write the following command to the Anaconda command prompt. conda install -c conda-forge spacyor pip install -U spacy If you locally use libraries other than Anaconda, you may use the following command. pip install -U spacy As we use the English language for the demonstration purpose, we need to download the necessary elements of the English language. Run the command to the command prompt. N.B. — You must have to run this command as admin or use sudo. python -m spacy download en ◉ Working with spaCy import spacynlp = spacy.load('en_core_web_sm') When we run the following piece of code, it will import the spaCy library and load the model to nlp . If we call the object nlp on a text, spaCy will tokenize the text and save it to a Doc object. After that, the Doc object is again passed through different steps, and the process is known as a pipeline. Generally, the pipeline contains tagger, lemmatizer, parser, and named entity recognizer. The following image clearly describes the pipeline process[5]. By running the code nlp.pipepline, we may find out the components of the pipeline. There are some token attributes for finding the original token text, lemmatization, pos tagging, etc. In the following table, there are some other attributes. The tokenization technique splits the text into its small units. Let’s have an example[6]. doc = nlp('"Let\'s go to N.Y.!"')for token in doc: print(token.text) If we run the code, we will find the output as below. "Let'sgotoN.Y.!" The doc object contains tokens of the text, and the attribute .text holds the original text. spaCy is very smart as it doesn’t separate N.Y. as well as consider ‘s as a token. The following image clearly describes the process of tokenization. In a sentence, a word or a group of words indicates names (e.g., Name of location, person, area, country, state, monetary values, and so on). The primary purpose of a named entity is to identify it. The named entities can be accessible with ents attributes of Doc object. Output of the code Google | 's | monthly | revenue | is | $ | 6 | million | ______________________________________________________Google - ORG - Companies, agencies, institutions, etc.monthly - DATE - Absolute or relative dates or periods$6 million - MONEY - Monetary values, including unit The first line of the output shows the tokens of the sentence, and the rest of the lines indicate the named entities along with the proper documentation. By using the .noun_chunks attribute, we will get the base noun phrase. spaCy has a built-in visualizer to visualize the named entity. For doing so, we have to import displacy module from spaCy library. The following code shows the output as follows. from spacy import displacydoc = nlp(u'Over last few years USA generates $6 million revenue.')displacy.render(doc, style='ent', jupyter=True) Output With spaCy, we can also visualize the dependencies of the token of a sentence. For demonstration purposes, follow the piece of the following code. from spacy import displacydocument = nlp(u'Bangladesh is a beautiful country')displacy.render(document, style='dep', jupyter=True, options={'distance': 110}) Output Stemming means chopping the words/ tokens to find out their root words. But it doesn’t always provide meaningful strings. The spaCy library doesn’t have any stemmer; instead, it entirely relies on lemmatization. ◉Porter Stemmer Porter stemmer has its own mapping rules by which words are chopped in different stages. The algorithm uses five phases for reducing the word. Firstly, the suffixes are removed with some predefined rules, which are given below. Here, S1 denotes the suffixes of longer text, and S2 denotes the reduced form after the reduction of the word. At a time, only one rule can be applied. The above rules are more complex than the first rules. The m denotes the measure of the length. If you want to know more about the porter stemmer algorithm, please visit the link[7]. Let’s have a coding example. import nltkfrom nltk.stem.porter import *p_stemmer = PorterStemmer()words = ['run','runner','running','ran','runs','easily','fairly']for word in words: print(word+' --> '+p_stemmer.stem(word)) Output run --> runrunner --> runnerrunning --> runran --> ranruns --> runeasily --> easilifairly --> fairli ◉Snowball Stemmer The stemmer is an improved version of the porter stemmer, and it gives better results than the previous stemming algorithm in case of logic and speed. Let’s implement with NLTK. from nltk.stem.snowball import SnowballStemmers_stemmer = SnowballStemmer(language='english')words = ['run','runner','running','ran','runs','easily','fairly']for word in words: print(word+' --> '+s_stemmer.stem(word)) Output run --> runrunner --> runnerrunning --> runran --> ranruns --> runeasily --> easilifairly --> fair It seems the result is slightly improved. Lemmatization is not just reducing or chopping the words like stemming. The main idea of lemmatization is to find out the main root word. Please read out my previous article from here to learn more about lemmatization. The above code produces the following output He PRON 561228191312463089 -PRON-is VERB 10382539506755952630 bea DET 11901859001352538922 arunner NOUN 12640964157389618806 runnerrunning VERB 12767647472892411841 runin ADP 3002984154512732771 ina DET 11901859001352538922 acompetition NOUN 4661638505416061516 competitionbecause ADP 16950148841647037698 becausehe PRON 561228191312463089 -PRON-loves VERB 3702023516439754181 loveto PART 3791531372978436496 torun VERB 12767647472892411841 runsince ADP 10066841407251338481 sincehe PRON 561228191312463089 -PRON-ran VERB 12767647472892411841 runtoday NOUN 11042482332948150395 today The .pos_ attribute returns the parts of speech for a token, .lemma provides the hash value for a particular token, and .lemma_ gives the lemma for a token. If we observe the token running, run, ran, we will find it comes from the same lemma run. It’s really an interesting and amazing job. Stop words come so frequently in the sentence but don’t important to change the meaning of a sentence. Like a, an, the, then, etc. In the spaCy library, there are 305 stop words by default. We can modify the list of the stop words according to our needs. Let’s have a codified example. import spacynlp = spacy.load('en_core_web_sm')print(nlp.Defaults.stop_words) Output {'hers', 'show', 'though', 'various', 'sixty', 'say', 'quite', 'ten', 'anything', 'although', 'hereby', 'in', 'ours', 'herself', 'among', 'unless', 'and', 'whole', 'anywhere', 'latter', 'therein', 'whereafter', 'that', 'one', 'whose', 'either', 'within', 'eight', 'three', 'latterly', 'anyone', 'a', 'less', 'former', 'been', 'same', 'anyway', 'else', 'cannot', 'five', 'i', 'until', 'last', 'thus', 'give', 'move', 'thereafter', 'via', 'than', 'empty', 'off', 'neither', 'too', 'please', 'over', 'just', 'otherwise', 'has', 'her', 'put', 'its', 'whether', 'herein', 'myself', 'me', 'nevertheless', 'whatever', 'someone', 'towards', 'whereby', 'onto', 'sometimes', 'thence', 'them', 'done', 'at', 'back', 'nor', 'another', 'behind', 'together', 'take', 'amongst', 'being', 'seemed', 'seeming', 'fifteen', 'do', 'further', 'something', 'again', 'this', 'were', 'wherein', 'how', 'up', 'must', 'get', 'whereas', 'much', 'upon', 'yet', 'both', 'many', 'very', 'may', 'after', 'regarding', 'full', 'through', 'below', 'his', 'well', 'everything', 'so', 'our', 'should', 'seem', 'while', 'for', 'might', 'mine', 'when', 'with', 'you', 'few', 'never', 'because', 'own', 'also', 'due', 'hence', 'it', 'more', 'their', 'such', 'becomes', 'first', 'hereupon', 'since', 'third', 'twenty', 'who', 'she', 'nobody', 'name', 'really', 'enough', 'least', 'two', 'whoever', 'which', 'yours', 'moreover', 'seems', 'before', 'therefore', 'then', 'used', 'even', 'nowhere', 'without', 'other', 'around', 'made', 'hundred', 'no', 'twelve', 'several', 'your', 'meanwhile', 'per', 'except', 'yourselves', 'why', 'some', 'not', 'yourself', 'sometime', 'somehow', 'become', 'beyond', 'almost', 'will', 'somewhere', 'the', 'everyone', 'about', 'everywhere', 'anyhow', 'side', 'next', 'fifty', 'they', 'most', 'perhaps', 'across', 'themselves', 'besides', 'against', 'can', 'him', 'there', 'noone', 'under', 'formerly', 'already', 'all', 'if', 'my', 'or', 'serious', 'four', 'thereupon', 'whence', 'here', 'whither', 'beside', 'wherever', 'to', 'himself', 'between', 'ourselves', 'none', 'on', 'became', 'an', 'have', 'part', 'did', 'had', 'each', 'six', 'those', 'from', 'whenever', 'any', 'am', 'would', 'make', 'could', 'does', 'go', 'call', 'indeed', 'these', 'often', 'above', 'during', 'by', 'nine', 'thereby', 'others', 'afterwards', 'throughout', 'whom', 'amount', 'as', 'hereafter', 'top', 'mostly', 'us', 'whereupon', 'once', 'only', 'still', 'namely', 'forty', 'ca', 'along', 'be', 'itself', 'where', 'see', 'into', 'toward', 'but', 'is', 'keep', 'bottom', 'ever', 'becoming', 'every', 'always', 'front', 'nothing', 'we', 'of', 'out', 'eleven', 'alone', 'he', 'however', 'rather', 'down', 'thru', 'now', 'using', 'are', 'doing', 'what', 'beforehand', 're', 'was', 'elsewhere'} ◉Checking a specific token whether it is a stop word or not. nlp.vocab['myself'].is_stop It returns True as the default list of stop words contains the word ‘myself’. nlp.vocab['mystery'].is_stop The code returns False as the default list of stop words doesn’t contain the word ‘mystery’ . ◉Adding and removing a stop word to the default spaCy stop words list The code nlp.Defaults.stop_words.add(‘btw’) adds the string btw to the default list and nlp.Defaults.stop_words.remove(‘hers’) removes the word hers from the default stop word list. spaCy offers rule-based matching tools named Matcher, it allows us to set rules or regular expressions to match with a Doc object, and it returns a list containing the found matches. To learn more, visit the link[7]. ◉Rule-based Matcher ➤Importing Matcher library and creating a matcher object. from spacy.matcher import Matchermatcher = Matcher(nlp.vocab) ➤Creating a pattern and add it to the matcher pattern_1 = [{'LOWER': 'solarpower'}]pattern_2 = [{'LOWER': 'solar'}, {'LOWER': 'power'}]pattern_3 = [{'LOWER': 'solar'}, {'IS_PUNCT': True}, {'LOWER': 'power'}]matcher.add('SolarPower', None, pattern1, pattern2, pattern3) The above piece of code contains three patterns. pattern_1 denotes any match with the lowercase solarpower . pattern_2 denotes any match with adjacent lowercase solar and power. pattern_3 denotes any match with lowercase solar and power along with any punctuation mark between them. ➤Applying the matcher to a doc object. document = nlp(u'The Solar Power industry continues to grow as demand \for solarpower increases. Solar-power cars are gaining popularity.')found_matches = matcher(document)print(found_matches) matcher returns a list of tuples. Each tuple contains an ID for the match, with start & end tokens that map to the span doc[start:end]. ➤Finding out the text for the matches. for match_id, start, end in found_matches: # get string representation string_id = nlp.vocab.strings[match_id] # get the matched span span = doc[start:end] print(match_id, string_id, start, end, span.text) Output 8656102463236116519 SolarPower 1 3 Solar Power8656102463236116519 SolarPower 10 11 solarpower8656102463236116519 SolarPower 13 16 Solar-power The match_id is simply the hash value of the string_ID 'SolarPower'. ◉Phrase Matcher If you want to learn about PhraseMatcher, please visit the link [8]. NLP is one of the amazing techniques in modern computing by which computers can recognize our Natural Languages. There are some techniques by which computer processes the natural language because the human and machine learning process is different. Different libraries like spaCy, NLTK have made the process easy for us. It is impossible to accommodate all necessary techniques in a single article. So, keep your eyes on the upcoming articles for more amazing implementation techniques and projects of NLP. You may also read out the following articles on NLP written by me. towardsdatascience.com towardsdatascience.com towardsdatascience.com [1]. https://en.wikipedia.org/wiki/Natural_language_processing [2]. spaCy · Industrial-strength Natural Language Processing in Python [3]. NLTK :: Natural Language Toolkit
[ { "code": null, "e": 425, "s": 165, "text": "Natural Language Processing (NLP) is a very interesting technique because, with this technique, the computer can recognize our natural language and respond like an intelligent person. At first, when I came to know about the magic of NLP, it was amazing to me." }, { "code": null, "e": 616, "s": 425, "text": "[If you want to know about my journey to NLP as well as the basics of NLP, I will strongly recommend you to read out the article — A Complete Guideline to Natural Language Processing (NLP).]" }, { "code": null, "e": 936, "s": 616, "text": "I believe practical experience is the best way to learn a technique, and only theoretical knowledge doesn’t help. Apple’s Siri, Microsoft’s Cortana, Google’s Voice Assistance, Amazon’s Alexa, etc., all of them are using NLP. How interesting their works are! And hopefully, we will also create some interesting projects." }, { "code": null, "e": 1160, "s": 936, "text": "So, it’s time to make our hands dirty by having a hands-on experience of implementing tokenization, lemmatization, stemming, stop word, POS tagging, etc. We also learn which python library is best for practical use and why." }, { "code": null, "e": 1187, "s": 1160, "text": "Let’s get started........." }, { "code": null, "e": 1472, "s": 1187, "text": "Natural language processing (NLP) is a subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data[1]." }, { "code": null, "e": 1547, "s": 1472, "text": "Both spaCy and NLTK are open-source Natural Language Processing libraries." }, { "code": null, "e": 1555, "s": 1547, "text": "◉ spaCy" }, { "code": null, "e": 2080, "s": 1555, "text": "spaCy first came into the spotlight in 2015 as an open source NLP library. It can perform most of the NLP tasks efficiently. spaCy mainly implements the most common efficient NLP techniques for performing the task. There is no option to select a specific algorithm to perform a task. For example, there is more than one technique for stemming, and you want to choose one of them. Unfortunately, spaCy does not provide us the flexibility; rather, it automatically selects the best commonly used algorithm to perform the task." }, { "code": null, "e": 2166, "s": 2080, "text": "If you want to know more about spaCy, please visit the official website of spaCy [2]." }, { "code": null, "e": 2173, "s": 2166, "text": "◉ NLTK" }, { "code": null, "e": 2466, "s": 2173, "text": "NLTK stands for Natural Language Toolkit, one of the oldest and popular Natural Language Processing Library. It was first released in 2001, which means it is much older than spaCy. It facilitates many NLP functionalities, but it is less efficient. You can select different algorithms in NLTK." }, { "code": null, "e": 2528, "s": 2466, "text": "You may have the official documentation of NLTK from here[3]." }, { "code": null, "e": 2569, "s": 2528, "text": "➤ Comparative Analysis of NLTK and spaCy" }, { "code": null, "e": 2779, "s": 2569, "text": "Both NLTK and spaCy are important libraries for NLP. Some tasks are efficient in spaCy, and some are efficient in NLTK. We need to use both libraries in different circumstances, and let’s see some comparisons." }, { "code": null, "e": 2909, "s": 2779, "text": "The above figure clearly indicates that spaCy is 20 times and 443 times faster than NLTK in the case of tokenization and tagging." }, { "code": null, "e": 3125, "s": 2909, "text": "We can not classify the libraries based on superiority; instead, both are needed in different cases. In general, spaCy works better than NLTK in comparison to the speed and implementation, but NLTK is also required." }, { "code": null, "e": 3389, "s": 3125, "text": "Throughout the article I will show you the basic implementation of NLP tasks like tokenization, stemming, lemmatization, POS tagging, text matching, etc. Let’s make our hands dirty with some code. First of all, I will show how to create the environment for spaCy." }, { "code": null, "e": 3479, "s": 3389, "text": "If you use Anaconda, you must write the following command to the Anaconda command prompt." }, { "code": null, "e": 3537, "s": 3479, "text": "conda install -c conda-forge spacyor pip install -U spacy" }, { "code": null, "e": 3622, "s": 3537, "text": "If you locally use libraries other than Anaconda, you may use the following command." }, { "code": null, "e": 3643, "s": 3622, "text": "pip install -U spacy" }, { "code": null, "e": 3812, "s": 3643, "text": "As we use the English language for the demonstration purpose, we need to download the necessary elements of the English language. Run the command to the command prompt." }, { "code": null, "e": 3875, "s": 3812, "text": "N.B. — You must have to run this command as admin or use sudo." }, { "code": null, "e": 3903, "s": 3875, "text": "python -m spacy download en" }, { "code": null, "e": 3924, "s": 3903, "text": "◉ Working with spaCy" }, { "code": null, "e": 3971, "s": 3924, "text": "import spacynlp = spacy.load('en_core_web_sm')" }, { "code": null, "e": 4429, "s": 3971, "text": "When we run the following piece of code, it will import the spaCy library and load the model to nlp . If we call the object nlp on a text, spaCy will tokenize the text and save it to a Doc object. After that, the Doc object is again passed through different steps, and the process is known as a pipeline. Generally, the pipeline contains tagger, lemmatizer, parser, and named entity recognizer. The following image clearly describes the pipeline process[5]." }, { "code": null, "e": 4671, "s": 4429, "text": "By running the code nlp.pipepline, we may find out the components of the pipeline. There are some token attributes for finding the original token text, lemmatization, pos tagging, etc. In the following table, there are some other attributes." }, { "code": null, "e": 4762, "s": 4671, "text": "The tokenization technique splits the text into its small units. Let’s have an example[6]." }, { "code": null, "e": 4834, "s": 4762, "text": "doc = nlp('\"Let\\'s go to N.Y.!\"')for token in doc: print(token.text)" }, { "code": null, "e": 4888, "s": 4834, "text": "If we run the code, we will find the output as below." }, { "code": null, "e": 4905, "s": 4888, "text": "\"Let'sgotoN.Y.!\"" }, { "code": null, "e": 5148, "s": 4905, "text": "The doc object contains tokens of the text, and the attribute .text holds the original text. spaCy is very smart as it doesn’t separate N.Y. as well as consider ‘s as a token. The following image clearly describes the process of tokenization." }, { "code": null, "e": 5420, "s": 5148, "text": "In a sentence, a word or a group of words indicates names (e.g., Name of location, person, area, country, state, monetary values, and so on). The primary purpose of a named entity is to identify it. The named entities can be accessible with ents attributes of Doc object." }, { "code": null, "e": 5439, "s": 5420, "text": "Output of the code" }, { "code": null, "e": 5711, "s": 5439, "text": "Google | 's | monthly | revenue | is | $ | 6 | million | ______________________________________________________Google - ORG - Companies, agencies, institutions, etc.monthly - DATE - Absolute or relative dates or periods$6 million - MONEY - Monetary values, including unit" }, { "code": null, "e": 5936, "s": 5711, "text": "The first line of the output shows the tokens of the sentence, and the rest of the lines indicate the named entities along with the proper documentation. By using the .noun_chunks attribute, we will get the base noun phrase." }, { "code": null, "e": 6115, "s": 5936, "text": "spaCy has a built-in visualizer to visualize the named entity. For doing so, we have to import displacy module from spaCy library. The following code shows the output as follows." }, { "code": null, "e": 6256, "s": 6115, "text": "from spacy import displacydoc = nlp(u'Over last few years USA generates $6 million revenue.')displacy.render(doc, style='ent', jupyter=True)" }, { "code": null, "e": 6263, "s": 6256, "text": "Output" }, { "code": null, "e": 6410, "s": 6263, "text": "With spaCy, we can also visualize the dependencies of the token of a sentence. For demonstration purposes, follow the piece of the following code." }, { "code": null, "e": 6568, "s": 6410, "text": "from spacy import displacydocument = nlp(u'Bangladesh is a beautiful country')displacy.render(document, style='dep', jupyter=True, options={'distance': 110})" }, { "code": null, "e": 6575, "s": 6568, "text": "Output" }, { "code": null, "e": 6787, "s": 6575, "text": "Stemming means chopping the words/ tokens to find out their root words. But it doesn’t always provide meaningful strings. The spaCy library doesn’t have any stemmer; instead, it entirely relies on lemmatization." }, { "code": null, "e": 6803, "s": 6787, "text": "◉Porter Stemmer" }, { "code": null, "e": 7031, "s": 6803, "text": "Porter stemmer has its own mapping rules by which words are chopped in different stages. The algorithm uses five phases for reducing the word. Firstly, the suffixes are removed with some predefined rules, which are given below." }, { "code": null, "e": 7183, "s": 7031, "text": "Here, S1 denotes the suffixes of longer text, and S2 denotes the reduced form after the reduction of the word. At a time, only one rule can be applied." }, { "code": null, "e": 7395, "s": 7183, "text": "The above rules are more complex than the first rules. The m denotes the measure of the length. If you want to know more about the porter stemmer algorithm, please visit the link[7]. Let’s have a coding example." }, { "code": null, "e": 7591, "s": 7395, "text": "import nltkfrom nltk.stem.porter import *p_stemmer = PorterStemmer()words = ['run','runner','running','ran','runs','easily','fairly']for word in words: print(word+' --> '+p_stemmer.stem(word))" }, { "code": null, "e": 7598, "s": 7591, "text": "Output" }, { "code": null, "e": 7699, "s": 7598, "text": "run --> runrunner --> runnerrunning --> runran --> ranruns --> runeasily --> easilifairly --> fairli" }, { "code": null, "e": 7717, "s": 7699, "text": "◉Snowball Stemmer" }, { "code": null, "e": 7895, "s": 7717, "text": "The stemmer is an improved version of the porter stemmer, and it gives better results than the previous stemming algorithm in case of logic and speed. Let’s implement with NLTK." }, { "code": null, "e": 8116, "s": 7895, "text": "from nltk.stem.snowball import SnowballStemmers_stemmer = SnowballStemmer(language='english')words = ['run','runner','running','ran','runs','easily','fairly']for word in words: print(word+' --> '+s_stemmer.stem(word))" }, { "code": null, "e": 8123, "s": 8116, "text": "Output" }, { "code": null, "e": 8222, "s": 8123, "text": "run --> runrunner --> runnerrunning --> runran --> ranruns --> runeasily --> easilifairly --> fair" }, { "code": null, "e": 8264, "s": 8222, "text": "It seems the result is slightly improved." }, { "code": null, "e": 8483, "s": 8264, "text": "Lemmatization is not just reducing or chopping the words like stemming. The main idea of lemmatization is to find out the main root word. Please read out my previous article from here to learn more about lemmatization." }, { "code": null, "e": 8528, "s": 8483, "text": "The above code produces the following output" }, { "code": null, "e": 9333, "s": 8528, "text": "He PRON 561228191312463089 -PRON-is VERB 10382539506755952630 bea DET 11901859001352538922 arunner NOUN 12640964157389618806 runnerrunning VERB 12767647472892411841 runin ADP 3002984154512732771 ina DET 11901859001352538922 acompetition NOUN 4661638505416061516 competitionbecause ADP 16950148841647037698 becausehe PRON 561228191312463089 -PRON-loves VERB 3702023516439754181 loveto PART 3791531372978436496 torun VERB 12767647472892411841 runsince ADP 10066841407251338481 sincehe PRON 561228191312463089 -PRON-ran VERB 12767647472892411841 runtoday NOUN 11042482332948150395 today" }, { "code": null, "e": 9624, "s": 9333, "text": "The .pos_ attribute returns the parts of speech for a token, .lemma provides the hash value for a particular token, and .lemma_ gives the lemma for a token. If we observe the token running, run, ran, we will find it comes from the same lemma run. It’s really an interesting and amazing job." }, { "code": null, "e": 9910, "s": 9624, "text": "Stop words come so frequently in the sentence but don’t important to change the meaning of a sentence. Like a, an, the, then, etc. In the spaCy library, there are 305 stop words by default. We can modify the list of the stop words according to our needs. Let’s have a codified example." }, { "code": null, "e": 9987, "s": 9910, "text": "import spacynlp = spacy.load('en_core_web_sm')print(nlp.Defaults.stop_words)" }, { "code": null, "e": 9994, "s": 9987, "text": "Output" }, { "code": null, "e": 12756, "s": 9994, "text": "{'hers', 'show', 'though', 'various', 'sixty', 'say', 'quite', 'ten', 'anything', 'although', 'hereby', 'in', 'ours', 'herself', 'among', 'unless', 'and', 'whole', 'anywhere', 'latter', 'therein', 'whereafter', 'that', 'one', 'whose', 'either', 'within', 'eight', 'three', 'latterly', 'anyone', 'a', 'less', 'former', 'been', 'same', 'anyway', 'else', 'cannot', 'five', 'i', 'until', 'last', 'thus', 'give', 'move', 'thereafter', 'via', 'than', 'empty', 'off', 'neither', 'too', 'please', 'over', 'just', 'otherwise', 'has', 'her', 'put', 'its', 'whether', 'herein', 'myself', 'me', 'nevertheless', 'whatever', 'someone', 'towards', 'whereby', 'onto', 'sometimes', 'thence', 'them', 'done', 'at', 'back', 'nor', 'another', 'behind', 'together', 'take', 'amongst', 'being', 'seemed', 'seeming', 'fifteen', 'do', 'further', 'something', 'again', 'this', 'were', 'wherein', 'how', 'up', 'must', 'get', 'whereas', 'much', 'upon', 'yet', 'both', 'many', 'very', 'may', 'after', 'regarding', 'full', 'through', 'below', 'his', 'well', 'everything', 'so', 'our', 'should', 'seem', 'while', 'for', 'might', 'mine', 'when', 'with', 'you', 'few', 'never', 'because', 'own', 'also', 'due', 'hence', 'it', 'more', 'their', 'such', 'becomes', 'first', 'hereupon', 'since', 'third', 'twenty', 'who', 'she', 'nobody', 'name', 'really', 'enough', 'least', 'two', 'whoever', 'which', 'yours', 'moreover', 'seems', 'before', 'therefore', 'then', 'used', 'even', 'nowhere', 'without', 'other', 'around', 'made', 'hundred', 'no', 'twelve', 'several', 'your', 'meanwhile', 'per', 'except', 'yourselves', 'why', 'some', 'not', 'yourself', 'sometime', 'somehow', 'become', 'beyond', 'almost', 'will', 'somewhere', 'the', 'everyone', 'about', 'everywhere', 'anyhow', 'side', 'next', 'fifty', 'they', 'most', 'perhaps', 'across', 'themselves', 'besides', 'against', 'can', 'him', 'there', 'noone', 'under', 'formerly', 'already', 'all', 'if', 'my', 'or', 'serious', 'four', 'thereupon', 'whence', 'here', 'whither', 'beside', 'wherever', 'to', 'himself', 'between', 'ourselves', 'none', 'on', 'became', 'an', 'have', 'part', 'did', 'had', 'each', 'six', 'those', 'from', 'whenever', 'any', 'am', 'would', 'make', 'could', 'does', 'go', 'call', 'indeed', 'these', 'often', 'above', 'during', 'by', 'nine', 'thereby', 'others', 'afterwards', 'throughout', 'whom', 'amount', 'as', 'hereafter', 'top', 'mostly', 'us', 'whereupon', 'once', 'only', 'still', 'namely', 'forty', 'ca', 'along', 'be', 'itself', 'where', 'see', 'into', 'toward', 'but', 'is', 'keep', 'bottom', 'ever', 'becoming', 'every', 'always', 'front', 'nothing', 'we', 'of', 'out', 'eleven', 'alone', 'he', 'however', 'rather', 'down', 'thru', 'now', 'using', 'are', 'doing', 'what', 'beforehand', 're', 'was', 'elsewhere'}" }, { "code": null, "e": 12817, "s": 12756, "text": "◉Checking a specific token whether it is a stop word or not." }, { "code": null, "e": 12845, "s": 12817, "text": "nlp.vocab['myself'].is_stop" }, { "code": null, "e": 12923, "s": 12845, "text": "It returns True as the default list of stop words contains the word ‘myself’." }, { "code": null, "e": 12952, "s": 12923, "text": "nlp.vocab['mystery'].is_stop" }, { "code": null, "e": 13046, "s": 12952, "text": "The code returns False as the default list of stop words doesn’t contain the word ‘mystery’ ." }, { "code": null, "e": 13116, "s": 13046, "text": "◉Adding and removing a stop word to the default spaCy stop words list" }, { "code": null, "e": 13298, "s": 13116, "text": "The code nlp.Defaults.stop_words.add(‘btw’) adds the string btw to the default list and nlp.Defaults.stop_words.remove(‘hers’) removes the word hers from the default stop word list." }, { "code": null, "e": 13515, "s": 13298, "text": "spaCy offers rule-based matching tools named Matcher, it allows us to set rules or regular expressions to match with a Doc object, and it returns a list containing the found matches. To learn more, visit the link[7]." }, { "code": null, "e": 13535, "s": 13515, "text": "◉Rule-based Matcher" }, { "code": null, "e": 13593, "s": 13535, "text": "➤Importing Matcher library and creating a matcher object." }, { "code": null, "e": 13655, "s": 13593, "text": "from spacy.matcher import Matchermatcher = Matcher(nlp.vocab)" }, { "code": null, "e": 13701, "s": 13655, "text": "➤Creating a pattern and add it to the matcher" }, { "code": null, "e": 13924, "s": 13701, "text": "pattern_1 = [{'LOWER': 'solarpower'}]pattern_2 = [{'LOWER': 'solar'}, {'LOWER': 'power'}]pattern_3 = [{'LOWER': 'solar'}, {'IS_PUNCT': True}, {'LOWER': 'power'}]matcher.add('SolarPower', None, pattern1, pattern2, pattern3)" }, { "code": null, "e": 13973, "s": 13924, "text": "The above piece of code contains three patterns." }, { "code": null, "e": 14033, "s": 13973, "text": "pattern_1 denotes any match with the lowercase solarpower ." }, { "code": null, "e": 14102, "s": 14033, "text": "pattern_2 denotes any match with adjacent lowercase solar and power." }, { "code": null, "e": 14207, "s": 14102, "text": "pattern_3 denotes any match with lowercase solar and power along with any punctuation mark between them." }, { "code": null, "e": 14246, "s": 14207, "text": "➤Applying the matcher to a doc object." }, { "code": null, "e": 14439, "s": 14246, "text": "document = nlp(u'The Solar Power industry continues to grow as demand \\for solarpower increases. Solar-power cars are gaining popularity.')found_matches = matcher(document)print(found_matches)" }, { "code": null, "e": 14575, "s": 14439, "text": "matcher returns a list of tuples. Each tuple contains an ID for the match, with start & end tokens that map to the span doc[start:end]." }, { "code": null, "e": 14614, "s": 14575, "text": "➤Finding out the text for the matches." }, { "code": null, "e": 14842, "s": 14614, "text": "for match_id, start, end in found_matches: # get string representation string_id = nlp.vocab.strings[match_id] # get the matched span span = doc[start:end] print(match_id, string_id, start, end, span.text)" }, { "code": null, "e": 14849, "s": 14842, "text": "Output" }, { "code": null, "e": 14991, "s": 14849, "text": "8656102463236116519 SolarPower 1 3 Solar Power8656102463236116519 SolarPower 10 11 solarpower8656102463236116519 SolarPower 13 16 Solar-power" }, { "code": null, "e": 15060, "s": 14991, "text": "The match_id is simply the hash value of the string_ID 'SolarPower'." }, { "code": null, "e": 15076, "s": 15060, "text": "◉Phrase Matcher" }, { "code": null, "e": 15145, "s": 15076, "text": "If you want to learn about PhraseMatcher, please visit the link [8]." }, { "code": null, "e": 15719, "s": 15145, "text": "NLP is one of the amazing techniques in modern computing by which computers can recognize our Natural Languages. There are some techniques by which computer processes the natural language because the human and machine learning process is different. Different libraries like spaCy, NLTK have made the process easy for us. It is impossible to accommodate all necessary techniques in a single article. So, keep your eyes on the upcoming articles for more amazing implementation techniques and projects of NLP. You may also read out the following articles on NLP written by me." }, { "code": null, "e": 15742, "s": 15719, "text": "towardsdatascience.com" }, { "code": null, "e": 15765, "s": 15742, "text": "towardsdatascience.com" }, { "code": null, "e": 15788, "s": 15765, "text": "towardsdatascience.com" }, { "code": null, "e": 15851, "s": 15788, "text": "[1]. https://en.wikipedia.org/wiki/Natural_language_processing" }, { "code": null, "e": 15922, "s": 15851, "text": "[2]. spaCy · Industrial-strength Natural Language Processing in Python" } ]
Express.js | app.set() Function - GeeksforGeeks
10 Jun, 2020 The app.set() function is used to assigns the setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. Syntax: app.set(name, value) Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.set('title', 'GeeksforGeeks'); app.get('/', (req, res) => { res.send(app.get('title'));}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks GeeksforGeeks So this is how you can use the express app.set() function which assigns setting name to value. Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Express.js express.Router() Function Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24439, "s": 24411, "text": "\n10 Jun, 2020" }, { "code": null, "e": 24618, "s": 24439, "text": "The app.set() function is used to assigns the setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server." }, { "code": null, "e": 24626, "s": 24618, "text": "Syntax:" }, { "code": null, "e": 24647, "s": 24626, "text": "app.set(name, value)" }, { "code": null, "e": 24679, "s": 24647, "text": "Installation of express module:" }, { "code": null, "e": 25070, "s": 24679, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 25191, "s": 25070, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 25211, "s": 25191, "text": "npm install express" }, { "code": null, "e": 25335, "s": 25211, "text": "After installing express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 25355, "s": 25335, "text": "npm version express" }, { "code": null, "e": 25503, "s": 25355, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 25517, "s": 25503, "text": "node index.js" }, { "code": null, "e": 25536, "s": 25517, "text": "Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.set('title', 'GeeksforGeeks'); app.get('/', (req, res) => { res.send(app.get('title'));}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);}); ", "e": 25820, "s": 25536, "text": null }, { "code": null, "e": 25846, "s": 25820, "text": "Steps to run the program:" }, { "code": null, "e": 26169, "s": 25846, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks" }, { "code": null, "e": 26212, "s": 26169, "text": "The project structure will look like this:" }, { "code": null, "e": 26304, "s": 26212, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 26324, "s": 26304, "text": "npm install express" }, { "code": null, "e": 26412, "s": 26324, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000" }, { "code": null, "e": 26426, "s": 26412, "text": "node index.js" }, { "code": null, "e": 26434, "s": 26426, "text": "Output:" }, { "code": null, "e": 26464, "s": 26434, "text": "Server listening on PORT 3000" }, { "code": null, "e": 26567, "s": 26464, "text": "Now open the browser and go to http://localhost:3000/, you will get the following output:GeeksforGeeks" }, { "code": null, "e": 26581, "s": 26567, "text": "GeeksforGeeks" }, { "code": null, "e": 26676, "s": 26581, "text": "So this is how you can use the express app.set() function which assigns setting name to value." }, { "code": null, "e": 26687, "s": 26676, "text": "Express.js" }, { "code": null, "e": 26695, "s": 26687, "text": "Node.js" }, { "code": null, "e": 26712, "s": 26695, "text": "Web Technologies" }, { "code": null, "e": 26810, "s": 26712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26819, "s": 26810, "text": "Comments" }, { "code": null, "e": 26832, "s": 26819, "text": "Old Comments" }, { "code": null, "e": 26861, "s": 26832, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 26898, "s": 26861, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26928, "s": 26898, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 26985, "s": 26928, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27039, "s": 26985, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27081, "s": 27039, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27143, "s": 27081, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27186, "s": 27143, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27236, "s": 27186, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CSS | font-size Property - GeeksforGeeks
25 Aug, 2021 The font-size property in CSS is used to set the font size of text in HTML document. Syntax: font-size: medium|xx-small|x-small|small|large|x-large |xx-large|smaller|larger|length|initial|inherit; Default Value: medium Property Values: absolute-size: The absolute-size is used to set the font size absolutely. The default value of absolute-size is medium. The list of absolute-size property are xx-small, x-small, small, medium, large, x-large, xx-large. Syntax: font-size: medium|xx-small|x-small|small|large|x-large|xx-large; Example: html <!DOCTYPE html><html> <head> <title> CSS font-size property </title> <!-- CSS style to set font-size property --> <style> .xxsmall { color:green; font-size:xx-small; } .xsmall { color:green; font-size:x-small; } .small { color:green; font-size:small; } .medium { color:green; font-size:medium; } .large { color:green; font-size:large; } .xlarge { color:green; font-size:x-large; } .xxlarge { color:green; font-size:xx-large; } </style> </head> <body> <h1>font-size property</h1> <div class = "xxsmall">font-size: xx-small;</div> <div class = "xsmall">font-size: x-small;</div> <div class = "small">font-size: small;</div> <div class = "medium">font-size: medium;</div> <div class = "large">font-size: large;</div> <div class = "xlarge">font-size: x-large;</div> <div class = "xxlarge">font-size: xx-large;</div> </body></html> Output: relative-size: It contains two value smaller and larger. The font-size is smaller or larger depends on the parent element. Syntax: font-size: smaller|larger; Example: html <!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .smaller { color:green; font-size:smaller; } .larger { color:green; font-size:larger; } </style> </head> <body> <h1>font-size property</h1> <div class = "smaller">font-size: smaller;</div> <div class = "larger">font-size: larger;</div> </body></html> Output: length: This property is used to set the font-size in length. The length can be in form of px, cm etc. Syntax: font-size: length; Example: html <!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .length { color:green; font-size: 40px; } </style> </head> <body> <h1>font-size property</h1> <div class = "length">font-size: length;</div> </body></html> Output: global: This property contains three types of values such as initial | inherit | unset. Syntax: font-size: initial|inherit|unset; Example: html <!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .length { color:green; font-size: initial; } </style> </head> <body> <h1>font-size property</h1> <div class = "length">font-size: initial;</div> </body></html> Output: Supported Browsers: The browser supported by font-size property are listed below: Google Chrome 1.0 Internet Explorer 5.5 Firefox 1.0 Safari 1.0 Opera 7.0 ManasChhabra2 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 23586, "s": 23558, "text": "\n25 Aug, 2021" }, { "code": null, "e": 23671, "s": 23586, "text": "The font-size property in CSS is used to set the font size of text in HTML document." }, { "code": null, "e": 23681, "s": 23671, "text": "Syntax: " }, { "code": null, "e": 23796, "s": 23681, "text": "font-size: medium|xx-small|x-small|small|large|x-large\n |xx-large|smaller|larger|length|initial|inherit;" }, { "code": null, "e": 23812, "s": 23796, "text": "Default Value: " }, { "code": null, "e": 23819, "s": 23812, "text": "medium" }, { "code": null, "e": 23838, "s": 23819, "text": "Property Values: " }, { "code": null, "e": 24058, "s": 23838, "text": "absolute-size: The absolute-size is used to set the font size absolutely. The default value of absolute-size is medium. The list of absolute-size property are xx-small, x-small, small, medium, large, x-large, xx-large. " }, { "code": null, "e": 24068, "s": 24058, "text": "Syntax: " }, { "code": null, "e": 24133, "s": 24068, "text": "font-size: medium|xx-small|x-small|small|large|x-large|xx-large;" }, { "code": null, "e": 24144, "s": 24133, "text": "Example: " }, { "code": null, "e": 24149, "s": 24144, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS font-size property </title> <!-- CSS style to set font-size property --> <style> .xxsmall { color:green; font-size:xx-small; } .xsmall { color:green; font-size:x-small; } .small { color:green; font-size:small; } .medium { color:green; font-size:medium; } .large { color:green; font-size:large; } .xlarge { color:green; font-size:x-large; } .xxlarge { color:green; font-size:xx-large; } </style> </head> <body> <h1>font-size property</h1> <div class = \"xxsmall\">font-size: xx-small;</div> <div class = \"xsmall\">font-size: x-small;</div> <div class = \"small\">font-size: small;</div> <div class = \"medium\">font-size: medium;</div> <div class = \"large\">font-size: large;</div> <div class = \"xlarge\">font-size: x-large;</div> <div class = \"xxlarge\">font-size: xx-large;</div> </body></html> ", "e": 25496, "s": 24149, "text": null }, { "code": null, "e": 25506, "s": 25496, "text": "Output: " }, { "code": null, "e": 25632, "s": 25508, "text": "relative-size: It contains two value smaller and larger. The font-size is smaller or larger depends on the parent element. " }, { "code": null, "e": 25642, "s": 25632, "text": "Syntax: " }, { "code": null, "e": 25669, "s": 25642, "text": "font-size: smaller|larger;" }, { "code": null, "e": 25680, "s": 25669, "text": "Example: " }, { "code": null, "e": 25685, "s": 25680, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .smaller { color:green; font-size:smaller; } .larger { color:green; font-size:larger; } </style> </head> <body> <h1>font-size property</h1> <div class = \"smaller\">font-size: smaller;</div> <div class = \"larger\">font-size: larger;</div> </body></html> ", "e": 26277, "s": 25685, "text": null }, { "code": null, "e": 26287, "s": 26277, "text": "Output: " }, { "code": null, "e": 26393, "s": 26289, "text": "length: This property is used to set the font-size in length. The length can be in form of px, cm etc. " }, { "code": null, "e": 26403, "s": 26393, "text": "Syntax: " }, { "code": null, "e": 26422, "s": 26403, "text": "font-size: length;" }, { "code": null, "e": 26433, "s": 26422, "text": "Example: " }, { "code": null, "e": 26438, "s": 26433, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .length { color:green; font-size: 40px; } </style> </head> <body> <h1>font-size property</h1> <div class = \"length\">font-size: length;</div> </body></html> ", "e": 26876, "s": 26438, "text": null }, { "code": null, "e": 26886, "s": 26876, "text": "Output: " }, { "code": null, "e": 26977, "s": 26888, "text": "global: This property contains three types of values such as initial | inherit | unset. " }, { "code": null, "e": 26987, "s": 26977, "text": "Syntax: " }, { "code": null, "e": 27021, "s": 26987, "text": "font-size: initial|inherit|unset;" }, { "code": null, "e": 27032, "s": 27021, "text": "Example: " }, { "code": null, "e": 27037, "s": 27032, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS font-size Property </title> <!-- CSS property to set font-size --> <style> .length { color:green; font-size: initial; } </style> </head> <body> <h1>font-size property</h1> <div class = \"length\">font-size: initial;</div> </body></html> ", "e": 27479, "s": 27037, "text": null }, { "code": null, "e": 27489, "s": 27479, "text": "Output: " }, { "code": null, "e": 27575, "s": 27491, "text": "Supported Browsers: The browser supported by font-size property are listed below: " }, { "code": null, "e": 27593, "s": 27575, "text": "Google Chrome 1.0" }, { "code": null, "e": 27615, "s": 27593, "text": "Internet Explorer 5.5" }, { "code": null, "e": 27627, "s": 27615, "text": "Firefox 1.0" }, { "code": null, "e": 27638, "s": 27627, "text": "Safari 1.0" }, { "code": null, "e": 27648, "s": 27638, "text": "Opera 7.0" }, { "code": null, "e": 27664, "s": 27650, "text": "ManasChhabra2" }, { "code": null, "e": 27679, "s": 27664, "text": "CSS-Properties" }, { "code": null, "e": 27686, "s": 27679, "text": "Picked" }, { "code": null, "e": 27690, "s": 27686, "text": "CSS" }, { "code": null, "e": 27707, "s": 27690, "text": "Web Technologies" }, { "code": null, "e": 27805, "s": 27707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27814, "s": 27805, "text": "Comments" }, { "code": null, "e": 27827, "s": 27814, "text": "Old Comments" }, { "code": null, "e": 27889, "s": 27827, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27939, "s": 27889, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27997, "s": 27939, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28045, "s": 27997, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28082, "s": 28045, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28124, "s": 28082, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28157, "s": 28124, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28219, "s": 28157, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28269, "s": 28219, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How does 'void*' differ in C and C++? - GeeksforGeeks
28 Nov, 2021 C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++ For example, the following is valid in C but not C++: void* ptr; int *i = ptr; // Implicit conversion from void* to int* Similarly, int *j = malloc(sizeof(int) * 5); // Implicit conversion from void* to int* In order to make the above code compile in C++ as well, we have to use explicit casting, as shown below, void* ptr; int *i = (int *) ptr; int *j = (int *) malloc(sizeof(int) * 5); Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C rand() and srand() in C/C++ Substring in C++ Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25769, "s": 25741, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25930, "s": 25769, "text": "C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++" }, { "code": null, "e": 25985, "s": 25930, "text": "For example, the following is valid in C but not C++: " }, { "code": null, "e": 26052, "s": 25985, "text": "void* ptr;\nint *i = ptr; // Implicit conversion from void* to int*" }, { "code": null, "e": 26063, "s": 26052, "text": "Similarly," }, { "code": null, "e": 26141, "s": 26063, "text": "int *j = malloc(sizeof(int) * 5); // Implicit conversion from void* to int* " }, { "code": null, "e": 26246, "s": 26141, "text": "In order to make the above code compile in C++ as well, we have to use explicit casting, as shown below," }, { "code": null, "e": 26321, "s": 26246, "text": "void* ptr;\nint *i = (int *) ptr;\nint *j = (int *) malloc(sizeof(int) * 5);" }, { "code": null, "e": 26446, "s": 26321, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26460, "s": 26446, "text": "anshikajain26" }, { "code": null, "e": 26471, "s": 26460, "text": "C Language" }, { "code": null, "e": 26475, "s": 26471, "text": "C++" }, { "code": null, "e": 26479, "s": 26475, "text": "CPP" }, { "code": null, "e": 26577, "s": 26479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26612, "s": 26577, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26658, "s": 26612, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26680, "s": 26658, "text": "Function Pointer in C" }, { "code": null, "e": 26708, "s": 26680, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26725, "s": 26708, "text": "Substring in C++" }, { "code": null, "e": 26743, "s": 26725, "text": "Vector in C++ STL" }, { "code": null, "e": 26762, "s": 26743, "text": "Inheritance in C++" }, { "code": null, "e": 26808, "s": 26762, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 26851, "s": 26808, "text": "Map in C++ Standard Template Library (STL)" } ]
C++ Program for How to check if a given number is Fibonacci number? - GeeksforGeeks
14 Jan, 2022 Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). CPP // C++ program to check if x is a perfect square#include <iostream>#include <math.h>using namespace std; // A utility function that returns true if x is perfect squarebool isPerfectSquare(int x){ int s = sqrt(x); return (s * s == x);} // Returns true if n is a Fibonacci Number, else falsebool isFibonacci(int n){ // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both // is a perfect square return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);} // A utility function to test above functionsint main(){ for (int i = 1; i <= 10; i++) isFibonacci(i) ? cout << i << " is a Fibonacci Number \n" : cout << i << " is a not Fibonacci Number \n"; return 0;} 1 is a Fibonacci Number 2 is a Fibonacci Number 3 is a Fibonacci Number 4 is a not Fibonacci Number 5 is a Fibonacci Number 6 is a not Fibonacci Number 7 is a not Fibonacci Number 8 is a Fibonacci Number 9 is a not Fibonacci Number 10 is a not Fibonacci Number Please refer complete article on How to check if a given number is Fibonacci number? for more details! varshagumber28 simranarora5sos C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Handling the Divide by Zero Exception in C++ Hamming code Implementation in C/C++ Different ways to print elements of vector Dynamic _Cast in C++ isdigit() function in C/C++ with Examples Student record management system using linked list
[ { "code": null, "e": 24553, "s": 24525, "text": "\n14 Jan, 2022" }, { "code": null, "e": 24707, "s": 24553, "text": "Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : " }, { "code": null, "e": 24779, "s": 24707, "text": "Input : 8\nOutput : Yes\n\nInput : 34\nOutput : Yes\n\nInput : 41\nOutput : No" }, { "code": null, "e": 25024, "s": 24779, "text": "Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). " }, { "code": null, "e": 25028, "s": 25024, "text": "CPP" }, { "code": "// C++ program to check if x is a perfect square#include <iostream>#include <math.h>using namespace std; // A utility function that returns true if x is perfect squarebool isPerfectSquare(int x){ int s = sqrt(x); return (s * s == x);} // Returns true if n is a Fibonacci Number, else falsebool isFibonacci(int n){ // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both // is a perfect square return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);} // A utility function to test above functionsint main(){ for (int i = 1; i <= 10; i++) isFibonacci(i) ? cout << i << \" is a Fibonacci Number \\n\" : cout << i << \" is a not Fibonacci Number \\n\"; return 0;}", "e": 25752, "s": 25028, "text": null }, { "code": null, "e": 26022, "s": 25752, "text": "1 is a Fibonacci Number \n2 is a Fibonacci Number \n3 is a Fibonacci Number \n4 is a not Fibonacci Number \n5 is a Fibonacci Number \n6 is a not Fibonacci Number \n7 is a not Fibonacci Number \n8 is a Fibonacci Number \n9 is a not Fibonacci Number \n10 is a not Fibonacci Number" }, { "code": null, "e": 26127, "s": 26024, "text": "Please refer complete article on How to check if a given number is Fibonacci number? for more details!" }, { "code": null, "e": 26142, "s": 26127, "text": "varshagumber28" }, { "code": null, "e": 26158, "s": 26142, "text": "simranarora5sos" }, { "code": null, "e": 26171, "s": 26158, "text": "C++ Programs" }, { "code": null, "e": 26269, "s": 26171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26278, "s": 26269, "text": "Comments" }, { "code": null, "e": 26291, "s": 26278, "text": "Old Comments" }, { "code": null, "e": 26332, "s": 26291, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 26391, "s": 26332, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 26412, "s": 26391, "text": "Const keyword in C++" }, { "code": null, "e": 26424, "s": 26412, "text": "cout in C++" }, { "code": null, "e": 26469, "s": 26424, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 26506, "s": 26469, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 26549, "s": 26506, "text": "Different ways to print elements of vector" }, { "code": null, "e": 26570, "s": 26549, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 26612, "s": 26570, "text": "isdigit() function in C/C++ with Examples" } ]
Literals in C#
The fixed values are called literals. The constants refer to fixed values that the program may not alter during its execution. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. Let us learn about integer, float, and string literals in C# − An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. Here are some example of Integer Literals − 20 // int 30u // unsigned int 30l // long A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Here are some examples of Float Literals − 2.64734 314159E-5F String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. Here are some examples of String Literals − Hello, World" "Welcome, \
[ { "code": null, "e": 1189, "s": 1062, "text": "The fixed values are called literals. The constants refer to fixed values that the program may not alter during its execution." }, { "code": null, "e": 1373, "s": 1189, "text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well." }, { "code": null, "e": 1436, "s": 1373, "text": "Let us learn about integer, float, and string literals in C# −" }, { "code": null, "e": 1601, "s": 1436, "text": "An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal." }, { "code": null, "e": 1645, "s": 1601, "text": "Here are some example of Integer Literals −" }, { "code": null, "e": 1687, "s": 1645, "text": "20 // int\n30u // unsigned int\n30l // long" }, { "code": null, "e": 1877, "s": 1687, "text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form." }, { "code": null, "e": 1920, "s": 1877, "text": "Here are some examples of Float Literals −" }, { "code": null, "e": 1939, "s": 1920, "text": "2.64734\n314159E-5F" }, { "code": null, "e": 2145, "s": 1939, "text": "String literals or constants are enclosed in double quotes \"\" or with @\"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters." }, { "code": null, "e": 2189, "s": 2145, "text": "Here are some examples of String Literals −" }, { "code": null, "e": 2215, "s": 2189, "text": "Hello, World\"\n\"Welcome, \\" } ]
LocalTime plusMinutes() method in Java with Examples - GeeksforGeeks
04 Dec, 2018 The plusMinutes() method of LocalTime class is used to add specified number of Minutes value to this LocalTime and return the result as a LocalTime object. This instant is immutable. The calculation wraps around midnight. Syntax: public LocalTime plusMinutes(long MinutesToAdd) Parameters: This method accepts a single parameter MinutesToAdd which is the value of Minutes to be added, it can be a negative value. Return value: This method returns a LocalTime based on this time with the Minutes added. Below programs illustrate the plusMinutes() method: Program 1: // Java program to demonstrate// LocalTime.plusMinutes() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse("19:34:50.63"); // print LocalTime System.out.println("LocalTime before addition: " + time); // add 55 Minutes using plusMinutes() LocalTime value = time.plusMinutes(55); // print result System.out.println("LocalTime after addition: " + value); }} LocalTime before addition: 19:34:50.630 LocalTime after addition: 20:29:50.630 Program 2: // Java program to demonstrate// LocalTime.plusMinutes() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse("01:00:01"); // print LocalTime System.out.println("LocalTime before addition: " + time); // add -600 Minutes using plusMinutes() LocalTime value = time.plusMinutes(-600); // print result System.out.println("LocalTime after addition: " + value); }} LocalTime before addition: 01:00:01 LocalTime after addition: 15:00:01 References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#plusMinutes(long) Java-Functions Java-LocalTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 23945, "s": 23917, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24167, "s": 23945, "text": "The plusMinutes() method of LocalTime class is used to add specified number of Minutes value to this LocalTime and return the result as a LocalTime object. This instant is immutable. The calculation wraps around midnight." }, { "code": null, "e": 24175, "s": 24167, "text": "Syntax:" }, { "code": null, "e": 24224, "s": 24175, "text": "public LocalTime plusMinutes(long MinutesToAdd)\n" }, { "code": null, "e": 24359, "s": 24224, "text": "Parameters: This method accepts a single parameter MinutesToAdd which is the value of Minutes to be added, it can be a negative value." }, { "code": null, "e": 24448, "s": 24359, "text": "Return value: This method returns a LocalTime based on this time with the Minutes added." }, { "code": null, "e": 24500, "s": 24448, "text": "Below programs illustrate the plusMinutes() method:" }, { "code": null, "e": 24511, "s": 24500, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalTime.plusMinutes() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse(\"19:34:50.63\"); // print LocalTime System.out.println(\"LocalTime before addition: \" + time); // add 55 Minutes using plusMinutes() LocalTime value = time.plusMinutes(55); // print result System.out.println(\"LocalTime after addition: \" + value); }}", "e": 25103, "s": 24511, "text": null }, { "code": null, "e": 25183, "s": 25103, "text": "LocalTime before addition: 19:34:50.630\nLocalTime after addition: 20:29:50.630\n" }, { "code": null, "e": 25194, "s": 25183, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalTime.plusMinutes() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time = LocalTime.parse(\"01:00:01\"); // print LocalTime System.out.println(\"LocalTime before addition: \" + time); // add -600 Minutes using plusMinutes() LocalTime value = time.plusMinutes(-600); // print result System.out.println(\"LocalTime after addition: \" + value); }}", "e": 25787, "s": 25194, "text": null }, { "code": null, "e": 25859, "s": 25787, "text": "LocalTime before addition: 01:00:01\nLocalTime after addition: 15:00:01\n" }, { "code": null, "e": 25957, "s": 25859, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#plusMinutes(long)" }, { "code": null, "e": 25972, "s": 25957, "text": "Java-Functions" }, { "code": null, "e": 25987, "s": 25972, "text": "Java-LocalTime" }, { "code": null, "e": 26005, "s": 25987, "text": "Java-time package" }, { "code": null, "e": 26010, "s": 26005, "text": "Java" }, { "code": null, "e": 26015, "s": 26010, "text": "Java" }, { "code": null, "e": 26113, "s": 26015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26122, "s": 26113, "text": "Comments" }, { "code": null, "e": 26135, "s": 26122, "text": "Old Comments" }, { "code": null, "e": 26186, "s": 26135, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26216, "s": 26186, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26247, "s": 26216, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26266, "s": 26247, "text": "Interfaces in Java" }, { "code": null, "e": 26298, "s": 26266, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26316, "s": 26298, "text": "ArrayList in Java" }, { "code": null, "e": 26336, "s": 26316, "text": "Stack Class in Java" }, { "code": null, "e": 26368, "s": 26336, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26392, "s": 26368, "text": "Singleton Class in Java" } ]
Feature selection techniques for classification and Python tips for their application | by Gabriel Azevedo | Towards Data Science
Selecting which features to use is a crucial step in any machine learning project and a recurrent task in the day-to-day of a Data Scientist. In this article, I review the most common types of feature selection techniques used in practice for classification problems, dividing them into 6 major categories. I provide tips on how to use them in a machine learning project and give examples in Python code whenever possible. Are you ready? The main methods are summarised in the table below and discussed in the following sections. Two of the biggest problems in Machine Learning are overfitting (fitting aspects of data that are not generalizable outside the dataset) and the curse of dimensionality (the unintuitive and sparse properties of data in high dimensions). Feature selection helps to avoid both of these problems by reducing the number of features in the model, trying to optimize the model performance. In doing so, feature selection also provides an extra benefit: Model interpretation. With fewer features, the output model becomes simpler and easier to interpret, and it becomes more likely for a human to trust future predictions made by the model. One simple method to reduce the number of features consists of applying a Dimensionality Reduction technique to the data. This is often done in an unsupervised way, i.e., without using the labels themselves. Dimensionality reduction does not actually select a subset of features but instead produces a new set of features in a lower dimension space. This new set can be used in the classification process itself. The example below uses the features on reduced dimensions to do classification. More precisely, it uses the first 2 components of Principal Component Analysis (PCA) as the new set of features. from sklearn.datasets import load_irisfrom sklearn.decomposition import PCAfrom sklearn.svm import SVCimport matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapimport numpy as nph = .01x_min, x_max = -4,4y_min, y_max = -1.5,1.5# loading datasetdata = load_iris()X, y = data.data, data.target# selecting first 2 components of PCAX_pca = PCA().fit_transform(X)X_selected = X_pca[:,:2]# training classifier and evaluating on the whole planeclf = SVC(kernel='linear')clf.fit(X_selected,y)xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)# Plottingcmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])plt.figure(figsize=(10,5))plt.pcolormesh(xx, yy, Z, alpha=.6,cmap=cmap_light)plt.title('PCA - Iris dataset')plt.xlabel('Dimension 1')plt.ylabel('Dimension 2')plt.scatter(X_pca[:,0],X_pca[:,1],c=data.target,cmap=cmap_bold)plt.show() Another use of dimensionality reduction in the context of evaluating features is for visualization: in a lower-dimensional space, it is easier to visually verify if the data is potentially separable, which helps to set expectations on the classification accuracy. In practice, we perform dimensionality reduction (e.g. PCA) over a subset of features and check how the labels are distributed in the reduced space. If they appear to be separate, this is a clear sign that high classification performance is expected when using this set of features. In the example below, in a reduced space with 2 dimensions, the different labels are shown to be fairly separable. This signs to the fact that one could expect high performance when training and testing a classifier. from sklearn.datasets import load_irisfrom sklearn.decomposition import PCAimport matplotlib.pyplot as pltfrom mlxtend.plotting import plot_pca_correlation_graphdata = load_iris()X, y = data.data, data.targetplt.figure(figsize=(10,5))X_pca = PCA().fit_transform(X)plt.title('PCA - Iris dataset')plt.xlabel('Dimension 1')plt.ylabel('Dimension 2')plt.scatter(X_pca[:,0],X_pca[:,1],c=data.target)_ = plot_pca_correlation_graph(X,data.feature_names) In addition to that, I also plot the correlation circle, which tells the correlations between each of the original dimension and the new PCA dimensions. Intuitively, this graph tells about how much each original feature contributes to the newly created PCA components. In the example above, petal length and width show high correlation with the first PCA dimension and sepal width highly contributes to the second dimension. Filter methods aim at ranking the importance of the features without making use of any type of classification algorithm. Univariate filter methods evaluate each feature individually and do not consider feature interactions. These methods consist of providing a score to each feature, often based on statistical tests. The scores usually either measure the dependency between the dependent variable and the features (e.g. Chi2 and, for regression, Pearls correlation coefficient), or the difference between the distributions of the features given the class label (F-test and T-test). The scores often make assumptions about the statistical properties of the underlying data. Understanding these assumptions is important to decide which test to use, even though some of them are robust to violations of the assumptions. Scores based on statistical tests provide a p-value, that may be used to rule out some features. This is done if the p-value is above a certain threshold (typically 0.01 or 0.05). Common tests include: The package sklearn implements some filter methods. However, as most of them are based on statistical tests, statistics packages (such asstatsmodels) could also be used. One example is shown below: from sklearn.feature_selection import f_classif, chi2, mutual_info_classiffrom statsmodels.stats.multicomp import pairwise_tukeyhsdfrom sklearn.datasets import load_irisdata = load_iris()X,y = data.data, data.targetchi2_score, chi_2_p_value = chi2(X,y)f_score, f_p_value = f_classif(X,y)mut_info_score = mutual_info_classif(X,y)pairwise_tukeyhsd = [list(pairwise_tukeyhsd(X[:,i],y).reject) for i in range(4)]print('chi2 score ', chi2_score)print('chi2 p-value ', chi_2_p_value)print('F - score score ', f_score)print('F - score p-value ', f_p_value)print('mutual info ', mut_info_score)print('pairwise_tukeyhsd',pairwise_tukeyhsd)Out:chi2 score [ 10.82 3.71 116.31 67.05]chi2 p-value [0. 0.16 0. 0. ]F - score score [ 119.26 49.16 1180.16 960.01]F - score p-value [0. 0. 0. 0.]mutual info [0.51 0.27 0.98 0.98]pairwise_tukeyhsd [[True, True, True], [True, True, True], [True, True, True], [True, True, True]] Boxplots / Violin plots may help to visualize the distribution of the feature given the class. For the Iris dataset, an example is shown below. This is useful in that statistical tests often only evaluate the difference between the mean of such distributions. These plots, therefore, provide more information about the quality of the features import pandas as pdimport seaborn as snssns.set()df = pd.DataFrame(data.data,columns=data.feature_names)df['target'] = data.targetdf_temp = pd.melt(df,id_vars='target',value_vars=list(df.columns)[:-1], var_name="Feature", value_name="Value")g = sns.FacetGrid(data = df_temp, col="Feature", col_wrap=4, size=4.5,sharey = False)g.map(sns.boxplot,"target", "Value");g = sns.FacetGrid(data = df_temp, col="Feature", col_wrap=4, size=4.5,sharey = False)g.map(sns.violinplot,"target", "Value"); The ROC curve may be used to rank features in importance order, which gives a visual way to rank features performances. This technique is most suitable for binary classification tasks. To apply in problems with multiple classes this, one could use micro or macro averages or multiple comparison based criteria (similarly to the pairwise Tukey’s range test). The example below plots the ROC curve of various features. from sklearn.datasets import load_irisimport matplotlib.pyplot as pltfrom sklearn.metrics import aucimport numpy as np# loading datasetdata = load_iris()X, y = data.data, data.targety_ = y == 2plt.figure(figsize=(13,7))for col in range(X.shape[1]): tpr,fpr = [],[] for threshold in np.linspace(min(X[:,col]),max(X[:,col]),100): detP = X[:,col] < threshold tpr.append(sum(detP & y_)/sum(y_))# TP/P, aka recall fpr.append(sum(detP & (~y_))/sum((~y_)))# FP/N if auc(fpr,tpr) < .5: aux = tpr tpr = fpr fpr = aux plt.plot(fpr,tpr,label=data.feature_names[col] + ', auc = '\ + str(np.round(auc(fpr,tpr),decimals=3)))plt.title('ROC curve - Iris features')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.legend()plt.show() These methods take into account the correlations between variables and do so without considering any type of classification algorithm. mRMR (minimum Redundancy Maximum Relevance) is a heuristic algorithm to find a close to optimal subset of features by considering both the features importances and the correlations between them. The idea is that, even if two features are highly relevant, it may not be a good idea to add both of them to the feature set if they are highly correlated. In that case, adding both features would increase the model complexity (increasing the possibility of overfitting) but would not add significant information, due to the correlation between the features. In a set S of N features, the relevance of the features (D) is computed as follows: where I is the mutual information operator. The redundancy of the features is denoted as follows: The mRMR score for the set S is defined as (D - R). The goal is to find the subset of features with a maximum value of (D-R). In practice, however, we perform an incremental search (aka forward selection) in which, at each step, we add the feature that yields the greatest mRMR. The algorithm is implemented in C by the authors of the algorithm themselves. You can find the source code of the package, as well as the original paper here. A (not maintained) python wrapper was created on the name pymrmr. In case of issues with pymrmr, I advise calling the C — level function directly. The code below exemplifies the use of pymrmr . Note that the columns of the pandas data-frame should be formatted as described in the C level package (here). import pandas as pdimport pymrmrdf = pd.read_csv('some_df.csv')# Pass a dataframe with a predetermined configuration. # Check http://home.penglab.com/proj/mRMR/ for the dataset requirementspymrmr.mRMR(df, 'MIQ', 10) Output: *** This program and the respective minimum Redundancy Maximum Relevance (mRMR) algorithm were developed by Hanchuan Peng <hanchuan.peng@gmail.com>for the paper "Feature selection based on mutual information: criteria of max-dependency, max-relevance, and min-redundancy," Hanchuan Peng, Fuhui Long, and Chris Ding, IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. 27, No. 8, pp.1226-1238, 2005.*** MaxRel features *** Order Fea Name Score 1 765 v765 0.375 2 1423 v1423 0.337 3 513 v513 0.321 4 249 v249 0.309 5 267 v267 0.304 6 245 v245 0.304 7 1582 v1582 0.280 8 897 v897 0.269 9 1771 v1771 0.269 10 1772 v1772 0.269*** mRMR features *** Order Fea Name Score 1 765 v765 0.375 2 1123 v1123 24.913 3 1772 v1772 3.984 4 286 v286 2.280 5 467 v467 1.979 6 377 v377 1.768 7 513 v513 1.803 8 1325 v1325 1.634 9 1972 v1972 1.741 10 1412 v1412 1.689Out[1]: ['v765', 'v1123', 'v1772', 'v286', 'v467', 'v377', 'v513', 'v1325', 'v1972', 'v1412'] The main idea behind a wrapper method is to search which set of features works best for a specific classifier. The methods can be summarised as follows, and differ in regards to the search algorithm used. Choose a performance metric (Likelihood, AIC, BIC, F1-score, accuracy, MSE, MAE...), noted as M.Choose a classifier / regressor / ... , noted as C in here.Search different features subsets with a given search method. For each subset S, do the following: Choose a performance metric (Likelihood, AIC, BIC, F1-score, accuracy, MSE, MAE...), noted as M. Choose a classifier / regressor / ... , noted as C in here. Search different features subsets with a given search method. For each subset S, do the following: Train and test C in a cross-validation pattern, using S as the classifier’s features; Obtain the average score from the cross-validation procedure (for the metric M) and assign this score to the subset S; Choose a new subset and redo step a. Step three leaves unspecified the type which search method will be used. Testing all possible subsets of features is prohibitive (Brute Force selection) in virtually any situation since it would require performing step 3 an exponential number of times (2 to the power of the number of features). Besides the time complexity, with such a large number of possibilities, it would be likely that a certain combination of features performs best simply by random chance, which makes the brute force solution more prone to overfitting. Search algorithms tend to work well in practice to solve this issue. They tend to achieve a performance close to the brute force solution, with much less time complexity and less chance of overfitting. Forward selection and Backward selection (aka pruning) are much used in practice, as well as some small variations of their search process. Backward selection consists of starting with a model with the full number of features and, at each step, removing the feature without which the model has the highest score. Forward selection goes on the opposite way: it starts with an empty set of features and adds the feature that best improves the current score. Forward/Backward selection are still prone to overfitting, as, usually, scores tend to improve by adding more features. One way to avoid such situation is to use scores that penalize the complexity of the model, such as AIC or BIC. An illustration of a wrapper method structure is shown below. It is important to note that the feature set is (1) found through a search method and (2) cross-validated on the same classifier it is intended to be used for. Step three also leaves open the cross-validation parameters. Usually, a k-fold procedure is used. Using a large k, however, introduces extra complexity to the overall wrapper method. mlxtend (http://rasbt.github.io/mlxtend/) is a useful package for diverse data science-related tasks. The wrapper methods on this package can be found on SequentialFeatureSelector. It provides Forward and Backward feature selection with some variations. The package also provides a way to visualize the score as a function of the number of features through the function plot_sequential_feature_selection. The example below was extracted from the package’s main page. from mlxtend.feature_selection import SequentialFeatureSelector as SFSfrom mlxtend.plotting import plot_sequential_feature_selection as plot_sfsfrom sklearn.linear_model import LinearRegressionfrom sklearn.datasets import load_bostonboston = load_boston()X, y = boston.data, boston.targetlr = LinearRegression()sfs = SFS(lr, k_features=13, forward=True, floating=False, scoring='neg_mean_squared_error', cv=10)sfs = sfs.fit(X, y)fig = plot_sfs(sfs.get_metric_dict(), kind='std_err')plt.title('Sequential Forward Selection (w. StdErr)')plt.grid()plt.show() Training a classifier boils down to an optimization problem, where we try to minimize a function of its parameters (noted here as θ). This function is known loss function (noted as L(θ)). In a more general framework, we usually want to minimize an objective function that takes into account both the loss function and a penalty (or regularisation)(Ω(θ)) to the complexity of the model: obj(θ)=L(θ)+Ω(θ) For linear classifiers (e.g. Linear SVM, Logistic Regression), the loss function is noted as : Where each xj corresponds to one data sample and WTxj denotes the inner product of the coefficient vector (w1,w2,...w_n) with the features in each sample. For Linear SVM and Logistic Regression the hinge and logistic losses are, respectively: The two most common penalties for linear classifiers are the L-1 and L-2 penalties: The higher the value of λ, the stronger the penalty and the optimal objective function will tend to end up in shrinking more and more the coefficients w_i. The “L1” penalty is known to create sparse models, which simply means that, it tends to select some features out of the model by making some of the coefficients equal zero during the optimization process. Another common penalty is L-2. While L-2 shrinks the coefficients and therefore helps avoid overfitting, it does not create sparse models, so it is not suitable as a feature selection technique. For some linear classifiers (Linear SVM, Logistic Regression), the L-1 penalty can be efficiently used, meaning that there are efficient numerical methods to optimize the resulting objective function. The same is not true for several other classifiers (various Kernel SVM methods, Decision Trees,...). Therefore, different regularisation methods should be used for different classifiers. An example of Logistic regression with regularisation is shown below, and we can see that the algorithms rule out some of the features as C decreases (think if C as 1/λ). import numpy as npimport matplotlib.pyplot as pltfrom sklearn.svm import LinearSVCfrom sklearn.model_selection import ShuffleSplitfrom sklearn.model_selection import GridSearchCVfrom sklearn.utils import check_random_statefrom sklearn import datasetsfrom sklearn.linear_model import LogisticRegressionrnd = check_random_state(1)# set up datasetn_samples = 3000n_features = 15# l1 data (only 5 informative features)X, y = datasets.make_classification(n_samples=n_samples, n_features=n_features, n_informative=5, random_state=1)cs = np.logspace(-2.3, 0, 50)coefs = []for c in cs: clf = LogisticRegression(solver='liblinear',C=c,penalty='l1') # clf = LinearSVC(C=c,penalty='l1', loss='squared_hinge', dual=False, tol=1e-3) clf.fit(X,y) coefs.append(list(clf.coef_[0])) coefs = np.array(coefs)plt.figure(figsize=(10,5))for i,col in enumerate(range(n_features)): plt.plot(cs,coefs[:,col])plt.xscale('log')plt.title('L1 penalty - Logistic regression')plt.xlabel('C')plt.ylabel('Coefficient value')plt.show() Another common feature selection technique consists in extracting a feature importance rank from tree base models. The feature importances are essentially the mean of the individual trees’ improvement in the splitting criterion produced by each variable. In other words, it is how much the score (so-called “impurity” on the decision tree notation) was improved when splitting the tree using that specific variable. They can be used to rank features and then select a subset of them. However, the feature importances should be used with care, as they suffer from biases and, and presents an unexpected behavior regarding highly correlated features regardless of how strong they are. As shown in this paper, random forest feature importances are biased towards features with more categories. Besides, if two features are highly correlated, both of their scores largely decrease, regardless of the quality of the features. Below is an example of how to extract the feature importances from a random forest. Although a regressor, the process would be the same for a classifier. from sklearn.datasets import load_bostonfrom sklearn.ensemble import RandomForestRegressorimport numpy as npboston = load_boston()X = boston.dataY = boston.targetfeat_names = boston.feature_names rf = RandomForestRegressor()rf.fit(X, Y)print("Features sorted by their score:")print(sorted(zip(map(lambda x: round(x, 4), rf.feature_importances_), feat_names), reverse=True))Out:Features sorted by their score:[(0.4334, 'LSTAT'), (0.3709, 'RM'), (0.0805, 'DIS'), (0.0314, 'CRIM'), (0.0225, 'NOX'), (0.0154, 'TAX'), (0.0133, 'PTRATIO'), (0.0115, 'AGE'), (0.011, 'B'), (0.0043, 'INDUS'), (0.0032, 'RAD'), (0.0016, 'CHAS'), (0.0009, 'ZN')] As explained above, the “impurity” is a score used by the decision tree algorithm when deciding to split a node. There are many decision tree algorithms (IDR3, C4.5, CART,...), but the general rule is that the variable with which we split a node in the tree is the one that generates the highest improvement on the impurity. The most common impurities are the Gini Impurity and Entropy. An improvement on the Gini impurity is known as “Gini importance” while An improvement on the Entropy is the Information Gain. (Thanks to Henrique Gasparini Fiuza do Nascimento for the suggestion!) SHAP is actually much more than just that. It is an algorithm to provide model explanation out of any predictive model. For tree based models, however, it is specially useful: the authors developed a high speed and exact (not only local) explanation for such models, compatible with XGBoost, LightGBM, CatBoost, and scikit-learn tree models. I encourage checking out the explanation capabilities provided by SHAP (such as Feature dependance, interaction effects, model monitoring...). Below, I plot (only) the feature importances output by SHAP, which are more reliable than those output by the original tree model when ranking them for feature selection. This example was extracted from their github page. import xgboostimport shap# load JS visualization code to notebookshap.initjs()# train XGBoost modelX,y = shap.datasets.boston()model = xgboost.train({"learning_rate": 0.01}, xgboost.DMatrix(X, label=y), 100)# explain the model's predictions using SHAP values# (same syntax works for LightGBM, CatBoost, and scikit-learn models)explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X)shap.summary_plot(shap_values, X, plot_type="bar") Embedded methods are usually very efficient to avoid overfitting and select useful variables. They are also time efficient as they are embedded on the objective function. Their main downside is that they may not be available to the desired classifier. Wrapper methods tend to work very well in practice. However, they are computationally expensive, specially when dealing hundreds of features. But if you have the computational resources, they are an excellent way to go. If the feature set is very large (on the order of hundreds or thousands), because filter methods are fast, they can work well as a first stage of selection, to rule out some variables. Subsequently another method can be applied to the already reduced feature set. This is particular useful if you want to create combinations of features, multiplying or dividing them, for example. An Introduction to Variable and Feature Selection Bias in random forest variable importance measures: Illustrations, sources and a solution Feature Selection for Classification: A Review
[ { "code": null, "e": 609, "s": 171, "text": "Selecting which features to use is a crucial step in any machine learning project and a recurrent task in the day-to-day of a Data Scientist. In this article, I review the most common types of feature selection techniques used in practice for classification problems, dividing them into 6 major categories. I provide tips on how to use them in a machine learning project and give examples in Python code whenever possible. Are you ready?" }, { "code": null, "e": 701, "s": 609, "text": "The main methods are summarised in the table below and discussed in the following sections." }, { "code": null, "e": 938, "s": 701, "text": "Two of the biggest problems in Machine Learning are overfitting (fitting aspects of data that are not generalizable outside the dataset) and the curse of dimensionality (the unintuitive and sparse properties of data in high dimensions)." }, { "code": null, "e": 1335, "s": 938, "text": "Feature selection helps to avoid both of these problems by reducing the number of features in the model, trying to optimize the model performance. In doing so, feature selection also provides an extra benefit: Model interpretation. With fewer features, the output model becomes simpler and easier to interpret, and it becomes more likely for a human to trust future predictions made by the model." }, { "code": null, "e": 1543, "s": 1335, "text": "One simple method to reduce the number of features consists of applying a Dimensionality Reduction technique to the data. This is often done in an unsupervised way, i.e., without using the labels themselves." }, { "code": null, "e": 1748, "s": 1543, "text": "Dimensionality reduction does not actually select a subset of features but instead produces a new set of features in a lower dimension space. This new set can be used in the classification process itself." }, { "code": null, "e": 1941, "s": 1748, "text": "The example below uses the features on reduced dimensions to do classification. More precisely, it uses the first 2 components of Principal Component Analysis (PCA) as the new set of features." }, { "code": null, "e": 2972, "s": 1941, "text": "from sklearn.datasets import load_irisfrom sklearn.decomposition import PCAfrom sklearn.svm import SVCimport matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapimport numpy as nph = .01x_min, x_max = -4,4y_min, y_max = -1.5,1.5# loading datasetdata = load_iris()X, y = data.data, data.target# selecting first 2 components of PCAX_pca = PCA().fit_transform(X)X_selected = X_pca[:,:2]# training classifier and evaluating on the whole planeclf = SVC(kernel='linear')clf.fit(X_selected,y)xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)# Plottingcmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])plt.figure(figsize=(10,5))plt.pcolormesh(xx, yy, Z, alpha=.6,cmap=cmap_light)plt.title('PCA - Iris dataset')plt.xlabel('Dimension 1')plt.ylabel('Dimension 2')plt.scatter(X_pca[:,0],X_pca[:,1],c=data.target,cmap=cmap_bold)plt.show()" }, { "code": null, "e": 3519, "s": 2972, "text": "Another use of dimensionality reduction in the context of evaluating features is for visualization: in a lower-dimensional space, it is easier to visually verify if the data is potentially separable, which helps to set expectations on the classification accuracy. In practice, we perform dimensionality reduction (e.g. PCA) over a subset of features and check how the labels are distributed in the reduced space. If they appear to be separate, this is a clear sign that high classification performance is expected when using this set of features." }, { "code": null, "e": 3736, "s": 3519, "text": "In the example below, in a reduced space with 2 dimensions, the different labels are shown to be fairly separable. This signs to the fact that one could expect high performance when training and testing a classifier." }, { "code": null, "e": 4182, "s": 3736, "text": "from sklearn.datasets import load_irisfrom sklearn.decomposition import PCAimport matplotlib.pyplot as pltfrom mlxtend.plotting import plot_pca_correlation_graphdata = load_iris()X, y = data.data, data.targetplt.figure(figsize=(10,5))X_pca = PCA().fit_transform(X)plt.title('PCA - Iris dataset')plt.xlabel('Dimension 1')plt.ylabel('Dimension 2')plt.scatter(X_pca[:,0],X_pca[:,1],c=data.target)_ = plot_pca_correlation_graph(X,data.feature_names)" }, { "code": null, "e": 4607, "s": 4182, "text": "In addition to that, I also plot the correlation circle, which tells the correlations between each of the original dimension and the new PCA dimensions. Intuitively, this graph tells about how much each original feature contributes to the newly created PCA components. In the example above, petal length and width show high correlation with the first PCA dimension and sepal width highly contributes to the second dimension." }, { "code": null, "e": 4728, "s": 4607, "text": "Filter methods aim at ranking the importance of the features without making use of any type of classification algorithm." }, { "code": null, "e": 4925, "s": 4728, "text": "Univariate filter methods evaluate each feature individually and do not consider feature interactions. These methods consist of providing a score to each feature, often based on statistical tests." }, { "code": null, "e": 5190, "s": 4925, "text": "The scores usually either measure the dependency between the dependent variable and the features (e.g. Chi2 and, for regression, Pearls correlation coefficient), or the difference between the distributions of the features given the class label (F-test and T-test)." }, { "code": null, "e": 5425, "s": 5190, "text": "The scores often make assumptions about the statistical properties of the underlying data. Understanding these assumptions is important to decide which test to use, even though some of them are robust to violations of the assumptions." }, { "code": null, "e": 5605, "s": 5425, "text": "Scores based on statistical tests provide a p-value, that may be used to rule out some features. This is done if the p-value is above a certain threshold (typically 0.01 or 0.05)." }, { "code": null, "e": 5627, "s": 5605, "text": "Common tests include:" }, { "code": null, "e": 5797, "s": 5627, "text": "The package sklearn implements some filter methods. However, as most of them are based on statistical tests, statistics packages (such asstatsmodels) could also be used." }, { "code": null, "e": 5825, "s": 5797, "text": "One example is shown below:" }, { "code": null, "e": 6790, "s": 5825, "text": "from sklearn.feature_selection import f_classif, chi2, mutual_info_classiffrom statsmodels.stats.multicomp import pairwise_tukeyhsdfrom sklearn.datasets import load_irisdata = load_iris()X,y = data.data, data.targetchi2_score, chi_2_p_value = chi2(X,y)f_score, f_p_value = f_classif(X,y)mut_info_score = mutual_info_classif(X,y)pairwise_tukeyhsd = [list(pairwise_tukeyhsd(X[:,i],y).reject) for i in range(4)]print('chi2 score ', chi2_score)print('chi2 p-value ', chi_2_p_value)print('F - score score ', f_score)print('F - score p-value ', f_p_value)print('mutual info ', mut_info_score)print('pairwise_tukeyhsd',pairwise_tukeyhsd)Out:chi2 score [ 10.82 3.71 116.31 67.05]chi2 p-value [0. 0.16 0. 0. ]F - score score [ 119.26 49.16 1180.16 960.01]F - score p-value [0. 0. 0. 0.]mutual info [0.51 0.27 0.98 0.98]pairwise_tukeyhsd [[True, True, True], [True, True, True], [True, True, True], [True, True, True]]" }, { "code": null, "e": 6934, "s": 6790, "text": "Boxplots / Violin plots may help to visualize the distribution of the feature given the class. For the Iris dataset, an example is shown below." }, { "code": null, "e": 7133, "s": 6934, "text": "This is useful in that statistical tests often only evaluate the difference between the mean of such distributions. These plots, therefore, provide more information about the quality of the features" }, { "code": null, "e": 7640, "s": 7133, "text": "import pandas as pdimport seaborn as snssns.set()df = pd.DataFrame(data.data,columns=data.feature_names)df['target'] = data.targetdf_temp = pd.melt(df,id_vars='target',value_vars=list(df.columns)[:-1], var_name=\"Feature\", value_name=\"Value\")g = sns.FacetGrid(data = df_temp, col=\"Feature\", col_wrap=4, size=4.5,sharey = False)g.map(sns.boxplot,\"target\", \"Value\");g = sns.FacetGrid(data = df_temp, col=\"Feature\", col_wrap=4, size=4.5,sharey = False)g.map(sns.violinplot,\"target\", \"Value\");" }, { "code": null, "e": 7760, "s": 7640, "text": "The ROC curve may be used to rank features in importance order, which gives a visual way to rank features performances." }, { "code": null, "e": 7998, "s": 7760, "text": "This technique is most suitable for binary classification tasks. To apply in problems with multiple classes this, one could use micro or macro averages or multiple comparison based criteria (similarly to the pairwise Tukey’s range test)." }, { "code": null, "e": 8057, "s": 7998, "text": "The example below plots the ROC curve of various features." }, { "code": null, "e": 8881, "s": 8057, "text": "from sklearn.datasets import load_irisimport matplotlib.pyplot as pltfrom sklearn.metrics import aucimport numpy as np# loading datasetdata = load_iris()X, y = data.data, data.targety_ = y == 2plt.figure(figsize=(13,7))for col in range(X.shape[1]): tpr,fpr = [],[] for threshold in np.linspace(min(X[:,col]),max(X[:,col]),100): detP = X[:,col] < threshold tpr.append(sum(detP & y_)/sum(y_))# TP/P, aka recall fpr.append(sum(detP & (~y_))/sum((~y_)))# FP/N if auc(fpr,tpr) < .5: aux = tpr tpr = fpr fpr = aux plt.plot(fpr,tpr,label=data.feature_names[col] + ', auc = '\\ + str(np.round(auc(fpr,tpr),decimals=3)))plt.title('ROC curve - Iris features')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.legend()plt.show()" }, { "code": null, "e": 9016, "s": 8881, "text": "These methods take into account the correlations between variables and do so without considering any type of classification algorithm." }, { "code": null, "e": 9211, "s": 9016, "text": "mRMR (minimum Redundancy Maximum Relevance) is a heuristic algorithm to find a close to optimal subset of features by considering both the features importances and the correlations between them." }, { "code": null, "e": 9570, "s": 9211, "text": "The idea is that, even if two features are highly relevant, it may not be a good idea to add both of them to the feature set if they are highly correlated. In that case, adding both features would increase the model complexity (increasing the possibility of overfitting) but would not add significant information, due to the correlation between the features." }, { "code": null, "e": 9654, "s": 9570, "text": "In a set S of N features, the relevance of the features (D) is computed as follows:" }, { "code": null, "e": 9698, "s": 9654, "text": "where I is the mutual information operator." }, { "code": null, "e": 9752, "s": 9698, "text": "The redundancy of the features is denoted as follows:" }, { "code": null, "e": 10031, "s": 9752, "text": "The mRMR score for the set S is defined as (D - R). The goal is to find the subset of features with a maximum value of (D-R). In practice, however, we perform an incremental search (aka forward selection) in which, at each step, we add the feature that yields the greatest mRMR." }, { "code": null, "e": 10190, "s": 10031, "text": "The algorithm is implemented in C by the authors of the algorithm themselves. You can find the source code of the package, as well as the original paper here." }, { "code": null, "e": 10337, "s": 10190, "text": "A (not maintained) python wrapper was created on the name pymrmr. In case of issues with pymrmr, I advise calling the C — level function directly." }, { "code": null, "e": 10495, "s": 10337, "text": "The code below exemplifies the use of pymrmr . Note that the columns of the pandas data-frame should be formatted as described in the C level package (here)." }, { "code": null, "e": 10711, "s": 10495, "text": "import pandas as pdimport pymrmrdf = pd.read_csv('some_df.csv')# Pass a dataframe with a predetermined configuration. # Check http://home.penglab.com/proj/mRMR/ for the dataset requirementspymrmr.mRMR(df, 'MIQ', 10)" }, { "code": null, "e": 10719, "s": 10711, "text": "Output:" }, { "code": null, "e": 11996, "s": 10719, "text": "*** This program and the respective minimum Redundancy Maximum Relevance (mRMR) algorithm were developed by Hanchuan Peng <hanchuan.peng@gmail.com>for the paper \"Feature selection based on mutual information: criteria of max-dependency, max-relevance, and min-redundancy,\" Hanchuan Peng, Fuhui Long, and Chris Ding, IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. 27, No. 8, pp.1226-1238, 2005.*** MaxRel features *** Order Fea Name Score 1 765 v765 0.375 2 1423 v1423 0.337 3 513 v513 0.321 4 249 v249 0.309 5 267 v267 0.304 6 245 v245 0.304 7 1582 v1582 0.280 8 897 v897 0.269 9 1771 v1771 0.269 10 1772 v1772 0.269*** mRMR features *** Order Fea Name Score 1 765 v765 0.375 2 1123 v1123 24.913 3 1772 v1772 3.984 4 286 v286 2.280 5 467 v467 1.979 6 377 v377 1.768 7 513 v513 1.803 8 1325 v1325 1.634 9 1972 v1972 1.741 10 1412 v1412 1.689Out[1]: ['v765', 'v1123', 'v1772', 'v286', 'v467', 'v377', 'v513', 'v1325', 'v1972', 'v1412']" }, { "code": null, "e": 12201, "s": 11996, "text": "The main idea behind a wrapper method is to search which set of features works best for a specific classifier. The methods can be summarised as follows, and differ in regards to the search algorithm used." }, { "code": null, "e": 12455, "s": 12201, "text": "Choose a performance metric (Likelihood, AIC, BIC, F1-score, accuracy, MSE, MAE...), noted as M.Choose a classifier / regressor / ... , noted as C in here.Search different features subsets with a given search method. For each subset S, do the following:" }, { "code": null, "e": 12552, "s": 12455, "text": "Choose a performance metric (Likelihood, AIC, BIC, F1-score, accuracy, MSE, MAE...), noted as M." }, { "code": null, "e": 12612, "s": 12552, "text": "Choose a classifier / regressor / ... , noted as C in here." }, { "code": null, "e": 12711, "s": 12612, "text": "Search different features subsets with a given search method. For each subset S, do the following:" }, { "code": null, "e": 12797, "s": 12711, "text": "Train and test C in a cross-validation pattern, using S as the classifier’s features;" }, { "code": null, "e": 12916, "s": 12797, "text": "Obtain the average score from the cross-validation procedure (for the metric M) and assign this score to the subset S;" }, { "code": null, "e": 12953, "s": 12916, "text": "Choose a new subset and redo step a." }, { "code": null, "e": 13482, "s": 12953, "text": "Step three leaves unspecified the type which search method will be used. Testing all possible subsets of features is prohibitive (Brute Force selection) in virtually any situation since it would require performing step 3 an exponential number of times (2 to the power of the number of features). Besides the time complexity, with such a large number of possibilities, it would be likely that a certain combination of features performs best simply by random chance, which makes the brute force solution more prone to overfitting." }, { "code": null, "e": 13684, "s": 13482, "text": "Search algorithms tend to work well in practice to solve this issue. They tend to achieve a performance close to the brute force solution, with much less time complexity and less chance of overfitting." }, { "code": null, "e": 13824, "s": 13684, "text": "Forward selection and Backward selection (aka pruning) are much used in practice, as well as some small variations of their search process." }, { "code": null, "e": 14140, "s": 13824, "text": "Backward selection consists of starting with a model with the full number of features and, at each step, removing the feature without which the model has the highest score. Forward selection goes on the opposite way: it starts with an empty set of features and adds the feature that best improves the current score." }, { "code": null, "e": 14372, "s": 14140, "text": "Forward/Backward selection are still prone to overfitting, as, usually, scores tend to improve by adding more features. One way to avoid such situation is to use scores that penalize the complexity of the model, such as AIC or BIC." }, { "code": null, "e": 14594, "s": 14372, "text": "An illustration of a wrapper method structure is shown below. It is important to note that the feature set is (1) found through a search method and (2) cross-validated on the same classifier it is intended to be used for." }, { "code": null, "e": 14777, "s": 14594, "text": "Step three also leaves open the cross-validation parameters. Usually, a k-fold procedure is used. Using a large k, however, introduces extra complexity to the overall wrapper method." }, { "code": null, "e": 15031, "s": 14777, "text": "mlxtend (http://rasbt.github.io/mlxtend/) is a useful package for diverse data science-related tasks. The wrapper methods on this package can be found on SequentialFeatureSelector. It provides Forward and Backward feature selection with some variations." }, { "code": null, "e": 15182, "s": 15031, "text": "The package also provides a way to visualize the score as a function of the number of features through the function plot_sequential_feature_selection." }, { "code": null, "e": 15244, "s": 15182, "text": "The example below was extracted from the package’s main page." }, { "code": null, "e": 15849, "s": 15244, "text": "from mlxtend.feature_selection import SequentialFeatureSelector as SFSfrom mlxtend.plotting import plot_sequential_feature_selection as plot_sfsfrom sklearn.linear_model import LinearRegressionfrom sklearn.datasets import load_bostonboston = load_boston()X, y = boston.data, boston.targetlr = LinearRegression()sfs = SFS(lr, k_features=13, forward=True, floating=False, scoring='neg_mean_squared_error', cv=10)sfs = sfs.fit(X, y)fig = plot_sfs(sfs.get_metric_dict(), kind='std_err')plt.title('Sequential Forward Selection (w. StdErr)')plt.grid()plt.show()" }, { "code": null, "e": 16037, "s": 15849, "text": "Training a classifier boils down to an optimization problem, where we try to minimize a function of its parameters (noted here as θ). This function is known loss function (noted as L(θ))." }, { "code": null, "e": 16235, "s": 16037, "text": "In a more general framework, we usually want to minimize an objective function that takes into account both the loss function and a penalty (or regularisation)(Ω(θ)) to the complexity of the model:" }, { "code": null, "e": 16252, "s": 16235, "text": "obj(θ)=L(θ)+Ω(θ)" }, { "code": null, "e": 16347, "s": 16252, "text": "For linear classifiers (e.g. Linear SVM, Logistic Regression), the loss function is noted as :" }, { "code": null, "e": 16502, "s": 16347, "text": "Where each xj corresponds to one data sample and WTxj denotes the inner product of the coefficient vector (w1,w2,...w_n) with the features in each sample." }, { "code": null, "e": 16590, "s": 16502, "text": "For Linear SVM and Logistic Regression the hinge and logistic losses are, respectively:" }, { "code": null, "e": 16674, "s": 16590, "text": "The two most common penalties for linear classifiers are the L-1 and L-2 penalties:" }, { "code": null, "e": 16830, "s": 16674, "text": "The higher the value of λ, the stronger the penalty and the optimal objective function will tend to end up in shrinking more and more the coefficients w_i." }, { "code": null, "e": 17035, "s": 16830, "text": "The “L1” penalty is known to create sparse models, which simply means that, it tends to select some features out of the model by making some of the coefficients equal zero during the optimization process." }, { "code": null, "e": 17230, "s": 17035, "text": "Another common penalty is L-2. While L-2 shrinks the coefficients and therefore helps avoid overfitting, it does not create sparse models, so it is not suitable as a feature selection technique." }, { "code": null, "e": 17618, "s": 17230, "text": "For some linear classifiers (Linear SVM, Logistic Regression), the L-1 penalty can be efficiently used, meaning that there are efficient numerical methods to optimize the resulting objective function. The same is not true for several other classifiers (various Kernel SVM methods, Decision Trees,...). Therefore, different regularisation methods should be used for different classifiers." }, { "code": null, "e": 17789, "s": 17618, "text": "An example of Logistic regression with regularisation is shown below, and we can see that the algorithms rule out some of the features as C decreases (think if C as 1/λ)." }, { "code": null, "e": 18891, "s": 17789, "text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn.svm import LinearSVCfrom sklearn.model_selection import ShuffleSplitfrom sklearn.model_selection import GridSearchCVfrom sklearn.utils import check_random_statefrom sklearn import datasetsfrom sklearn.linear_model import LogisticRegressionrnd = check_random_state(1)# set up datasetn_samples = 3000n_features = 15# l1 data (only 5 informative features)X, y = datasets.make_classification(n_samples=n_samples, n_features=n_features, n_informative=5, random_state=1)cs = np.logspace(-2.3, 0, 50)coefs = []for c in cs: clf = LogisticRegression(solver='liblinear',C=c,penalty='l1') # clf = LinearSVC(C=c,penalty='l1', loss='squared_hinge', dual=False, tol=1e-3) clf.fit(X,y) coefs.append(list(clf.coef_[0])) coefs = np.array(coefs)plt.figure(figsize=(10,5))for i,col in enumerate(range(n_features)): plt.plot(cs,coefs[:,col])plt.xscale('log')plt.title('L1 penalty - Logistic regression')plt.xlabel('C')plt.ylabel('Coefficient value')plt.show()" }, { "code": null, "e": 19006, "s": 18891, "text": "Another common feature selection technique consists in extracting a feature importance rank from tree base models." }, { "code": null, "e": 19307, "s": 19006, "text": "The feature importances are essentially the mean of the individual trees’ improvement in the splitting criterion produced by each variable. In other words, it is how much the score (so-called “impurity” on the decision tree notation) was improved when splitting the tree using that specific variable." }, { "code": null, "e": 19574, "s": 19307, "text": "They can be used to rank features and then select a subset of them. However, the feature importances should be used with care, as they suffer from biases and, and presents an unexpected behavior regarding highly correlated features regardless of how strong they are." }, { "code": null, "e": 19812, "s": 19574, "text": "As shown in this paper, random forest feature importances are biased towards features with more categories. Besides, if two features are highly correlated, both of their scores largely decrease, regardless of the quality of the features." }, { "code": null, "e": 19966, "s": 19812, "text": "Below is an example of how to extract the feature importances from a random forest. Although a regressor, the process would be the same for a classifier." }, { "code": null, "e": 20614, "s": 19966, "text": "from sklearn.datasets import load_bostonfrom sklearn.ensemble import RandomForestRegressorimport numpy as npboston = load_boston()X = boston.dataY = boston.targetfeat_names = boston.feature_names rf = RandomForestRegressor()rf.fit(X, Y)print(\"Features sorted by their score:\")print(sorted(zip(map(lambda x: round(x, 4), rf.feature_importances_), feat_names), reverse=True))Out:Features sorted by their score:[(0.4334, 'LSTAT'), (0.3709, 'RM'), (0.0805, 'DIS'), (0.0314, 'CRIM'), (0.0225, 'NOX'), (0.0154, 'TAX'), (0.0133, 'PTRATIO'), (0.0115, 'AGE'), (0.011, 'B'), (0.0043, 'INDUS'), (0.0032, 'RAD'), (0.0016, 'CHAS'), (0.0009, 'ZN')]" }, { "code": null, "e": 20939, "s": 20614, "text": "As explained above, the “impurity” is a score used by the decision tree algorithm when deciding to split a node. There are many decision tree algorithms (IDR3, C4.5, CART,...), but the general rule is that the variable with which we split a node in the tree is the one that generates the highest improvement on the impurity." }, { "code": null, "e": 21128, "s": 20939, "text": "The most common impurities are the Gini Impurity and Entropy. An improvement on the Gini impurity is known as “Gini importance” while An improvement on the Entropy is the Information Gain." }, { "code": null, "e": 21199, "s": 21128, "text": "(Thanks to Henrique Gasparini Fiuza do Nascimento for the suggestion!)" }, { "code": null, "e": 21541, "s": 21199, "text": "SHAP is actually much more than just that. It is an algorithm to provide model explanation out of any predictive model. For tree based models, however, it is specially useful: the authors developed a high speed and exact (not only local) explanation for such models, compatible with XGBoost, LightGBM, CatBoost, and scikit-learn tree models." }, { "code": null, "e": 21906, "s": 21541, "text": "I encourage checking out the explanation capabilities provided by SHAP (such as Feature dependance, interaction effects, model monitoring...). Below, I plot (only) the feature importances output by SHAP, which are more reliable than those output by the original tree model when ranking them for feature selection. This example was extracted from their github page." }, { "code": null, "e": 22359, "s": 21906, "text": "import xgboostimport shap# load JS visualization code to notebookshap.initjs()# train XGBoost modelX,y = shap.datasets.boston()model = xgboost.train({\"learning_rate\": 0.01}, xgboost.DMatrix(X, label=y), 100)# explain the model's predictions using SHAP values# (same syntax works for LightGBM, CatBoost, and scikit-learn models)explainer = shap.TreeExplainer(model)shap_values = explainer.shap_values(X)shap.summary_plot(shap_values, X, plot_type=\"bar\")" }, { "code": null, "e": 22611, "s": 22359, "text": "Embedded methods are usually very efficient to avoid overfitting and select useful variables. They are also time efficient as they are embedded on the objective function. Their main downside is that they may not be available to the desired classifier." }, { "code": null, "e": 22831, "s": 22611, "text": "Wrapper methods tend to work very well in practice. However, they are computationally expensive, specially when dealing hundreds of features. But if you have the computational resources, they are an excellent way to go." }, { "code": null, "e": 23212, "s": 22831, "text": "If the feature set is very large (on the order of hundreds or thousands), because filter methods are fast, they can work well as a first stage of selection, to rule out some variables. Subsequently another method can be applied to the already reduced feature set. This is particular useful if you want to create combinations of features, multiplying or dividing them, for example." }, { "code": null, "e": 23262, "s": 23212, "text": "An Introduction to Variable and Feature Selection" }, { "code": null, "e": 23352, "s": 23262, "text": "Bias in random forest variable importance measures: Illustrations, sources and a solution" } ]
Playit
#myDIV { background-color:lightblue; transform:scaleY(1.1);}
[]
Asymptotic Analysis and comparison of sorting algorithms - GeeksforGeeks
30 May, 2018 It is a well established fact that merge sort runs faster than insertion sort. Using asymptotic analysis we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2). It is obvious because merge sort uses a divide-and-conquer approach by recursively solving the problems where as insertion sort follows an incremental approach.If we scrutinize the time complexity analysis even further, we’ll get to know that insertion sort isn’t that bad enough. Surprisingly, insertion sort beats merge sort on smaller input size. This is because there are few constants which we ignore while deducing the time complexity. On larger input sizes of the order 10^4 this doesn’t influence the behavior of our function. But when input sizes fall below, say less than 40, then the constants in the equation dominate the input size ‘n’.So far, so good. But I wasn’t satisfied with such mathematical analysis. As a computer science undergrad we must believe in writing code. I’ve written a C program to get a feel of how the algorithms compete against each other for various input sizes. And also, why such rigorous mathematical analysis is done on establishing running time complexities of these sorting algorithms.Implementation: //C++ code to compare performance of sorting algorithms#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <time.h>#define MAX_ELEMENT_IN_ARRAY 1000000001 int cmpfunc (const void * a, const void * b){ // Compare function used by qsort return ( *(int*)a - *(int*)b );} int* generate_random_array(int n){ srand(time(NULL)); int *a = malloc(sizeof(int) * n), i; for(i = 0; i < n; ++i) a[i] = rand() % MAX_ELEMENT_IN_ARRAY; return a;} int* copy_array(int a[], int n){ int *arr = malloc(sizeof(int) * n); int i; for(i = 0; i < n ;++i) arr[i] = a[i]; return arr;} //Code for Insertion Sortvoid insertion_sort_asc(int a[], int start, int end){ int i; for(i = start + 1; i <= end ; ++i) { int key = a[i]; int j = i - 1; while(j >= start && a[j] > key) { a[j + 1] = a[j]; --j; } a[j + 1] = key; }} //Code for Merge Sortvoid merge(int a[], int start, int end, int mid){ int i = start, j = mid + 1, k = 0; int *aux = malloc(sizeof(int) * (end - start + 1)); while(i <= mid && j <= end) { if(a[i] <= a[j]) aux[k++] = a[i++]; else aux[k++] = a[j++]; } while(i <= mid) aux[k++] = a[i++]; while(j <= end) aux[k++] = a[j++]; j = 0; for(i = start;i <= end;++i) a[i] = aux[j++]; free(aux);} void _merge_sort(int a[],int start,int end){ if(start < end) { int mid = start + (end - start) / 2; _merge_sort(a,start,mid); _merge_sort(a,mid + 1,end); merge(a,start,end,mid); }}void merge_sort(int a[],int n){ return _merge_sort(a,0,n - 1);} void insertion_and_merge_sort_combine(int a[], int start, int end, int k){ // Performs insertion sort if size of array is less than or equal to k // Otherwise, uses mergesort if(start < end) { int size = end - start + 1; if(size <= k) { //printf("Performed insertion sort- start = %d and end = %d\n", start, end); return insertion_sort_asc(a,start,end); } int mid = start + (end - start) / 2; insertion_and_merge_sort_combine(a,start,mid,k); insertion_and_merge_sort_combine(a,mid + 1,end,k); merge(a,start,end,mid); }} void test_sorting_runtimes(int size,int num_of_times){ // Measuring the runtime of the sorting algorithms int number_of_times = num_of_times; int t = number_of_times; int n = size; double insertion_sort_time = 0, merge_sort_time = 0; double merge_sort_and_insertion_sort_mix_time = 0, qsort_time = 0; while(t--) { clock_t start, end; int *a = generate_random_array(n); int *b = copy_array(a,n); start = clock(); insertion_sort_asc(b,0,n-1); end = clock(); insertion_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(b); int *c = copy_array(a,n); start = clock(); merge_sort(c,n); end = clock(); merge_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(c); int *d = copy_array(a,n); start = clock(); insertion_and_merge_sort_combine(d,0,n-1,40); end = clock(); merge_sort_and_insertion_sort_mix_time+=((double) (end - start))/CLOCKS_PER_SEC; free(d); start = clock(); qsort(a,n,sizeof(int),cmpfunc); end = clock(); qsort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(a); } insertion_sort_time /= number_of_times; merge_sort_time /= number_of_times; merge_sort_and_insertion_sort_mix_time /= number_of_times; qsort_time /= number_of_times; printf("\nTime taken to sort:\n" "%-35s %f\n" "%-35s %f\n" "%-35s %f\n" "%-35s %f\n\n", "(i)Insertion sort: ", insertion_sort_time, "(ii)Merge sort: ", merge_sort_time, "(iii)Insertion-mergesort-hybrid: ", merge_sort_and_insertion_sort_mix_time, "(iv)Qsort library function: ", qsort_time);} int main(int argc, char const *argv[]){ int t; scanf("%d", &t); while(t--) { int size, num_of_times; scanf("%d %d", &size, &num_of_times); test_sorting_runtimes(size,num_of_times); } return 0;} I have compared the running times of the following algorithms: Insertion sort: The traditional algorithm with no modifications/optimisation. It performs very well for smaller input sizes. And yes, it does beat merge sort Merge sort: Follows the divide-and-conquer approach. For input sizes of the order 10^5 this algorithm is of the right choice. It renders insertion sort impractical for such large input sizes. Combined version of insertion sort and merge sort: I have tweaked the logic of merge sort a little bit to achieve a considerably better running time for smaller input sizes. As we know, merge sort splits its input into two halves until it is trivial enough to sort the elements. But here, when the input size falls below a threshold such as ’n’ < 40 then this hybrid algorithm makes a call to traditional insertion sort procedure. From the fact that insertion sort runs faster on smaller inputs and merge sort runs faster on larger inputs, this algorithm makes best use both the worlds. Quick sort: I have not implemented this procedure. This is the library function qsort() which is available in . I have considered this algorithm in order to know the significance of implementation. It requires a great deal of programming expertise to minimize the number of steps and make at most use of the underlying language primitives to implement an algorithm in the best way possible. This is the main reason why it is recommended to use library functions. They are written to handle anything and everything. They optimize to the maximum extent possible. And before I forget, from my analysis qsort() runs blazingly fast on virtually any input size! The Analysis: Input: The user has to supply the number of times he/she wants to test the algorithm corresponding to number of test cases. For each test case the user must enter two space separated integers denoting the input size ’n’ and the ‘num_of_times’ denoting the number of times he/she wants to run the analysis and take average. (Clarification: If ‘num_of_times’ is 10 then each of the algorithm specified above runs 10 times and the average is taken. This is done because the input array is generated randomly corresponding to the input size which you specify. The input array could be all sorted. Our it could correspond to the worst case .i.e. descending order. In order to avoid running times of such input arrays. The algorithm is run ‘num_of_times‘ and the average is taken.)clock() routine and CLOCKS_PER_SEC macro from is used to measure the time taken.Compilation: I have written the above code in Linux environment (Ubuntu 16.04 LTS). Copy the code snippet above. Compile it using gcc, key in the inputs as specified and admire the power of sorting algorithms! Results: As you can see for small input sizes, insertion sort beats merge sort by 2 * 10^-6 sec. But this difference in time is not so significant. On the other hand, the hybrid algorithm and qsort() library function, both perform as good as insertion sort.The input size is now increased by approximately 100 times to n = 1000 from n = 30. The difference is now tangible. Merge sort runs 10 times faster than insertion sort. There is again a tie between the performance of the hybrid algorithm and the qsort() routine. This suggests that the qsort() is implemented in a way which is more or less similar to our hybrid algorithm i.e., switching between different algorithms to make the best out of them.Finally, the input size is increased to 10^5 (1 Lakh!) which is most probably the ideal size used in practical scenario’s. Compared to the previous input n = 1000 where merge sort beat insertion sort by running 10 times faster, here the difference is even more significant. Merge sort beats insertion sort by 100 times!The hybrid algorithm which we have written in fact does out perform the traditional merge sort by running 0.01 sec faster. And lastly, qsort() the library function, finally proves us that implementation also plays a crucial role while measuring the running times meticulously by running 3 milliseconds faster! Note: Do not run the above program with n >= 10^6 since it will take a lot of computing power. Thank you and Happy coding! This article is contributed by Aditya Ch. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Analysis GBlog Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete 3-coloring is NP Complete Proof that Independent Set in Graph theory is NP Complete Difference between Deterministic and Non-deterministic Algorithms Proof that Hamiltonian Cycle is NP-Complete Roadmap to Become a Web Developer in 2022 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Socket Programming in C/C++ DSA Sheet by Love Babbar GET and POST requests using Python
[ { "code": null, "e": 25046, "s": 25018, "text": "\n30 May, 2018" }, { "code": null, "e": 26279, "s": 25046, "text": "It is a well established fact that merge sort runs faster than insertion sort. Using asymptotic analysis we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2). It is obvious because merge sort uses a divide-and-conquer approach by recursively solving the problems where as insertion sort follows an incremental approach.If we scrutinize the time complexity analysis even further, we’ll get to know that insertion sort isn’t that bad enough. Surprisingly, insertion sort beats merge sort on smaller input size. This is because there are few constants which we ignore while deducing the time complexity. On larger input sizes of the order 10^4 this doesn’t influence the behavior of our function. But when input sizes fall below, say less than 40, then the constants in the equation dominate the input size ‘n’.So far, so good. But I wasn’t satisfied with such mathematical analysis. As a computer science undergrad we must believe in writing code. I’ve written a C program to get a feel of how the algorithms compete against each other for various input sizes. And also, why such rigorous mathematical analysis is done on establishing running time complexities of these sorting algorithms.Implementation:" }, { "code": "//C++ code to compare performance of sorting algorithms#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <time.h>#define MAX_ELEMENT_IN_ARRAY 1000000001 int cmpfunc (const void * a, const void * b){ // Compare function used by qsort return ( *(int*)a - *(int*)b );} int* generate_random_array(int n){ srand(time(NULL)); int *a = malloc(sizeof(int) * n), i; for(i = 0; i < n; ++i) a[i] = rand() % MAX_ELEMENT_IN_ARRAY; return a;} int* copy_array(int a[], int n){ int *arr = malloc(sizeof(int) * n); int i; for(i = 0; i < n ;++i) arr[i] = a[i]; return arr;} //Code for Insertion Sortvoid insertion_sort_asc(int a[], int start, int end){ int i; for(i = start + 1; i <= end ; ++i) { int key = a[i]; int j = i - 1; while(j >= start && a[j] > key) { a[j + 1] = a[j]; --j; } a[j + 1] = key; }} //Code for Merge Sortvoid merge(int a[], int start, int end, int mid){ int i = start, j = mid + 1, k = 0; int *aux = malloc(sizeof(int) * (end - start + 1)); while(i <= mid && j <= end) { if(a[i] <= a[j]) aux[k++] = a[i++]; else aux[k++] = a[j++]; } while(i <= mid) aux[k++] = a[i++]; while(j <= end) aux[k++] = a[j++]; j = 0; for(i = start;i <= end;++i) a[i] = aux[j++]; free(aux);} void _merge_sort(int a[],int start,int end){ if(start < end) { int mid = start + (end - start) / 2; _merge_sort(a,start,mid); _merge_sort(a,mid + 1,end); merge(a,start,end,mid); }}void merge_sort(int a[],int n){ return _merge_sort(a,0,n - 1);} void insertion_and_merge_sort_combine(int a[], int start, int end, int k){ // Performs insertion sort if size of array is less than or equal to k // Otherwise, uses mergesort if(start < end) { int size = end - start + 1; if(size <= k) { //printf(\"Performed insertion sort- start = %d and end = %d\\n\", start, end); return insertion_sort_asc(a,start,end); } int mid = start + (end - start) / 2; insertion_and_merge_sort_combine(a,start,mid,k); insertion_and_merge_sort_combine(a,mid + 1,end,k); merge(a,start,end,mid); }} void test_sorting_runtimes(int size,int num_of_times){ // Measuring the runtime of the sorting algorithms int number_of_times = num_of_times; int t = number_of_times; int n = size; double insertion_sort_time = 0, merge_sort_time = 0; double merge_sort_and_insertion_sort_mix_time = 0, qsort_time = 0; while(t--) { clock_t start, end; int *a = generate_random_array(n); int *b = copy_array(a,n); start = clock(); insertion_sort_asc(b,0,n-1); end = clock(); insertion_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(b); int *c = copy_array(a,n); start = clock(); merge_sort(c,n); end = clock(); merge_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(c); int *d = copy_array(a,n); start = clock(); insertion_and_merge_sort_combine(d,0,n-1,40); end = clock(); merge_sort_and_insertion_sort_mix_time+=((double) (end - start))/CLOCKS_PER_SEC; free(d); start = clock(); qsort(a,n,sizeof(int),cmpfunc); end = clock(); qsort_time += ((double) (end - start)) / CLOCKS_PER_SEC; free(a); } insertion_sort_time /= number_of_times; merge_sort_time /= number_of_times; merge_sort_and_insertion_sort_mix_time /= number_of_times; qsort_time /= number_of_times; printf(\"\\nTime taken to sort:\\n\" \"%-35s %f\\n\" \"%-35s %f\\n\" \"%-35s %f\\n\" \"%-35s %f\\n\\n\", \"(i)Insertion sort: \", insertion_sort_time, \"(ii)Merge sort: \", merge_sort_time, \"(iii)Insertion-mergesort-hybrid: \", merge_sort_and_insertion_sort_mix_time, \"(iv)Qsort library function: \", qsort_time);} int main(int argc, char const *argv[]){ int t; scanf(\"%d\", &t); while(t--) { int size, num_of_times; scanf(\"%d %d\", &size, &num_of_times); test_sorting_runtimes(size,num_of_times); } return 0;}", "e": 30650, "s": 26279, "text": null }, { "code": null, "e": 30713, "s": 30650, "text": "I have compared the running times of the following algorithms:" }, { "code": null, "e": 30871, "s": 30713, "text": "Insertion sort: The traditional algorithm with no modifications/optimisation. It performs very well for smaller input sizes. And yes, it does beat merge sort" }, { "code": null, "e": 31063, "s": 30871, "text": "Merge sort: Follows the divide-and-conquer approach. For input sizes of the order 10^5 this algorithm is of the right choice. It renders insertion sort impractical for such large input sizes." }, { "code": null, "e": 31650, "s": 31063, "text": "Combined version of insertion sort and merge sort: I have tweaked the logic of merge sort a little bit to achieve a considerably better running time for smaller input sizes. As we know, merge sort splits its input into two halves until it is trivial enough to sort the elements. But here, when the input size falls below a threshold such as ’n’ < 40 then this hybrid algorithm makes a call to traditional insertion sort procedure. From the fact that insertion sort runs faster on smaller inputs and merge sort runs faster on larger inputs, this algorithm makes best use both the worlds." }, { "code": null, "e": 32306, "s": 31650, "text": "Quick sort: I have not implemented this procedure. This is the library function qsort() which is available in . I have considered this algorithm in order to know the significance of implementation. It requires a great deal of programming expertise to minimize the number of steps and make at most use of the underlying language primitives to implement an algorithm in the best way possible. This is the main reason why it is recommended to use library functions. They are written to handle anything and everything. They optimize to the maximum extent possible. And before I forget, from my analysis qsort() runs blazingly fast on virtually any input size!" }, { "code": null, "e": 32320, "s": 32306, "text": "The Analysis:" }, { "code": null, "e": 33385, "s": 32320, "text": "Input: The user has to supply the number of times he/she wants to test the algorithm corresponding to number of test cases. For each test case the user must enter two space separated integers denoting the input size ’n’ and the ‘num_of_times’ denoting the number of times he/she wants to run the analysis and take average. (Clarification: If ‘num_of_times’ is 10 then each of the algorithm specified above runs 10 times and the average is taken. This is done because the input array is generated randomly corresponding to the input size which you specify. The input array could be all sorted. Our it could correspond to the worst case .i.e. descending order. In order to avoid running times of such input arrays. The algorithm is run ‘num_of_times‘ and the average is taken.)clock() routine and CLOCKS_PER_SEC macro from is used to measure the time taken.Compilation: I have written the above code in Linux environment (Ubuntu 16.04 LTS). Copy the code snippet above. Compile it using gcc, key in the inputs as specified and admire the power of sorting algorithms!" }, { "code": null, "e": 34718, "s": 33385, "text": "Results: As you can see for small input sizes, insertion sort beats merge sort by 2 * 10^-6 sec. But this difference in time is not so significant. On the other hand, the hybrid algorithm and qsort() library function, both perform as good as insertion sort.The input size is now increased by approximately 100 times to n = 1000 from n = 30. The difference is now tangible. Merge sort runs 10 times faster than insertion sort. There is again a tie between the performance of the hybrid algorithm and the qsort() routine. This suggests that the qsort() is implemented in a way which is more or less similar to our hybrid algorithm i.e., switching between different algorithms to make the best out of them.Finally, the input size is increased to 10^5 (1 Lakh!) which is most probably the ideal size used in practical scenario’s. Compared to the previous input n = 1000 where merge sort beat insertion sort by running 10 times faster, here the difference is even more significant. Merge sort beats insertion sort by 100 times!The hybrid algorithm which we have written in fact does out perform the traditional merge sort by running 0.01 sec faster. And lastly, qsort() the library function, finally proves us that implementation also plays a crucial role while measuring the running times meticulously by running 3 milliseconds faster! " }, { "code": null, "e": 34842, "s": 34718, "text": "Note: Do not run the above program with n >= 10^6 since it will take a lot of computing power. Thank you and Happy coding! " }, { "code": null, "e": 35139, "s": 34842, "text": "This article is contributed by Aditya Ch. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 35264, "s": 35139, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35273, "s": 35264, "text": "Analysis" }, { "code": null, "e": 35279, "s": 35273, "text": "GBlog" }, { "code": null, "e": 35287, "s": 35279, "text": "Sorting" }, { "code": null, "e": 35295, "s": 35287, "text": "Sorting" }, { "code": null, "e": 35393, "s": 35295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35460, "s": 35393, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 35486, "s": 35460, "text": "3-coloring is NP Complete" }, { "code": null, "e": 35544, "s": 35486, "text": "Proof that Independent Set in Graph theory is NP Complete" }, { "code": null, "e": 35610, "s": 35544, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 35654, "s": 35610, "text": "Proof that Hamiltonian Cycle is NP-Complete" }, { "code": null, "e": 35696, "s": 35654, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 35770, "s": 35696, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 35798, "s": 35770, "text": "Socket Programming in C/C++" }, { "code": null, "e": 35823, "s": 35798, "text": "DSA Sheet by Love Babbar" } ]
How to select subset of data with Index Labels?
Pandas have a dual selection capability to select the subset of data using the Index position or by using the Index labels. In this post, I will show you how to “Select a Subset Of Data Using Index Labels” using the index label. Remember, Python dictionaries and lists are built-in data structures that select their data either by using the index label or by index position. A dictionary’s key must be a string, integer, or tuple while a List must either use integers (the position) or slice objects for selection. Pandas have .loc and.iloc attributes available to perform index operations in their own unique ways. ). With.iloc attribute, pandas select only by position and work similarly to Python lists. The .loc attribute selects only by index label, which is similar to how Python dictionaries work. The loc and iloc attributes are available on both Series and DataFrame Import the movies dataset with the title as index. Import the movies dataset with the title as index. import pandas as pd movies = pd.read_csv( "movies_data.csv", index_col="title", usecols=["title","budget","vote_average","vote_count"] ) I always recommend sorting the index, especially if the index is made up of strings. You will notice the difference if you are dealing with a huge dataset when your index is sorted. I always recommend sorting the index, especially if the index is made up of strings. You will notice the difference if you are dealing with a huge dataset when your index is sorted. movies.sort_index(inplace = True) movies.head(3) I have sorted the index using sort_index and "inplace = True" parameter. One thing interesting about the syntax of the loc method is that it does not take parenthesis() rather takes square brackets[]. I think (might be wrong) this is because they wanted consistency i.e. you can use [] on a Series to extract rows, while applied on a Dataframe will fetch you the columns. One thing interesting about the syntax of the loc method is that it does not take parenthesis() rather takes square brackets[]. I think (might be wrong) this is because they wanted consistency i.e. you can use [] on a Series to extract rows, while applied on a Dataframe will fetch you the columns. # extract "Spider-Man 3" ( I'm not a big fan of spidy) movies.loc["Spider-Man 3"] budget 258000000.0 vote_average 5.9 vote_count 3576.0 Name: Spider-Man 3, dtype: float64 Use a slice to pull out many values. I'm going to pull the movies which I haven't watched. Because this is a string label we are going to get all the data for our search criteria including "Avatar". Use a slice to pull out many values. I'm going to pull the movies which I haven't watched. Because this is a string label we are going to get all the data for our search criteria including "Avatar". Remember − If you work with Python List the last value is excluded but since we are working with strings it's inclusive. movies.loc["Alien":"Avatar" ] 167 rows × 3 columns Can I get any two or more random movies that are not next to each other? Definitely yes, but you need to put more effort into passing a list of movies you need. Can I get any two or more random movies that are not next to each other? Definitely yes, but you need to put more effort into passing a list of movies you need. What I meant was you need to have square brackets with in a square bracket. movies.loc[["Avatar", "Avengers: Age of Ultron"]] Can I change the order of selection? Of course, you can help yourself by specifying the list of labels you need in an order. Can I change the order of selection? Of course, you can help yourself by specifying the list of labels you need in an order. While this looks cool to specify the list of labels you want to extract, do you know what happens if you spelled a value wrongly? Pandas would have stuck missing Values (NaN) for the wrongly spelled label. But those days are gone, with the latest updates it raises an exception. movies.loc[["Avengers: Age of Ultron","Avatar","When is Avengers next movie?"]] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-21-ebe975264840> in <module> ----> 1 movies.loc[["Avengers: Age of Ultron","Avatar","When is Avengers next movie?"]] ∽\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 1766 1767 maybe_callable = com.apply_if_callable(key, self.obj) −> 1768 return self._getitem_axis(maybe_callable, axis=axis) 1769 1770 def _is_scalar_access(self, key: Tuple): ∽\anaconda3\lib\site−packages\pandas\core\indexing.py in _getitem_axis(self, key, axis) 1952 raise ValueError("Cannot index with multidimensional key") 1953 −> 1954 return self._getitem_iterable(key, axis=axis) 1955 1956 # nested tuple slicing ∽\anaconda3\lib\site−packages\pandas\core\indexing.py in _getitem_iterable(self, key, axis) 1593 else: 1594 # A collection of keys −> 1595 keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False) 1596 return self.obj._reindex_with_indexers( 1597 {axis: [keyarr, indexer]}, copy=True, allow_dups=True ∽\anaconda3\lib\site−packages\pandas\core\indexing.py in _get_listlike_indexer(self, key, axis, raise_missing) 1550 keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr) 1551 −> 1552 self._validate_read_indexer( 1553 keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing 1554 ) ∽\anaconda3\lib\site−packages\pandas\core\indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing) 1652 # just raising 1653 if not (ax.is_categorical() or ax.is_interval()): −> 1654 raise KeyError( 1655 "Passing list−likes to .loc or [] with any missing labels " 1656 "is no longer supported, see " KeyError: 'Passing list−likes to .loc or [] with any missing labels is no longer supported, see https://pandas.pydata.org/pandas−docs/stable/user_guide/indexing.html#deprecate−loc−reindex−listlike' One way to take care is by checking the values in the index directly. "When is Avengers next movie?" in movies.index If you want to ignore the error and move on you can use below approach movies.query("title in ('Avatar','When is Avengers next Movie?')")
[ { "code": null, "e": 1291, "s": 1062, "text": "Pandas have a dual selection capability to select the subset of data using the Index position or by using the Index labels. In this post, I will show you how to “Select a Subset Of Data Using Index Labels” using the index label." }, { "code": null, "e": 1577, "s": 1291, "text": "Remember, Python dictionaries and lists are built-in data structures that select their data either by using the index label or by index position. A dictionary’s key must be a string, integer, or tuple while a List must either use integers (the position) or slice objects for selection." }, { "code": null, "e": 1867, "s": 1577, "text": "Pandas have .loc and.iloc attributes available to perform index operations in their own unique ways. ). With.iloc attribute, pandas select only by position and work similarly to Python lists. The .loc attribute selects only by index label, which is similar to how Python dictionaries work." }, { "code": null, "e": 1938, "s": 1867, "text": "The loc and iloc attributes are available on both Series and DataFrame" }, { "code": null, "e": 1989, "s": 1938, "text": "Import the movies dataset with the title as index." }, { "code": null, "e": 2040, "s": 1989, "text": "Import the movies dataset with the title as index." }, { "code": null, "e": 2186, "s": 2040, "text": "import pandas as pd\nmovies = pd.read_csv(\n \"movies_data.csv\",\n index_col=\"title\",\n usecols=[\"title\",\"budget\",\"vote_average\",\"vote_count\"]\n)" }, { "code": null, "e": 2368, "s": 2186, "text": "I always recommend sorting the index, especially if the index is made up of strings. You will notice the difference if you are dealing with a huge dataset when your index is sorted." }, { "code": null, "e": 2550, "s": 2368, "text": "I always recommend sorting the index, especially if the index is made up of strings. You will notice the difference if you are dealing with a huge dataset when your index is sorted." }, { "code": null, "e": 2599, "s": 2550, "text": "movies.sort_index(inplace = True)\nmovies.head(3)" }, { "code": null, "e": 2672, "s": 2599, "text": "I have sorted the index using sort_index and \"inplace = True\" parameter." }, { "code": null, "e": 2971, "s": 2672, "text": "One thing interesting about the syntax of the loc method is that it does not take parenthesis() rather takes square brackets[]. I think (might be wrong) this is because they wanted consistency i.e. you can use [] on a Series to extract rows, while applied on a Dataframe will fetch you the columns." }, { "code": null, "e": 3270, "s": 2971, "text": "One thing interesting about the syntax of the loc method is that it does not take parenthesis() rather takes square brackets[]. I think (might be wrong) this is because they wanted consistency i.e. you can use [] on a Series to extract rows, while applied on a Dataframe will fetch you the columns." }, { "code": null, "e": 3352, "s": 3270, "text": "# extract \"Spider-Man 3\" ( I'm not a big fan of spidy)\nmovies.loc[\"Spider-Man 3\"]" }, { "code": null, "e": 3441, "s": 3352, "text": "budget 258000000.0\nvote_average 5.9\nvote_count 3576.0\nName: Spider-Man 3, dtype: float64" }, { "code": null, "e": 3640, "s": 3441, "text": "Use a slice to pull out many values. I'm going to pull the movies which I haven't watched. Because this is a string label we are going to get all the data for our search criteria including \"Avatar\"." }, { "code": null, "e": 3839, "s": 3640, "text": "Use a slice to pull out many values. I'm going to pull the movies which I haven't watched. Because this is a string label we are going to get all the data for our search criteria including \"Avatar\"." }, { "code": null, "e": 3960, "s": 3839, "text": "Remember − If you work with Python List the last value is excluded but since we are working with strings it's inclusive." }, { "code": null, "e": 3990, "s": 3960, "text": "movies.loc[\"Alien\":\"Avatar\" ]" }, { "code": null, "e": 4011, "s": 3990, "text": "167 rows × 3 columns" }, { "code": null, "e": 4172, "s": 4011, "text": "Can I get any two or more random movies that are not next to each other? Definitely yes, but you need to put more effort into passing a list of movies you need." }, { "code": null, "e": 4333, "s": 4172, "text": "Can I get any two or more random movies that are not next to each other? Definitely yes, but you need to put more effort into passing a list of movies you need." }, { "code": null, "e": 4409, "s": 4333, "text": "What I meant was you need to have square brackets with in a square bracket." }, { "code": null, "e": 4459, "s": 4409, "text": "movies.loc[[\"Avatar\", \"Avengers: Age of Ultron\"]]" }, { "code": null, "e": 4584, "s": 4459, "text": "Can I change the order of selection? Of course, you can help yourself by specifying the list of labels you need in an order." }, { "code": null, "e": 4709, "s": 4584, "text": "Can I change the order of selection? Of course, you can help yourself by specifying the list of labels you need in an order." }, { "code": null, "e": 4988, "s": 4709, "text": "While this looks cool to specify the list of labels you want to extract, do you know what happens if you spelled a value wrongly? Pandas would have stuck missing Values (NaN) for the wrongly spelled label. But those days are gone, with the latest updates it raises an exception." }, { "code": null, "e": 5068, "s": 4988, "text": "movies.loc[[\"Avengers: Age of Ultron\",\"Avatar\",\"When is Avengers next movie?\"]]" }, { "code": null, "e": 6967, "s": 5068, "text": "---------------------------------------------------------------------------\nKeyError Traceback (most recent call last)\n<ipython-input-21-ebe975264840> in <module>\n----> 1 movies.loc[[\"Avengers: Age of Ultron\",\"Avatar\",\"When is Avengers next movie?\"]]\n\n∽\\anaconda3\\lib\\site-packages\\pandas\\core\\indexing.py in __getitem__(self, key)\n1766\n1767 maybe_callable = com.apply_if_callable(key, self.obj)\n−> 1768 return self._getitem_axis(maybe_callable, axis=axis)\n1769\n1770 def _is_scalar_access(self, key: Tuple):\n\n∽\\anaconda3\\lib\\site−packages\\pandas\\core\\indexing.py in _getitem_axis(self, key, axis)\n1952 raise ValueError(\"Cannot index with multidimensional key\")\n1953\n−> 1954 return self._getitem_iterable(key, axis=axis)\n1955\n1956 # nested tuple slicing\n\n∽\\anaconda3\\lib\\site−packages\\pandas\\core\\indexing.py in _getitem_iterable(self, key, axis)\n1593 else:\n1594 # A collection of keys\n−> 1595 keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False)\n1596 return self.obj._reindex_with_indexers(\n1597 {axis: [keyarr, indexer]}, copy=True, allow_dups=True\n\n∽\\anaconda3\\lib\\site−packages\\pandas\\core\\indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)\n1550 keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)\n1551\n−> 1552 self._validate_read_indexer(\n1553 keyarr, indexer, o._get_axis_number(axis), raise_missing=raise_missing\n1554 )\n\n∽\\anaconda3\\lib\\site−packages\\pandas\\core\\indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)\n1652 # just raising\n1653 if not (ax.is_categorical() or ax.is_interval()):\n−> 1654 raise KeyError(\n1655 \"Passing list−likes to .loc or [] with any missing labels \"\n1656 \"is no longer supported, see \"\n\nKeyError: 'Passing list−likes to .loc or [] with any missing labels is no longer supported, see https://pandas.pydata.org/pandas−docs/stable/user_guide/indexing.html#deprecate−loc−reindex−listlike'" }, { "code": null, "e": 7037, "s": 6967, "text": "One way to take care is by checking the values in the index directly." }, { "code": null, "e": 7084, "s": 7037, "text": "\"When is Avengers next movie?\" in movies.index" }, { "code": null, "e": 7155, "s": 7084, "text": "If you want to ignore the error and move on you can use below approach" }, { "code": null, "e": 7222, "s": 7155, "text": "movies.query(\"title in ('Avatar','When is Avengers next Movie?')\")" } ]
Correlated Variables in Monte Carlo Simulations | by Bassel Karami | Towards Data Science
Table of contents: Introduction Problem Statement Data preparation Wrong method 1 — Independent simulation (parametric) Wrong method 2 — Independent simulation (non-parametric) Method 1 — Multivariate distribution Method 2— Copulas with marginal distributions Method 3— Simulating historical combinations of sales growth Method 4— Decorrelating store sales growth using PCA Monte Carlo simulation is a great forecasting tool for sales, asset returns, project ROI, and more. In a previous article, I provide a practical introduction of how monte Carlo simulations can be used in a business setting to predict a range of possible business outcomes and their associated probabilities. In this article, we will tackle the challenge of correlated variables in Monte Carlo simulations. We will look into 4 appropriate approaches for handling the correlation. In our sample dataset, 20 years ago, annual chocolate ice cream sales were $5 million, vanilla sales were $4 million. Demand for chocolate ice cream was 25% greater than that of vanilla. Demand for both chocolate and vanilla has grown over the previous 20 years, but the gap between chocolate and vanilla sales has narrowed. In the last year, chocolate ice cream sales were $12.6 million, vanilla sales were $11.9 million. Demand for chocolate is now only 6% greater than vanilla. NOTE — Chocolate and vanilla ice cream sales are positively correlated to each other, i.e. chocolate ice cream sales and vanilla ice cream sales tend to increase together and decrease together. Question: Can next year be the year where vanilla ice cream sales exceed chocolate ice cream sales? Solution: We can run a Monte Carlo simulation to answer our question. It would be WRONG to simulate chocolate and vanilla ice cream sales independently. We first configure sample starting sales figures for chocolate and vanilla ice cream sales. The chosen figures are $5 million and $4 million respectively. We assume most people have a slight preference for chocolate ice cream. START_CHOC = 5START_VAN = 4 We then want to draw 20 random annual sales growth rates, assuming that growth rates for vanilla and chocolate ice cream sales follow a multivariate normal distribution. This is an extension of the normal distribution where we assume that the growth rates in sales for both ice cream flavors follow normal distributions, but there is a relationship between the two normal distributions. We assume the mean growth rate for both flavors is 5%, with a standard deviation of 10%, and the correlation between the growth rates of both flavors is 0.9. # Config for multivariate normal distributionCORR = 0.9MU = 1.05SIGMA = 0.1 Below is the code to generate the growth rates and annual sales that are produced. # Generate sales and growth rates for 20 periods# using a multivariate normal distributioncov_matrix = [[(SIGMA**2), CORR*(SIGMA**2)], [CORR*(SIGMA**2), (SIGMA**2)]]distribution = ss.multivariate_normal( mean=[MU, MU], cov=cov_matrix)sample_data = distribution.rvs(20, random_state=5)chocolate_growth = sample_data[:, 0]vanilla_growth = sample_data[:, 1]chocolate_sales = np.cumprod([START_CHOC] + list(chocolate_growth))vanilla_sales = np.cumprod([START_VAN] + list(vanilla_growth))# Prepare dataframesgrowth_df = pd.DataFrame(data={ "Growth Rate - Chocolate": chocolate_growth, "Growth Rate - Vanilla": vanilla_growth})sales_df = pd.DataFrame(data={ "Sales Chocolate (USD mln)": chocolate_sales, "Sales Vanilla (USD mln)": vanilla_sales})df = pd.concat([growth_df, sales_df], axis=1)df First, we will run a Monte Carlo simulation where we look into the statistical distributions of vanilla and chocolate sales, but treat both distributions as independent variables. This is a wrong approach since vanilla and chocolate ice cream sales are correlated to each other. We know the parameters of the distribution since we have created the dataset assuming the growth rates in sales for both chocolate and vanilla follows a normal distribution with mean 1.05 (5% growth on average) and standard deviation 0.1 (10%). See previous section. However, let’s assume we didn’t know the parameters in order to replicate the challenges we would face in a real-life situation. We would have to estimate the parameters using historical data. # Estimate meansmean_choc = np.mean(df["Growth Rate - Chocolate"])print(f"Mean (Chocolate): {mean_choc}")mean_van = np.mean(df["Growth Rate - Vanilla"])print(f"Mean (Vanilla): {mean_van}")# Estimate standard deviationsstd_choc = np.std(df["Growth Rate - Chocolate"], ddof=1)print(f"StDev (Chocolate): {std_choc}")std_van = np.std(df["Growth Rate - Vanilla"], ddof=1)print(f"StDev (Vanilla): {std_van}")# Define normal distributionsdistribution_choc = ss.norm(mean_choc, std_choc)distribution_van = ss.norm(mean_van, std_van) Next, we simulate 1000 sample growth rates for each of chocolate and vanilla ice cream sales. growth_vanilla = distribution_choc.rvs(1000, random_state=1)growth_chocolate = distribution_van.rvs(1000, random_state=2) Now let’s prepare a function we can use to check if vanilla sales would exceed chocolate sales given those growth rates. def exceed_check(growth_vanilla, growth_chocolate): '''This function takes sample growth rates for vanilla and chocolate ice cream sales and checks if vanilla ice cream sales would exceed chocolate given the combination of growth rates. Args: growth_vanilla (list): growth rates for vanilla sales growth_chocolate (list): growth rates for chocolate sales Returns: flags_list (list): A list of True/False flags indicating whether vanilla sales exceeds chocolate sales for the given combination of growth rates mean_pass_rate: Mean value of flags_list indicating the probability vanilla sales exceeds chocolates given the combination of growth rates ''' # Last year's chocolate and vanilla ice cream sales # set as constants to improve performance FINAL_CHOCOLATE = 12.59 FINAL_VANILLA = 11.94 flags_list = [v*FINAL_VANILLA > c*FINAL_CHOCOLATE for v,c in zip(growth_vanilla, growth_chocolate)] mean_pass_rate = np.mean(flags_list) return flags_list, mean_pass_rate Finally, let’s check the probability of vanilla sales exceeding chocolate... exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 34.1% In the second wrong approach, we simulate sales growth rates for chocolate and vanilla independently, but we do not assume any statistical distribution. We draw sample growth rates from history. growth_vanilla = df["Growth Rate - Vanilla"].dropna( ).sample(1000, replace=True, random_state=1)growth_chocolate = df["Growth Rate - Chocolate"].dropna( ).sample(1000, replace=True, random_state=2) Now we check for the probability of vanilla sales exceeding chocolate... exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 35.9% So far, both wrong approaches where we treat chocolate and vanilla sales independently give us a probability between 34% and 36%... there is a good chance next year will be the year for vanilla ice cream fans after all... The first appropriate approach we will use to check if vanilla sales may exceed chocolate sales is to estimate the multivariate distribution that represents data and to draw potential growth rates from that sample. A multivariate distribution models the combined distribution of multiple variable. Correlations are captured. Remember we actually generated the data from a multivariate normal distribution with means of 1.05 for both chocolate and vanilla, standard deviations of 0.1, and a correlation of 0.9. Here though we will assume we dont know the parameters and we’ll use the historical data to estimate the distribution parameters as we did in the independent parametric simulation (“Wrong method 1” section). We have already estimated the means and standard deviations in the aforementioned sections, but we still need to estimate the correlation between chocolate and vanilla ice cream sales. corr = df.corr().iloc[0, 1]corr We can now draw 1000 sample growth rates from the multivariate normal distribution... # We need to recalculate the covariance matrix# using the estimated paramaterscov_matrix = [[std_choc**2, corr*std_choc*std_van], [corr*std_choc*std_van, std_van**2]]growth_rates = ss.multivariate_normal( mean=[mean_choc, mean_van], cov=cov_matrix).rvs(1000, random_state=1)growth_chocolate = growth_rates[:, 0]growth_vanilla = growth_rates[:, 1] Finally, we calculate the probability of vanilla sales exceeding chocolate... exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 11.3%! Notice how the probability is now much lower after we have taken the correlation between chocolate and vanilla ice cream sales into consideration. Looks like chocolate may remain the dominant flavor after all... In the previous section, we looked at a multivariate normal distribution. Both chocolate and vanilla ice cream sales followed a normal distribution each and they are correlated. This made it easy to represent them in a multivariate normal distribution. Sometimes we may have 2 or more variables that come from different statistical distributions and there is no known multivariate distribution that can explain their combined distribution. If we do know the individual (marginal) distributions of the variables + we know the correlations between them, then copulas can help. A detailed explanation of copulas is out of scope, but simply put... Suppose the lowest possible value a variable can have is 0 and the highest is 1. Copulas generate a combination of values in this range such that the relationship implied by the correlation between the variables is maintained. Since our variables are chocolate and vanilla ice cream sales and they are positively correlated, copulas will draw values for growth in chocolate ice cream sales closer to 1 (highest value) when vanilla also has a high value and vice verse. There are existing libraries that can be installed to utilize copulas, but below we’ll use a hack to construct a copula (a Gaussian one) from scratch and it might help to understand the process better. First, we need to recalculate the correlation between our 2 variables, chocolate and vanilla sales growth, because copulas are based on rank correlation. In the previous section we calculated the Pearson Correlation Coefficient, but now we will use Kendall’s Tau which is a measure of rank correlation. Rank correlation is based on calculating the correlation between the ranks of the values rather than the values themselves. corr = ss.kendalltau( df.dropna().iloc[:, 0], df.dropna().iloc[:, 1])[0]corr Now we can construct our copula... # We set variances to 1 because the covariance matrix we # are constructing will be used with a multivariate normal # distribution of means 0 and std 1 to derive a copulacov_matrix = [[1, corr], [corr, 1]]# We will draw 1000 combinations from the distributionrandom_vals = ss.multivariate_normal(cov=cov).rvs( 1000, random_state=1)# Finally a cumulative density function for a distribution# ranges between 0 to 1 so it will be used to convert the# drawn samples to the values we need for our copulacopula = ss.norm.cdf(random_vals)print(copula.shape)copula We can see the copula has 1000 correlated entries across 2 variables and they range from 0 to 1. Below is a scatter plot of the correlated copula values for our 2 variables. sns.scatterplot(x=copula[:, 0], y=copula[:, 1]) The copula values between 0 and 1 capture the correlation between the variables, so now we just have to convert the 0–1 values to the actual values we want to use for the sales growth rates of chocolate and vanilla ice cream. We use percent point functions for the distributions of each variable to the conversion. We have already estimated the distributions in the independent parametric simulation section (“Wrong method 1”). The difference is that we now don’t just randomly draw values from each distribution, instead, we use the copula values and percent point functions to draw correlated random values from each distribution. # distribution_choc and distribution_van area already# calculated in previous sectionsgrowth_chocolate = distribution_choc.ppf(copula[:, 0])growth_vanilla = distribution_van.ppf(copula[:, 1]) Finally, let’s pass those growth rates to our function to check the likelihood of vanilla sales exceeding chocolate... exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 11.1% The probability of 11% is similar to the probability from the previous section and confirms that we have grossly overestimated the probability in the 2 wrong approaches we applied at first. There are several steps in this approach and probably a more thorough explanation of different concepts is needed. The one thing to keep in mind though is that the values between 0 and 1 that we generated using our copula can be used with any combination of statistical distributions. Our example is easy where both variables’ distributions are normal, so the approach in the previous section (multivariate normal distribution) is sufficient and actually should yield the same results as this section. But imagine a different scenario where variable A is normally distribution, variable B is binomial etc. In such cases, copulas would be needed. A hypothetical scenario would be forecasting movie ticket sales and popcorn sales where we model the number of cinema visitors as a Poisson distribution and then we model the popcorn sales using a Binomial distribution where every cinema visitor who bought a ticket has a certain probability of buying popcorn. This is a simple approach similar to the independent non-parametric simulation (section “Wrong method 2”), where we don’t estimate any statistical distributions and we directly draw samples from history. The correction we apply is that we don’t independently take historical growth rates for chocolate and vanilla sales from different points of history. Instead we randomly take a point in history and we take both growth rates from that same point in history. We then draw another point in history and do the same until we get to number of rounds of simulation we want to run. We replay history and take growth rates for both flavors from Year 5 in the first round of simulations, for example, then Year 11 for the 2nd round etc. In the independent approach in the section “Wrong method 2”, we could take the growth rate for vanilla from Year 5, for example, and the growth rate for chocolate from Year 11 in the same round of simulation. We were replaying the history of chocolate and vanilla ice cream sales independently of one another. resampled_history = df[["Growth Rate - Chocolate", "Growth Rate - Vanilla"]].dropna( ).sample(1000, replace=True, random_state=1)growth_chocolate = resampled_history["Growth Rate - Chocolate"]growth_vanilla = resampled_history["Growth Rate - Vanilla"]exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 21% This probability is higher than the expected ~11% derived from the last 2 appropriate methods but lower than the ~35% implied by the wrong simulation approaches. This method relies on having sufficient history and is normally more suitable for financial data, for example, where we have many historical data points. In our example, we only have 20 years of data representing 20 combinations of historical growth rates for chocolate and vanilla ice cream sales. This is a small number and we would be giving too much weight for a few points that happened in the past. In the previous method, the challenge in our approach is that we were resampling from only 20 data points because we had 20 combinations of historical vanilla and chocolate ice cream sales growth. In the independent non-parametric simulation (“Wrong method 2” section), the approach was wrong because we treated vanilla and chocolate sales growth rates as independent. This allowed us though to have 400 (20 x 20) historical data points to resample from since we could combine any of the 20 historical sales growth rates for chocolate with any of the 20 historical growth rates of vanilla. We were are able to combine the growth rate of chocolate in Year 1 with vanilla in Year 2... in method 3, we couldn’t. In this final method, we follow a very similar approach where we do not estimate any statistical distributions and we replay historical growth rates. The cornenrstone of this method is that we first decorrelate the growth rates of ice cream sales of both flavors. This approach will allow us to combine components of historical growth rates of chocolates from a certain year with those of vanilla from a different year since we eliminated the correlation that we have to control for. We end up with more data points to resample from. Step 1 is to use a decorrelation method. We use PCA in this example which I assume you are familiar with. The Choletsky decomposition is also a popular alternative used in finance. Note that PCA is commonly used in data science for dimensionality reduction but what we are really interested in is the fact that PCA components are decorrelated. In our case, we are not looking to reduce dimensions so we will pass in two variables (sales growth rates for chocolate and vanilla) and we will obtain two decorrelated components. Since these principal components are decorrelated, we can mix and match the components from different points in history and get 400 combinations of chocolate and vanilla sales growth rates that we can resample from. pca = PCA(n_components=2)# Normalize chocolate and vanilla growth rates to apply PCAnormalized_chocolate = ( df["Growth Rate - Chocolate"].dropna() - mean_choc) / std_chocnormalized_vanilla = ( df["Growth Rate - Vanilla"].dropna() - mean_van) / std_van# Apply PCA transformation on normalized valuescomponents = pca.fit_transform( np.array([normalized_chocolate, normalized_vanilla]).T)components We next run 1000 simulations where we sample from the components array. np.random.seed(1)sampled_components = [[x[0], x[1]] for x in zip( # Sampling 1000 entries from first PCA component np.random.choice(components[:, 0], 1000), # 2nd PCA component np.random.choice(components[:, 1], 1000))] Next step is to convert the sampled component values into growth rates by inversing the transformations (normalization and PCA) we have done. inverse_pca = pca.inverse_transform(sampled_components)# Denormalizinggrowth_chocolate = [(x * std_choc) + mean_choc for x in inverse_pca[:, 0]]growth_vanilla = [(x * std_van) + mean_van for x in inverse_pca[:, 1]] Finally... exceed_check(growth_vanilla, growth_chocolate)[1] Probability: 17.1% which is closer to the 11% we are expecting based on methods 1 and 2. Below are the probabilities we have generated for vanilla ice cream sales overtaking chocolate. We used 2 wrong approaches and 4 appropriate ones. The 2 wrong methods, which run the Monte Carlo simulations assuming vanilla and chocolate ice cream sales are independent, grossly overestimate the probability vanilla sales could overtake chocolate next year. Since the sales for both flavors are assumed to be independent, there is an unrealistically high probability assumed where vanilla sales will see a much higher than normal growth rate while chocolate sees a much lower than usual growth rate. Reality indicates that the sales for both flavors are positively correlated to each other, so in most cases, growth is high for both flavors or low for both flavors with a slight variation in performance. Methods 1 and 2, which imply a 11% probability vanilla overtakes chocolate, are the most accurate. That is because the actual data was derived from a multivariate normal distribution. However, the choice of best method to use depends on the dataset at hand. Methods 1 and 2 require that the underlying statistical distribution can be estimated fairly accurately. Methods 3 and 4 rely on having a sufficiently large dataset. The most important takeaway is to not ignore correlations in Monte Carlo simulations.
[ { "code": null, "e": 191, "s": 172, "text": "Table of contents:" }, { "code": null, "e": 204, "s": 191, "text": "Introduction" }, { "code": null, "e": 222, "s": 204, "text": "Problem Statement" }, { "code": null, "e": 239, "s": 222, "text": "Data preparation" }, { "code": null, "e": 292, "s": 239, "text": "Wrong method 1 — Independent simulation (parametric)" }, { "code": null, "e": 349, "s": 292, "text": "Wrong method 2 — Independent simulation (non-parametric)" }, { "code": null, "e": 386, "s": 349, "text": "Method 1 — Multivariate distribution" }, { "code": null, "e": 432, "s": 386, "text": "Method 2— Copulas with marginal distributions" }, { "code": null, "e": 493, "s": 432, "text": "Method 3— Simulating historical combinations of sales growth" }, { "code": null, "e": 546, "s": 493, "text": "Method 4— Decorrelating store sales growth using PCA" }, { "code": null, "e": 646, "s": 546, "text": "Monte Carlo simulation is a great forecasting tool for sales, asset returns, project ROI, and more." }, { "code": null, "e": 854, "s": 646, "text": "In a previous article, I provide a practical introduction of how monte Carlo simulations can be used in a business setting to predict a range of possible business outcomes and their associated probabilities." }, { "code": null, "e": 1025, "s": 854, "text": "In this article, we will tackle the challenge of correlated variables in Monte Carlo simulations. We will look into 4 appropriate approaches for handling the correlation." }, { "code": null, "e": 1212, "s": 1025, "text": "In our sample dataset, 20 years ago, annual chocolate ice cream sales were $5 million, vanilla sales were $4 million. Demand for chocolate ice cream was 25% greater than that of vanilla." }, { "code": null, "e": 1506, "s": 1212, "text": "Demand for both chocolate and vanilla has grown over the previous 20 years, but the gap between chocolate and vanilla sales has narrowed. In the last year, chocolate ice cream sales were $12.6 million, vanilla sales were $11.9 million. Demand for chocolate is now only 6% greater than vanilla." }, { "code": null, "e": 1700, "s": 1506, "text": "NOTE — Chocolate and vanilla ice cream sales are positively correlated to each other, i.e. chocolate ice cream sales and vanilla ice cream sales tend to increase together and decrease together." }, { "code": null, "e": 1800, "s": 1700, "text": "Question: Can next year be the year where vanilla ice cream sales exceed chocolate ice cream sales?" }, { "code": null, "e": 1870, "s": 1800, "text": "Solution: We can run a Monte Carlo simulation to answer our question." }, { "code": null, "e": 1953, "s": 1870, "text": "It would be WRONG to simulate chocolate and vanilla ice cream sales independently." }, { "code": null, "e": 2180, "s": 1953, "text": "We first configure sample starting sales figures for chocolate and vanilla ice cream sales. The chosen figures are $5 million and $4 million respectively. We assume most people have a slight preference for chocolate ice cream." }, { "code": null, "e": 2208, "s": 2180, "text": "START_CHOC = 5START_VAN = 4" }, { "code": null, "e": 2595, "s": 2208, "text": "We then want to draw 20 random annual sales growth rates, assuming that growth rates for vanilla and chocolate ice cream sales follow a multivariate normal distribution. This is an extension of the normal distribution where we assume that the growth rates in sales for both ice cream flavors follow normal distributions, but there is a relationship between the two normal distributions." }, { "code": null, "e": 2753, "s": 2595, "text": "We assume the mean growth rate for both flavors is 5%, with a standard deviation of 10%, and the correlation between the growth rates of both flavors is 0.9." }, { "code": null, "e": 2829, "s": 2753, "text": "# Config for multivariate normal distributionCORR = 0.9MU = 1.05SIGMA = 0.1" }, { "code": null, "e": 2912, "s": 2829, "text": "Below is the code to generate the growth rates and annual sales that are produced." }, { "code": null, "e": 3729, "s": 2912, "text": "# Generate sales and growth rates for 20 periods# using a multivariate normal distributioncov_matrix = [[(SIGMA**2), CORR*(SIGMA**2)], [CORR*(SIGMA**2), (SIGMA**2)]]distribution = ss.multivariate_normal( mean=[MU, MU], cov=cov_matrix)sample_data = distribution.rvs(20, random_state=5)chocolate_growth = sample_data[:, 0]vanilla_growth = sample_data[:, 1]chocolate_sales = np.cumprod([START_CHOC] + list(chocolate_growth))vanilla_sales = np.cumprod([START_VAN] + list(vanilla_growth))# Prepare dataframesgrowth_df = pd.DataFrame(data={ \"Growth Rate - Chocolate\": chocolate_growth, \"Growth Rate - Vanilla\": vanilla_growth})sales_df = pd.DataFrame(data={ \"Sales Chocolate (USD mln)\": chocolate_sales, \"Sales Vanilla (USD mln)\": vanilla_sales})df = pd.concat([growth_df, sales_df], axis=1)df" }, { "code": null, "e": 4008, "s": 3729, "text": "First, we will run a Monte Carlo simulation where we look into the statistical distributions of vanilla and chocolate sales, but treat both distributions as independent variables. This is a wrong approach since vanilla and chocolate ice cream sales are correlated to each other." }, { "code": null, "e": 4275, "s": 4008, "text": "We know the parameters of the distribution since we have created the dataset assuming the growth rates in sales for both chocolate and vanilla follows a normal distribution with mean 1.05 (5% growth on average) and standard deviation 0.1 (10%). See previous section." }, { "code": null, "e": 4468, "s": 4275, "text": "However, let’s assume we didn’t know the parameters in order to replicate the challenges we would face in a real-life situation. We would have to estimate the parameters using historical data." }, { "code": null, "e": 5024, "s": 4468, "text": "# Estimate meansmean_choc = np.mean(df[\"Growth Rate - Chocolate\"])print(f\"Mean (Chocolate): {mean_choc}\")mean_van = np.mean(df[\"Growth Rate - Vanilla\"])print(f\"Mean (Vanilla): {mean_van}\")# Estimate standard deviationsstd_choc = np.std(df[\"Growth Rate - Chocolate\"], ddof=1)print(f\"StDev (Chocolate): {std_choc}\")std_van = np.std(df[\"Growth Rate - Vanilla\"], ddof=1)print(f\"StDev (Vanilla): {std_van}\")# Define normal distributionsdistribution_choc = ss.norm(mean_choc, std_choc)distribution_van = ss.norm(mean_van, std_van)" }, { "code": null, "e": 5118, "s": 5024, "text": "Next, we simulate 1000 sample growth rates for each of chocolate and vanilla ice cream sales." }, { "code": null, "e": 5248, "s": 5118, "text": "growth_vanilla = distribution_choc.rvs(1000, random_state=1)growth_chocolate = distribution_van.rvs(1000, random_state=2)" }, { "code": null, "e": 5369, "s": 5248, "text": "Now let’s prepare a function we can use to check if vanilla sales would exceed chocolate sales given those growth rates." }, { "code": null, "e": 6444, "s": 5369, "text": "def exceed_check(growth_vanilla, growth_chocolate): '''This function takes sample growth rates for vanilla and chocolate ice cream sales and checks if vanilla ice cream sales would exceed chocolate given the combination of growth rates. Args: growth_vanilla (list): growth rates for vanilla sales growth_chocolate (list): growth rates for chocolate sales Returns: flags_list (list): A list of True/False flags indicating whether vanilla sales exceeds chocolate sales for the given combination of growth rates mean_pass_rate: Mean value of flags_list indicating the probability vanilla sales exceeds chocolates given the combination of growth rates ''' # Last year's chocolate and vanilla ice cream sales # set as constants to improve performance FINAL_CHOCOLATE = 12.59 FINAL_VANILLA = 11.94 flags_list = [v*FINAL_VANILLA > c*FINAL_CHOCOLATE for v,c in zip(growth_vanilla, growth_chocolate)] mean_pass_rate = np.mean(flags_list) return flags_list, mean_pass_rate" }, { "code": null, "e": 6521, "s": 6444, "text": "Finally, let’s check the probability of vanilla sales exceeding chocolate..." }, { "code": null, "e": 6571, "s": 6521, "text": "exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 6590, "s": 6571, "text": "Probability: 34.1%" }, { "code": null, "e": 6785, "s": 6590, "text": "In the second wrong approach, we simulate sales growth rates for chocolate and vanilla independently, but we do not assume any statistical distribution. We draw sample growth rates from history." }, { "code": null, "e": 6990, "s": 6785, "text": "growth_vanilla = df[\"Growth Rate - Vanilla\"].dropna( ).sample(1000, replace=True, random_state=1)growth_chocolate = df[\"Growth Rate - Chocolate\"].dropna( ).sample(1000, replace=True, random_state=2)" }, { "code": null, "e": 7063, "s": 6990, "text": "Now we check for the probability of vanilla sales exceeding chocolate..." }, { "code": null, "e": 7113, "s": 7063, "text": "exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 7132, "s": 7113, "text": "Probability: 35.9%" }, { "code": null, "e": 7354, "s": 7132, "text": "So far, both wrong approaches where we treat chocolate and vanilla sales independently give us a probability between 34% and 36%... there is a good chance next year will be the year for vanilla ice cream fans after all..." }, { "code": null, "e": 7679, "s": 7354, "text": "The first appropriate approach we will use to check if vanilla sales may exceed chocolate sales is to estimate the multivariate distribution that represents data and to draw potential growth rates from that sample. A multivariate distribution models the combined distribution of multiple variable. Correlations are captured." }, { "code": null, "e": 8072, "s": 7679, "text": "Remember we actually generated the data from a multivariate normal distribution with means of 1.05 for both chocolate and vanilla, standard deviations of 0.1, and a correlation of 0.9. Here though we will assume we dont know the parameters and we’ll use the historical data to estimate the distribution parameters as we did in the independent parametric simulation (“Wrong method 1” section)." }, { "code": null, "e": 8257, "s": 8072, "text": "We have already estimated the means and standard deviations in the aforementioned sections, but we still need to estimate the correlation between chocolate and vanilla ice cream sales." }, { "code": null, "e": 8289, "s": 8257, "text": "corr = df.corr().iloc[0, 1]corr" }, { "code": null, "e": 8375, "s": 8289, "text": "We can now draw 1000 sample growth rates from the multivariate normal distribution..." }, { "code": null, "e": 8742, "s": 8375, "text": "# We need to recalculate the covariance matrix# using the estimated paramaterscov_matrix = [[std_choc**2, corr*std_choc*std_van], [corr*std_choc*std_van, std_van**2]]growth_rates = ss.multivariate_normal( mean=[mean_choc, mean_van], cov=cov_matrix).rvs(1000, random_state=1)growth_chocolate = growth_rates[:, 0]growth_vanilla = growth_rates[:, 1]" }, { "code": null, "e": 8820, "s": 8742, "text": "Finally, we calculate the probability of vanilla sales exceeding chocolate..." }, { "code": null, "e": 8870, "s": 8820, "text": "exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 9037, "s": 8870, "text": "Probability: 11.3%! Notice how the probability is now much lower after we have taken the correlation between chocolate and vanilla ice cream sales into consideration." }, { "code": null, "e": 9102, "s": 9037, "text": "Looks like chocolate may remain the dominant flavor after all..." }, { "code": null, "e": 9355, "s": 9102, "text": "In the previous section, we looked at a multivariate normal distribution. Both chocolate and vanilla ice cream sales followed a normal distribution each and they are correlated. This made it easy to represent them in a multivariate normal distribution." }, { "code": null, "e": 9677, "s": 9355, "text": "Sometimes we may have 2 or more variables that come from different statistical distributions and there is no known multivariate distribution that can explain their combined distribution. If we do know the individual (marginal) distributions of the variables + we know the correlations between them, then copulas can help." }, { "code": null, "e": 9746, "s": 9677, "text": "A detailed explanation of copulas is out of scope, but simply put..." }, { "code": null, "e": 10215, "s": 9746, "text": "Suppose the lowest possible value a variable can have is 0 and the highest is 1. Copulas generate a combination of values in this range such that the relationship implied by the correlation between the variables is maintained. Since our variables are chocolate and vanilla ice cream sales and they are positively correlated, copulas will draw values for growth in chocolate ice cream sales closer to 1 (highest value) when vanilla also has a high value and vice verse." }, { "code": null, "e": 10417, "s": 10215, "text": "There are existing libraries that can be installed to utilize copulas, but below we’ll use a hack to construct a copula (a Gaussian one) from scratch and it might help to understand the process better." }, { "code": null, "e": 10844, "s": 10417, "text": "First, we need to recalculate the correlation between our 2 variables, chocolate and vanilla sales growth, because copulas are based on rank correlation. In the previous section we calculated the Pearson Correlation Coefficient, but now we will use Kendall’s Tau which is a measure of rank correlation. Rank correlation is based on calculating the correlation between the ranks of the values rather than the values themselves." }, { "code": null, "e": 10924, "s": 10844, "text": "corr = ss.kendalltau( df.dropna().iloc[:, 0], df.dropna().iloc[:, 1])[0]corr" }, { "code": null, "e": 10959, "s": 10924, "text": "Now we can construct our copula..." }, { "code": null, "e": 11533, "s": 10959, "text": "# We set variances to 1 because the covariance matrix we # are constructing will be used with a multivariate normal # distribution of means 0 and std 1 to derive a copulacov_matrix = [[1, corr], [corr, 1]]# We will draw 1000 combinations from the distributionrandom_vals = ss.multivariate_normal(cov=cov).rvs( 1000, random_state=1)# Finally a cumulative density function for a distribution# ranges between 0 to 1 so it will be used to convert the# drawn samples to the values we need for our copulacopula = ss.norm.cdf(random_vals)print(copula.shape)copula" }, { "code": null, "e": 11630, "s": 11533, "text": "We can see the copula has 1000 correlated entries across 2 variables and they range from 0 to 1." }, { "code": null, "e": 11707, "s": 11630, "text": "Below is a scatter plot of the correlated copula values for our 2 variables." }, { "code": null, "e": 11755, "s": 11707, "text": "sns.scatterplot(x=copula[:, 0], y=copula[:, 1])" }, { "code": null, "e": 11981, "s": 11755, "text": "The copula values between 0 and 1 capture the correlation between the variables, so now we just have to convert the 0–1 values to the actual values we want to use for the sales growth rates of chocolate and vanilla ice cream." }, { "code": null, "e": 12388, "s": 11981, "text": "We use percent point functions for the distributions of each variable to the conversion. We have already estimated the distributions in the independent parametric simulation section (“Wrong method 1”). The difference is that we now don’t just randomly draw values from each distribution, instead, we use the copula values and percent point functions to draw correlated random values from each distribution." }, { "code": null, "e": 12580, "s": 12388, "text": "# distribution_choc and distribution_van area already# calculated in previous sectionsgrowth_chocolate = distribution_choc.ppf(copula[:, 0])growth_vanilla = distribution_van.ppf(copula[:, 1])" }, { "code": null, "e": 12699, "s": 12580, "text": "Finally, let’s pass those growth rates to our function to check the likelihood of vanilla sales exceeding chocolate..." }, { "code": null, "e": 12749, "s": 12699, "text": "exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 12768, "s": 12749, "text": "Probability: 11.1%" }, { "code": null, "e": 12958, "s": 12768, "text": "The probability of 11% is similar to the probability from the previous section and confirms that we have grossly overestimated the probability in the 2 wrong approaches we applied at first." }, { "code": null, "e": 13243, "s": 12958, "text": "There are several steps in this approach and probably a more thorough explanation of different concepts is needed. The one thing to keep in mind though is that the values between 0 and 1 that we generated using our copula can be used with any combination of statistical distributions." }, { "code": null, "e": 13604, "s": 13243, "text": "Our example is easy where both variables’ distributions are normal, so the approach in the previous section (multivariate normal distribution) is sufficient and actually should yield the same results as this section. But imagine a different scenario where variable A is normally distribution, variable B is binomial etc. In such cases, copulas would be needed." }, { "code": null, "e": 13915, "s": 13604, "text": "A hypothetical scenario would be forecasting movie ticket sales and popcorn sales where we model the number of cinema visitors as a Poisson distribution and then we model the popcorn sales using a Binomial distribution where every cinema visitor who bought a ticket has a certain probability of buying popcorn." }, { "code": null, "e": 14119, "s": 13915, "text": "This is a simple approach similar to the independent non-parametric simulation (section “Wrong method 2”), where we don’t estimate any statistical distributions and we directly draw samples from history." }, { "code": null, "e": 14493, "s": 14119, "text": "The correction we apply is that we don’t independently take historical growth rates for chocolate and vanilla sales from different points of history. Instead we randomly take a point in history and we take both growth rates from that same point in history. We then draw another point in history and do the same until we get to number of rounds of simulation we want to run." }, { "code": null, "e": 14646, "s": 14493, "text": "We replay history and take growth rates for both flavors from Year 5 in the first round of simulations, for example, then Year 11 for the 2nd round etc." }, { "code": null, "e": 14956, "s": 14646, "text": "In the independent approach in the section “Wrong method 2”, we could take the growth rate for vanilla from Year 5, for example, and the growth rate for chocolate from Year 11 in the same round of simulation. We were replaying the history of chocolate and vanilla ice cream sales independently of one another." }, { "code": null, "e": 15264, "s": 14956, "text": "resampled_history = df[[\"Growth Rate - Chocolate\", \"Growth Rate - Vanilla\"]].dropna( ).sample(1000, replace=True, random_state=1)growth_chocolate = resampled_history[\"Growth Rate - Chocolate\"]growth_vanilla = resampled_history[\"Growth Rate - Vanilla\"]exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 15443, "s": 15264, "text": "Probability: 21% This probability is higher than the expected ~11% derived from the last 2 appropriate methods but lower than the ~35% implied by the wrong simulation approaches." }, { "code": null, "e": 15597, "s": 15443, "text": "This method relies on having sufficient history and is normally more suitable for financial data, for example, where we have many historical data points." }, { "code": null, "e": 15848, "s": 15597, "text": "In our example, we only have 20 years of data representing 20 combinations of historical growth rates for chocolate and vanilla ice cream sales. This is a small number and we would be giving too much weight for a few points that happened in the past." }, { "code": null, "e": 16045, "s": 15848, "text": "In the previous method, the challenge in our approach is that we were resampling from only 20 data points because we had 20 combinations of historical vanilla and chocolate ice cream sales growth." }, { "code": null, "e": 16557, "s": 16045, "text": "In the independent non-parametric simulation (“Wrong method 2” section), the approach was wrong because we treated vanilla and chocolate sales growth rates as independent. This allowed us though to have 400 (20 x 20) historical data points to resample from since we could combine any of the 20 historical sales growth rates for chocolate with any of the 20 historical growth rates of vanilla. We were are able to combine the growth rate of chocolate in Year 1 with vanilla in Year 2... in method 3, we couldn’t." }, { "code": null, "e": 16707, "s": 16557, "text": "In this final method, we follow a very similar approach where we do not estimate any statistical distributions and we replay historical growth rates." }, { "code": null, "e": 17091, "s": 16707, "text": "The cornenrstone of this method is that we first decorrelate the growth rates of ice cream sales of both flavors. This approach will allow us to combine components of historical growth rates of chocolates from a certain year with those of vanilla from a different year since we eliminated the correlation that we have to control for. We end up with more data points to resample from." }, { "code": null, "e": 17272, "s": 17091, "text": "Step 1 is to use a decorrelation method. We use PCA in this example which I assume you are familiar with. The Choletsky decomposition is also a popular alternative used in finance." }, { "code": null, "e": 17832, "s": 17272, "text": "Note that PCA is commonly used in data science for dimensionality reduction but what we are really interested in is the fact that PCA components are decorrelated. In our case, we are not looking to reduce dimensions so we will pass in two variables (sales growth rates for chocolate and vanilla) and we will obtain two decorrelated components. Since these principal components are decorrelated, we can mix and match the components from different points in history and get 400 combinations of chocolate and vanilla sales growth rates that we can resample from." }, { "code": null, "e": 18242, "s": 17832, "text": "pca = PCA(n_components=2)# Normalize chocolate and vanilla growth rates to apply PCAnormalized_chocolate = ( df[\"Growth Rate - Chocolate\"].dropna() - mean_choc) / std_chocnormalized_vanilla = ( df[\"Growth Rate - Vanilla\"].dropna() - mean_van) / std_van# Apply PCA transformation on normalized valuescomponents = pca.fit_transform( np.array([normalized_chocolate, normalized_vanilla]).T)components" }, { "code": null, "e": 18314, "s": 18242, "text": "We next run 1000 simulations where we sample from the components array." }, { "code": null, "e": 18546, "s": 18314, "text": "np.random.seed(1)sampled_components = [[x[0], x[1]] for x in zip( # Sampling 1000 entries from first PCA component np.random.choice(components[:, 0], 1000), # 2nd PCA component np.random.choice(components[:, 1], 1000))]" }, { "code": null, "e": 18688, "s": 18546, "text": "Next step is to convert the sampled component values into growth rates by inversing the transformations (normalization and PCA) we have done." }, { "code": null, "e": 18911, "s": 18688, "text": "inverse_pca = pca.inverse_transform(sampled_components)# Denormalizinggrowth_chocolate = [(x * std_choc) + mean_choc for x in inverse_pca[:, 0]]growth_vanilla = [(x * std_van) + mean_van for x in inverse_pca[:, 1]]" }, { "code": null, "e": 18922, "s": 18911, "text": "Finally..." }, { "code": null, "e": 18972, "s": 18922, "text": "exceed_check(growth_vanilla, growth_chocolate)[1]" }, { "code": null, "e": 19061, "s": 18972, "text": "Probability: 17.1% which is closer to the 11% we are expecting based on methods 1 and 2." }, { "code": null, "e": 19208, "s": 19061, "text": "Below are the probabilities we have generated for vanilla ice cream sales overtaking chocolate. We used 2 wrong approaches and 4 appropriate ones." }, { "code": null, "e": 19418, "s": 19208, "text": "The 2 wrong methods, which run the Monte Carlo simulations assuming vanilla and chocolate ice cream sales are independent, grossly overestimate the probability vanilla sales could overtake chocolate next year." }, { "code": null, "e": 19865, "s": 19418, "text": "Since the sales for both flavors are assumed to be independent, there is an unrealistically high probability assumed where vanilla sales will see a much higher than normal growth rate while chocolate sees a much lower than usual growth rate. Reality indicates that the sales for both flavors are positively correlated to each other, so in most cases, growth is high for both flavors or low for both flavors with a slight variation in performance." }, { "code": null, "e": 20123, "s": 19865, "text": "Methods 1 and 2, which imply a 11% probability vanilla overtakes chocolate, are the most accurate. That is because the actual data was derived from a multivariate normal distribution. However, the choice of best method to use depends on the dataset at hand." }, { "code": null, "e": 20289, "s": 20123, "text": "Methods 1 and 2 require that the underlying statistical distribution can be estimated fairly accurately. Methods 3 and 4 rely on having a sufficiently large dataset." } ]
GATE | GATE-CS-2004 | Question 82 - GeeksforGeeks
04 Feb, 2019 Let A[1, ..., n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is θ(m). Consider the following program fragment written in a C like language: counter = 0;for (i = 1; i < = n; i++){ if (A[i] == 1) counter++; else { f(counter); counter = 0; }} The complexity of this program fragment is(A) Ω(n2)(B) Ω(nlog n) and O(n2)(C) θ(n)(D) O(n)Answer: (C)Explanation: Please note that inside the else condition, f() is called first, then counter is set to 0. Consider the following cases: a) All 1s in A[]: Time taken is Θ(n) as only counter++ is executed n times. b) All 0s in A[]: Time taken is Θ(n) as only f(0) is called n times c) Half 1s, then half 0s: Time taken is Θ(n) as only f(n/2) is called once. Quiz of this Question OnkarMarbhal GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | 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 GATE | GATE CS 2011 | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2012 | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n04 Feb, 2019" }, { "code": null, "e": 24269, "s": 24075, "text": "Let A[1, ..., n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is θ(m). Consider the following program fragment written in a C like language:" }, { "code": "counter = 0;for (i = 1; i < = n; i++){ if (A[i] == 1) counter++; else { f(counter); counter = 0; }}", "e": 24411, "s": 24269, "text": null }, { "code": null, "e": 24616, "s": 24411, "text": "The complexity of this program fragment is(A) Ω(n2)(B) Ω(nlog n) and O(n2)(C) θ(n)(D) O(n)Answer: (C)Explanation: Please note that inside the else condition, f() is called first, then counter is set to 0." }, { "code": null, "e": 24646, "s": 24616, "text": "Consider the following cases:" }, { "code": null, "e": 24923, "s": 24646, "text": "a) All 1s in A[]: Time taken is Θ(n) as\n only counter++ is executed n times.\n\nb) All 0s in A[]: Time taken is Θ(n) as\n only f(0) is called n times\n\nc) Half 1s, then half 0s: Time taken is Θ(n) as\n only f(n/2) is called once." }, { "code": null, "e": 24945, "s": 24923, "text": "Quiz of this Question" }, { "code": null, "e": 24958, "s": 24945, "text": "OnkarMarbhal" }, { "code": null, "e": 24971, "s": 24958, "text": "GATE-CS-2004" }, { "code": null, "e": 24989, "s": 24971, "text": "GATE-GATE-CS-2004" }, { "code": null, "e": 24994, "s": 24989, "text": "GATE" }, { "code": null, "e": 25092, "s": 24994, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25101, "s": 25092, "text": "Comments" }, { "code": null, "e": 25114, "s": 25101, "text": "Old Comments" }, { "code": null, "e": 25156, "s": 25114, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25198, "s": 25156, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25232, "s": 25198, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25274, "s": 25232, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25328, "s": 25274, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25361, "s": 25328, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25403, "s": 25361, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25437, "s": 25403, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 25479, "s": 25437, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
How can I create MySQL stored procedure with IN parameter?
To make it understand we are using the table named ‘student_info’ which have the following values − mysql> Select * from student_info; +-----+---------+------------+------------+ | id | Name | Address | Subject | +-----+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | | 125 | Raman | Shimla | Computers | +------+--------+------------+------------+ 4 rows in set (0.00 sec) Now, with the help of the following query, we will create a stored procedure with IN parameter which will show all the details of a particular student by providing the name as the parameter. mysql> DELIMITER // ; mysql> Create PROCEDURE detail(IN S_Name VARCHAR(20)) -> BEGIN -> SELECT * From Student_info WHERE Name = S_Name; -> END // Query OK, 0 rows affected (0.16 sec) mysql> DELIMITER ; S_Name is the IN parameter of the stored procedure ‘detail’. If we want to see all the details of the student name ‘Gaurav’ then it can be done with the help of the following query − mysql> CALL detail('Gaurav'); +-----+--------+---------+------------+ | id | Name | Address | Subject | +-----+--------+---------+------------+ | 105 | Gaurav | Jaipur | Literature | +-----+--------+---------+------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec) mysql> CALL detail('Raman'); +-----+-------+---------+-----------+ | id | Name | Address | Subject | +-----+-------+---------+-----------+ | 125 | Raman | Shimla | Computers | +-----+-------+---------+-----------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.01 sec)
[ { "code": null, "e": 1162, "s": 1062, "text": "To make it understand we are using the table named ‘student_info’ which have the following values −" }, { "code": null, "e": 1574, "s": 1162, "text": "mysql> Select * from student_info;\n+-----+---------+------------+------------+\n| id | Name | Address | Subject |\n+-----+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Shimla | Computers |\n+------+--------+------------+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1765, "s": 1574, "text": "Now, with the help of the following query, we will create a stored procedure with IN parameter which will show all the details of a particular student by providing the name as the parameter." }, { "code": null, "e": 1979, "s": 1765, "text": "mysql> DELIMITER // ;\nmysql> Create PROCEDURE detail(IN S_Name VARCHAR(20))\n -> BEGIN\n -> SELECT * From Student_info WHERE Name = S_Name;\n -> END //\nQuery OK, 0 rows affected (0.16 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 2162, "s": 1979, "text": "S_Name is the IN parameter of the stored procedure ‘detail’. If we want to see all the details of the student name ‘Gaurav’ then it can be done with the help of the following query −" }, { "code": null, "e": 2736, "s": 2162, "text": "mysql> CALL detail('Gaurav');\n+-----+--------+---------+------------+\n| id | Name | Address | Subject |\n+-----+--------+---------+------------+\n| 105 | Gaurav | Jaipur | Literature |\n+-----+--------+---------+------------+\n1 row in set (0.00 sec)\n\nQuery OK, 0 rows affected (0.01 sec)\n\nmysql> CALL detail('Raman');\n+-----+-------+---------+-----------+\n| id | Name | Address | Subject |\n+-----+-------+---------+-----------+\n| 125 | Raman | Shimla | Computers |\n+-----+-------+---------+-----------+\n1 row in set (0.00 sec)\n\nQuery OK, 0 rows affected (0.01 sec)" } ]
C++ Vector Library - pop_back() Function
The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one. Following is the declaration for std::vector::pop_back() function form std::vector header. void pop_back(); None None This member function never throws exception. Calling this function on empty vector causes undefined behavior. Constant i.e. O(1) The following example shows the usage of std::vector::pop_back() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v = {1, 2, 3, 4, 5}; /* Remove last three elements */ v.pop_back(); v.pop_back(); v.pop_back(); for (int i = 0; i < v.size(); ++i) cout << v[i] << endl; return 0; } Let us compile and run the above program, this will produce the following result − 1 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2712, "s": 2603, "text": "The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one." }, { "code": null, "e": 2803, "s": 2712, "text": "Following is the declaration for std::vector::pop_back() function form std::vector header." }, { "code": null, "e": 2821, "s": 2803, "text": "void pop_back();\n" }, { "code": null, "e": 2826, "s": 2821, "text": "None" }, { "code": null, "e": 2831, "s": 2826, "text": "None" }, { "code": null, "e": 2941, "s": 2831, "text": "This member function never throws exception. Calling this function on empty vector causes undefined behavior." }, { "code": null, "e": 2960, "s": 2941, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3035, "s": 2960, "text": "The following example shows the usage of std::vector::pop_back() function." }, { "code": null, "e": 3320, "s": 3035, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v = {1, 2, 3, 4, 5};\n\n /* Remove last three elements */\n v.pop_back();\n v.pop_back();\n v.pop_back();\n\n for (int i = 0; i < v.size(); ++i)\n cout << v[i] << endl;\n\n return 0;\n}" }, { "code": null, "e": 3403, "s": 3320, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3408, "s": 3403, "text": "1\n2\n" }, { "code": null, "e": 3415, "s": 3408, "text": " Print" }, { "code": null, "e": 3426, "s": 3415, "text": " Add Notes" } ]
How do I close all the open pyplot windows (Matplotlib)?
plt.figure().close(): Close a figure window. close() by itself closes the current figure close(h), where h is a Figure instance, closes that figure close(num) closes the figure with number=num close(name), where name is a string, closes the figure with that label close('all') closes all the figure windows from matplotlib import pyplot as plt fig = plt.figure() ax = fig.add_subplot() plt.show() plt.close() Now, swap the statements "plt.show()" and "plt.close()" in the code. You wouldn't get to see any plot as the output because the plot would already have been closed.
[ { "code": null, "e": 1107, "s": 1062, "text": "plt.figure().close(): Close a figure window." }, { "code": null, "e": 1151, "s": 1107, "text": "close() by itself closes the current figure" }, { "code": null, "e": 1210, "s": 1151, "text": "close(h), where h is a Figure instance, closes that figure" }, { "code": null, "e": 1255, "s": 1210, "text": "close(num) closes the figure with number=num" }, { "code": null, "e": 1326, "s": 1255, "text": "close(name), where name is a string, closes the figure with that label" }, { "code": null, "e": 1369, "s": 1326, "text": "close('all') closes all the figure windows" }, { "code": null, "e": 1471, "s": 1369, "text": "from matplotlib import pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot()\nplt.show()\nplt.close()" }, { "code": null, "e": 1636, "s": 1471, "text": "Now, swap the statements \"plt.show()\" and \"plt.close()\" in the code. You wouldn't get to see any plot as the output because the plot would already have been closed." } ]
How to download all historic intraday OHCL data from IEX: with Python, asynchronously, via API & for free. | by Julius Kittler | Towards Data Science
Are you looking for a way to get large amounts of 1-min intraday stock price data for free? To backtest your trading algorithms and train your models locally? There is a very sweet way to do this and I will show you right below. In this article, I will show you how to download free intraday data from the IEX exchange. Note that IEX is a stock exchange in the U.S. with >8K ticker symbols traded every day. Never heard about it? Find more information here. Importantly, this article will show you how to download the OHCL intraday data for all >8K tickers from the IEX exchange efficiently and regularly. There are three reasons why you should get your intraday data from IEX: It’s free. IEX is the only platform that lets you regularly download large amounts of intraday OHCL (open, high, close, low) data for free. Usually, intraday data is expensive if you want to obtain large data sets.IEX has a great API. The IEX API is well documented, easy to understand, and above all it supports asynchronous requests flawlessly.You can paper-trade on Alpaca. Alpaca is the best API for algorithmic trading that I have found. They offer free, unlimited paper trading for IEX ticker symbols. Hence, you can directly put your strategies that you developed with the IEX data to practice. It’s free. IEX is the only platform that lets you regularly download large amounts of intraday OHCL (open, high, close, low) data for free. Usually, intraday data is expensive if you want to obtain large data sets. IEX has a great API. The IEX API is well documented, easy to understand, and above all it supports asynchronous requests flawlessly. You can paper-trade on Alpaca. Alpaca is the best API for algorithmic trading that I have found. They offer free, unlimited paper trading for IEX ticker symbols. Hence, you can directly put your strategies that you developed with the IEX data to practice. Let me mention three other services that I have tested and that you may consider as alternative sources for intraday OHCL data. All of these may be interesting for particular reasons. World Trading Data: If you want to collect intraday OHCL data from other exchanges e.g. NASDAQ, NYSE and also non-US exchanges, this is a very cheap option. Example: With the $16/month plan, you can get 2-min resolution data for ca. 50k stocks. However, it will take you frequent downloads (1 session per day for 2 weeks every other 2 weeks) and your downloads will be quite slow since World Trading Data is not very supportive of asynchronous requests in my experience.Tiingo: If you want to collect historic 1-min intraday data from IEX since approx. 2017, Tiingo is the cheapest option. It will only cost you ca. $10 in total since Tiingo has very generous API call limits. Note: the IEX API does not allow you to access intraday data more than 30 calendar days in the past. Therefore, Tiingo may be interesting if you want to get historic data for a longer time period quickly. In contrast to that, the IEX API is great for regular and completely free downloads.Alphavantage: If you are looking to regularly collect intraday OHCL data for other exchanges e.g. NASDAQ, NYSE and don’t need a large amount of ticker symbols, then Alphavantage may be sufficient to get this data for free. Alphavantage covers a very large amount of tickers. However, the API call limits for the free plan are rather limited (5 API calls per minute, 500 calls per day). World Trading Data: If you want to collect intraday OHCL data from other exchanges e.g. NASDAQ, NYSE and also non-US exchanges, this is a very cheap option. Example: With the $16/month plan, you can get 2-min resolution data for ca. 50k stocks. However, it will take you frequent downloads (1 session per day for 2 weeks every other 2 weeks) and your downloads will be quite slow since World Trading Data is not very supportive of asynchronous requests in my experience. Tiingo: If you want to collect historic 1-min intraday data from IEX since approx. 2017, Tiingo is the cheapest option. It will only cost you ca. $10 in total since Tiingo has very generous API call limits. Note: the IEX API does not allow you to access intraday data more than 30 calendar days in the past. Therefore, Tiingo may be interesting if you want to get historic data for a longer time period quickly. In contrast to that, the IEX API is great for regular and completely free downloads. Alphavantage: If you are looking to regularly collect intraday OHCL data for other exchanges e.g. NASDAQ, NYSE and don’t need a large amount of ticker symbols, then Alphavantage may be sufficient to get this data for free. Alphavantage covers a very large amount of tickers. However, the API call limits for the free plan are rather limited (5 API calls per minute, 500 calls per day). The script introduced below is what I personally use to collect 1-min intraday data from IEX. You may want to adjust the script for your own purposes. Maybe however, it’s just what you are looking for. I wrote the script with the following three purposes in mind: Collect the data for later processing e.g. backtesting and training machine learning models. (Not: to feed your life algorithms with data)Store the data locally e.g. on your computer or maybe even in a cloud storage folder on your computer. (Not: to put the data into a database)Make the download simple e.g. I want to be able to run the script any time with python download_IEX.py(Not: having to pass any parameters or having to do the download on specific days) Collect the data for later processing e.g. backtesting and training machine learning models. (Not: to feed your life algorithms with data) Store the data locally e.g. on your computer or maybe even in a cloud storage folder on your computer. (Not: to put the data into a database) Make the download simple e.g. I want to be able to run the script any time with python download_IEX.py(Not: having to pass any parameters or having to do the download on specific days) Whenever you execute the script with python download_IEX.py, you are starting a new download session (for all dates in the past for which data is available and not downloaded yet). Each download session works as follows: Initializing log: The script initiates a new log file for the current session (see init_logging()). E.g. if you conduct your session on October 26, you will find the corresponding log file in script/log/20191026.log. Essentially, each log file contains the printouts that you could see in the terminal when executing the script.Fetching dates: The script fetches all dates for which downloads have to be done (see get_dates()). For this, it checks the existing folders in the output directory and takes a note of the dates for which data has been downloaded already. The required dates are then computed as all dates that are 30 days or less in the past and not yet in the output folder.Conducting download: The script then conducts a separate asynchronous download session for each of the fetched dates from step 2. For each date, an asynchronous download session is prepared (see asyncio_prep()), e.g. all available tickers from the IEX API are fetched. Then, this session is executed with the function download_tickers_asynchronous(), which asynchronously fetches and writes the data for the individual tickers (see get_csv() and write_csv()). Initializing log: The script initiates a new log file for the current session (see init_logging()). E.g. if you conduct your session on October 26, you will find the corresponding log file in script/log/20191026.log. Essentially, each log file contains the printouts that you could see in the terminal when executing the script. Fetching dates: The script fetches all dates for which downloads have to be done (see get_dates()). For this, it checks the existing folders in the output directory and takes a note of the dates for which data has been downloaded already. The required dates are then computed as all dates that are 30 days or less in the past and not yet in the output folder. Conducting download: The script then conducts a separate asynchronous download session for each of the fetched dates from step 2. For each date, an asynchronous download session is prepared (see asyncio_prep()), e.g. all available tickers from the IEX API are fetched. Then, this session is executed with the function download_tickers_asynchronous(), which asynchronously fetches and writes the data for the individual tickers (see get_csv() and write_csv()). To set up the script, you need to complete the following three steps. Download the repository to your computer Download the repository to your computer You can find the Github repository here. Download the repository by going to Clone or download and then on Download zip . Then, place the downloaded file IEX_historical-prices-master.zip in a folder of your choice on your computer and extract the zip directory. You should now have a folder (with a name of your choice) that contains the following files: 2. Get your free API key from IEX Go to the IEX Cloud website and register for free. Then find your free API token under API Tokens at SECRET (see red square in the screenshot below). 3. Set up your script/config.json file Open a new file in a text editor of your choice, e.g. Visual Studio Code. Then, put the following into the first three lines of the new file and replace YOUR_TOKEN with the SECRET token from the previous step. {"TOKEN": "YOUR_TOKEN"} Now, click Save as and save the new file with the name config.json in the script directory. Your folder should now look like this: After setting up the script as described above, you can open a new terminal at the script folder and execute the script withpython download_IEX.py. If all required packages are installed (see the imports at the beginning of download_IEX.py), the script will start downloading the IEX intraday data. In the terminal, you will see the following for each downloaded file: the timestamp, the ticker symbol, the index of the ticker symbol (among all available IEX tickers) and the date for which the ticker was downloaded: You can interrupt the download simply by interrupting the script that’s being executed. (If you execute the script in the terminal, control+c does the trick on Mac.) Later on, you can just resume the script by restarting it with python download_IEX.py but you will have to restart the download for the date for which data was currently being downloaded when you interrupted the script. Importantly, by default no files or folders are deleted when the script starts. Therefore, you might want to manually delete the folder for the date with incomplete downloads. That way, the script will do a fresh start for the mentioned date when you restart it with python download_IEX.py. If you want to use this script for regularly downloading IEX data, you will want to run it at least every four weeks. The reason is that according to the documentation, the API lets you download data for “30 trailing calendar days” (see IEX documentation). This means that if you were to only do a download session e.g. every eight weeks, you will lack data for some days. However, I was actually able to get data for more than 30 trailing calendar days. Probably the documentation meant to say “30 trailing calendar week days”. In any case, it’s safe to execute the script every four weeks. Note that whenever you run the script, you won’t need to set any parameters since it automatically detects for which dates you have downloaded data already and for which dates you can download data from IEX. Therefore, you could also execute the script e.g. every two weeks or have irregular breaks between your download sessions (sometimes two weeks, sometimes more). You can see that the script automatically creates a folder structure by year, ISO calendar week and date. For every date, the script performs a separate asynchronous download session. This means that you will have folders for each trading date that contain separate csv files: one csv file for each ticker. Essentially, the script gives you the raw data that comes from IEX. How you process this data later on is up to you. E.g. you might want to append all files for the same ticker to get one single file per ticker symbol. Important notes: When the asynchronous download session for one specific day is completed, the folder for this day is zipped automatically to save space. Hence, you may want to unzip the folders before processing the raw data. Each date folder contains three data folders DONE, ERROR, and NONE. You will want to use the files in the folder DONE because these files contain actual intraday data for valid ticker symbols. The files in the folder ERROR are mostly test tickers from IEX (see this GitHub issue) and the files in the folder NONE correspond to tickers that did not have any trades that day (see this GitHub issue). In the DONE folder of a given date, you will find one csv file for every ticker: And each of these files contains the same OHCL information. Here is an example for Apple (AAPL): Source code on Github IEX Cloud documentation API for paper-trading IEX tickers Thanks for reading and looking forward to your feedback!
[ { "code": null, "e": 401, "s": 172, "text": "Are you looking for a way to get large amounts of 1-min intraday stock price data for free? To backtest your trading algorithms and train your models locally? There is a very sweet way to do this and I will show you right below." }, { "code": null, "e": 630, "s": 401, "text": "In this article, I will show you how to download free intraday data from the IEX exchange. Note that IEX is a stock exchange in the U.S. with >8K ticker symbols traded every day. Never heard about it? Find more information here." }, { "code": null, "e": 778, "s": 630, "text": "Importantly, this article will show you how to download the OHCL intraday data for all >8K tickers from the IEX exchange efficiently and regularly." }, { "code": null, "e": 850, "s": 778, "text": "There are three reasons why you should get your intraday data from IEX:" }, { "code": null, "e": 1452, "s": 850, "text": "It’s free. IEX is the only platform that lets you regularly download large amounts of intraday OHCL (open, high, close, low) data for free. Usually, intraday data is expensive if you want to obtain large data sets.IEX has a great API. The IEX API is well documented, easy to understand, and above all it supports asynchronous requests flawlessly.You can paper-trade on Alpaca. Alpaca is the best API for algorithmic trading that I have found. They offer free, unlimited paper trading for IEX ticker symbols. Hence, you can directly put your strategies that you developed with the IEX data to practice." }, { "code": null, "e": 1667, "s": 1452, "text": "It’s free. IEX is the only platform that lets you regularly download large amounts of intraday OHCL (open, high, close, low) data for free. Usually, intraday data is expensive if you want to obtain large data sets." }, { "code": null, "e": 1800, "s": 1667, "text": "IEX has a great API. The IEX API is well documented, easy to understand, and above all it supports asynchronous requests flawlessly." }, { "code": null, "e": 2056, "s": 1800, "text": "You can paper-trade on Alpaca. Alpaca is the best API for algorithmic trading that I have found. They offer free, unlimited paper trading for IEX ticker symbols. Hence, you can directly put your strategies that you developed with the IEX data to practice." }, { "code": null, "e": 2240, "s": 2056, "text": "Let me mention three other services that I have tested and that you may consider as alternative sources for intraday OHCL data. All of these may be interesting for particular reasons." }, { "code": null, "e": 3592, "s": 2240, "text": "World Trading Data: If you want to collect intraday OHCL data from other exchanges e.g. NASDAQ, NYSE and also non-US exchanges, this is a very cheap option. Example: With the $16/month plan, you can get 2-min resolution data for ca. 50k stocks. However, it will take you frequent downloads (1 session per day for 2 weeks every other 2 weeks) and your downloads will be quite slow since World Trading Data is not very supportive of asynchronous requests in my experience.Tiingo: If you want to collect historic 1-min intraday data from IEX since approx. 2017, Tiingo is the cheapest option. It will only cost you ca. $10 in total since Tiingo has very generous API call limits. Note: the IEX API does not allow you to access intraday data more than 30 calendar days in the past. Therefore, Tiingo may be interesting if you want to get historic data for a longer time period quickly. In contrast to that, the IEX API is great for regular and completely free downloads.Alphavantage: If you are looking to regularly collect intraday OHCL data for other exchanges e.g. NASDAQ, NYSE and don’t need a large amount of ticker symbols, then Alphavantage may be sufficient to get this data for free. Alphavantage covers a very large amount of tickers. However, the API call limits for the free plan are rather limited (5 API calls per minute, 500 calls per day)." }, { "code": null, "e": 4063, "s": 3592, "text": "World Trading Data: If you want to collect intraday OHCL data from other exchanges e.g. NASDAQ, NYSE and also non-US exchanges, this is a very cheap option. Example: With the $16/month plan, you can get 2-min resolution data for ca. 50k stocks. However, it will take you frequent downloads (1 session per day for 2 weeks every other 2 weeks) and your downloads will be quite slow since World Trading Data is not very supportive of asynchronous requests in my experience." }, { "code": null, "e": 4560, "s": 4063, "text": "Tiingo: If you want to collect historic 1-min intraday data from IEX since approx. 2017, Tiingo is the cheapest option. It will only cost you ca. $10 in total since Tiingo has very generous API call limits. Note: the IEX API does not allow you to access intraday data more than 30 calendar days in the past. Therefore, Tiingo may be interesting if you want to get historic data for a longer time period quickly. In contrast to that, the IEX API is great for regular and completely free downloads." }, { "code": null, "e": 4946, "s": 4560, "text": "Alphavantage: If you are looking to regularly collect intraday OHCL data for other exchanges e.g. NASDAQ, NYSE and don’t need a large amount of ticker symbols, then Alphavantage may be sufficient to get this data for free. Alphavantage covers a very large amount of tickers. However, the API call limits for the free plan are rather limited (5 API calls per minute, 500 calls per day)." }, { "code": null, "e": 5210, "s": 4946, "text": "The script introduced below is what I personally use to collect 1-min intraday data from IEX. You may want to adjust the script for your own purposes. Maybe however, it’s just what you are looking for. I wrote the script with the following three purposes in mind:" }, { "code": null, "e": 5674, "s": 5210, "text": "Collect the data for later processing e.g. backtesting and training machine learning models. (Not: to feed your life algorithms with data)Store the data locally e.g. on your computer or maybe even in a cloud storage folder on your computer. (Not: to put the data into a database)Make the download simple e.g. I want to be able to run the script any time with python download_IEX.py(Not: having to pass any parameters or having to do the download on specific days)" }, { "code": null, "e": 5813, "s": 5674, "text": "Collect the data for later processing e.g. backtesting and training machine learning models. (Not: to feed your life algorithms with data)" }, { "code": null, "e": 5955, "s": 5813, "text": "Store the data locally e.g. on your computer or maybe even in a cloud storage folder on your computer. (Not: to put the data into a database)" }, { "code": null, "e": 6140, "s": 5955, "text": "Make the download simple e.g. I want to be able to run the script any time with python download_IEX.py(Not: having to pass any parameters or having to do the download on specific days)" }, { "code": null, "e": 6361, "s": 6140, "text": "Whenever you execute the script with python download_IEX.py, you are starting a new download session (for all dates in the past for which data is available and not downloaded yet). Each download session works as follows:" }, { "code": null, "e": 7508, "s": 6361, "text": "Initializing log: The script initiates a new log file for the current session (see init_logging()). E.g. if you conduct your session on October 26, you will find the corresponding log file in script/log/20191026.log. Essentially, each log file contains the printouts that you could see in the terminal when executing the script.Fetching dates: The script fetches all dates for which downloads have to be done (see get_dates()). For this, it checks the existing folders in the output directory and takes a note of the dates for which data has been downloaded already. The required dates are then computed as all dates that are 30 days or less in the past and not yet in the output folder.Conducting download: The script then conducts a separate asynchronous download session for each of the fetched dates from step 2. For each date, an asynchronous download session is prepared (see asyncio_prep()), e.g. all available tickers from the IEX API are fetched. Then, this session is executed with the function download_tickers_asynchronous(), which asynchronously fetches and writes the data for the individual tickers (see get_csv() and write_csv())." }, { "code": null, "e": 7837, "s": 7508, "text": "Initializing log: The script initiates a new log file for the current session (see init_logging()). E.g. if you conduct your session on October 26, you will find the corresponding log file in script/log/20191026.log. Essentially, each log file contains the printouts that you could see in the terminal when executing the script." }, { "code": null, "e": 8197, "s": 7837, "text": "Fetching dates: The script fetches all dates for which downloads have to be done (see get_dates()). For this, it checks the existing folders in the output directory and takes a note of the dates for which data has been downloaded already. The required dates are then computed as all dates that are 30 days or less in the past and not yet in the output folder." }, { "code": null, "e": 8657, "s": 8197, "text": "Conducting download: The script then conducts a separate asynchronous download session for each of the fetched dates from step 2. For each date, an asynchronous download session is prepared (see asyncio_prep()), e.g. all available tickers from the IEX API are fetched. Then, this session is executed with the function download_tickers_asynchronous(), which asynchronously fetches and writes the data for the individual tickers (see get_csv() and write_csv())." }, { "code": null, "e": 8727, "s": 8657, "text": "To set up the script, you need to complete the following three steps." }, { "code": null, "e": 8768, "s": 8727, "text": "Download the repository to your computer" }, { "code": null, "e": 8809, "s": 8768, "text": "Download the repository to your computer" }, { "code": null, "e": 9071, "s": 8809, "text": "You can find the Github repository here. Download the repository by going to Clone or download and then on Download zip . Then, place the downloaded file IEX_historical-prices-master.zip in a folder of your choice on your computer and extract the zip directory." }, { "code": null, "e": 9164, "s": 9071, "text": "You should now have a folder (with a name of your choice) that contains the following files:" }, { "code": null, "e": 9198, "s": 9164, "text": "2. Get your free API key from IEX" }, { "code": null, "e": 9348, "s": 9198, "text": "Go to the IEX Cloud website and register for free. Then find your free API token under API Tokens at SECRET (see red square in the screenshot below)." }, { "code": null, "e": 9387, "s": 9348, "text": "3. Set up your script/config.json file" }, { "code": null, "e": 9597, "s": 9387, "text": "Open a new file in a text editor of your choice, e.g. Visual Studio Code. Then, put the following into the first three lines of the new file and replace YOUR_TOKEN with the SECRET token from the previous step." }, { "code": null, "e": 9621, "s": 9597, "text": "{\"TOKEN\": \"YOUR_TOKEN\"}" }, { "code": null, "e": 9752, "s": 9621, "text": "Now, click Save as and save the new file with the name config.json in the script directory. Your folder should now look like this:" }, { "code": null, "e": 10051, "s": 9752, "text": "After setting up the script as described above, you can open a new terminal at the script folder and execute the script withpython download_IEX.py. If all required packages are installed (see the imports at the beginning of download_IEX.py), the script will start downloading the IEX intraday data." }, { "code": null, "e": 10270, "s": 10051, "text": "In the terminal, you will see the following for each downloaded file: the timestamp, the ticker symbol, the index of the ticker symbol (among all available IEX tickers) and the date for which the ticker was downloaded:" }, { "code": null, "e": 10656, "s": 10270, "text": "You can interrupt the download simply by interrupting the script that’s being executed. (If you execute the script in the terminal, control+c does the trick on Mac.) Later on, you can just resume the script by restarting it with python download_IEX.py but you will have to restart the download for the date for which data was currently being downloaded when you interrupted the script." }, { "code": null, "e": 10947, "s": 10656, "text": "Importantly, by default no files or folders are deleted when the script starts. Therefore, you might want to manually delete the folder for the date with incomplete downloads. That way, the script will do a fresh start for the mentioned date when you restart it with python download_IEX.py." }, { "code": null, "e": 11320, "s": 10947, "text": "If you want to use this script for regularly downloading IEX data, you will want to run it at least every four weeks. The reason is that according to the documentation, the API lets you download data for “30 trailing calendar days” (see IEX documentation). This means that if you were to only do a download session e.g. every eight weeks, you will lack data for some days." }, { "code": null, "e": 11539, "s": 11320, "text": "However, I was actually able to get data for more than 30 trailing calendar days. Probably the documentation meant to say “30 trailing calendar week days”. In any case, it’s safe to execute the script every four weeks." }, { "code": null, "e": 11908, "s": 11539, "text": "Note that whenever you run the script, you won’t need to set any parameters since it automatically detects for which dates you have downloaded data already and for which dates you can download data from IEX. Therefore, you could also execute the script e.g. every two weeks or have irregular breaks between your download sessions (sometimes two weeks, sometimes more)." }, { "code": null, "e": 12215, "s": 11908, "text": "You can see that the script automatically creates a folder structure by year, ISO calendar week and date. For every date, the script performs a separate asynchronous download session. This means that you will have folders for each trading date that contain separate csv files: one csv file for each ticker." }, { "code": null, "e": 12434, "s": 12215, "text": "Essentially, the script gives you the raw data that comes from IEX. How you process this data later on is up to you. E.g. you might want to append all files for the same ticker to get one single file per ticker symbol." }, { "code": null, "e": 12451, "s": 12434, "text": "Important notes:" }, { "code": null, "e": 12661, "s": 12451, "text": "When the asynchronous download session for one specific day is completed, the folder for this day is zipped automatically to save space. Hence, you may want to unzip the folders before processing the raw data." }, { "code": null, "e": 13059, "s": 12661, "text": "Each date folder contains three data folders DONE, ERROR, and NONE. You will want to use the files in the folder DONE because these files contain actual intraday data for valid ticker symbols. The files in the folder ERROR are mostly test tickers from IEX (see this GitHub issue) and the files in the folder NONE correspond to tickers that did not have any trades that day (see this GitHub issue)." }, { "code": null, "e": 13140, "s": 13059, "text": "In the DONE folder of a given date, you will find one csv file for every ticker:" }, { "code": null, "e": 13237, "s": 13140, "text": "And each of these files contains the same OHCL information. Here is an example for Apple (AAPL):" }, { "code": null, "e": 13259, "s": 13237, "text": "Source code on Github" }, { "code": null, "e": 13283, "s": 13259, "text": "IEX Cloud documentation" }, { "code": null, "e": 13317, "s": 13283, "text": "API for paper-trading IEX tickers" } ]
Multiplication of Matrix using threads - GeeksforGeeks
17 Aug, 2021 Multiplication of matrix does take time surely. Time complexity of matrix multiplication is O(n^3) using normal matrix multiplication. And Strassen algorithm improves it and its time complexity is O(n^(2.8074)).But, Is there any way to improve the performance of matrix multiplication using the normal method. Multi-threading can be done to improve it. In multi-threading, instead of utilizing a single core of your processor, we utilizes all or more core to solve the problem.We create different threads, each thread evaluating some part of matrix multiplication. Depending upon the number of cores your processor has, you can create the number of threads required. Although you can create as many threads as you need, a better way is to create each thread for one core.In second approach,we create a separate thread for each element in resultant matrix. Using pthread_exit() we return computed value from each thread which is collected by pthread_join(). This approach does not make use of any global variables. Examples: Input : Matrix A 1 0 0 0 1 0 0 0 1 Matrix B 2 3 2 4 5 1 7 8 6 Output : Multiplication of A and B 2 3 2 4 5 1 7 8 6 NOTE* It is advised to execute the program in linux based system Compile in linux using following code: g++ -pthread program_name.cpp CPP // CPP Program to multiply two matrix using pthreads#include <bits/stdc++.h>using namespace std; // maximum size of matrix#define MAX 4 // maximum number of threads#define MAX_THREAD 4 int matA[MAX][MAX];int matB[MAX][MAX];int matC[MAX][MAX];int step_i = 0; void* multi(void* arg){ int i = step_i++; //i denotes row number of resultant matC for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) matC[i][j] += matA[i][k] * matB[k][j];} // Driver Codeint main(){ // Generating random values in matA and matB for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { matA[i][j] = rand() % 10; matB[i][j] = rand() % 10; } } // Displaying matA cout << endl << "Matrix A" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matA[i][j] << " "; cout << endl; } // Displaying matB cout << endl << "Matrix B" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matB[i][j] << " "; cout << endl; } // declaring four threads pthread_t threads[MAX_THREAD]; // Creating four threads, each evaluating its own part for (int i = 0; i < MAX_THREAD; i++) { int* p; pthread_create(&threads[i], NULL, multi, (void*)(p)); } // joining and waiting for all threads to complete for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); // Displaying the result matrix cout << endl << "Multiplication of A and B" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matC[i][j] << " "; cout << endl; } return 0;} Output: Matrix A 3 7 3 6 9 2 0 3 0 2 1 7 2 2 7 9 Matrix B 6 5 5 2 1 7 9 6 6 6 8 9 0 3 5 2 Multiplication of A and B 43 100 132 87 56 68 78 36 8 41 61 35 56 93 129 97 An approach without using global variables:NOTE* It is advised to execute the program in linux based system Compile in linux using following code: g++ -pthread program_name.cpp C // C Program to multiply two matrix using pthreads without// use of global variables#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<stdlib.h>#define MAX 4 //Each thread computes single element in the resultant matrixvoid *mult(void* arg){ int *data = (int *)arg; int k = 0, i = 0; int x = data[0]; for (i = 1; i <= x; i++) k += data[i]*data[i+x]; int *p = (int*)malloc(sizeof(int)); *p = k; //Used to terminate a thread and the return value is passed as a pointer pthread_exit(p);} //Driver codeint main(){ int matA[MAX][MAX]; int matB[MAX][MAX]; int r1=MAX,c1=MAX,r2=MAX,c2=MAX,i,j,k; // Generating random values in matA for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) matA[i][j] = rand() % 10; // Generating random values in matB for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) matB[i][j] = rand() % 10; // Displaying matA for (i = 0; i < r1; i++){ for(j = 0; j < c1; j++) printf("%d ",matA[i][j]); printf("\n"); } // Displaying matB for (i = 0; i < r2; i++){ for(j = 0; j < c2; j++) printf("%d ",matB[i][j]); printf("\n"); } int max = r1*c2; //declaring array of threads of size r1*c2 pthread_t *threads; threads = (pthread_t*)malloc(max*sizeof(pthread_t)); int count = 0; int* data = NULL; for (i = 0; i < r1; i++) for (j = 0; j < c2; j++) { //storing row and column elements in data data = (int *)malloc((20)*sizeof(int)); data[0] = c1; for (k = 0; k < c1; k++) data[k+1] = matA[i][k]; for (k = 0; k < r2; k++) data[k+c1+1] = matB[k][j]; //creating threads pthread_create(&threads[count++], NULL, mult, (void*)(data)); } printf("RESULTANT MATRIX IS :- \n"); for (i = 0; i < max; i++) { void *k; //Joining all threads and collecting return value pthread_join(threads[i], &k); int *p = (int *)k; printf("%d ",*p); if ((i + 1) % c2 == 0) printf("\n"); } return 0;} Output: Matrix A 3 7 3 6 9 2 0 3 0 2 1 7 2 2 7 9 Matrix B 6 5 5 2 1 7 9 6 6 6 8 9 0 3 5 2 Multiplication of A and B 43 100 132 87 56 68 78 36 8 41 61 35 56 93 129 97 GauravKshirsagar1 nidhi_biet krishil Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Unique paths in a Grid with Obstacles A Boolean Matrix Question Shortest distance between two cells in a matrix or grid Program for Conway's Game Of Life
[ { "code": null, "e": 26167, "s": 26139, "text": "\n17 Aug, 2021" }, { "code": null, "e": 27182, "s": 26167, "text": "Multiplication of matrix does take time surely. Time complexity of matrix multiplication is O(n^3) using normal matrix multiplication. And Strassen algorithm improves it and its time complexity is O(n^(2.8074)).But, Is there any way to improve the performance of matrix multiplication using the normal method. Multi-threading can be done to improve it. In multi-threading, instead of utilizing a single core of your processor, we utilizes all or more core to solve the problem.We create different threads, each thread evaluating some part of matrix multiplication. Depending upon the number of cores your processor has, you can create the number of threads required. Although you can create as many threads as you need, a better way is to create each thread for one core.In second approach,we create a separate thread for each element in resultant matrix. Using pthread_exit() we return computed value from each thread which is collected by pthread_join(). This approach does not make use of any global variables. " }, { "code": null, "e": 27194, "s": 27182, "text": "Examples: " }, { "code": null, "e": 27318, "s": 27194, "text": "Input : \nMatrix A\n 1 0 0\n 0 1 0\n 0 0 1\n\nMatrix B\n 2 3 2\n 4 5 1\n 7 8 6\n\nOutput : Multiplication of A and B\n2 3 2\n4 5 1\n7 8 6" }, { "code": null, "e": 27426, "s": 27320, "text": "NOTE* It is advised to execute the program in linux based system Compile in linux using following code: " }, { "code": null, "e": 27456, "s": 27426, "text": "g++ -pthread program_name.cpp" }, { "code": null, "e": 27462, "s": 27458, "text": "CPP" }, { "code": "// CPP Program to multiply two matrix using pthreads#include <bits/stdc++.h>using namespace std; // maximum size of matrix#define MAX 4 // maximum number of threads#define MAX_THREAD 4 int matA[MAX][MAX];int matB[MAX][MAX];int matC[MAX][MAX];int step_i = 0; void* multi(void* arg){ int i = step_i++; //i denotes row number of resultant matC for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) matC[i][j] += matA[i][k] * matB[k][j];} // Driver Codeint main(){ // Generating random values in matA and matB for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { matA[i][j] = rand() % 10; matB[i][j] = rand() % 10; } } // Displaying matA cout << endl << \"Matrix A\" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matA[i][j] << \" \"; cout << endl; } // Displaying matB cout << endl << \"Matrix B\" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matB[i][j] << \" \"; cout << endl; } // declaring four threads pthread_t threads[MAX_THREAD]; // Creating four threads, each evaluating its own part for (int i = 0; i < MAX_THREAD; i++) { int* p; pthread_create(&threads[i], NULL, multi, (void*)(p)); } // joining and waiting for all threads to complete for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); // Displaying the result matrix cout << endl << \"Multiplication of A and B\" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matC[i][j] << \" \"; cout << endl; } return 0;}", "e": 29219, "s": 27462, "text": null }, { "code": null, "e": 29229, "s": 29219, "text": "Output: " }, { "code": null, "e": 29401, "s": 29229, "text": "Matrix A\n3 7 3 6 \n9 2 0 3 \n0 2 1 7 \n2 2 7 9 \n\nMatrix B\n6 5 5 2 \n1 7 9 6 \n6 6 8 9 \n0 3 5 2 \n\nMultiplication of A and B\n43 100 132 87 \n56 68 78 36 \n8 41 61 35 \n56 93 129 97 " }, { "code": null, "e": 29550, "s": 29401, "text": "An approach without using global variables:NOTE* It is advised to execute the program in linux based system Compile in linux using following code: " }, { "code": null, "e": 29580, "s": 29550, "text": "g++ -pthread program_name.cpp" }, { "code": null, "e": 29584, "s": 29582, "text": "C" }, { "code": "// C Program to multiply two matrix using pthreads without// use of global variables#include<stdio.h>#include<pthread.h>#include<unistd.h>#include<stdlib.h>#define MAX 4 //Each thread computes single element in the resultant matrixvoid *mult(void* arg){ int *data = (int *)arg; int k = 0, i = 0; int x = data[0]; for (i = 1; i <= x; i++) k += data[i]*data[i+x]; int *p = (int*)malloc(sizeof(int)); *p = k; //Used to terminate a thread and the return value is passed as a pointer pthread_exit(p);} //Driver codeint main(){ int matA[MAX][MAX]; int matB[MAX][MAX]; int r1=MAX,c1=MAX,r2=MAX,c2=MAX,i,j,k; // Generating random values in matA for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) matA[i][j] = rand() % 10; // Generating random values in matB for (i = 0; i < r1; i++) for (j = 0; j < c1; j++) matB[i][j] = rand() % 10; // Displaying matA for (i = 0; i < r1; i++){ for(j = 0; j < c1; j++) printf(\"%d \",matA[i][j]); printf(\"\\n\"); } // Displaying matB for (i = 0; i < r2; i++){ for(j = 0; j < c2; j++) printf(\"%d \",matB[i][j]); printf(\"\\n\"); } int max = r1*c2; //declaring array of threads of size r1*c2 pthread_t *threads; threads = (pthread_t*)malloc(max*sizeof(pthread_t)); int count = 0; int* data = NULL; for (i = 0; i < r1; i++) for (j = 0; j < c2; j++) { //storing row and column elements in data data = (int *)malloc((20)*sizeof(int)); data[0] = c1; for (k = 0; k < c1; k++) data[k+1] = matA[i][k]; for (k = 0; k < r2; k++) data[k+c1+1] = matB[k][j]; //creating threads pthread_create(&threads[count++], NULL, mult, (void*)(data)); } printf(\"RESULTANT MATRIX IS :- \\n\"); for (i = 0; i < max; i++) { void *k; //Joining all threads and collecting return value pthread_join(threads[i], &k); int *p = (int *)k; printf(\"%d \",*p); if ((i + 1) % c2 == 0) printf(\"\\n\"); } return 0;}", "e": 32032, "s": 29584, "text": null }, { "code": null, "e": 32042, "s": 32032, "text": "Output: " }, { "code": null, "e": 32213, "s": 32042, "text": "Matrix A\n3 7 3 6 \n9 2 0 3 \n0 2 1 7 \n2 2 7 9\n\nMatrix B\n6 5 5 2 \n1 7 9 6 \n6 6 8 9 \n0 3 5 2 \n\nMultiplication of A and B\n43 100 132 87 \n56 68 78 36 \n8 41 61 35 \n56 93 129 97 " }, { "code": null, "e": 32233, "s": 32215, "text": "GauravKshirsagar1" }, { "code": null, "e": 32244, "s": 32233, "text": "nidhi_biet" }, { "code": null, "e": 32252, "s": 32244, "text": "krishil" }, { "code": null, "e": 32259, "s": 32252, "text": "Matrix" }, { "code": null, "e": 32266, "s": 32259, "text": "Matrix" }, { "code": null, "e": 32364, "s": 32266, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32414, "s": 32364, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 32471, "s": 32414, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 32508, "s": 32471, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 32549, "s": 32508, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 32613, "s": 32549, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 32648, "s": 32613, "text": "Python program to add two Matrices" }, { "code": null, "e": 32686, "s": 32648, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 32712, "s": 32686, "text": "A Boolean Matrix Question" }, { "code": null, "e": 32768, "s": 32712, "text": "Shortest distance between two cells in a matrix or grid" } ]
How to create a new thread in Python - GeeksforGeeks
30 Sep, 2021 Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there are two ways to create a new Thread. In this article, we will also be making use of the threading module in Python. Below is a detailed list of those processes: Below has a coding example followed by the code explanation for creating new threads using class in python. Python3 # import the threading moduleimport threading class thread(threading.Thread): def __init__(self, thread_name, thread_ID): threading.Thread.__init__(self) self.thread_name = thread_name self.thread_ID = thread_ID # helper function to execute the threads def run(self): print(str(self.thread_name) +" "+ str(self.thread_ID)); thread1 = thread("GFG", 1000)thread2 = thread("GeeksforGeeks", 2000); thread1.start()thread2.start() print("Exit") Output: GFG 1000 GeeksforGeeks 2000 Exit Now let’s look into what we did up there in the code. We created a sub-class of the thread class.Then we override the __init__ function of the thread class.Then we override the run method to define the behavior of the thread.The start() method starts a Python thread. We created a sub-class of the thread class. Then we override the __init__ function of the thread class. Then we override the run method to define the behavior of the thread. The start() method starts a Python thread. The below code shows the creation of new thread using a function: Python3 from threading import Threadfrom time import sleep # function to create threadsdef threaded_function(arg): for i in range(arg): print("running") # wait 1 sec in between each thread sleep(1) if __name__ == "__main__": thread = Thread(target = threaded_function, args = (10, )) thread.start() thread.join() print("thread finished...exiting") Output: running running running running running running running running running running thread finished...exiting So what we did in the above code, We defined a function to create a thread.Then we used the threading module to create a thread that invoked the function as its target.Then we used start() method to start the Python thread. We defined a function to create a thread. Then we used the threading module to create a thread that invoked the function as its target. Then we used start() method to start the Python thread. ayushharwani2011 sarveshad65 Python-threading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25941, "s": 25913, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26224, "s": 25941, "text": "Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes." }, { "code": null, "e": 26402, "s": 26224, "text": "In Python, there are two ways to create a new Thread. In this article, we will also be making use of the threading module in Python. Below is a detailed list of those processes:" }, { "code": null, "e": 26512, "s": 26402, "text": "Below has a coding example followed by the code explanation for creating new threads using class in python. " }, { "code": null, "e": 26520, "s": 26512, "text": "Python3" }, { "code": "# import the threading moduleimport threading class thread(threading.Thread): def __init__(self, thread_name, thread_ID): threading.Thread.__init__(self) self.thread_name = thread_name self.thread_ID = thread_ID # helper function to execute the threads def run(self): print(str(self.thread_name) +\" \"+ str(self.thread_ID)); thread1 = thread(\"GFG\", 1000)thread2 = thread(\"GeeksforGeeks\", 2000); thread1.start()thread2.start() print(\"Exit\")", "e": 27001, "s": 26520, "text": null }, { "code": null, "e": 27010, "s": 27001, "text": "Output: " }, { "code": null, "e": 27043, "s": 27010, "text": "GFG 1000\nGeeksforGeeks 2000\nExit" }, { "code": null, "e": 27099, "s": 27043, "text": "Now let’s look into what we did up there in the code. " }, { "code": null, "e": 27314, "s": 27099, "text": "We created a sub-class of the thread class.Then we override the __init__ function of the thread class.Then we override the run method to define the behavior of the thread.The start() method starts a Python thread. " }, { "code": null, "e": 27358, "s": 27314, "text": "We created a sub-class of the thread class." }, { "code": null, "e": 27418, "s": 27358, "text": "Then we override the __init__ function of the thread class." }, { "code": null, "e": 27488, "s": 27418, "text": "Then we override the run method to define the behavior of the thread." }, { "code": null, "e": 27532, "s": 27488, "text": "The start() method starts a Python thread. " }, { "code": null, "e": 27600, "s": 27532, "text": "The below code shows the creation of new thread using a function: " }, { "code": null, "e": 27608, "s": 27600, "text": "Python3" }, { "code": "from threading import Threadfrom time import sleep # function to create threadsdef threaded_function(arg): for i in range(arg): print(\"running\") # wait 1 sec in between each thread sleep(1) if __name__ == \"__main__\": thread = Thread(target = threaded_function, args = (10, )) thread.start() thread.join() print(\"thread finished...exiting\")", "e": 27994, "s": 27608, "text": null }, { "code": null, "e": 28003, "s": 27994, "text": "Output: " }, { "code": null, "e": 28109, "s": 28003, "text": "running\nrunning\nrunning\nrunning\nrunning\nrunning\nrunning\nrunning\nrunning\nrunning\nthread finished...exiting" }, { "code": null, "e": 28144, "s": 28109, "text": "So what we did in the above code, " }, { "code": null, "e": 28336, "s": 28144, "text": "We defined a function to create a thread.Then we used the threading module to create a thread that invoked the function as its target.Then we used start() method to start the Python thread. " }, { "code": null, "e": 28378, "s": 28336, "text": "We defined a function to create a thread." }, { "code": null, "e": 28472, "s": 28378, "text": "Then we used the threading module to create a thread that invoked the function as its target." }, { "code": null, "e": 28530, "s": 28472, "text": "Then we used start() method to start the Python thread. " }, { "code": null, "e": 28549, "s": 28532, "text": "ayushharwani2011" }, { "code": null, "e": 28561, "s": 28549, "text": "sarveshad65" }, { "code": null, "e": 28578, "s": 28561, "text": "Python-threading" }, { "code": null, "e": 28585, "s": 28578, "text": "Python" }, { "code": null, "e": 28683, "s": 28585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28701, "s": 28683, "text": "Python Dictionary" }, { "code": null, "e": 28736, "s": 28701, "text": "Read a file line by line in Python" }, { "code": null, "e": 28768, "s": 28736, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28790, "s": 28768, "text": "Enumerate() in Python" }, { "code": null, "e": 28832, "s": 28790, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28862, "s": 28832, "text": "Iterate over a list in Python" }, { "code": null, "e": 28888, "s": 28862, "text": "Python String | replace()" }, { "code": null, "e": 28917, "s": 28888, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28961, "s": 28917, "text": "Reading and Writing to text files in Python" } ]
Node.js fs.write() Method - GeeksforGeeks
11 Oct, 2021 File-writing is an important aspect of programming. Every programming language has a well-defined file module that can be used to perform file operations. JavaScript and Node.js also have file module which provides various inbuilt methods for performing read, write, rename, delete and other operations on files. The file module of Node.js is called the fs module. By default, the fs module writes files with an encoding of ‘UTF-8’. The fs.write() method is an inbuilt application programming interface of fs module which is used to specify the position in a file to begin writing at a buffer to write, as well as which part of the buffer to write out to the file. The fs.write() method can also be used without a buffer by simply using a string variable. The examples given below demonstrate the use of buffer as well as string in the fs.write() method. It is an asynchronous method. Syntax: Using bufferfs.write(fd, buffer, offset, length, position, callback) fs.write(fd, buffer, offset, length, position, callback) Using stringfs.write(fd, string, position, encoding, callback) fs.write(fd, string, position, encoding, callback) Parameters: The method accept the following parameters as mentioned above and described below: fd: A file descriptor the value returned by opening the file using the fs.open() method. It contains an integer value. buffer: It contains the buffer type value like Buffer, TypedArray, DataView. offset: It is an integer value that determines the part of the buffer to be written to the file. length: It is an integer value that specifies the number of bytes to write into the file. position: It is an integer value that holds the position refers to the offset from the beginning of the file where the data is to be written. callback: It contains callback function that receives error and number of bytes written to the file. string: Write string to the file specified by fd. encoding: The default encoding value is UTF-8. Return Value: The callback function receives either error or the number of bytes written. If an error is received then an error message is printed else the number of bytes written is printed. Example 1: // Node.js program to demonstrate the // fs.write() method // Include fs moduleconst fs=require("fs"); // File path where data is to be written// Here, we assume that the file to be in// the same location as the .js filevar path = 'input.txt'; // Declare a buffer and write the// data in the bufferlet buffer = new Buffer.from('GeeksforGeeks: ' + 'A computer science portal for geeks\n'); // The fs.open() method takes a "flag"// as the second argument. If the file// does not exist, an empty file is// created. 'a' stands for append mode// which means that if the program is// run multiple time data will be// appended to the output file instead// of overwriting the existing data.fs.open(path, 'a', function(err, fd) { // If the output file does not exists // an error is thrown else data in the // buffer is written to the output file if(err) { console.log('Cant open file'); }else { fs.write(fd, buffer, 0, buffer.length, null, function(err,writtenbytes) { if(err) { console.log('Cant write to file'); }else { console.log(writtenbytes + ' characters added to file'); } }) }}) Output: 51 characters added to file input.txt file data: GeeksforGeeks: A computer science portal for geeks Explanation:On successful execution of the program, the data stored in the buffer is appended to the required file. In case the file does not exist beforehand, a new file is created and data is appended to it. Example 2: // Node.js program to demonstrate the // fs.write() method // Include fs moduleconst fs=require("fs"); const str = "Hello world";const filename = "input.txt"; fs.open(filename, "a", (err, fd)=>{ if(err){ console.log(err.message); }else{ fs.write(fd, str, (err, bytes)=>{ if(err){ console.log(err.message); }else{ console.log(bytes +' bytes written'); } }) }}) Output: 11 bytes written input.txt file data: Hello world Explanation: On successful execution of the program, the string value is written(appended) to the required file. Reference: https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback https://nodejs.org/api/fs.html#fs_fs_write_fd_string_position_encoding_callback Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.render() Function Mongoose | findByIdAndUpdate() Function 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": 25795, "s": 25767, "text": "\n11 Oct, 2021" }, { "code": null, "e": 26228, "s": 25795, "text": "File-writing is an important aspect of programming. Every programming language has a well-defined file module that can be used to perform file operations. JavaScript and Node.js also have file module which provides various inbuilt methods for performing read, write, rename, delete and other operations on files. The file module of Node.js is called the fs module. By default, the fs module writes files with an encoding of ‘UTF-8’." }, { "code": null, "e": 26680, "s": 26228, "text": "The fs.write() method is an inbuilt application programming interface of fs module which is used to specify the position in a file to begin writing at a buffer to write, as well as which part of the buffer to write out to the file. The fs.write() method can also be used without a buffer by simply using a string variable. The examples given below demonstrate the use of buffer as well as string in the fs.write() method. It is an asynchronous method." }, { "code": null, "e": 26688, "s": 26680, "text": "Syntax:" }, { "code": null, "e": 26757, "s": 26688, "text": "Using bufferfs.write(fd, buffer, offset, length, position, callback)" }, { "code": null, "e": 26814, "s": 26757, "text": "fs.write(fd, buffer, offset, length, position, callback)" }, { "code": null, "e": 26877, "s": 26814, "text": "Using stringfs.write(fd, string, position, encoding, callback)" }, { "code": null, "e": 26928, "s": 26877, "text": "fs.write(fd, string, position, encoding, callback)" }, { "code": null, "e": 27023, "s": 26928, "text": "Parameters: The method accept the following parameters as mentioned above and described below:" }, { "code": null, "e": 27142, "s": 27023, "text": "fd: A file descriptor the value returned by opening the file using the fs.open() method. It contains an integer value." }, { "code": null, "e": 27219, "s": 27142, "text": "buffer: It contains the buffer type value like Buffer, TypedArray, DataView." }, { "code": null, "e": 27316, "s": 27219, "text": "offset: It is an integer value that determines the part of the buffer to be written to the file." }, { "code": null, "e": 27406, "s": 27316, "text": "length: It is an integer value that specifies the number of bytes to write into the file." }, { "code": null, "e": 27548, "s": 27406, "text": "position: It is an integer value that holds the position refers to the offset from the beginning of the file where the data is to be written." }, { "code": null, "e": 27649, "s": 27548, "text": "callback: It contains callback function that receives error and number of bytes written to the file." }, { "code": null, "e": 27699, "s": 27649, "text": "string: Write string to the file specified by fd." }, { "code": null, "e": 27746, "s": 27699, "text": "encoding: The default encoding value is UTF-8." }, { "code": null, "e": 27938, "s": 27746, "text": "Return Value: The callback function receives either error or the number of bytes written. If an error is received then an error message is printed else the number of bytes written is printed." }, { "code": null, "e": 27949, "s": 27938, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // fs.write() method // Include fs moduleconst fs=require(\"fs\"); // File path where data is to be written// Here, we assume that the file to be in// the same location as the .js filevar path = 'input.txt'; // Declare a buffer and write the// data in the bufferlet buffer = new Buffer.from('GeeksforGeeks: ' + 'A computer science portal for geeks\\n'); // The fs.open() method takes a \"flag\"// as the second argument. If the file// does not exist, an empty file is// created. 'a' stands for append mode// which means that if the program is// run multiple time data will be// appended to the output file instead// of overwriting the existing data.fs.open(path, 'a', function(err, fd) { // If the output file does not exists // an error is thrown else data in the // buffer is written to the output file if(err) { console.log('Cant open file'); }else { fs.write(fd, buffer, 0, buffer.length, null, function(err,writtenbytes) { if(err) { console.log('Cant write to file'); }else { console.log(writtenbytes + ' characters added to file'); } }) }})", "e": 29183, "s": 27949, "text": null }, { "code": null, "e": 29191, "s": 29183, "text": "Output:" }, { "code": null, "e": 29219, "s": 29191, "text": "51 characters added to file" }, { "code": null, "e": 29240, "s": 29219, "text": "input.txt file data:" }, { "code": null, "e": 29291, "s": 29240, "text": "GeeksforGeeks: A computer science portal for geeks" }, { "code": null, "e": 29501, "s": 29291, "text": "Explanation:On successful execution of the program, the data stored in the buffer is appended to the required file. In case the file does not exist beforehand, a new file is created and data is appended to it." }, { "code": null, "e": 29512, "s": 29501, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // fs.write() method // Include fs moduleconst fs=require(\"fs\"); const str = \"Hello world\";const filename = \"input.txt\"; fs.open(filename, \"a\", (err, fd)=>{ if(err){ console.log(err.message); }else{ fs.write(fd, str, (err, bytes)=>{ if(err){ console.log(err.message); }else{ console.log(bytes +' bytes written'); } }) }})", "e": 29983, "s": 29512, "text": null }, { "code": null, "e": 29991, "s": 29983, "text": "Output:" }, { "code": null, "e": 30008, "s": 29991, "text": "11 bytes written" }, { "code": null, "e": 30029, "s": 30008, "text": "input.txt file data:" }, { "code": null, "e": 30041, "s": 30029, "text": "Hello world" }, { "code": null, "e": 30154, "s": 30041, "text": "Explanation: On successful execution of the program, the string value is written(appended) to the required file." }, { "code": null, "e": 30165, "s": 30154, "text": "Reference:" }, { "code": null, "e": 30250, "s": 30165, "text": "https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback" }, { "code": null, "e": 30330, "s": 30250, "text": "https://nodejs.org/api/fs.html#fs_fs_write_fd_string_position_encoding_callback" }, { "code": null, "e": 30348, "s": 30330, "text": "Node.js-fs-module" }, { "code": null, "e": 30355, "s": 30348, "text": "Picked" }, { "code": null, "e": 30363, "s": 30355, "text": "Node.js" }, { "code": null, "e": 30380, "s": 30363, "text": "Web Technologies" }, { "code": null, "e": 30478, "s": 30380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30535, "s": 30478, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 30589, "s": 30535, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 30626, "s": 30589, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 30659, "s": 30626, "text": "Express.js res.render() Function" }, { "code": null, "e": 30699, "s": 30659, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 30739, "s": 30699, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30784, "s": 30739, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30827, "s": 30784, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30877, "s": 30827, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create a DataFrame from a Numpy array and specify the index column and column headers - GeeksforGeeks
28 Jul, 2020 Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules.Create a Numpy array.Create list of index values and column values for the DataFrame.Create the DataFrame.Display the DataFrame. Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343]]) # creating a list of index namesindex_values = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] # creating a list of column namescolumn_values = ['number', 'squares', 'cubes'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) Output : Example 2 : # importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['Aditya', 20], ['Samruddhi', 15], ['Rohan', 21], ['Anantha', 20], ['Abhinandan', 21]]) # creating a list of index namesindex_values = ['A', 'B', 'C', 'D', 'E'] # creating a list of column namescolumn_values = ['Names', 'Age'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) Output : Example 3 : # importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['CEO', 20, 5], ['CTO', 22, 4.5], ['CFO', 21, 3], ['CMO', 24, 2]]) # creating a list of index namesindex_values = [1, 2, 3, 4] # creating a list of column namescolumn_values = ['Names', 'Age', 'Net worth in Millions'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df) Output : pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26311, "s": 26283, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26453, "s": 26311, "text": "Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame." }, { "code": null, "e": 26464, "s": 26453, "text": "Approach :" }, { "code": null, "e": 26629, "s": 26464, "text": "Import the Pandas and Numpy modules.Create a Numpy array.Create list of index values and column values for the DataFrame.Create the DataFrame.Display the DataFrame." }, { "code": null, "e": 26666, "s": 26629, "text": "Import the Pandas and Numpy modules." }, { "code": null, "e": 26688, "s": 26666, "text": "Create a Numpy array." }, { "code": null, "e": 26753, "s": 26688, "text": "Create list of index values and column values for the DataFrame." }, { "code": null, "e": 26775, "s": 26753, "text": "Create the DataFrame." }, { "code": null, "e": 26798, "s": 26775, "text": "Display the DataFrame." }, { "code": null, "e": 26810, "s": 26798, "text": "Example 1 :" }, { "code": "# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([[1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125], [6, 36, 216], [7, 49, 343]]) # creating a list of index namesindex_values = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] # creating a list of column namescolumn_values = ['number', 'squares', 'cubes'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df)", "e": 27433, "s": 26810, "text": null }, { "code": null, "e": 27442, "s": 27433, "text": "Output :" }, { "code": null, "e": 27454, "s": 27442, "text": "Example 2 :" }, { "code": "# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['Aditya', 20], ['Samruddhi', 15], ['Rohan', 21], ['Anantha', 20], ['Abhinandan', 21]]) # creating a list of index namesindex_values = ['A', 'B', 'C', 'D', 'E'] # creating a list of column namescolumn_values = ['Names', 'Age'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df)", "e": 28003, "s": 27454, "text": null }, { "code": null, "e": 28012, "s": 28003, "text": "Output :" }, { "code": null, "e": 28024, "s": 28012, "text": "Example 3 :" }, { "code": "# importiong the modulesimport pandas as pdimport numpy as np # creating the Numpy arrayarray = np.array([['CEO', 20, 5], ['CTO', 22, 4.5], ['CFO', 21, 3], ['CMO', 24, 2]]) # creating a list of index namesindex_values = [1, 2, 3, 4] # creating a list of column namescolumn_values = ['Names', 'Age', 'Net worth in Millions'] # creating the dataframedf = pd.DataFrame(data = array, index = index_values, columns = column_values) # displaying the dataframeprint(df)", "e": 28564, "s": 28024, "text": null }, { "code": null, "e": 28573, "s": 28564, "text": "Output :" }, { "code": null, "e": 28598, "s": 28573, "text": "pandas-dataframe-program" }, { "code": null, "e": 28622, "s": 28598, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28636, "s": 28622, "text": "Python-pandas" }, { "code": null, "e": 28643, "s": 28636, "text": "Python" }, { "code": null, "e": 28741, "s": 28643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28759, "s": 28741, "text": "Python Dictionary" }, { "code": null, "e": 28791, "s": 28759, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28813, "s": 28791, "text": "Enumerate() in Python" }, { "code": null, "e": 28855, "s": 28813, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28884, "s": 28855, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28928, "s": 28884, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28965, "s": 28928, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29001, "s": 28965, "text": "Convert integer to string in Python" }, { "code": null, "e": 29043, "s": 29001, "text": "Check if element exists in list in Python" } ]
Python | Pandas DatetimeIndex.to_frame() - GeeksforGeeks
29 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.to_frame() function create a DataFrame with a column containing the Index. By default the labels of the DatetimeIndex object is used as an index for the newly constructed Dataframe. Syntax: DatetimeIndex.to_frame(index=True) Parameters :index : Set the index of the returned DataFrame as the original Index Return : DataFrame containing the original Index data. Example #1: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object. Also set the index value to False # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx) Output : Now we want to construct a DataFrame out of the DatetimeIndex object. # construct the DataFramedidx.to_frame(index = False) Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object. Example #2: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object. # importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx) Output : Now we want to construct a DataFrame out of the DatetimeIndex object. # construct the DataFramedidx.to_frame(index = True) Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object. Python pandas-datetimeIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2018" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25954, "s": 25751, "text": "Pandas DatetimeIndex.to_frame() function create a DataFrame with a column containing the Index. By default the labels of the DatetimeIndex object is used as an index for the newly constructed Dataframe." }, { "code": null, "e": 25997, "s": 25954, "text": "Syntax: DatetimeIndex.to_frame(index=True)" }, { "code": null, "e": 26079, "s": 25997, "text": "Parameters :index : Set the index of the returned DataFrame as the original Index" }, { "code": null, "e": 26134, "s": 26079, "text": "Return : DataFrame containing the original Index data." }, { "code": null, "e": 26284, "s": 26134, "text": "Example #1: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object. Also set the index value to False" }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx)", "e": 26512, "s": 26284, "text": null }, { "code": null, "e": 26521, "s": 26512, "text": "Output :" }, { "code": null, "e": 26591, "s": 26521, "text": "Now we want to construct a DataFrame out of the DatetimeIndex object." }, { "code": "# construct the DataFramedidx.to_frame(index = False)", "e": 26645, "s": 26591, "text": null }, { "code": null, "e": 26891, "s": 26645, "text": "Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object. Example #2: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)", "e": 27109, "s": 26891, "text": null }, { "code": null, "e": 27118, "s": 27109, "text": "Output :" }, { "code": null, "e": 27188, "s": 27118, "text": "Now we want to construct a DataFrame out of the DatetimeIndex object." }, { "code": "# construct the DataFramedidx.to_frame(index = True)", "e": 27241, "s": 27188, "text": null }, { "code": null, "e": 27371, "s": 27241, "text": "Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object." }, { "code": null, "e": 27399, "s": 27371, "text": "Python pandas-datetimeIndex" }, { "code": null, "e": 27413, "s": 27399, "text": "Python-pandas" }, { "code": null, "e": 27420, "s": 27413, "text": "Python" }, { "code": null, "e": 27518, "s": 27420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27550, "s": 27518, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27592, "s": 27550, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27634, "s": 27592, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27690, "s": 27634, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27717, "s": 27690, "text": "Python Classes and Objects" }, { "code": null, "e": 27756, "s": 27717, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27787, "s": 27756, "text": "Python | os.path.join() method" }, { "code": null, "e": 27816, "s": 27787, "text": "Create a directory in Python" }, { "code": null, "e": 27838, "s": 27816, "text": "Defaultdict in Python" } ]
Perl | File Handling Introduction - GeeksforGeeks
01 Apr, 2019 In Perl, a FileHandle associates a name to an external file, that can be used until the end of the program or until the FileHandle is closed. In short, a FileHandle is like a connection that can be used to modify the contents of an external file and a name is given to the connection (the FileHandle) for faster access and ease.The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively. File Handling is usually done through the open function. Syntax: open(FileHandle, Mode, FileName); Parameters: FileHandle- The reference to the file, that can be used within the program or until its closure. Mode- Mode in which a file is to be opened. FileName- The name of the file to be opened. Also, Mode and FileName can be clubbed to form a single expression for open. Syntax: open(FileHandle, Expression);Parameters: FileHandle- The reference to the file, that can be used within the program or until its closure. Expression- Mode and FileName clubbed together. The FileHandle is closed using the close function. Syntax: close(FileHandle);Parameters: FileHandle- The FileHandle to be closed. Reading from a FileHandle can be done through the print function. Syntax: print(<FileHandle>);Parameters: FileHandle- FileHandle opened in read mode or a similar mode. Writing to a File can also be done through the print function. Syntax: print FileHandle StringParameters: FileHandle- FileHandle opened in write mode or a similar mode. String- The String to be inserted in the file. Examples:Consider a file Hello.txt containing the string “Welcome to GeeksForGeeks!!!” initially. Mode = “<"This is read-only Mode. This mode is used to Read the content line by line from the file.#!/usr/bin/perl # Opening a File in Read-only modeopen(r, "<", "Hello.txt"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r);Output:Mode = “>”This is write-only Mode. Original contents of the File are cleared once it is opened in this Mode. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening File in Write modeopen(w, ">", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nWriting to File..."; # Writing to Hello.txt using printprint w "Content of this file is changed"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output:Mode=”>>”This is Append Mode. Original content of the File is not cleared when it is opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening the File in Append modeopen(A, ">>", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nAppending to File..."; # Appending to Hello.txt using printprint A " Hello Geeks!!!"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output:Mode = “+<“This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot create a new File.#!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, "+<", "Hello.txt"); # Print original contents of the File. # rw is set to the end.print("Existing Content of Hello.txt: ".<rw>); # The string is attached at the end # of the original contents of the file.print rw "Added using Read-Write Mode."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint("\nUpdated contents of Hello.txt: ".<rw>); # Close the FileHandleclose(rw); Output:Mode = “+>”This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can create a new File, if one with the name is not found, but a “+<” cannot.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, "+>", "Hello.txt"); # Original contents of the File# are cleared when the File is openedprint("\nContents of Hello.txt gets cleared..."); # The string is written to the Fileprint rw "Hello!!! This is updated file."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print("\nUpdated Content of Hello.txt: " .<rw>); # Closing the Fileclose(rw);Output:Mode = “+>>”This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A new File with same name is created, if one is not Found.# Open Hello.txt in Read-Append Modeopen(ra, "+>>", "Hello.txt"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint("Existing Content of the File: " . <ra>); print "\nAppending to the File...."; # The string is appended to the Fileprint ra "Added using Read-Append Mode"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint("\nUpdated content of the File: " . <ra>); # Closing the Fileclose(rw);Output: Redirecting Output Output can be redirected away from the Console and into a file using the select function.Syntax: select FileHandle;Parameters:FileHandle – FileHandle of the File to be selected.Steps:Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.Select the FileHandle using select function.Now, anything that is printed using the print function is redirected to the File.Example:# Open a FileHandle in Write Mode.open(File, ">", "Hello.txt"); # This sets File as the default FileHandleselect File; # Writes to Fileprint("This goes to the File."); # Writes to Fileprint File "\nThis goes to the File too."; # This sets STDOUT as default FileHandleselect STDOUT; print("This goes to the console."); # Close the FileHandle.close(File); Output in the Console:Contents of Hello.txt:Original File:Updated File:My Personal Notes arrow_drop_upSave Mode = “<"This is read-only Mode. This mode is used to Read the content line by line from the file.#!/usr/bin/perl # Opening a File in Read-only modeopen(r, "<", "Hello.txt"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r);Output: #!/usr/bin/perl # Opening a File in Read-only modeopen(r, "<", "Hello.txt"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r); Output: Mode = “>”This is write-only Mode. Original contents of the File are cleared once it is opened in this Mode. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening File in Write modeopen(w, ">", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nWriting to File..."; # Writing to Hello.txt using printprint w "Content of this file is changed"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output: #!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening File in Write modeopen(w, ">", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nWriting to File..."; # Writing to Hello.txt using printprint w "Content of this file is changed"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output: Mode=”>>”This is Append Mode. Original content of the File is not cleared when it is opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening the File in Append modeopen(A, ">>", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nAppending to File..."; # Appending to Hello.txt using printprint A " Hello Geeks!!!"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output: #!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Opening the File in Append modeopen(A, ">>", "Hello.txt"); # Set r to the beginning of Hello.txtseek r, 0, 0; print "\nAppending to File..."; # Appending to Hello.txt using printprint A " Hello Geeks!!!"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint("\nUpdated Content of Hello.txt: ".<r>); # Close the FileHandleclose(r); Output: Mode = “+<“This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot create a new File.#!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, "+<", "Hello.txt"); # Print original contents of the File. # rw is set to the end.print("Existing Content of Hello.txt: ".<rw>); # The string is attached at the end # of the original contents of the file.print rw "Added using Read-Write Mode."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint("\nUpdated contents of Hello.txt: ".<rw>); # Close the FileHandleclose(rw); Output: #!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, "+<", "Hello.txt"); # Print original contents of the File. # rw is set to the end.print("Existing Content of Hello.txt: ".<rw>); # The string is attached at the end # of the original contents of the file.print rw "Added using Read-Write Mode."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint("\nUpdated contents of Hello.txt: ".<rw>); # Close the FileHandleclose(rw); Output: Mode = “+>”This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can create a new File, if one with the name is not found, but a “+<” cannot.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, "+>", "Hello.txt"); # Original contents of the File# are cleared when the File is openedprint("\nContents of Hello.txt gets cleared..."); # The string is written to the Fileprint rw "Hello!!! This is updated file."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print("\nUpdated Content of Hello.txt: " .<rw>); # Closing the Fileclose(rw);Output: #!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, "<", "Hello.txt"); # Printing the existing content of the fileprint("Existing Content of Hello.txt: " . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, "+>", "Hello.txt"); # Original contents of the File# are cleared when the File is openedprint("\nContents of Hello.txt gets cleared..."); # The string is written to the Fileprint rw "Hello!!! This is updated file."; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print("\nUpdated Content of Hello.txt: " .<rw>); # Closing the Fileclose(rw); Output: Mode = “+>>”This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A new File with same name is created, if one is not Found.# Open Hello.txt in Read-Append Modeopen(ra, "+>>", "Hello.txt"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint("Existing Content of the File: " . <ra>); print "\nAppending to the File...."; # The string is appended to the Fileprint ra "Added using Read-Append Mode"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint("\nUpdated content of the File: " . <ra>); # Closing the Fileclose(rw);Output: Redirecting Output Output can be redirected away from the Console and into a file using the select function.Syntax: select FileHandle;Parameters:FileHandle – FileHandle of the File to be selected.Steps:Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.Select the FileHandle using select function.Now, anything that is printed using the print function is redirected to the File.Example:# Open a FileHandle in Write Mode.open(File, ">", "Hello.txt"); # This sets File as the default FileHandleselect File; # Writes to Fileprint("This goes to the File."); # Writes to Fileprint File "\nThis goes to the File too."; # This sets STDOUT as default FileHandleselect STDOUT; print("This goes to the console."); # Close the FileHandle.close(File); Output in the Console:Contents of Hello.txt:Original File:Updated File:My Personal Notes arrow_drop_upSave # Open Hello.txt in Read-Append Modeopen(ra, "+>>", "Hello.txt"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint("Existing Content of the File: " . <ra>); print "\nAppending to the File...."; # The string is appended to the Fileprint ra "Added using Read-Append Mode"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint("\nUpdated content of the File: " . <ra>); # Closing the Fileclose(rw); Output: Output can be redirected away from the Console and into a file using the select function. Syntax: select FileHandle;Parameters: FileHandle – FileHandle of the File to be selected. Steps: Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”. Select the FileHandle using select function. Now, anything that is printed using the print function is redirected to the File.Example: # Open a FileHandle in Write Mode.open(File, ">", "Hello.txt"); # This sets File as the default FileHandleselect File; # Writes to Fileprint("This goes to the File."); # Writes to Fileprint File "\nThis goes to the File too."; # This sets STDOUT as default FileHandleselect STDOUT; print("This goes to the console."); # Close the FileHandle.close(File); Output in the Console:Contents of Hello.txt:Original File: Updated File: Perl-files Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | grep() Function Perl | substr() function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | Removing leading and trailing white spaces (trim) Use of print() and say() in Perl Perl | length() Function
[ { "code": null, "e": 26549, "s": 26521, "text": "\n01 Apr, 2019" }, { "code": null, "e": 27034, "s": 26549, "text": "In Perl, a FileHandle associates a name to an external file, that can be used until the end of the program or until the FileHandle is closed. In short, a FileHandle is like a connection that can be used to modify the contents of an external file and a name is given to the connection (the FileHandle) for faster access and ease.The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively." }, { "code": null, "e": 27091, "s": 27034, "text": "File Handling is usually done through the open function." }, { "code": null, "e": 27133, "s": 27091, "text": "Syntax: open(FileHandle, Mode, FileName);" }, { "code": null, "e": 27145, "s": 27133, "text": "Parameters:" }, { "code": null, "e": 27242, "s": 27145, "text": "FileHandle- The reference to the file, that can be used within the program or until its closure." }, { "code": null, "e": 27286, "s": 27242, "text": "Mode- Mode in which a file is to be opened." }, { "code": null, "e": 27331, "s": 27286, "text": "FileName- The name of the file to be opened." }, { "code": null, "e": 27408, "s": 27331, "text": "Also, Mode and FileName can be clubbed to form a single expression for open." }, { "code": null, "e": 27457, "s": 27408, "text": "Syntax: open(FileHandle, Expression);Parameters:" }, { "code": null, "e": 27554, "s": 27457, "text": "FileHandle- The reference to the file, that can be used within the program or until its closure." }, { "code": null, "e": 27602, "s": 27554, "text": "Expression- Mode and FileName clubbed together." }, { "code": null, "e": 27653, "s": 27602, "text": "The FileHandle is closed using the close function." }, { "code": null, "e": 27691, "s": 27653, "text": "Syntax: close(FileHandle);Parameters:" }, { "code": null, "e": 27732, "s": 27691, "text": "FileHandle- The FileHandle to be closed." }, { "code": null, "e": 27801, "s": 27734, "text": " Reading from a FileHandle can be done through the print function." }, { "code": null, "e": 27841, "s": 27801, "text": "Syntax: print(<FileHandle>);Parameters:" }, { "code": null, "e": 27903, "s": 27841, "text": "FileHandle- FileHandle opened in read mode or a similar mode." }, { "code": null, "e": 27966, "s": 27903, "text": "Writing to a File can also be done through the print function." }, { "code": null, "e": 28009, "s": 27966, "text": "Syntax: print FileHandle StringParameters:" }, { "code": null, "e": 28072, "s": 28009, "text": "FileHandle- FileHandle opened in write mode or a similar mode." }, { "code": null, "e": 28119, "s": 28072, "text": "String- The String to be inserted in the file." }, { "code": null, "e": 28217, "s": 28119, "text": "Examples:Consider a file Hello.txt containing the string “Welcome to GeeksForGeeks!!!” initially." }, { "code": null, "e": 33109, "s": 28217, "text": "Mode = “<\"This is read-only Mode. This mode is used to Read the content line by line from the file.#!/usr/bin/perl # Opening a File in Read-only modeopen(r, \"<\", \"Hello.txt\"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r);Output:Mode = “>”This is write-only Mode. Original contents of the File are cleared once it is opened in this Mode. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening File in Write modeopen(w, \">\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nWriting to File...\"; # Writing to Hello.txt using printprint w \"Content of this file is changed\"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); Output:Mode=”>>”This is Append Mode. Original content of the File is not cleared when it is opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening the File in Append modeopen(A, \">>\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nAppending to File...\"; # Appending to Hello.txt using printprint A \" Hello Geeks!!!\"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); Output:Mode = “+<“This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot create a new File.#!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, \"+<\", \"Hello.txt\"); # Print original contents of the File. # rw is set to the end.print(\"Existing Content of Hello.txt: \".<rw>); # The string is attached at the end # of the original contents of the file.print rw \"Added using Read-Write Mode.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint(\"\\nUpdated contents of Hello.txt: \".<rw>); # Close the FileHandleclose(rw); Output:Mode = “+>”This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can create a new File, if one with the name is not found, but a “+<” cannot.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, \"+>\", \"Hello.txt\"); # Original contents of the File# are cleared when the File is openedprint(\"\\nContents of Hello.txt gets cleared...\"); # The string is written to the Fileprint rw \"Hello!!! This is updated file.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print(\"\\nUpdated Content of Hello.txt: \" .<rw>); # Closing the Fileclose(rw);Output:Mode = “+>>”This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A new File with same name is created, if one is not Found.# Open Hello.txt in Read-Append Modeopen(ra, \"+>>\", \"Hello.txt\"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint(\"Existing Content of the File: \" . <ra>); print \"\\nAppending to the File....\"; # The string is appended to the Fileprint ra \"Added using Read-Append Mode\"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint(\"\\nUpdated content of the File: \" . <ra>); # Closing the Fileclose(rw);Output: Redirecting Output Output can be redirected away from the Console and into a file using the select function.Syntax: select FileHandle;Parameters:FileHandle – FileHandle of the File to be selected.Steps:Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.Select the FileHandle using select function.Now, anything that is printed using the print function is redirected to the File.Example:# Open a FileHandle in Write Mode.open(File, \">\", \"Hello.txt\"); # This sets File as the default FileHandleselect File; # Writes to Fileprint(\"This goes to the File.\"); # Writes to Fileprint File \"\\nThis goes to the File too.\"; # This sets STDOUT as default FileHandleselect STDOUT; print(\"This goes to the console.\"); # Close the FileHandle.close(File); Output in the Console:Contents of Hello.txt:Original File:Updated File:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33365, "s": 33109, "text": "Mode = “<\"This is read-only Mode. This mode is used to Read the content line by line from the file.#!/usr/bin/perl # Opening a File in Read-only modeopen(r, \"<\", \"Hello.txt\"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r);Output:" }, { "code": "#!/usr/bin/perl # Opening a File in Read-only modeopen(r, \"<\", \"Hello.txt\"); # Printing content of the Fileprint(<r>); # Closing the Fileclose(r);", "e": 33515, "s": 33365, "text": null }, { "code": null, "e": 33523, "s": 33515, "text": "Output:" }, { "code": null, "e": 34308, "s": 33523, "text": "Mode = “>”This is write-only Mode. Original contents of the File are cleared once it is opened in this Mode. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening File in Write modeopen(w, \">\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nWriting to File...\"; # Writing to Hello.txt using printprint w \"Content of this file is changed\"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); Output:" }, { "code": "#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening File in Write modeopen(w, \">\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nWriting to File...\"; # Writing to Hello.txt using printprint w \"Content of this file is changed\"; # Closing the FileHandleclose(w); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); ", "e": 34915, "s": 34308, "text": null }, { "code": null, "e": 34923, "s": 34915, "text": "Output:" }, { "code": null, "e": 35777, "s": 34923, "text": "Mode=”>>”This is Append Mode. Original content of the File is not cleared when it is opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It creates a new File with the same name, if one is not found.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening the File in Append modeopen(A, \">>\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nAppending to File...\"; # Appending to Hello.txt using printprint A \" Hello Geeks!!!\"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); Output:" }, { "code": "#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Opening the File in Append modeopen(A, \">>\", \"Hello.txt\"); # Set r to the beginning of Hello.txtseek r, 0, 0; print \"\\nAppending to File...\"; # Appending to Hello.txt using printprint A \" Hello Geeks!!!\"; # close the FileHandleclose(A); # Set r to the beginning of Hello.txtseek r, 0, 0; # Print the current contents of Hello.txtprint(\"\\nUpdated Content of Hello.txt: \".<r>); # Close the FileHandleclose(r); ", "e": 36376, "s": 35777, "text": null }, { "code": null, "e": 36384, "s": 36376, "text": "Output:" }, { "code": null, "e": 37018, "s": 36384, "text": "Mode = “+<“This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot create a new File.#!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, \"+<\", \"Hello.txt\"); # Print original contents of the File. # rw is set to the end.print(\"Existing Content of Hello.txt: \".<rw>); # The string is attached at the end # of the original contents of the file.print rw \"Added using Read-Write Mode.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint(\"\\nUpdated contents of Hello.txt: \".<rw>); # Close the FileHandleclose(rw); Output:" }, { "code": "#!/usr/bin/perl # Open Hello.txt in Read-Write Modeopen(rw, \"+<\", \"Hello.txt\"); # Print original contents of the File. # rw is set to the end.print(\"Existing Content of Hello.txt: \".<rw>); # The string is attached at the end # of the original contents of the file.print rw \"Added using Read-Write Mode.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; # Printing the Updated content of the Fileprint(\"\\nUpdated contents of Hello.txt: \".<rw>); # Close the FileHandleclose(rw); ", "e": 37523, "s": 37018, "text": null }, { "code": null, "e": 37531, "s": 37523, "text": "Output:" }, { "code": null, "e": 38317, "s": 37531, "text": "Mode = “+>”This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can create a new File, if one with the name is not found, but a “+<” cannot.#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, \"+>\", \"Hello.txt\"); # Original contents of the File# are cleared when the File is openedprint(\"\\nContents of Hello.txt gets cleared...\"); # The string is written to the Fileprint rw \"Hello!!! This is updated file.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print(\"\\nUpdated Content of Hello.txt: \" .<rw>); # Closing the Fileclose(rw);Output:" }, { "code": "#!/usr/bin/perl # Opening File Hello.txt in Read modeopen(r, \"<\", \"Hello.txt\"); # Printing the existing content of the fileprint(\"Existing Content of Hello.txt: \" . <r>); # Closing the Fileclose(r); # Open Hello.txt in Read-Write Modeopen(rw, \"+>\", \"Hello.txt\"); # Original contents of the File# are cleared when the File is openedprint(\"\\nContents of Hello.txt gets cleared...\"); # The string is written to the Fileprint rw \"Hello!!! This is updated file.\"; # Set rw to the beginning of the File for reading.seek rw, 0, 0; print(\"\\nUpdated Content of Hello.txt: \" .<rw>); # Closing the Fileclose(rw);", "e": 38934, "s": 38317, "text": null }, { "code": null, "e": 38942, "s": 38934, "text": "Output:" }, { "code": null, "e": 40524, "s": 38942, "text": "Mode = “+>>”This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A new File with same name is created, if one is not Found.# Open Hello.txt in Read-Append Modeopen(ra, \"+>>\", \"Hello.txt\"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint(\"Existing Content of the File: \" . <ra>); print \"\\nAppending to the File....\"; # The string is appended to the Fileprint ra \"Added using Read-Append Mode\"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint(\"\\nUpdated content of the File: \" . <ra>); # Closing the Fileclose(rw);Output: Redirecting Output Output can be redirected away from the Console and into a file using the select function.Syntax: select FileHandle;Parameters:FileHandle – FileHandle of the File to be selected.Steps:Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.Select the FileHandle using select function.Now, anything that is printed using the print function is redirected to the File.Example:# Open a FileHandle in Write Mode.open(File, \">\", \"Hello.txt\"); # This sets File as the default FileHandleselect File; # Writes to Fileprint(\"This goes to the File.\"); # Writes to Fileprint File \"\\nThis goes to the File too.\"; # This sets STDOUT as default FileHandleselect STDOUT; print(\"This goes to the console.\"); # Close the FileHandle.close(File); Output in the Console:Contents of Hello.txt:Original File:Updated File:My Personal Notes\narrow_drop_upSave" }, { "code": "# Open Hello.txt in Read-Append Modeopen(ra, \"+>>\", \"Hello.txt\"); # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Original content of the File # is NOT cleared when the File is openedprint(\"Existing Content of the File: \" . <ra>); print \"\\nAppending to the File....\"; # The string is appended to the Fileprint ra \"Added using Read-Append Mode\"; # Set ra to the beginning of the File for reading.seek ra, 0, 0; # Printing the updated contentprint(\"\\nUpdated content of the File: \" . <ra>); # Closing the Fileclose(rw);", "e": 41072, "s": 40524, "text": null }, { "code": null, "e": 41080, "s": 41072, "text": "Output:" }, { "code": null, "e": 41173, "s": 41082, "text": " Output can be redirected away from the Console and into a file using the select function." }, { "code": null, "e": 41211, "s": 41173, "text": "Syntax: select FileHandle;Parameters:" }, { "code": null, "e": 41263, "s": 41211, "text": "FileHandle – FileHandle of the File to be selected." }, { "code": null, "e": 41270, "s": 41263, "text": "Steps:" }, { "code": null, "e": 41334, "s": 41270, "text": "Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”." }, { "code": null, "e": 41379, "s": 41334, "text": "Select the FileHandle using select function." }, { "code": null, "e": 41469, "s": 41379, "text": "Now, anything that is printed using the print function is redirected to the File.Example:" }, { "code": "# Open a FileHandle in Write Mode.open(File, \">\", \"Hello.txt\"); # This sets File as the default FileHandleselect File; # Writes to Fileprint(\"This goes to the File.\"); # Writes to Fileprint File \"\\nThis goes to the File too.\"; # This sets STDOUT as default FileHandleselect STDOUT; print(\"This goes to the console.\"); # Close the FileHandle.close(File); ", "e": 41834, "s": 41469, "text": null }, { "code": null, "e": 41893, "s": 41834, "text": "Output in the Console:Contents of Hello.txt:Original File:" }, { "code": null, "e": 41907, "s": 41893, "text": "Updated File:" }, { "code": null, "e": 41918, "s": 41907, "text": "Perl-files" }, { "code": null, "e": 41925, "s": 41918, "text": "Picked" }, { "code": null, "e": 41930, "s": 41925, "text": "Perl" }, { "code": null, "e": 41935, "s": 41930, "text": "Perl" }, { "code": null, "e": 42033, "s": 41935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42057, "s": 42033, "text": "Perl | split() Function" }, { "code": null, "e": 42080, "s": 42057, "text": "Perl | push() Function" }, { "code": null, "e": 42104, "s": 42080, "text": "Perl | chomp() Function" }, { "code": null, "e": 42127, "s": 42104, "text": "Perl | grep() Function" }, { "code": null, "e": 42152, "s": 42127, "text": "Perl | substr() function" }, { "code": null, "e": 42177, "s": 42152, "text": "Perl | exists() Function" }, { "code": null, "e": 42218, "s": 42177, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 42275, "s": 42218, "text": "Perl | Removing leading and trailing white spaces (trim)" }, { "code": null, "e": 42308, "s": 42275, "text": "Use of print() and say() in Perl" } ]
How to Install Linux on Windows PowerShell Subsystem? - GeeksforGeeks
06 Oct, 2021 There are several ways to Install a Linux subsystem on your Windows PC Powershell Environment. It is good for learners, but it is recommended using original Linux OS if you are a developer as the Subsystem lacks the pre-installed Linux tools. Before we begin installing a Linux subsystem, we need to first enable a Windows feature for Subsystems. To install Linux Subsystem, there is a need to Turn Windows features ON. Steps to do the same are as follows: Step 1: Search and open Turn Windows features on or off in Start Menu. Step 2: Look for Windows Subsystem for Linux and enable it. Step 3: Once the installation is over, reboot your system to finish adding the changes. Downloading and Installing Linux OS:There are two ways to download and install any Linux OS in the Windows Subsystem: Downloading from the Microsoft Store Downloading using Windows PowerShell Step 1: Open MS Store and search for Linux. Now, download any of the listed Linux OSs. Step 2: Click on the Get button and begin with the downloading of Kali Linux OS. Step 3: Once the Installation is over click on the Launch button. Step 4: Begin with the final installation process on the command-line. Step 5: Provide a Username and password for your Linux OS and finish the installation process. Step 1: Search for Windows Powershell in the Start Menu and open it. Step 2: Type the following command to install Linux OS and press Enter: Invoke-WebRequest -Uri https://wsldownload.azureedge.net/Ubuntu_1604.2019.523.0_x64.appx -OutFile Ubuntu.appx -UseBasicParsing Add-AppxPackage .\Ubuntu.appx Step 3: Launch Ubuntu from the Start Menu and begin with the rest of the Installation process: Step 4: Provide Username and password to setup your Linux OS and finish the installation process. Once the installation of the Linux Subsystem is over, it can be launched anytime with Windows PowerShell. Just type the name of the OS in the PowerShell and press Enter. how-to-install Technical Scripter 2019 How To Installation Guide Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Align Text in HTML? How to Install OpenCV for Python on Windows? How to filter object array based on attributes? Java Tutorial How to Install FFmpeg on Windows? Installation of Node.js on Linux How to Install OpenCV for Python on Windows? How to Install FFmpeg on Windows? How to Install Anaconda on Windows? How to Install Pygame on Windows ?
[ { "code": null, "e": 25935, "s": 25907, "text": "\n06 Oct, 2021" }, { "code": null, "e": 26178, "s": 25935, "text": "There are several ways to Install a Linux subsystem on your Windows PC Powershell Environment. It is good for learners, but it is recommended using original Linux OS if you are a developer as the Subsystem lacks the pre-installed Linux tools." }, { "code": null, "e": 26282, "s": 26178, "text": "Before we begin installing a Linux subsystem, we need to first enable a Windows feature for Subsystems." }, { "code": null, "e": 26392, "s": 26282, "text": "To install Linux Subsystem, there is a need to Turn Windows features ON. Steps to do the same are as follows:" }, { "code": null, "e": 26729, "s": 26392, "text": "Step 1: Search and open Turn Windows features on or off in Start Menu. Step 2: Look for Windows Subsystem for Linux and enable it. Step 3: Once the installation is over, reboot your system to finish adding the changes. Downloading and Installing Linux OS:There are two ways to download and install any Linux OS in the Windows Subsystem:" }, { "code": null, "e": 26766, "s": 26729, "text": "Downloading from the Microsoft Store" }, { "code": null, "e": 26803, "s": 26766, "text": "Downloading using Windows PowerShell" }, { "code": null, "e": 27203, "s": 26803, "text": "Step 1: Open MS Store and search for Linux. Now, download any of the listed Linux OSs. Step 2: Click on the Get button and begin with the downloading of Kali Linux OS. Step 3: Once the Installation is over click on the Launch button. Step 4: Begin with the final installation process on the command-line. Step 5: Provide a Username and password for your Linux OS and finish the installation process." }, { "code": null, "e": 27344, "s": 27203, "text": "Step 1: Search for Windows Powershell in the Start Menu and open it. Step 2: Type the following command to install Linux OS and press Enter:" }, { "code": null, "e": 27501, "s": 27344, "text": "Invoke-WebRequest -Uri https://wsldownload.azureedge.net/Ubuntu_1604.2019.523.0_x64.appx -OutFile Ubuntu.appx -UseBasicParsing\nAdd-AppxPackage .\\Ubuntu.appx" }, { "code": null, "e": 27865, "s": 27501, "text": " Step 3: Launch Ubuntu from the Start Menu and begin with the rest of the Installation process: Step 4: Provide Username and password to setup your Linux OS and finish the installation process. Once the installation of the Linux Subsystem is over, it can be launched anytime with Windows PowerShell. Just type the name of the OS in the PowerShell and press Enter." }, { "code": null, "e": 27880, "s": 27865, "text": "how-to-install" }, { "code": null, "e": 27904, "s": 27880, "text": "Technical Scripter 2019" }, { "code": null, "e": 27911, "s": 27904, "text": "How To" }, { "code": null, "e": 27930, "s": 27911, "text": "Installation Guide" }, { "code": null, "e": 27941, "s": 27930, "text": "Linux-Unix" }, { "code": null, "e": 27960, "s": 27941, "text": "Technical Scripter" }, { "code": null, "e": 28058, "s": 27960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28085, "s": 28058, "text": "How to Align Text in HTML?" }, { "code": null, "e": 28130, "s": 28085, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 28178, "s": 28130, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28192, "s": 28178, "text": "Java Tutorial" }, { "code": null, "e": 28226, "s": 28192, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28259, "s": 28226, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28304, "s": 28259, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 28338, "s": 28304, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 28374, "s": 28338, "text": "How to Install Anaconda on Windows?" } ]
Detect Cycle in a 2D grid - GeeksforGeeks
14 Jun, 2021 Given a 2D grid arr[][] with different characters, the task is to detect whether it contains a cycle or not. A sequence of characters or integers c1, c2, .... cM is called a cycle if and only if it meets the following condition: M should at least be 4. All characters belong to the same character or integer. For all 0 <= i <= M -1 : ci and ci + 1 are adjacent. Also, cM and c1 should also be adjacent that is they if they share a common edge. Examples: Input: arr[][] = {{‘A’, ‘A’, ‘A’, ‘A’}, {‘A’, ‘B’, ‘C’, ‘A’}, {‘A’, ‘D’, ‘D’, ‘A’}};Output: NoExplanation:There is no cycle in the above matrix as there is no such component which matches the requirements of being a cycle. Input: arr[N][M] = {{‘A’, ‘A’, ‘A’, ‘A’}, {‘A’, ‘B’, ‘C’, ‘A’}, {‘A’, ‘A’, ‘A’, ‘A’}}; Output: Yes Explanation:Cells mentioned below forms a cycle because all requirements are fulfilled.{(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)}. Approach: The idea is to use DFS Traversal on the grid to detect a cycle in it. Below are the steps: Pick every cell of the given matrix ((0, 0) to (N – 1, M – 1)) because there is no definite position of the cycle. If there exists a cycle, then all the cells of the cycle should have the same value, and they should be connected and also check that the last and the first element should form a loop (they should have different parents). Take a boolean variable that will store the result of the function isCycle() which will be a 1 or 0 respectively, indicating whether there is a cycle or not. If the function returns 1, then switch the ans variable to true, and break the loop else continue. If the ans remains unmarked till the last then print No otherwise print Yes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Define size of grid#define N 3#define M 4 // To store direction of all the four// adjacent cellsconst int directionInX[4] = { -1, 0, 1, 0 };const int directionInY[4] = { 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notbool isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return 1; return 0;} // Boolean function which will check// whether the given array consist// of a cycle or notbool isCycle(int x, int y, char arr[N][M], bool visited[N][M], int parentX, int parentY){ // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for (int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == 1 && arr[newX][newY] == arr[x][y] && !(parentX == newX and parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == 1) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { bool check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == 1) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridvoid detectCycle(char arr[N][M]){ // To store the visited cell bool visited[N][M]; // Initially marking all // the cells as unvisited for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) visited[i][j] = false; // Boolean variable for // storing the result bool cycle = 0; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for (int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for (int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == 0) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { cout << "Yes"; } // Cycle was not encountered else { cout << "No"; }} // Driver codeint main(){ // Given grid arr[][] char arr[N][M] = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function Call detectCycle(arr); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Define size of gridstatic final int N = 3;static final int M = 4; // To store direction of all the four// adjacent cellsstatic int directionInX[] = new int[]{ -1, 0, 1, 0 };static int directionInY[] = new int[]{ 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notstatic boolean isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return true; else return false;} // Boolean function which will check// whether the given array consist// of a cycle or notstatic boolean isCycle(int x, int y, char arr[][], boolean visited[][], int parentX, int parentY){ // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX][newY] == arr[x][y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { boolean check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridstatic void detectCycle(char arr[][]){ // To store the visited cell boolean [][]visited = new boolean[N][M]; // Initially marking all // the cells as unvisited for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) visited[i][j] = false; // Boolean variable for // storing the result boolean cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for(int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { System.out.print("Yes"); } // Cycle was not encountered else { System.out.print("No"); }} // Driver codepublic static void main(String[] args){ // Given grid arr[][] char arr[][] = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function call detectCycle(arr);}} // This code is contributed by amal kumar choubey # Python3 program for the above approach # Store direction of all the four# adjacent cells. We'll move along# the grid using pairs of valuesdirectionInX = [ -1, 0, 1, 0 ]directionInY = [ 0, 1, 0, -1 ] # Function for checking# if a cell is valid or notdef isValid(x, y, N, M): if (x < N and x >= 0 and y < M and y >= 0): return True return False # Function which will check whether# the given array consist of a cycle or notdef isCycle(x, y, arr, visited, parentX, parentY): # Mark the current vertex as visited visited[x][y] = True N, M = 3, 4 # Loop for generate all possibilities # of adjacent cells and checking them for k in range(4): newX = x + directionInX[k] newY = y + directionInY[k] if (isValid(newX, newY, N, M) and arr[newX][newY] == arr[x][y] and not (parentX == newX and parentY == newY)): # Check if there exist # cycle then return true if visited[newX][newY]: # Return True as the # cycle exists return True # If the cycle is not found # then keep checking recursively else: check = isCycle(newX, newY, arr, visited, x, y) if check: return True # If there was no cycle, taking # x and y as source then return false return False # Function to detect Cycle in a griddef detectCycle(arr): N, M = 3, 4 # Initially all the cells are unvisited visited = [[False] * M for _ in range(N)] # Variable to store the result cycle = False # As there is no fixed position # of the cycle we have to loop # through all the elements for i in range(N): # If cycle is present and # we have already detected # it, then break this loop if cycle == True: break for j in range(M): # Taking (-1, -1) as source # node's parent if visited[i][j] == False: cycle = isCycle(i, j, arr, visited, -1, -1) # If we have encountered a # cycle then break this loop if cycle == True: break # Cycle was encountered if cycle == True: print("Yes") # Cycle was not encountered else: print("No") # Driver codearr = [ [ 'A', 'A', 'A', 'A' ], [ 'A', 'B', 'C', 'A' ], [ 'A', 'D', 'D', 'A' ] ] # Function calldetectCycle(arr) # This code is contributed by soum1071 // C# program for the above approachusing System; class GFG{ // Define size of gridstatic readonly int N = 3;static readonly int M = 4; // To store direction of all the four// adjacent cellsstatic int []directionInX = new int[]{ -1, 0, 1, 0 };static int []directionInY = new int[]{ 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notstatic bool isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return true; else return false;} // Boolean function which will check// whether the given array consist// of a cycle or notstatic bool isCycle(int x, int y, char [,]arr, bool [,]visited, int parentX, int parentY){ // Mark the current vertex true visited[x, y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX, newY] == arr[x, y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX, newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { bool check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridstatic void detectCycle(char [,]arr){ // To store the visited cell bool [,]visited = new bool[N, M]; // Initially marking all // the cells as unvisited for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) visited[i, j] = false; // Boolean variable for // storing the result bool cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i,j] for(int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i, j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { Console.Write("Yes"); } // Cycle was not encountered else { Console.Write("No"); }} // Driver codepublic static void Main(String[] args){ // Given grid [,]arr char [,]arr = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function call detectCycle(arr);}} // This code is contributed by amal kumar choubey <script> // Javascript program for the above approach // Define size of grid let N = 3; let M = 4; // To store direction of all the four // adjacent cells let directionInX = [ -1, 0, 1, 0 ]; let directionInY = [ 0, 1, 0, -1 ]; // Boolean function for checking // if a cell is valid or not function isValid(x, y) { if (x < N && x >= 0 && y < M && y >= 0) return true; else return false; } // Boolean function which will check // whether the given array consist // of a cycle or not function isCycle(x, y, arr, visited, parentX, parentY) { // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(let k = 0; k < 4; k++) { let newX = x + directionInX[k]; let newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX][newY] == arr[x][y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { let check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false; } // Function to detect Cycle in a grid function detectCycle(arr) { // To store the visited cell let visited = new Array(N); // Initially marking all // the cells as unvisited for(let i = 0; i < N; i++) { visited[i] = new Array(M); for(let j = 0; j < M; j++) { visited[i][j] = false; } } // Boolean variable for // storing the result let cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for(let i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(let j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { document.write("Yes"); } // Cycle was not encountered else { document.write("No"); } } // Given grid arr[][] let arr = [ [ 'A', 'A', 'A', 'A' ], [ 'A', 'B', 'C', 'A' ], [ 'A', 'D', 'D', 'A' ] ]; // Function call detectCycle(arr); // This code is contributed by divyeshrabadiy07.</script> No Time Complexity: O(N * M)Auxiliary Space: O(N * M) Amal Kumar Choubey soum1071 simranarora5sos divyeshrabadiya07 graph-cycle Arrays Matrix Pattern Searching Recursion Searching Arrays Searching Recursion Matrix Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26067, "s": 26039, "text": "\n14 Jun, 2021" }, { "code": null, "e": 26176, "s": 26067, "text": "Given a 2D grid arr[][] with different characters, the task is to detect whether it contains a cycle or not." }, { "code": null, "e": 26297, "s": 26176, "text": "A sequence of characters or integers c1, c2, .... cM is called a cycle if and only if it meets the following condition:" }, { "code": null, "e": 26321, "s": 26297, "text": "M should at least be 4." }, { "code": null, "e": 26431, "s": 26321, "text": "All characters belong to the same character or integer. For all 0 <= i <= M -1 : ci and ci + 1 are adjacent." }, { "code": null, "e": 26513, "s": 26431, "text": "Also, cM and c1 should also be adjacent that is they if they share a common edge." }, { "code": null, "e": 26523, "s": 26513, "text": "Examples:" }, { "code": null, "e": 26565, "s": 26523, "text": "Input: arr[][] = {{‘A’, ‘A’, ‘A’, ‘A’}, " }, { "code": null, "e": 26614, "s": 26565, "text": " {‘A’, ‘B’, ‘C’, ‘A’}, " }, { "code": null, "e": 26799, "s": 26614, "text": " {‘A’, ‘D’, ‘D’, ‘A’}};Output: NoExplanation:There is no cycle in the above matrix as there is no such component which matches the requirements of being a cycle." }, { "code": null, "e": 26873, "s": 26799, "text": "Input: arr[N][M] = {{‘A’, ‘A’, ‘A’, ‘A’}, " }, { "code": null, "e": 26957, "s": 26873, "text": " {‘A’, ‘B’, ‘C’, ‘A’}, " }, { "code": null, "e": 27010, "s": 26957, "text": " {‘A’, ‘A’, ‘A’, ‘A’}};" }, { "code": null, "e": 27193, "s": 27010, "text": "Output: Yes Explanation:Cells mentioned below forms a cycle because all requirements are fulfilled.{(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)}." }, { "code": null, "e": 27295, "s": 27193, "text": "Approach: The idea is to use DFS Traversal on the grid to detect a cycle in it. Below are the steps: " }, { "code": null, "e": 27410, "s": 27295, "text": "Pick every cell of the given matrix ((0, 0) to (N – 1, M – 1)) because there is no definite position of the cycle." }, { "code": null, "e": 27632, "s": 27410, "text": "If there exists a cycle, then all the cells of the cycle should have the same value, and they should be connected and also check that the last and the first element should form a loop (they should have different parents)." }, { "code": null, "e": 27889, "s": 27632, "text": "Take a boolean variable that will store the result of the function isCycle() which will be a 1 or 0 respectively, indicating whether there is a cycle or not. If the function returns 1, then switch the ans variable to true, and break the loop else continue." }, { "code": null, "e": 27966, "s": 27889, "text": "If the ans remains unmarked till the last then print No otherwise print Yes." }, { "code": null, "e": 28017, "s": 27966, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28021, "s": 28017, "text": "C++" }, { "code": null, "e": 28026, "s": 28021, "text": "Java" }, { "code": null, "e": 28034, "s": 28026, "text": "Python3" }, { "code": null, "e": 28037, "s": 28034, "text": "C#" }, { "code": null, "e": 28048, "s": 28037, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Define size of grid#define N 3#define M 4 // To store direction of all the four// adjacent cellsconst int directionInX[4] = { -1, 0, 1, 0 };const int directionInY[4] = { 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notbool isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return 1; return 0;} // Boolean function which will check// whether the given array consist// of a cycle or notbool isCycle(int x, int y, char arr[N][M], bool visited[N][M], int parentX, int parentY){ // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for (int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == 1 && arr[newX][newY] == arr[x][y] && !(parentX == newX and parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == 1) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { bool check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == 1) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridvoid detectCycle(char arr[N][M]){ // To store the visited cell bool visited[N][M]; // Initially marking all // the cells as unvisited for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) visited[i][j] = false; // Boolean variable for // storing the result bool cycle = 0; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for (int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for (int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == 0) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { cout << \"Yes\"; } // Cycle was not encountered else { cout << \"No\"; }} // Driver codeint main(){ // Given grid arr[][] char arr[N][M] = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function Call detectCycle(arr); return 0;}", "e": 31283, "s": 28048, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Define size of gridstatic final int N = 3;static final int M = 4; // To store direction of all the four// adjacent cellsstatic int directionInX[] = new int[]{ -1, 0, 1, 0 };static int directionInY[] = new int[]{ 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notstatic boolean isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return true; else return false;} // Boolean function which will check// whether the given array consist// of a cycle or notstatic boolean isCycle(int x, int y, char arr[][], boolean visited[][], int parentX, int parentY){ // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX][newY] == arr[x][y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { boolean check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridstatic void detectCycle(char arr[][]){ // To store the visited cell boolean [][]visited = new boolean[N][M]; // Initially marking all // the cells as unvisited for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) visited[i][j] = false; // Boolean variable for // storing the result boolean cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for(int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { System.out.print(\"Yes\"); } // Cycle was not encountered else { System.out.print(\"No\"); }} // Driver codepublic static void main(String[] args){ // Given grid arr[][] char arr[][] = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function call detectCycle(arr);}} // This code is contributed by amal kumar choubey", "e": 34885, "s": 31283, "text": null }, { "code": "# Python3 program for the above approach # Store direction of all the four# adjacent cells. We'll move along# the grid using pairs of valuesdirectionInX = [ -1, 0, 1, 0 ]directionInY = [ 0, 1, 0, -1 ] # Function for checking# if a cell is valid or notdef isValid(x, y, N, M): if (x < N and x >= 0 and y < M and y >= 0): return True return False # Function which will check whether# the given array consist of a cycle or notdef isCycle(x, y, arr, visited, parentX, parentY): # Mark the current vertex as visited visited[x][y] = True N, M = 3, 4 # Loop for generate all possibilities # of adjacent cells and checking them for k in range(4): newX = x + directionInX[k] newY = y + directionInY[k] if (isValid(newX, newY, N, M) and arr[newX][newY] == arr[x][y] and not (parentX == newX and parentY == newY)): # Check if there exist # cycle then return true if visited[newX][newY]: # Return True as the # cycle exists return True # If the cycle is not found # then keep checking recursively else: check = isCycle(newX, newY, arr, visited, x, y) if check: return True # If there was no cycle, taking # x and y as source then return false return False # Function to detect Cycle in a griddef detectCycle(arr): N, M = 3, 4 # Initially all the cells are unvisited visited = [[False] * M for _ in range(N)] # Variable to store the result cycle = False # As there is no fixed position # of the cycle we have to loop # through all the elements for i in range(N): # If cycle is present and # we have already detected # it, then break this loop if cycle == True: break for j in range(M): # Taking (-1, -1) as source # node's parent if visited[i][j] == False: cycle = isCycle(i, j, arr, visited, -1, -1) # If we have encountered a # cycle then break this loop if cycle == True: break # Cycle was encountered if cycle == True: print(\"Yes\") # Cycle was not encountered else: print(\"No\") # Driver codearr = [ [ 'A', 'A', 'A', 'A' ], [ 'A', 'B', 'C', 'A' ], [ 'A', 'D', 'D', 'A' ] ] # Function calldetectCycle(arr) # This code is contributed by soum1071", "e": 37645, "s": 34885, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Define size of gridstatic readonly int N = 3;static readonly int M = 4; // To store direction of all the four// adjacent cellsstatic int []directionInX = new int[]{ -1, 0, 1, 0 };static int []directionInY = new int[]{ 0, 1, 0, -1 }; // Boolean function for checking// if a cell is valid or notstatic bool isValid(int x, int y){ if (x < N && x >= 0 && y < M && y >= 0) return true; else return false;} // Boolean function which will check// whether the given array consist// of a cycle or notstatic bool isCycle(int x, int y, char [,]arr, bool [,]visited, int parentX, int parentY){ // Mark the current vertex true visited[x, y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(int k = 0; k < 4; k++) { int newX = x + directionInX[k]; int newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX, newY] == arr[x, y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX, newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { bool check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false;} // Function to detect Cycle in a gridstatic void detectCycle(char [,]arr){ // To store the visited cell bool [,]visited = new bool[N, M]; // Initially marking all // the cells as unvisited for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) visited[i, j] = false; // Boolean variable for // storing the result bool cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i,j] for(int i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(int j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i, j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { Console.Write(\"Yes\"); } // Cycle was not encountered else { Console.Write(\"No\"); }} // Driver codepublic static void Main(String[] args){ // Given grid [,]arr char [,]arr = { { 'A', 'A', 'A', 'A' }, { 'A', 'B', 'C', 'A' }, { 'A', 'D', 'D', 'A' } }; // Function call detectCycle(arr);}} // This code is contributed by amal kumar choubey", "e": 41202, "s": 37645, "text": null }, { "code": "<script> // Javascript program for the above approach // Define size of grid let N = 3; let M = 4; // To store direction of all the four // adjacent cells let directionInX = [ -1, 0, 1, 0 ]; let directionInY = [ 0, 1, 0, -1 ]; // Boolean function for checking // if a cell is valid or not function isValid(x, y) { if (x < N && x >= 0 && y < M && y >= 0) return true; else return false; } // Boolean function which will check // whether the given array consist // of a cycle or not function isCycle(x, y, arr, visited, parentX, parentY) { // Mark the current vertex true visited[x][y] = true; // Loop for generate all possibilities // of adjacent cells and checking them for(let k = 0; k < 4; k++) { let newX = x + directionInX[k]; let newY = y + directionInY[k]; if (isValid(newX, newY) == true && arr[newX][newY] == arr[x][y] && !(parentX == newX && parentY == newY)) { // Check if there exist // cycle then return true if (visited[newX][newY] == true) { // Return 1 because the // cycle exists return true; } // Check if not found, // keep checking recursively else { let check = isCycle(newX, newY, arr, visited, x, y); // Now, if check comes out // to be true then return 1 // indicating there exist cycle if (check == true) return true; } } } // If there was no cycle, // taking x and y as source // then return false return false; } // Function to detect Cycle in a grid function detectCycle(arr) { // To store the visited cell let visited = new Array(N); // Initially marking all // the cells as unvisited for(let i = 0; i < N; i++) { visited[i] = new Array(M); for(let j = 0; j < M; j++) { visited[i][j] = false; } } // Boolean variable for // storing the result let cycle = false; // As there is no fix position // of Cycle we will have to // check for every arr[i][j] for(let i = 0; i < N; i++) { // If cycle is present and // we have already detected // it, then break this loop if (cycle == true) break; for(let j = 0; j < M; j++) { // Taking (-1, -1) as // source node's parent if (visited[i][j] == false) { cycle = isCycle(i, j, arr, visited, -1, -1); } // If we have encountered a // cycle then break this loop if (cycle == true) break; } } // Cycle was encountered if (cycle == true) { document.write(\"Yes\"); } // Cycle was not encountered else { document.write(\"No\"); } } // Given grid arr[][] let arr = [ [ 'A', 'A', 'A', 'A' ], [ 'A', 'B', 'C', 'A' ], [ 'A', 'D', 'D', 'A' ] ]; // Function call detectCycle(arr); // This code is contributed by divyeshrabadiy07.</script>", "e": 44994, "s": 41202, "text": null }, { "code": null, "e": 44997, "s": 44994, "text": "No" }, { "code": null, "e": 45050, "s": 44999, "text": "Time Complexity: O(N * M)Auxiliary Space: O(N * M)" }, { "code": null, "e": 45069, "s": 45050, "text": "Amal Kumar Choubey" }, { "code": null, "e": 45078, "s": 45069, "text": "soum1071" }, { "code": null, "e": 45094, "s": 45078, "text": "simranarora5sos" }, { "code": null, "e": 45112, "s": 45094, "text": "divyeshrabadiya07" }, { "code": null, "e": 45124, "s": 45112, "text": "graph-cycle" }, { "code": null, "e": 45131, "s": 45124, "text": "Arrays" }, { "code": null, "e": 45138, "s": 45131, "text": "Matrix" }, { "code": null, "e": 45156, "s": 45138, "text": "Pattern Searching" }, { "code": null, "e": 45166, "s": 45156, "text": "Recursion" }, { "code": null, "e": 45176, "s": 45166, "text": "Searching" }, { "code": null, "e": 45183, "s": 45176, "text": "Arrays" }, { "code": null, "e": 45193, "s": 45183, "text": "Searching" }, { "code": null, "e": 45203, "s": 45193, "text": "Recursion" }, { "code": null, "e": 45210, "s": 45203, "text": "Matrix" }, { "code": null, "e": 45228, "s": 45210, "text": "Pattern Searching" }, { "code": null, "e": 45326, "s": 45228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45353, "s": 45326, "text": "Count pairs with given sum" }, { "code": null, "e": 45384, "s": 45353, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 45409, "s": 45384, "text": "Window Sliding Technique" }, { "code": null, "e": 45447, "s": 45409, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 45468, "s": 45447, "text": "Next Greater Element" }, { "code": null, "e": 45503, "s": 45468, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 45534, "s": 45503, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 45577, "s": 45534, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 45601, "s": 45577, "text": "Sudoku | Backtracking-7" } ]
Maximize the number of segments of length p, q and r - GeeksforGeeks
29 Nov, 2021 Given a rod of length L, the task is to cut the rod in such a way that the total number of segments of length p, q and r is maximized. The segments can only be of length p, q, and r. Examples: Input: l = 11, p = 2, q = 3, r = 5 Output: 5 Segments of 2, 2, 2, 2 and 3 Input: l = 7, p = 2, q = 5, r = 5 Output: 2 Segments of 2 and 5 Approach 1: This can be visualized as a classical recursion problem , which further narrows down to memoization ( top-down ) method of Dynamic Programming. Initially , we have length l present with us , we’d have three size choices to cut from this , either we can make a cut of length p , or q , or r. Let’s say we made a cut of length p , so the remaining length would be l-p and similarly with cuts q & r resulting in remaining lengths l-q & l-r respectively. We will call recursive function for the remaining lengths and at any subsequent instance we’ll have these three choices. We will store the answer from all these recursive calls & take the maximum out of them +1 as at any instance we’ll have 1 cut from this particular call as well. Also , note that the recursive call would be made if and only if the available length is greater than length we want to cut i.e. suppose p=3 , and after certain recursive calls the available length is 2 only , so we can’t cut this line in lengths of p anymore. Below is the pseudocode for the same: if(l==0) // Base Case return 0; int a,b,c; if(p<=l) a=func(l-p,p,q,r); if(q<=l) b=func(l-q,p,q,r); if(r<=l) c=func(l-r,p,q,r); return 1+max({a,b,c}); Below is the recursion tree for l=4,p=2,q=1 and r=1: Recursion Tree for l=4 , p=2 ,q=1 and r=1 One can clearly observe that at each call , the given length ( 4 initially ) is divided into 3 different subparts. Also , we can see that the recursion is being repeated for certain entries ( Red arrow represents repetitive call for l=2, Yellow for l=3 and Blue for l=1). Therefore , we can memoize the results in any container or array , so that repetition of same recursive calls is avoided. Now , the above pseudocode changes to : vector<int> dp(10005,-1); // Initialise DP Table ( Array can also be used ) if(l==0) // Base Case return 0; if(dp[l]!=-1) // If already memoized , return from here only return dp[l]; int a,b,c; if(p<=l) a=func(l-p,p,q,r); if(q<=l) b=func(l-q,p,q,r); if(r<=l) c=func(l-r,p,q,r); return dp[l]=1+max({a,b,c}); // Memoize the result in the dp table & return Let’s now follow the code for implementation of the above code : C++ //C++ Code to find maximum number of cut segments// Memoization DP #include <bits/stdc++.h>using namespace std; //Function to find the maximum number of cuts.int dp[10005]; int func(int l, int p, int q, int r){ if(l==0) return 0; // Base Case if(dp[l]!=-1) // If already memoized return dp[l]; int a(INT_MIN),b(INT_MIN),c(INT_MIN); // Intitialise a,b,& c with INT_MIN if(p<=l) // If Possible to make a cut of length p a=func(l-p,p,q,r); if(q<=l) // If possible to make a cut of length q b=func(l-q,p,q,r); if(r<=l) // If possible to make a cut of length r c=func(l-r,p,q,r); return dp[l]=1+max({a,b,c}); // Memoize & return } int maximizeTheCuts(int l, int p, int q, int r){ memset(dp,-1,sizeof(dp)); // Set Lookup table to -1 int ans=func(l,p,q,r); // Utility function call if(ans<0) return 0; // If returned answer is negative , that means cuts are not possible return ans; } int main(){ int l,p,q,r; cout<<"ENTER THE LENGTH OF THE ROD "<<endl; cin>>l; cout<<"ENTER THE VALUES OF p,q & r "<<endl; cin>>p>>q>>r; cout<<"THE MAXIMUM NUMBER OF SEGMENTS THAT CAN BE CUT OF LENGTH p,q & r FROM A ROD OF LENGTH l are "<<maximizeTheCuts(l,p,q,r)<<endl; return 0;} Time Complexity : O(n) where n is the length of rod or line segment that has to be cut. Space Complexity : O(n) where n is the length of rod or line segment that has to be cut. Approach 2: As the solution for a maximum number of cuts that can be made in a given length depends on the maximum number of cuts previously made in shorter lengths, this question could be solved by the approach of Dynamic Programming. Suppose we are given a length ‘l’. For finding the maximum number of cuts that can be made in length ‘l’, find the number of cuts made in shorter previous length ‘l-p’, ‘l-q’, ‘l-r’ lengths respectively. The required answer would be the max(l-p,l-q,l-r)+1 as one more cut should be needed after this to cut length ‘l’. So for solving this problem for a given length, find the maximum number of cuts that can be made in lengths ranging from ‘1’ to ‘l’. Example: l = 11, p = 2, q = 3, r = 5 Analysing lengths from 1 to 11: Not possible to cut->0Possible cut is of lengths 2->1 (2)Possible cut is of lengths 3->1 (3)Possible cuts are of lengths max(arr[4-2],arr[4-3])+1->2 (2,2)Possible cuts are of lengths max(arr[5-2],arr[5-3])+1->2 (2,3)Possible cuts are of lengths max(arr[6-2],arr[6-3],arr[6-5])+1->3 (2,2,2)Possible cuts are of lengths max(arr[7-2],arr[7-3],arr[7-5])+1->3 (2,3,2) or (2,2,3)Possible cuts are of lengths max(arr[8-2],arr[8-3],arr[8-5])+1->4 (2,2,2,2)Possible cuts are of lengths max(arr[9-2],arr[9-3],arr[9-5])+1->4 (2,3,2,2) or (2,2,3,2) or (2,2,2,3)Possible cuts are of lengths max(arr[10-2],arr[10-3],arr[10-5])+1->5 (2,2,2,2,2)Possible cuts are of lengths max(arr[11-2],arr[11-3],arr[11-5])+1->5 (2,3,2,2,2) or (2,2,3,2,2) or (2,2,2,3,2) or (2,2,2,2,3) Not possible to cut->0 Possible cut is of lengths 2->1 (2) Possible cut is of lengths 3->1 (3) Possible cuts are of lengths max(arr[4-2],arr[4-3])+1->2 (2,2) Possible cuts are of lengths max(arr[5-2],arr[5-3])+1->2 (2,3) Possible cuts are of lengths max(arr[6-2],arr[6-3],arr[6-5])+1->3 (2,2,2) Possible cuts are of lengths max(arr[7-2],arr[7-3],arr[7-5])+1->3 (2,3,2) or (2,2,3) Possible cuts are of lengths max(arr[8-2],arr[8-3],arr[8-5])+1->4 (2,2,2,2) Possible cuts are of lengths max(arr[9-2],arr[9-3],arr[9-5])+1->4 (2,3,2,2) or (2,2,3,2) or (2,2,2,3) Possible cuts are of lengths max(arr[10-2],arr[10-3],arr[10-5])+1->5 (2,2,2,2,2) Possible cuts are of lengths max(arr[11-2],arr[11-3],arr[11-5])+1->5 (2,3,2,2,2) or (2,2,3,2,2) or (2,2,2,3,2) or (2,2,2,2,3) Algorithm: Initialise an array DP[]={-1} and DP[0]=0.Run a loop from ‘1’ to ‘l’If DP[i]=-1 means it’s not possible to divide it using giving segments p,q,r so continue;DP[i+p]=max(DP[i+p],DP[i]+1)DP[i+q]=max(DP[i+q],DP[i]+1)DP[i+r]=max(DP[i+r],DP[i]+1)print DP[l] Initialise an array DP[]={-1} and DP[0]=0. Run a loop from ‘1’ to ‘l’ If DP[i]=-1 means it’s not possible to divide it using giving segments p,q,r so continue; DP[i+p]=max(DP[i+p],DP[i]+1) DP[i+q]=max(DP[i+q],DP[i]+1) DP[i+r]=max(DP[i+r],DP[i]+1) print DP[l] Pseudo Code: DP[l+1]={-1} DP[0]=0 for(i from 0 to l) if(DP[i]==-1) continue DP[i+p]=max(DP[i+p],DP[i]+1) DP[i+q]=max(DP[i+q],DP[i]+1) DP[i+r]=max(DP[i+r],DP[i]+1) print(DP[l]) Implementation: C++ Java Python3 C# Javascript // C++ program to maximize the number// of segments of length p, q and r#include <bits/stdc++.h>using namespace std; // Function that returns the maximum number// of segments possibleint findMaximum(int l, int p, int q, int r){ // Array to store the cut at each length int dp[l + 1]; // All values with -1 memset(dp, -1, sizeof(dp)); // if length of rod is 0 then total cuts will be 0 // so, initialize the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length is not possible if (dp[i] == -1) continue; // if a segment of p is possible if (i + p <= l) dp[i + p] = max(dp[i + p], dp[i] + 1); // if a segment of q is possible if (i + q <= l) dp[i + q] = max(dp[i + q], dp[i] + 1); // if a segment of r is possible if (i + r <= l) dp[i + r] = max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding to length l return dp[l];} // Driver Codeint main(){ int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); cout << ans; return 0;} // Java program to maximize// the number of segments// of length p, q and rimport java.io.*; class GFG { // Function that returns // the maximum number // of segments possible static int findMaximum(int l, int p, int q, int r) { // Array to store the // cut at each length int dp[] = new int[l + 1]; // All values with -1 for (int i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code public static void main(String[] args) { int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); System.out.println(ans); }} // This code is contributed// by anuj_67. # Python 3 program to# maximize the number# of segments of length# p, q and r # Function that returns# the maximum number# of segments possible def findMaximum(l, p, q, r): # Array to store the cut # at each length # All values with -1 dp = [-1]*(l + 1) # if length of rod is 0 then # total cuts will be 0 # so, initialize the dp[0] with 0 dp[0] = 0 for i in range(l+1): # if certain length is not # possible if (dp[i] == -1): continue # if a segment of p is possible if (i + p <= l): dp[i + p] = (max(dp[i + p], dp[i] + 1)) # if a segment of q is possible if (i + q <= l): dp[i + q] = (max(dp[i + q], dp[i] + 1)) # if a segment of r is possible if (i + r <= l): dp[i + r] = (max(dp[i + r], dp[i] + 1)) # if no segment can be cut then return 0 if dp[l] == -1: dp[l] = 0 # return value corresponding # to length l return dp[l] # Driver Codeif __name__ == "__main__": l = 11 p = 2 q = 3 r = 5 # Calling Function ans = findMaximum(l, p, q, r) print(ans) # This code is contributed by# ChitraNayal // C# program to maximize// the number of segments// of length p, q and rusing System; class GFG { // Function that returns // the maximum number // of segments possible static int findMaximum(int l, int p, int q, int r) { // Array to store the // cut at each length int[] dp = new int[l + 1]; // All values with -1 for (int i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.Max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.Max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.Max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code public static void Main() { int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); Console.WriteLine(ans); }} // This code is contributed// by anuj_67. <script>// Javascript program to maximize// the number of segments// of length p, q and r // Function that returns // the maximum number // of segments possible function findMaximum(l,p,q,r) { // Array to store the // cut at each length let dp = new Array(l + 1); // All values with -1 for (let i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (let i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code let l = 11, p = 2, q = 3, r = 5; // Calling Function let ans = findMaximum(l, p, q, r); document.write(ans); // This code is contributed by rag2127</script> 5 Complexity Analysis: Time Complexity: O(N). Use of a single for-loop till length ‘N’. Auxiliary Space: O(N). Use of an array ‘DP’ to keep track of segments Note: This problem can also be thought of as a minimum coin change problem because we are given a certain length to acquire which is the same as the value of the amount whose minimum change is needed. Now the x,y,z are the same as the denomination of the coin given. So length is the same as the amount and x y z are the same as denominations, thus we need to change only one condition that is instead of finding minimum we need to find the maximum and we will get the answer. As the minimum coin change problem is the basic dynamic programming question so this will help to solve this question also. The condition we need to change in minimum coin change problem for(ll i=1;i<=n;i++) { for(ll j=1;j<=3;j++) { if(i>=a[j]&&m[i-a[j]]!=-1) { dp[i]=max(dp[i],1+dp[i-a[j]]); } } } vt_m ukasp bidibaaz123 techwithintechtofar rg_1999 rag2127 tusharsingh432 singhvishal240891 24pranshu Algorithms-Dynamic Programming Arrays Greedy Algorithms Competitive Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming 5 Best Languages for Competitive Programming Most important type of Algorithms Difference between Backtracking and Branch-N-Bound technique String hashing using Polynomial rolling hash function Graph implementation using STL for competitive programming | Set 2 (Weighted graph) Implementing upper_bound() and lower_bound() in C
[ { "code": null, "e": 26281, "s": 26253, "text": "\n29 Nov, 2021" }, { "code": null, "e": 26465, "s": 26281, "text": "Given a rod of length L, the task is to cut the rod in such a way that the total number of segments of length p, q and r is maximized. The segments can only be of length p, q, and r. " }, { "code": null, "e": 26476, "s": 26465, "text": "Examples: " }, { "code": null, "e": 26550, "s": 26476, "text": "Input: l = 11, p = 2, q = 3, r = 5 Output: 5 Segments of 2, 2, 2, 2 and 3" }, { "code": null, "e": 26614, "s": 26550, "text": "Input: l = 7, p = 2, q = 5, r = 5 Output: 2 Segments of 2 and 5" }, { "code": null, "e": 26626, "s": 26614, "text": "Approach 1:" }, { "code": null, "e": 27620, "s": 26626, "text": "This can be visualized as a classical recursion problem , which further narrows down to memoization ( top-down ) method of Dynamic Programming. Initially , we have length l present with us , we’d have three size choices to cut from this , either we can make a cut of length p , or q , or r. Let’s say we made a cut of length p , so the remaining length would be l-p and similarly with cuts q & r resulting in remaining lengths l-q & l-r respectively. We will call recursive function for the remaining lengths and at any subsequent instance we’ll have these three choices. We will store the answer from all these recursive calls & take the maximum out of them +1 as at any instance we’ll have 1 cut from this particular call as well. Also , note that the recursive call would be made if and only if the available length is greater than length we want to cut i.e. suppose p=3 , and after certain recursive calls the available length is 2 only , so we can’t cut this line in lengths of p anymore." }, { "code": null, "e": 27658, "s": 27620, "text": "Below is the pseudocode for the same:" }, { "code": null, "e": 27826, "s": 27658, "text": "if(l==0) // Base Case\n return 0;\n \n \nint a,b,c;\nif(p<=l)\n a=func(l-p,p,q,r);\nif(q<=l)\n b=func(l-q,p,q,r);\nif(r<=l)\n c=func(l-r,p,q,r);\nreturn 1+max({a,b,c});" }, { "code": null, "e": 27879, "s": 27826, "text": "Below is the recursion tree for l=4,p=2,q=1 and r=1:" }, { "code": null, "e": 27921, "s": 27879, "text": "Recursion Tree for l=4 , p=2 ,q=1 and r=1" }, { "code": null, "e": 28315, "s": 27921, "text": "One can clearly observe that at each call , the given length ( 4 initially ) is divided into 3 different subparts. Also , we can see that the recursion is being repeated for certain entries ( Red arrow represents repetitive call for l=2, Yellow for l=3 and Blue for l=1). Therefore , we can memoize the results in any container or array , so that repetition of same recursive calls is avoided." }, { "code": null, "e": 28355, "s": 28315, "text": "Now , the above pseudocode changes to :" }, { "code": null, "e": 28786, "s": 28355, "text": "vector<int> dp(10005,-1); // Initialise DP Table ( Array can also be used )\n\n\nif(l==0) // Base Case\n return 0;\n \nif(dp[l]!=-1) // If already memoized , return from here only\n return dp[l];\nint a,b,c;\nif(p<=l)\n a=func(l-p,p,q,r);\nif(q<=l)\n b=func(l-q,p,q,r);\nif(r<=l)\n c=func(l-r,p,q,r);\n \n \nreturn dp[l]=1+max({a,b,c}); // Memoize the result in the dp table & return" }, { "code": null, "e": 28851, "s": 28786, "text": "Let’s now follow the code for implementation of the above code :" }, { "code": null, "e": 28855, "s": 28851, "text": "C++" }, { "code": "//C++ Code to find maximum number of cut segments// Memoization DP #include <bits/stdc++.h>using namespace std; //Function to find the maximum number of cuts.int dp[10005]; int func(int l, int p, int q, int r){ if(l==0) return 0; // Base Case if(dp[l]!=-1) // If already memoized return dp[l]; int a(INT_MIN),b(INT_MIN),c(INT_MIN); // Intitialise a,b,& c with INT_MIN if(p<=l) // If Possible to make a cut of length p a=func(l-p,p,q,r); if(q<=l) // If possible to make a cut of length q b=func(l-q,p,q,r); if(r<=l) // If possible to make a cut of length r c=func(l-r,p,q,r); return dp[l]=1+max({a,b,c}); // Memoize & return } int maximizeTheCuts(int l, int p, int q, int r){ memset(dp,-1,sizeof(dp)); // Set Lookup table to -1 int ans=func(l,p,q,r); // Utility function call if(ans<0) return 0; // If returned answer is negative , that means cuts are not possible return ans; } int main(){ int l,p,q,r; cout<<\"ENTER THE LENGTH OF THE ROD \"<<endl; cin>>l; cout<<\"ENTER THE VALUES OF p,q & r \"<<endl; cin>>p>>q>>r; cout<<\"THE MAXIMUM NUMBER OF SEGMENTS THAT CAN BE CUT OF LENGTH p,q & r FROM A ROD OF LENGTH l are \"<<maximizeTheCuts(l,p,q,r)<<endl; return 0;}", "e": 30421, "s": 28855, "text": null }, { "code": null, "e": 30509, "s": 30421, "text": "Time Complexity : O(n) where n is the length of rod or line segment that has to be cut." }, { "code": null, "e": 30598, "s": 30509, "text": "Space Complexity : O(n) where n is the length of rod or line segment that has to be cut." }, { "code": null, "e": 30611, "s": 30598, "text": "Approach 2: " }, { "code": null, "e": 31288, "s": 30611, "text": "As the solution for a maximum number of cuts that can be made in a given length depends on the maximum number of cuts previously made in shorter lengths, this question could be solved by the approach of Dynamic Programming. Suppose we are given a length ‘l’. For finding the maximum number of cuts that can be made in length ‘l’, find the number of cuts made in shorter previous length ‘l-p’, ‘l-q’, ‘l-r’ lengths respectively. The required answer would be the max(l-p,l-q,l-r)+1 as one more cut should be needed after this to cut length ‘l’. So for solving this problem for a given length, find the maximum number of cuts that can be made in lengths ranging from ‘1’ to ‘l’. " }, { "code": null, "e": 31299, "s": 31288, "text": "Example: " }, { "code": null, "e": 31360, "s": 31299, "text": "l = 11, p = 2, q = 3, r = 5 Analysing lengths from 1 to 11: " }, { "code": null, "e": 32115, "s": 31360, "text": "Not possible to cut->0Possible cut is of lengths 2->1 (2)Possible cut is of lengths 3->1 (3)Possible cuts are of lengths max(arr[4-2],arr[4-3])+1->2 (2,2)Possible cuts are of lengths max(arr[5-2],arr[5-3])+1->2 (2,3)Possible cuts are of lengths max(arr[6-2],arr[6-3],arr[6-5])+1->3 (2,2,2)Possible cuts are of lengths max(arr[7-2],arr[7-3],arr[7-5])+1->3 (2,3,2) or (2,2,3)Possible cuts are of lengths max(arr[8-2],arr[8-3],arr[8-5])+1->4 (2,2,2,2)Possible cuts are of lengths max(arr[9-2],arr[9-3],arr[9-5])+1->4 (2,3,2,2) or (2,2,3,2) or (2,2,2,3)Possible cuts are of lengths max(arr[10-2],arr[10-3],arr[10-5])+1->5 (2,2,2,2,2)Possible cuts are of lengths max(arr[11-2],arr[11-3],arr[11-5])+1->5 (2,3,2,2,2) or (2,2,3,2,2) or (2,2,2,3,2) or (2,2,2,2,3)" }, { "code": null, "e": 32138, "s": 32115, "text": "Not possible to cut->0" }, { "code": null, "e": 32174, "s": 32138, "text": "Possible cut is of lengths 2->1 (2)" }, { "code": null, "e": 32210, "s": 32174, "text": "Possible cut is of lengths 3->1 (3)" }, { "code": null, "e": 32273, "s": 32210, "text": "Possible cuts are of lengths max(arr[4-2],arr[4-3])+1->2 (2,2)" }, { "code": null, "e": 32336, "s": 32273, "text": "Possible cuts are of lengths max(arr[5-2],arr[5-3])+1->2 (2,3)" }, { "code": null, "e": 32410, "s": 32336, "text": "Possible cuts are of lengths max(arr[6-2],arr[6-3],arr[6-5])+1->3 (2,2,2)" }, { "code": null, "e": 32495, "s": 32410, "text": "Possible cuts are of lengths max(arr[7-2],arr[7-3],arr[7-5])+1->3 (2,3,2) or (2,2,3)" }, { "code": null, "e": 32571, "s": 32495, "text": "Possible cuts are of lengths max(arr[8-2],arr[8-3],arr[8-5])+1->4 (2,2,2,2)" }, { "code": null, "e": 32673, "s": 32571, "text": "Possible cuts are of lengths max(arr[9-2],arr[9-3],arr[9-5])+1->4 (2,3,2,2) or (2,2,3,2) or (2,2,2,3)" }, { "code": null, "e": 32754, "s": 32673, "text": "Possible cuts are of lengths max(arr[10-2],arr[10-3],arr[10-5])+1->5 (2,2,2,2,2)" }, { "code": null, "e": 32880, "s": 32754, "text": "Possible cuts are of lengths max(arr[11-2],arr[11-3],arr[11-5])+1->5 (2,3,2,2,2) or (2,2,3,2,2) or (2,2,2,3,2) or (2,2,2,2,3)" }, { "code": null, "e": 32892, "s": 32880, "text": "Algorithm: " }, { "code": null, "e": 33145, "s": 32892, "text": "Initialise an array DP[]={-1} and DP[0]=0.Run a loop from ‘1’ to ‘l’If DP[i]=-1 means it’s not possible to divide it using giving segments p,q,r so continue;DP[i+p]=max(DP[i+p],DP[i]+1)DP[i+q]=max(DP[i+q],DP[i]+1)DP[i+r]=max(DP[i+r],DP[i]+1)print DP[l]" }, { "code": null, "e": 33188, "s": 33145, "text": "Initialise an array DP[]={-1} and DP[0]=0." }, { "code": null, "e": 33215, "s": 33188, "text": "Run a loop from ‘1’ to ‘l’" }, { "code": null, "e": 33305, "s": 33215, "text": "If DP[i]=-1 means it’s not possible to divide it using giving segments p,q,r so continue;" }, { "code": null, "e": 33334, "s": 33305, "text": "DP[i+p]=max(DP[i+p],DP[i]+1)" }, { "code": null, "e": 33363, "s": 33334, "text": "DP[i+q]=max(DP[i+q],DP[i]+1)" }, { "code": null, "e": 33392, "s": 33363, "text": "DP[i+r]=max(DP[i+r],DP[i]+1)" }, { "code": null, "e": 33404, "s": 33392, "text": "print DP[l]" }, { "code": null, "e": 33418, "s": 33404, "text": "Pseudo Code: " }, { "code": null, "e": 33592, "s": 33418, "text": "DP[l+1]={-1}\nDP[0]=0\nfor(i from 0 to l)\n if(DP[i]==-1)\n continue\n DP[i+p]=max(DP[i+p],DP[i]+1)\n DP[i+q]=max(DP[i+q],DP[i]+1)\n DP[i+r]=max(DP[i+r],DP[i]+1)\n\nprint(DP[l])" }, { "code": null, "e": 33609, "s": 33592, "text": "Implementation: " }, { "code": null, "e": 33613, "s": 33609, "text": "C++" }, { "code": null, "e": 33618, "s": 33613, "text": "Java" }, { "code": null, "e": 33626, "s": 33618, "text": "Python3" }, { "code": null, "e": 33629, "s": 33626, "text": "C#" }, { "code": null, "e": 33640, "s": 33629, "text": "Javascript" }, { "code": "// C++ program to maximize the number// of segments of length p, q and r#include <bits/stdc++.h>using namespace std; // Function that returns the maximum number// of segments possibleint findMaximum(int l, int p, int q, int r){ // Array to store the cut at each length int dp[l + 1]; // All values with -1 memset(dp, -1, sizeof(dp)); // if length of rod is 0 then total cuts will be 0 // so, initialize the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length is not possible if (dp[i] == -1) continue; // if a segment of p is possible if (i + p <= l) dp[i + p] = max(dp[i + p], dp[i] + 1); // if a segment of q is possible if (i + q <= l) dp[i + q] = max(dp[i + q], dp[i] + 1); // if a segment of r is possible if (i + r <= l) dp[i + r] = max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding to length l return dp[l];} // Driver Codeint main(){ int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); cout << ans; return 0;}", "e": 34875, "s": 33640, "text": null }, { "code": "// Java program to maximize// the number of segments// of length p, q and rimport java.io.*; class GFG { // Function that returns // the maximum number // of segments possible static int findMaximum(int l, int p, int q, int r) { // Array to store the // cut at each length int dp[] = new int[l + 1]; // All values with -1 for (int i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code public static void main(String[] args) { int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); System.out.println(ans); }} // This code is contributed// by anuj_67.", "e": 36491, "s": 34875, "text": null }, { "code": "# Python 3 program to# maximize the number# of segments of length# p, q and r # Function that returns# the maximum number# of segments possible def findMaximum(l, p, q, r): # Array to store the cut # at each length # All values with -1 dp = [-1]*(l + 1) # if length of rod is 0 then # total cuts will be 0 # so, initialize the dp[0] with 0 dp[0] = 0 for i in range(l+1): # if certain length is not # possible if (dp[i] == -1): continue # if a segment of p is possible if (i + p <= l): dp[i + p] = (max(dp[i + p], dp[i] + 1)) # if a segment of q is possible if (i + q <= l): dp[i + q] = (max(dp[i + q], dp[i] + 1)) # if a segment of r is possible if (i + r <= l): dp[i + r] = (max(dp[i + r], dp[i] + 1)) # if no segment can be cut then return 0 if dp[l] == -1: dp[l] = 0 # return value corresponding # to length l return dp[l] # Driver Codeif __name__ == \"__main__\": l = 11 p = 2 q = 3 r = 5 # Calling Function ans = findMaximum(l, p, q, r) print(ans) # This code is contributed by# ChitraNayal", "e": 37757, "s": 36491, "text": null }, { "code": "// C# program to maximize// the number of segments// of length p, q and rusing System; class GFG { // Function that returns // the maximum number // of segments possible static int findMaximum(int l, int p, int q, int r) { // Array to store the // cut at each length int[] dp = new int[l + 1]; // All values with -1 for (int i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (int i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.Max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.Max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.Max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code public static void Main() { int l = 11, p = 2, q = 3, r = 5; // Calling Function int ans = findMaximum(l, p, q, r); Console.WriteLine(ans); }} // This code is contributed// by anuj_67.", "e": 39487, "s": 37757, "text": null }, { "code": "<script>// Javascript program to maximize// the number of segments// of length p, q and r // Function that returns // the maximum number // of segments possible function findMaximum(l,p,q,r) { // Array to store the // cut at each length let dp = new Array(l + 1); // All values with -1 for (let i = 0; i < l + 1; i++) dp[i] = -1; // if length of rod is 0 // then total cuts will // be 0 so, initialize // the dp[0] with 0 dp[0] = 0; for (let i = 0; i <= l; i++) { // if certain length // is not possible if (dp[i] == -1) continue; // if a segment of // p is possible if (i + p <= l) dp[i + p] = Math.max(dp[i + p], dp[i] + 1); // if a segment of // q is possible if (i + q <= l) dp[i + q] = Math.max(dp[i + q], dp[i] + 1); // if a segment of // r is possible if (i + r <= l) dp[i + r] = Math.max(dp[i + r], dp[i] + 1); } // if no segment can be cut then return 0 if (dp[l] == -1) { dp[l] = 0; } // return value corresponding // to length l return dp[l]; } // Driver Code let l = 11, p = 2, q = 3, r = 5; // Calling Function let ans = findMaximum(l, p, q, r); document.write(ans); // This code is contributed by rag2127</script>", "e": 41024, "s": 39487, "text": null }, { "code": null, "e": 41026, "s": 41024, "text": "5" }, { "code": null, "e": 41048, "s": 41026, "text": "Complexity Analysis: " }, { "code": null, "e": 41113, "s": 41048, "text": "Time Complexity: O(N). Use of a single for-loop till length ‘N’." }, { "code": null, "e": 41183, "s": 41113, "text": "Auxiliary Space: O(N). Use of an array ‘DP’ to keep track of segments" }, { "code": null, "e": 41784, "s": 41183, "text": "Note: This problem can also be thought of as a minimum coin change problem because we are given a certain length to acquire which is the same as the value of the amount whose minimum change is needed. Now the x,y,z are the same as the denomination of the coin given. So length is the same as the amount and x y z are the same as denominations, thus we need to change only one condition that is instead of finding minimum we need to find the maximum and we will get the answer. As the minimum coin change problem is the basic dynamic programming question so this will help to solve this question also." }, { "code": null, "e": 41847, "s": 41784, "text": "The condition we need to change in minimum coin change problem" }, { "code": null, "e": 42019, "s": 41847, "text": "for(ll i=1;i<=n;i++)\n{\n for(ll j=1;j<=3;j++)\n {\n if(i>=a[j]&&m[i-a[j]]!=-1)\n {\n dp[i]=max(dp[i],1+dp[i-a[j]]);\n }\n }\n}" }, { "code": null, "e": 42024, "s": 42019, "text": "vt_m" }, { "code": null, "e": 42030, "s": 42024, "text": "ukasp" }, { "code": null, "e": 42042, "s": 42030, "text": "bidibaaz123" }, { "code": null, "e": 42062, "s": 42042, "text": "techwithintechtofar" }, { "code": null, "e": 42070, "s": 42062, "text": "rg_1999" }, { "code": null, "e": 42078, "s": 42070, "text": "rag2127" }, { "code": null, "e": 42093, "s": 42078, "text": "tusharsingh432" }, { "code": null, "e": 42111, "s": 42093, "text": "singhvishal240891" }, { "code": null, "e": 42121, "s": 42111, "text": "24pranshu" }, { "code": null, "e": 42152, "s": 42121, "text": "Algorithms-Dynamic Programming" }, { "code": null, "e": 42159, "s": 42152, "text": "Arrays" }, { "code": null, "e": 42177, "s": 42159, "text": "Greedy Algorithms" }, { "code": null, "e": 42201, "s": 42177, "text": "Competitive Programming" }, { "code": null, "e": 42208, "s": 42201, "text": "Arrays" }, { "code": null, "e": 42306, "s": 42208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42339, "s": 42306, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 42385, "s": 42339, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 42443, "s": 42385, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 42484, "s": 42443, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 42529, "s": 42484, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 42563, "s": 42529, "text": "Most important type of Algorithms" }, { "code": null, "e": 42624, "s": 42563, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 42678, "s": 42624, "text": "String hashing using Polynomial rolling hash function" }, { "code": null, "e": 42762, "s": 42678, "text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)" } ]
Primitive Wrapper Classes are Immutable in Java
In Java Immutable class is a class which once created and it's contents can not be changed.On same concept Immutable objects are the objects whose state can not be changed once constructed. Wrapper classes are made to be immutable due to following advantages − Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state. Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state. The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction. The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction. The best use of the wrapper class as immutable objects is as the keys of a map. The best use of the wrapper class as immutable objects is as the keys of a map. Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead. Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead. class Demo { public static void main(String[] args) { Integer i = new Integer(20); //initialize a object of Integer class with value as 20. System.out.println(i); operate(i);// method to change value of object. System.out.println(i); //value doesn't change shows that object is immutable. } private static void operate(Integer i) { i = i + 1; } } 20 20
[ { "code": null, "e": 1252, "s": 1062, "text": "In Java Immutable class is a class which once created and it's contents can not be changed.On same concept Immutable objects are the objects whose state can not be changed once constructed." }, { "code": null, "e": 1323, "s": 1252, "text": "Wrapper classes are made to be immutable due to following advantages −" }, { "code": null, "e": 1552, "s": 1323, "text": "Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided." }, { "code": null, "e": 1781, "s": 1552, "text": "Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided." }, { "code": null, "e": 1932, "s": 1781, "text": "Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state." }, { "code": null, "e": 2083, "s": 1932, "text": "Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state." }, { "code": null, "e": 2250, "s": 2083, "text": "The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction." }, { "code": null, "e": 2417, "s": 2250, "text": "The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction." }, { "code": null, "e": 2497, "s": 2417, "text": "The best use of the wrapper class as immutable objects is as the keys of a map." }, { "code": null, "e": 2577, "s": 2497, "text": "The best use of the wrapper class as immutable objects is as the keys of a map." }, { "code": null, "e": 2834, "s": 2577, "text": "Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead." }, { "code": null, "e": 3091, "s": 2834, "text": "Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead." }, { "code": null, "e": 3480, "s": 3091, "text": "class Demo {\n public static void main(String[] args) {\n Integer i = new Integer(20); //initialize a object of Integer class with value as 20.\n System.out.println(i);\n operate(i);// method to change value of object.\n System.out.println(i); //value doesn't change shows that object is immutable.\n }\n private static void operate(Integer i) {\n i = i + 1;\n }\n}" }, { "code": null, "e": 3486, "s": 3480, "text": "20\n20" } ]
Rust - Tuple
Tuple is a compound data type. A scalar type can store only one type of data. For example, an i32 variable can store only a single integer value. In compound types, we can store more than one value at a time and it can be of different types. Tuples have a fixed length - once declared they cannot grow or shrink in size. The tuple index starts from 0. //Syntax1 let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3); //Syntax2 let tuple_name = (value1,value2,value3); The following example displays the values in a tuple. fn main() { let tuple:(i32,f64,u8) = (-325,4.9,22); println!("{:?}",tuple); } The println!("{ }",tuple) syntax cannot be used to display values in a tuple. This is because a tuple is a compound type. Use the println!("{:?}", tuple_name) syntax to print values in a tuple. (-325, 4.9, 22) The following example prints individual values in a tuple. fn main() { let tuple:(i32,f64,u8) = (-325,4.9,22); println!("integer is :{:?}",tuple.0); println!("float is :{:?}",tuple.1); println!("unsigned integer is :{:?}",tuple.2); } integer is :-325 float is :4.9 unsigned integer is :2 The following example passes a tuple as parameter to a function. Tuples are passed by value to functions. fn main(){ let b:(i32,bool,f64) = (110,true,10.9); print(b); } //pass the tuple as a parameter fn print(x:(i32,bool,f64)){ println!("Inside print method"); println!("{:?}",x); } Inside print method (110, true, 10.9) Destructing assignment is a feature of rust wherein we unpack the values of a tuple. This is achieved by assigning a tuple to distinct variables. Consider the following example − fn main(){ let b:(i32,bool,f64) = (30,true,7.9); print(b); } fn print(x:(i32,bool,f64)){ println!("Inside print method"); let (age,is_male,cgpa) = x; //assigns a tuple to distinct variables println!("Age is {} , isMale? {},cgpa is {}",age,is_male,cgpa); } Variable x is a tuple which is assigned to the let statement. Each variable - age, is_male and cgpa will contain the corresponding values in a tuple. Inside print method Age is 30 , isMale? true,cgpa is 7.9 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2329, "s": 2087, "text": "Tuple is a compound data type. A scalar type can store only one type of data. For example, an i32 variable can store only a single integer value. In compound types, we can store more than one value at a time and it can be of different types." }, { "code": null, "e": 2439, "s": 2329, "text": "Tuples have a fixed length - once declared they cannot grow or shrink in size. The tuple index starts from 0." }, { "code": null, "e": 2578, "s": 2439, "text": "//Syntax1\nlet tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3);\n\n//Syntax2\nlet tuple_name = (value1,value2,value3);\n" }, { "code": null, "e": 2632, "s": 2578, "text": "The following example displays the values in a tuple." }, { "code": null, "e": 2716, "s": 2632, "text": "fn main() {\n let tuple:(i32,f64,u8) = (-325,4.9,22);\n println!(\"{:?}\",tuple);\n}" }, { "code": null, "e": 2910, "s": 2716, "text": "The println!(\"{ }\",tuple) syntax cannot be used to display values in a tuple. This is because a tuple is a compound type. Use the println!(\"{:?}\", tuple_name) syntax to print values in a tuple." }, { "code": null, "e": 2927, "s": 2910, "text": "(-325, 4.9, 22)\n" }, { "code": null, "e": 2986, "s": 2927, "text": "The following example prints individual values in a tuple." }, { "code": null, "e": 3173, "s": 2986, "text": "fn main() {\n let tuple:(i32,f64,u8) = (-325,4.9,22);\n println!(\"integer is :{:?}\",tuple.0);\n println!(\"float is :{:?}\",tuple.1);\n println!(\"unsigned integer is :{:?}\",tuple.2);\n}" }, { "code": null, "e": 3228, "s": 3173, "text": "integer is :-325\nfloat is :4.9\nunsigned integer is :2\n" }, { "code": null, "e": 3334, "s": 3228, "text": "The following example passes a tuple as parameter to a function. Tuples are passed by value to functions." }, { "code": null, "e": 3525, "s": 3334, "text": "fn main(){\n let b:(i32,bool,f64) = (110,true,10.9);\n print(b);\n}\n//pass the tuple as a parameter\n\nfn print(x:(i32,bool,f64)){\n println!(\"Inside print method\");\n println!(\"{:?}\",x);\n}" }, { "code": null, "e": 3564, "s": 3525, "text": "Inside print method\n(110, true, 10.9)\n" }, { "code": null, "e": 3710, "s": 3564, "text": "Destructing assignment is a feature of rust wherein we unpack the values of a tuple. This is achieved by assigning a tuple to distinct variables." }, { "code": null, "e": 3743, "s": 3710, "text": "Consider the following example −" }, { "code": null, "e": 4022, "s": 3743, "text": "fn main(){\n let b:(i32,bool,f64) = (30,true,7.9);\n print(b);\n}\nfn print(x:(i32,bool,f64)){\n println!(\"Inside print method\");\n let (age,is_male,cgpa) = x; //assigns a tuple to \n distinct variables\n println!(\"Age is {} , isMale? {},cgpa is \n {}\",age,is_male,cgpa);\n}" }, { "code": null, "e": 4172, "s": 4022, "text": "Variable x is a tuple which is assigned to the let statement. Each variable - age, is_male and cgpa will contain the corresponding values in a tuple." }, { "code": null, "e": 4230, "s": 4172, "text": "Inside print method\nAge is 30 , isMale? true,cgpa is 7.9\n" }, { "code": null, "e": 4265, "s": 4230, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4288, "s": 4265, "text": " Stone River ELearning" }, { "code": null, "e": 4320, "s": 4288, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 4331, "s": 4320, "text": " Ken Burke" }, { "code": null, "e": 4338, "s": 4331, "text": " Print" }, { "code": null, "e": 4349, "s": 4338, "text": " Add Notes" } ]
Symfony - Components
As discussed earlier, Symfony components are standalone PHP library providing a specific feature, which can be used in any PHP application. Useful new components are being introduced in each and every release of Symfony. Currently, there are 30+ high quality components in Symfony framework. Let us learn about the usage of Symfony components in this chapter. Symfony components can be installed easily using the composer command. Following generic command can be used to install any Symfony component. cd /path/to/project/dir composer require symfony/<component_name> Let us create a simple php application and try to install Filesystem component. Step 1 − Create a folder for the application, filesystem-example cd /path/to/dev/folder mdkir filesystem-example cd filesystem-example Step 2 − Install Filesystem component using the following command. composer require symfony/filesystem Step 3 − Create a file main.php and enter the following code. <?php require_once __DIR__ . '/vendor/autoload.php'; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Exception\IOExceptionInterface; $fs = new Filesystem(); try { $fs->mkdir('./sample-dir'); $fs->touch('./sample-dir/text.txt'); } catch (IOExceptionInterface $e) { echo $e; } ?> The first line is very important, which loads all the necessary classes from all the components installed using the Composer command. The next lines use the Filesystem class. Step 4 − Run the application using the following command and it will create a new folder sample-dir and a file test.txt under it. php main.php Symfony provides components ranging from simple feature, say file system to advanced feature, say events, container technology, and dependency injection. Let us know about all the components one by one in the following sections. Filesystem component provides a basic system command related to files and directories such as file creation, folder creation, file existence, etc. Filesystem component can be installed using the following command. composer require symfony/filesystem Finder component provides fluent classes to find files and directories in a specified path. It provides an easy way to iterate over the files in a path. Finder component can be installed using the following command. composer require symfony/finder Console component provides various options to easily create commands, which can be executed in a terminal. Symfony uses the Command component extensively to provide various functionalities such as creating a new application, creating a bundle, etc. Even the PHP build in web server can be invoked using Symfony command, php bin/console server:run as seen in the installation section. The Console component can be installed using the following command. composer require symfony/console Let us create a simple application and create a command, HelloCommand using the Console component and invoke it. Step 1 − Create a project using the following command. cd /path/to/project composer require symfony/console Step 2 − Create a file main.php and include the following code. <?php require __DIR__ . '/vendor/autoload.php'; use Symfony\Component\Console\Application; $app = new Application(); $app->run(); ?> Application class sets up the necessary functionality of a bare-bone console application. Step 3 − Run the application, php main.php, which will produce the following result. Console Tool Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: help Displays help for a command list Lists commands Step 4 − Create a class called HelloCommand extending Command class in the main.php itself. use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; class HelloCommand extends Command { } The application uses following four classes available in Command component. Command − Used to create a new command Command − Used to create a new command InputInterface − Used to set user inputs InputInterface − Used to set user inputs InputArgument − Used to get user inputs InputArgument − Used to get user inputs OutputInterface − Used to print output to the console OutputInterface − Used to print output to the console step 5 − Create a function configure() and set name, description, and help text. protected function configure() { $this ->setName('app:hello') ->setDescription('Sample command, hello') ->setHelp('This command is a sample command') } step 6 − Create an input argument, user for the command and set as mandatory. protected function configure() { $this ->setName('app:hello') ->setDescription('Sample command, hello') ->setHelp('This command is a sample command') ->addArgument('name', InputArgument::REQUIRED, 'name of the user'); } step 7 − Create a function execute() with two arguments InputArgument and OutputArgument. protected function execute(InputInterface $input, OutputInterface $output) { } step 8 − Use InputArgument to get the user details entered by the user and print it to the console using OutputArgument. protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $output->writeln('Hello, ' . $name); } step 9 − Register the HelloCommand into the application using the add method of Application class. $app->add(new HelloCommand()); The complete application is as follows. <?php require __DIR__ . '/vendor/autoload.php'; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; class HelloCommand extends Command { protected function configure() { $this ->setName('app:hello') ->setDescription('Sample command, hello') ->setHelp('This command is a sample command') ->addArgument('name', InputArgument::REQUIRED, 'name of the user'); } protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $output->writeln('Hello, ' . $name); } $app = new Application(); $app->add(new HelloCommand()); $app->run(); } ?> Step 10 − Now, execute the application using the following command and the result will be Hello, Jon as expected. php main.php app:hello Jon Symfony comes with a pre-built binary called console in the bin directory of any Symfony web application, which can be used to invoke the commands in an application. Process component provides options to run any system command in a sub-process, in a safe and efficient manner. Process component can be installed using the following command. composer require symfony/process ClassLoader component provides implementation for both PSR-0 and PSR-4 class loader standard. It can be used to auto-load the classes. It will be depreciated in the near future. Composer-based class loader is preferred over this component. ClassLoader component can be installed using the following command. composer require symfony/class-loader PropertyAccess component provides various options to read and write an object and array details using the string notation. For example, an array Product with key price can be accessed dynamically using [price] string. $product = array( 'name' => 'Cake' 'price' => 10 ); var priceObj = $propertyAccesserObj->getValue($product, '[price]'); PropertyAccess component can be installed using the following command. composer require symfony/property-access PropertyInfo component is similar to PropertyAccess component, however it only works with PHP objects and provides much more functionality. class Product { private $name = 'Cake'; private $price = 10; public function getName() { return $this->name; } public function getPrice() { return $this->price; } } $class = Product::class; $properties = $propertyInfoObj->getProperties($class); /* Example Result -------------- array(2) { [0] => string(4) "name" [1] => string(5) "price" } */ PropertyInfo component can be installed using the following command. composer require symfony/property-info EventDispatcher component provides an event-based programming in PHP. It enables the objects to communicate with each other by dispatching events and listening to them. We will learn how to create event and listen to them in the Events and Event Listener chapter. EventDispatcher component can be installed using the following command. composer require symfony/event-dispatcher DependencyInjection component provides an easy and efficient mechanism to create an object with its dependency. When a project grows, it features a lot of classes with deep dependency, which needs to be handled correctly. Otherwise, the project fails. DependencyInjection provides a simple and robust container to handle the dependency. We will learn about the containers and the dependency injection concept in Service Container chapter. DependencyInjection component can be installed using the following command. composer require symfony/dependency-injection Serializer component provides an option to convert a PHP object into a specific format such as XML, JSON, Binary, etc., and then allows it to convert it back into an original object without any data loss. Serializer component can be installed using the following command. composer require symfony/serializer Config component provides options to load, parse, read, and validate configurations of type XML, YAML, PHP and ini. It provides various options to load configuration details from database as well. This is one of the important components useful in configuring web application in a clear and concise manner. Config component can be installed using the following command. composer require symfony/config ExpessionLanguage component provides a full-fledged expression engine. Expressions are one-liner intended to return a value. The expression engine enables to easily compile, parse, and get the value from an expression. It enables one or more expression to be used in a configuration environment (file) by a non-PHP programmer, say a system administrator. ExpressionLanguage component can be installed using the following command. composer require symfony/expression-language OptionsResolver component provides a way to validate the option system used in our system. For example, database setting is placed in an array, dboption with host, username, password, etc., as keys. You need to validate the entries before using it to connect to a database. OptionsResolver simplifies this task by providing a simple class OptionsResolver and a method resolver, which resolves the database setting and if there is any validation issue, it will report it. $options = array( 'host' => '<db_host>', 'username' => '<db_user>', 'password' => '<db_password>', ); $resolver = new OptionsResolver(); $resolver->setDefaults(array( 'host' => '<default_db_host>', 'username' => '<default_db_user>', 'password' => '<default_db_password>', )); $resolved_options = $resolver->resolve($options); OptionsResolver component can be installed using the following command. composer require symfony/options-resolver Dotenv component provides various options to parse .env files and the variable defined in them to be accessible via getenv(), $_ENV, or $_SERVER. Dotenv component can be installed using the following command. composer require symfony/dotenv Cache component provides an extended PSR-6 implementation. It can be used to add cache functionality to our web application. Since it follows PSR-6, it is easy to get started and it can be easily used in place of another PSR-6 based cache component. Cache component can be installed using the following command. composer require symfony/cache Intl component is the replacement library for C Intl extension. Intl component can be installed using the following command. composer require symfony/intl Translation component provides various options to internationalize our application. Normally, the translation details of different languages will be stored in a file, one file per language, and it will be loaded dynamically during runtime of the application. There are different formats to write a translation file. Translation component provides various options to load any type of format, such as plain PHP file, CSV, ini, Json, Yaml, ICU Resource file, etc. Translation component can be installed using the following command. composer require symfony/translation Workflow component provides advanced tools to process a finite state machine. By providing this functionality in a simple and object-oriented way, Workflow component enables advanced programming in PHP with relative ease. We will learn about it in detail in the Advanced Concept chapter. Workflow component can be installed using the following command. composer require symfony/workflow Yaml component provides an option that parses the YAML file format and converts it into PHP arrays. It also able to write YAML file from plain php array. Yaml component can be installed using the following command. composer require symfony/yaml Ldap component provides PHP classes to connect to a LDAP or Active directory server and authenticate the user against it. It provides an option to connect to a Windows domain controller. Ldap component can be installed using the following command. composer require symfony/ldap Debug component provides various options to enable debugging in PHP environment. Normally, debugging PHP code is hard but the debug component provides simple classes to ease the process of debugging and make it clean and structured. Debug component can be installed using the following command. composer require symfony/debug Stopwatch component provides Stopwatch class to profile our PHP code. A simple usage is as follows. use Symfony\Component\Stopwatch\Stopwatch; $stopwatch = new Stopwatch(); $stopwatch->start('somename'); // our code to profile $profiled_data = $stopwatch->stop('somename'); echo $profiled_data->getPeriods() Stopwatch component can be installed using the following command. composer require symfony/stopwatch VarDumper component provides better dump() function. Just include the VarDumper component and use the dump function to get the improved functionality. VarDumper component can be installed using the following command. composer require symfony/var-dumper BrowserKit component provides an abstract browser client interface. It can be used to test web application programmatically. For example, it can request a form, enter the sample data and submit it to find any issue in the form programmatically. BrowserKit component can be installed using the following command. composer require symfony/browser-kit PHPUnit Bridge component provides many options to improve the PHPUnit testing environment. PHPUnit Bridge component can be installed using the following command. composer require symfony/phpunit-bridge Asset component provides a generic asset handling in a web application. It generates URL for the assets such as CSS, HTML, JavaScript and also performs version maintenance. We will check the asset component in detail in View Engine chapter. Asset component can be installed using the following command. composer require symfony/asset CssSelector component provides an option to convert CSS based Selectors into XPath expression. A web developer knows the CSS based Selectors expression more than XPath expression, but the most efficient expression to find an element in HTML and XML document is XPath Expression. CssSelector enables the developer to write the expression in CSS Selectors, however, the component converts it to XPath expression before executing it. Thus, the developer has an advantage of simplicity of CSS Selectors and efficiency of XPath expression. CssSelector component can be installed using the following command. composer require symfony/css-selector DomCrawler component provides various options to find the element in HTML and XML document using DOM concept. It also provides option to use XPath expression to find an element. DomCrawler component can be used along with CssSelector component to use CSS selectors instead of XPath expression. DomCrawler component can be installed using the following command. composer require symfony/dom-crawler Form component enables easy creation of form in a web application. We will learn form programming in detail in Form chapter. Form component can be installed using the following command. composer require symfony/form HttpFoundation component provides an object-oriented layer to the HTTP specification. By default, PHP provides HTTP request and response details as array-based object such as $_GET, $_POST, $_FILES, $_SESSION, etc. HTTP based functionality such as setting a cookie can be done using simple, plain old function setCookie(). HttpFoundation provides all HTTP related functionality in a small set of classes like Request, Response, RedirectResponse, etc., We will learn about these classes in the later chapters. HttpFoundation component can be installed using the following command. composer require symfony/http-foundation HttpKernel component is the core component in the Symfony web setup. It provides all the functionalities required for a web application - from receiving the Request object to sending back the Response object. The complete architecture of the Symfony web application is provided by HttpKernel as discussed in the architecture of a Symfony web framework. HttpKernel component can be installed using the following command. composer require symfony/http-kernel Routing component maps the HTTP request to a pre-defined set of configuration variables. Routing decides which part of our application should handle a request. We will learn more about the routing in Routing chapter. Routing component can be installed using the following command. composer require symfony/filesystem Templating component provides the necessary infrastructure to build an efficient template system. Symfony uses the Templating component for its View engine implementation. We will learn more about Templating component in View engine chapter. Templating component can be installed using the following command. composer require symfony/templating Validator component provides an implementation of JSR-303 Bean Validation Specification. It can be used to validate a form in a web environment. We will learn more about Validator in Validation chapter. Validator component can be installed using the following command. composer require symfony/validator Security component provides complete security system for our web application, be it HTTP basic authentication, HTTP digest authentication, interactive form based authentication, X.509 certification login, etc. It also provides authorization mechanism based on the user role through in-built ACL system. We will learn more in detail in the Advanced Concept chapter. Security component can be installed using the following command. composer require symfony/security Print Add Notes Bookmark this page
[ { "code": null, "e": 2563, "s": 2203, "text": "As discussed earlier, Symfony components are standalone PHP library providing a specific feature, which can be used in any PHP application. Useful new components are being introduced in each and every release of Symfony. Currently, there are 30+ high quality components in Symfony framework. Let us learn about the usage of Symfony components in this chapter." }, { "code": null, "e": 2706, "s": 2563, "text": "Symfony components can be installed easily using the composer command. Following generic command can be used to install any Symfony component." }, { "code": null, "e": 2775, "s": 2706, "text": "cd /path/to/project/dir \ncomposer require symfony/<component_name> \n" }, { "code": null, "e": 2855, "s": 2775, "text": "Let us create a simple php application and try to install Filesystem component." }, { "code": null, "e": 2920, "s": 2855, "text": "Step 1 − Create a folder for the application, filesystem-example" }, { "code": null, "e": 2994, "s": 2920, "text": "cd /path/to/dev/folder \nmdkir filesystem-example \ncd filesystem-example \n" }, { "code": null, "e": 3061, "s": 2994, "text": "Step 2 − Install Filesystem component using the following command." }, { "code": null, "e": 3100, "s": 3061, "text": "composer require symfony/filesystem \n" }, { "code": null, "e": 3162, "s": 3100, "text": "Step 3 − Create a file main.php and enter the following code." }, { "code": null, "e": 3527, "s": 3162, "text": "<?php \n require_once __DIR__ . '/vendor/autoload.php'; \n use Symfony\\Component\\Filesystem\\Filesystem; \n use Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface; \n \n $fs = new Filesystem(); \n try { \n $fs->mkdir('./sample-dir'); \n $fs->touch('./sample-dir/text.txt'); \n } catch (IOExceptionInterface $e) { \n echo $e; \n } \n?> \n" }, { "code": null, "e": 3702, "s": 3527, "text": "The first line is very important, which loads all the necessary classes from all the components installed using the Composer command. The next lines use the Filesystem class." }, { "code": null, "e": 3832, "s": 3702, "text": "Step 4 − Run the application using the following command and it will create a new folder sample-dir and a file test.txt under it." }, { "code": null, "e": 3846, "s": 3832, "text": "php main.php\n" }, { "code": null, "e": 4075, "s": 3846, "text": "Symfony provides components ranging from simple feature, say file system to advanced feature, say events, container technology, and dependency injection. Let us know about all the components one by one in the following sections." }, { "code": null, "e": 4289, "s": 4075, "text": "Filesystem component provides a basic system command related to files and directories such as file creation, folder creation, file existence, etc. Filesystem component can be installed using the following command." }, { "code": null, "e": 4326, "s": 4289, "text": "composer require symfony/filesystem\n" }, { "code": null, "e": 4542, "s": 4326, "text": "Finder component provides fluent classes to find files and directories in a specified path. It provides an easy way to iterate over the files in a path. Finder component can be installed using the following command." }, { "code": null, "e": 4575, "s": 4542, "text": "composer require symfony/finder\n" }, { "code": null, "e": 5027, "s": 4575, "text": "Console component provides various options to easily create commands, which can be executed in a terminal. Symfony uses the Command component extensively to provide various functionalities such as creating a new application, creating a bundle, etc. Even the PHP build in web server can be invoked using Symfony command, php bin/console server:run as seen in the installation section. The Console component can be installed using the following command." }, { "code": null, "e": 5061, "s": 5027, "text": "composer require symfony/console\n" }, { "code": null, "e": 5174, "s": 5061, "text": "Let us create a simple application and create a command, HelloCommand using the Console component and invoke it." }, { "code": null, "e": 5229, "s": 5174, "text": "Step 1 − Create a project using the following command." }, { "code": null, "e": 5285, "s": 5229, "text": "cd /path/to/project \ncomposer require symfony/console \n" }, { "code": null, "e": 5349, "s": 5285, "text": "Step 2 − Create a file main.php and include the following code." }, { "code": null, "e": 5504, "s": 5349, "text": "<?php \n require __DIR__ . '/vendor/autoload.php'; \n use Symfony\\Component\\Console\\Application; \n \n $app = new Application(); \n $app->run(); \n?> " }, { "code": null, "e": 5594, "s": 5504, "text": "Application class sets up the necessary functionality of a bare-bone console application." }, { "code": null, "e": 5679, "s": 5594, "text": "Step 3 − Run the application, php main.php, which will produce the following result." }, { "code": null, "e": 6283, "s": 5679, "text": "Console Tool \nUsage: \n command [options] [arguments] \nOptions: \n -h, --help Display this help message \n -q, --quiet Do not output any message \n -V, --version Display this application version \n --ansi Force ANSI output \n --no-ansi Disable ANSI output \n -n, --no-interaction Do not ask any interactive question \n -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, \n 2 for more verbose output and 3 for debug \nAvailable commands: \n help Displays help for a command \n list Lists commands\n" }, { "code": null, "e": 6375, "s": 6283, "text": "Step 4 − Create a class called HelloCommand extending Command class in the main.php itself." }, { "code": null, "e": 6624, "s": 6375, "text": "use Symfony\\Component\\Console\\Command\\Command; \nuse Symfony\\Component\\Console\\Input\\InputInterface; \nuse Symfony\\Component\\Console\\Output\\OutputInterface; \nuse Symfony\\Component\\Console\\Input\\InputArgument;\n\nclass HelloCommand extends Command { \n}\n" }, { "code": null, "e": 6700, "s": 6624, "text": "The application uses following four classes available in Command component." }, { "code": null, "e": 6739, "s": 6700, "text": "Command − Used to create a new command" }, { "code": null, "e": 6778, "s": 6739, "text": "Command − Used to create a new command" }, { "code": null, "e": 6819, "s": 6778, "text": "InputInterface − Used to set user inputs" }, { "code": null, "e": 6860, "s": 6819, "text": "InputInterface − Used to set user inputs" }, { "code": null, "e": 6900, "s": 6860, "text": "InputArgument − Used to get user inputs" }, { "code": null, "e": 6940, "s": 6900, "text": "InputArgument − Used to get user inputs" }, { "code": null, "e": 6994, "s": 6940, "text": "OutputInterface − Used to print output to the console" }, { "code": null, "e": 7048, "s": 6994, "text": "OutputInterface − Used to print output to the console" }, { "code": null, "e": 7129, "s": 7048, "text": "step 5 − Create a function configure() and set name, description, and help text." }, { "code": null, "e": 7308, "s": 7129, "text": "protected function configure() { \n $this \n ->setName('app:hello') \n ->setDescription('Sample command, hello') \n ->setHelp('This command is a sample command') \n} " }, { "code": null, "e": 7386, "s": 7308, "text": "step 6 − Create an input argument, user for the command and set as mandatory." }, { "code": null, "e": 7639, "s": 7386, "text": "protected function configure() { \n $this \n ->setName('app:hello') \n ->setDescription('Sample command, hello') \n ->setHelp('This command is a sample command') \n ->addArgument('name', InputArgument::REQUIRED, 'name of the user'); \n}" }, { "code": null, "e": 7729, "s": 7639, "text": "step 7 − Create a function execute() with two arguments InputArgument and OutputArgument." }, { "code": null, "e": 7809, "s": 7729, "text": "protected function execute(InputInterface $input, OutputInterface $output) { \n}" }, { "code": null, "e": 7930, "s": 7809, "text": "step 8 − Use InputArgument to get the user details entered by the user and print it to the console using OutputArgument." }, { "code": null, "e": 8092, "s": 7930, "text": "protected function execute(InputInterface $input, OutputInterface $output) { \n $name = $input->getArgument('name'); \n $output->writeln('Hello, ' . $name); \n}" }, { "code": null, "e": 8191, "s": 8092, "text": "step 9 − Register the HelloCommand into the application using the add method of Application class." }, { "code": null, "e": 8224, "s": 8191, "text": "$app->add(new HelloCommand()); \n" }, { "code": null, "e": 8264, "s": 8224, "text": "The complete application is as follows." }, { "code": null, "e": 9228, "s": 8264, "text": "<?php \n require __DIR__ . '/vendor/autoload.php'; \n use Symfony\\Component\\Console\\Application; \n use Symfony\\Component\\Console\\Command\\Command; \n use Symfony\\Component\\Console\\Input\\InputInterface; \n use Symfony\\Component\\Console\\Output\\OutputInterface; \n use Symfony\\Component\\Console\\Input\\InputArgument; \n \n class HelloCommand extends Command { \n protected function configure() { \n $this \n ->setName('app:hello') \n ->setDescription('Sample command, hello') \n ->setHelp('This command is a sample command') \n ->addArgument('name', InputArgument::REQUIRED, 'name of the user'); \n } \n protected function execute(InputInterface $input, OutputInterface $output) { \n $name = $input->getArgument('name'); \n $output->writeln('Hello, ' . $name);\n } \n $app = new Application(); \n $app->add(new HelloCommand()); \n $app->run(); \n } \n?> " }, { "code": null, "e": 9342, "s": 9228, "text": "Step 10 − Now, execute the application using the following command and the result will be Hello, Jon as expected." }, { "code": null, "e": 9370, "s": 9342, "text": "php main.php app:hello Jon\n" }, { "code": null, "e": 9536, "s": 9370, "text": "Symfony comes with a pre-built binary called console in the bin directory of any Symfony web application, which can be used to invoke the commands in an application." }, { "code": null, "e": 9711, "s": 9536, "text": "Process component provides options to run any system command in a sub-process, in a safe and efficient manner. Process component can be installed using the following command." }, { "code": null, "e": 9745, "s": 9711, "text": "composer require symfony/process\n" }, { "code": null, "e": 10053, "s": 9745, "text": "ClassLoader component provides implementation for both PSR-0 and PSR-4 class loader standard. It can be used to auto-load the classes. It will be depreciated in the near future. Composer-based class loader is preferred over this component. ClassLoader component can be installed using the following command." }, { "code": null, "e": 10092, "s": 10053, "text": "composer require symfony/class-loader\n" }, { "code": null, "e": 10310, "s": 10092, "text": "PropertyAccess component provides various options to read and write an object and array details using the string notation. For example, an array Product with key price can be accessed dynamically using [price] string." }, { "code": null, "e": 10441, "s": 10310, "text": "$product = array( \n 'name' => 'Cake' \n 'price' => 10 \n); \nvar priceObj = $propertyAccesserObj->getValue($product, '[price]');" }, { "code": null, "e": 10512, "s": 10441, "text": "PropertyAccess component can be installed using the following command." }, { "code": null, "e": 10555, "s": 10512, "text": "composer require symfony/property-access \n" }, { "code": null, "e": 10695, "s": 10555, "text": "PropertyInfo component is similar to PropertyAccess component, however it only works with PHP objects and provides much more functionality." }, { "code": null, "e": 11119, "s": 10695, "text": "class Product { \n private $name = 'Cake'; \n private $price = 10; \n \n public function getName() { \n return $this->name; \n } \n public function getPrice() { \n return $this->price; \n } \n} \n$class = Product::class; \n$properties = $propertyInfoObj->getProperties($class); \n/* \n Example Result \n -------------- \n array(2) { \n [0] => string(4) \"name\" \n [1] => string(5) \"price\" \n } \n*/" }, { "code": null, "e": 11188, "s": 11119, "text": "PropertyInfo component can be installed using the following command." }, { "code": null, "e": 11228, "s": 11188, "text": "composer require symfony/property-info\n" }, { "code": null, "e": 11492, "s": 11228, "text": "EventDispatcher component provides an event-based programming in PHP. It enables the objects to communicate with each other by dispatching events and listening to them. We will learn how to create event and listen to them in the Events and Event Listener chapter." }, { "code": null, "e": 11564, "s": 11492, "text": "EventDispatcher component can be installed using the following command." }, { "code": null, "e": 11607, "s": 11564, "text": "composer require symfony/event-dispatcher\n" }, { "code": null, "e": 12046, "s": 11607, "text": "DependencyInjection component provides an easy and efficient mechanism to create an object with its dependency. When a project grows, it features a lot of classes with deep dependency, which needs to be handled correctly. Otherwise, the project fails. DependencyInjection provides a simple and robust container to handle the dependency. We will learn about the containers and the dependency injection concept in Service Container chapter." }, { "code": null, "e": 12122, "s": 12046, "text": "DependencyInjection component can be installed using the following command." }, { "code": null, "e": 12169, "s": 12122, "text": "composer require symfony/dependency-injection\n" }, { "code": null, "e": 12374, "s": 12169, "text": "Serializer component provides an option to convert a PHP object into a specific format such as XML, JSON, Binary, etc., and then allows it to convert it back into an original object without any data loss." }, { "code": null, "e": 12441, "s": 12374, "text": "Serializer component can be installed using the following command." }, { "code": null, "e": 12478, "s": 12441, "text": "composer require symfony/serializer\n" }, { "code": null, "e": 12847, "s": 12478, "text": "Config component provides options to load, parse, read, and validate configurations of type XML, YAML, PHP and ini. It provides various options to load configuration details from database as well. This is one of the important components useful in configuring web application in a clear and concise manner. Config component can be installed using the following command." }, { "code": null, "e": 12880, "s": 12847, "text": "composer require symfony/config\n" }, { "code": null, "e": 13310, "s": 12880, "text": "ExpessionLanguage component provides a full-fledged expression engine. Expressions are one-liner intended to return a value. The expression engine enables to easily compile, parse, and get the value from an expression. It enables one or more expression to be used in a configuration environment (file) by a non-PHP programmer, say a system administrator. ExpressionLanguage component can be installed using the following command." }, { "code": null, "e": 13356, "s": 13310, "text": "composer require symfony/expression-language\n" }, { "code": null, "e": 13827, "s": 13356, "text": "OptionsResolver component provides a way to validate the option system used in our system. For example, database setting is placed in an array, dboption with host, username, password, etc., as keys. You need to validate the entries before using it to connect to a database. OptionsResolver simplifies this task by providing a simple class OptionsResolver and a method resolver, which resolves the database setting and if there is any validation issue, it will report it." }, { "code": null, "e": 14191, "s": 13827, "text": "$options = array( \n 'host' => '<db_host>', \n 'username' => '<db_user>', \n 'password' => '<db_password>', \n); \n$resolver = new OptionsResolver(); \n$resolver->setDefaults(array( \n 'host' => '<default_db_host>', \n 'username' => '<default_db_user>', \n 'password' => '<default_db_password>', \n)); \n$resolved_options = $resolver->resolve($options);" }, { "code": null, "e": 14263, "s": 14191, "text": "OptionsResolver component can be installed using the following command." }, { "code": null, "e": 14307, "s": 14263, "text": "composer require symfony/options-resolver \n" }, { "code": null, "e": 14516, "s": 14307, "text": "Dotenv component provides various options to parse .env files and the variable defined in them to be accessible via getenv(), $_ENV, or $_SERVER. Dotenv component can be installed using the following command." }, { "code": null, "e": 14549, "s": 14516, "text": "composer require symfony/dotenv\n" }, { "code": null, "e": 14861, "s": 14549, "text": "Cache component provides an extended PSR-6 implementation. It can be used to add cache functionality to our web application. Since it follows PSR-6, it is easy to get started and it can be easily used in place of another PSR-6 based cache component. Cache component can be installed using the following command." }, { "code": null, "e": 14894, "s": 14861, "text": "composer require symfony/cache \n" }, { "code": null, "e": 15019, "s": 14894, "text": "Intl component is the replacement library for C Intl extension. Intl component can be installed using the following command." }, { "code": null, "e": 15050, "s": 15019, "text": "composer require symfony/intl\n" }, { "code": null, "e": 15579, "s": 15050, "text": "Translation component provides various options to internationalize our application. Normally, the translation details of different languages will be stored in a file, one file per language, and it will be loaded dynamically during runtime of the application. There are different formats to write a translation file. Translation component provides various options to load any type of format, such as plain PHP file, CSV, ini, Json, Yaml, ICU Resource file, etc. Translation component can be installed using the following command." }, { "code": null, "e": 15617, "s": 15579, "text": "composer require symfony/translation\n" }, { "code": null, "e": 15905, "s": 15617, "text": "Workflow component provides advanced tools to process a finite state machine. By providing this functionality in a simple and object-oriented way, Workflow component enables advanced programming in PHP with relative ease. We will learn about it in detail in the Advanced Concept chapter." }, { "code": null, "e": 15970, "s": 15905, "text": "Workflow component can be installed using the following command." }, { "code": null, "e": 16006, "s": 15970, "text": "composer require symfony/workflow \n" }, { "code": null, "e": 16221, "s": 16006, "text": "Yaml component provides an option that parses the YAML file format and converts it into PHP arrays. It also able to write YAML file from plain php array. Yaml component can be installed using the following command." }, { "code": null, "e": 16252, "s": 16221, "text": "composer require symfony/yaml\n" }, { "code": null, "e": 16500, "s": 16252, "text": "Ldap component provides PHP classes to connect to a LDAP or Active directory server and authenticate the user against it. It provides an option to connect to a Windows domain controller. Ldap component can be installed using the following command." }, { "code": null, "e": 16531, "s": 16500, "text": "composer require symfony/ldap\n" }, { "code": null, "e": 16826, "s": 16531, "text": "Debug component provides various options to enable debugging in PHP environment. Normally, debugging PHP code is hard but the debug component provides simple classes to ease the process of debugging and make it clean and structured. Debug component can be installed using the following command." }, { "code": null, "e": 16858, "s": 16826, "text": "composer require symfony/debug\n" }, { "code": null, "e": 16958, "s": 16858, "text": "Stopwatch component provides Stopwatch class to profile our PHP code. A simple usage is as follows." }, { "code": null, "e": 17174, "s": 16958, "text": "use Symfony\\Component\\Stopwatch\\Stopwatch; \n$stopwatch = new Stopwatch(); \n$stopwatch->start('somename'); \n\n// our code to profile \n$profiled_data = $stopwatch->stop('somename'); \necho $profiled_data->getPeriods()" }, { "code": null, "e": 17240, "s": 17174, "text": "Stopwatch component can be installed using the following command." }, { "code": null, "e": 17276, "s": 17240, "text": "composer require symfony/stopwatch\n" }, { "code": null, "e": 17493, "s": 17276, "text": "VarDumper component provides better dump() function. Just include the VarDumper component and use the dump function to get the improved functionality. VarDumper component can be installed using the following command." }, { "code": null, "e": 17530, "s": 17493, "text": "composer require symfony/var-dumper\n" }, { "code": null, "e": 17842, "s": 17530, "text": "BrowserKit component provides an abstract browser client interface. It can be used to test web application programmatically. For example, it can request a form, enter the sample data and submit it to find any issue in the form programmatically. BrowserKit component can be installed using the following command." }, { "code": null, "e": 17880, "s": 17842, "text": "composer require symfony/browser-kit\n" }, { "code": null, "e": 18042, "s": 17880, "text": "PHPUnit Bridge component provides many options to improve the PHPUnit testing environment. PHPUnit Bridge component can be installed using the following command." }, { "code": null, "e": 18083, "s": 18042, "text": "composer require symfony/phpunit-bridge\n" }, { "code": null, "e": 18386, "s": 18083, "text": "Asset component provides a generic asset handling in a web application. It generates URL for the assets such as CSS, HTML, JavaScript and also performs version maintenance. We will check the asset component in detail in View Engine chapter. Asset component can be installed using the following command." }, { "code": null, "e": 18418, "s": 18386, "text": "composer require symfony/asset\n" }, { "code": null, "e": 18697, "s": 18418, "text": "CssSelector component provides an option to convert CSS based Selectors into XPath expression. A web developer knows the CSS based Selectors expression more than XPath expression, but the most efficient expression to find an element in HTML and XML document is XPath Expression." }, { "code": null, "e": 18953, "s": 18697, "text": "CssSelector enables the developer to write the expression in CSS Selectors, however, the component converts it to XPath expression before executing it. Thus, the developer has an advantage of simplicity of CSS Selectors and efficiency of XPath expression." }, { "code": null, "e": 19021, "s": 18953, "text": "CssSelector component can be installed using the following command." }, { "code": null, "e": 19060, "s": 19021, "text": "composer require symfony/css-selector\n" }, { "code": null, "e": 19421, "s": 19060, "text": "DomCrawler component provides various options to find the element in HTML and XML document using DOM concept. It also provides option to use XPath expression to find an element. DomCrawler component can be used along with CssSelector component to use CSS selectors instead of XPath expression. DomCrawler component can be installed using the following command." }, { "code": null, "e": 19459, "s": 19421, "text": "composer require symfony/dom-crawler\n" }, { "code": null, "e": 19645, "s": 19459, "text": "Form component enables easy creation of form in a web application. We will learn form programming in detail in Form chapter. Form component can be installed using the following command." }, { "code": null, "e": 19676, "s": 19645, "text": "composer require symfony/form\n" }, { "code": null, "e": 20185, "s": 19676, "text": "HttpFoundation component provides an object-oriented layer to the HTTP specification. By default, PHP provides HTTP request and response details as array-based object such as $_GET, $_POST, $_FILES, $_SESSION, etc. HTTP based functionality such as setting a cookie can be done using simple, plain old function setCookie(). HttpFoundation provides all HTTP related functionality in a small set of classes like Request, Response, RedirectResponse, etc., We will learn about these classes in the later chapters." }, { "code": null, "e": 20256, "s": 20185, "text": "HttpFoundation component can be installed using the following command." }, { "code": null, "e": 20298, "s": 20256, "text": "composer require symfony/http-foundation\n" }, { "code": null, "e": 20651, "s": 20298, "text": "HttpKernel component is the core component in the Symfony web setup. It provides all the functionalities required for a web application - from receiving the Request object to sending back the Response object. The complete architecture of the Symfony web application is provided by HttpKernel as discussed in the architecture of a Symfony web framework." }, { "code": null, "e": 20718, "s": 20651, "text": "HttpKernel component can be installed using the following command." }, { "code": null, "e": 20756, "s": 20718, "text": "composer require symfony/http-kernel\n" }, { "code": null, "e": 20973, "s": 20756, "text": "Routing component maps the HTTP request to a pre-defined set of configuration variables. Routing decides which part of our application should handle a request. We will learn more about the routing in Routing chapter." }, { "code": null, "e": 21037, "s": 20973, "text": "Routing component can be installed using the following command." }, { "code": null, "e": 21074, "s": 21037, "text": "composer require symfony/filesystem\n" }, { "code": null, "e": 21316, "s": 21074, "text": "Templating component provides the necessary infrastructure to build an efficient template system. Symfony uses the Templating component for its View engine implementation. We will learn more about Templating component in View engine chapter." }, { "code": null, "e": 21383, "s": 21316, "text": "Templating component can be installed using the following command." }, { "code": null, "e": 21420, "s": 21383, "text": "composer require symfony/templating\n" }, { "code": null, "e": 21623, "s": 21420, "text": "Validator component provides an implementation of JSR-303 Bean Validation Specification. It can be used to validate a form in a web environment. We will learn more about Validator in Validation chapter." }, { "code": null, "e": 21689, "s": 21623, "text": "Validator component can be installed using the following command." }, { "code": null, "e": 21725, "s": 21689, "text": "composer require symfony/validator\n" }, { "code": null, "e": 22090, "s": 21725, "text": "Security component provides complete security system for our web application, be it HTTP basic authentication, HTTP digest authentication, interactive form based authentication, X.509 certification login, etc. It also provides authorization mechanism based on the user role through in-built ACL system. We will learn more in detail in the Advanced Concept chapter." }, { "code": null, "e": 22155, "s": 22090, "text": "Security component can be installed using the following command." }, { "code": null, "e": 22190, "s": 22155, "text": "composer require symfony/security\n" }, { "code": null, "e": 22197, "s": 22190, "text": " Print" }, { "code": null, "e": 22208, "s": 22197, "text": " Add Notes" } ]
Generating distinct subsequences of a given string in lexicographic order
07 Jul, 2022 Given a string s, make a list of all possible combinations of letters of a given string S. If there are two strings with the same set of characters, print the lexicographically smallest arrangement of the two stringsFor string abc, the list in lexicographic order subsequences are, a ab abc ac b bc cExamples: Input : s = "ab" Output : a ab b Input : xyzx Output : x xx xy xyx xyz xyzx xz xzx y yx yz yzx z zx The idea is to use a set (which is implemented using self balancing BST) to store subsequences so that duplicates can be tested.To generate all subsequences, we one by one remove every character and recur for remaining string. C++ Java Python 3 C# Javascript // C++ program to print all distinct subsequences// of a string.#include <bits/stdc++.h>using namespace std; // Finds and stores result in st for a given// string s.void generate(set<string>& st, string s){ if (s.size() == 0) return; // If current string is not already present. if (st.find(s) == st.end()) { st.insert(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.size(); i++) { string t = s; t.erase(i, 1); generate(st, t); } } return;} // Driver codeint main(){ string s = "xyz"; set<string> st; set<string>::iterator it; generate(st, s); for (auto it = st.begin(); it != st.end(); it++) cout << *it << endl; return 0;} // Java program to print all distinct subsequences// of a string.import java.util.*; class GFG { // Finds and stores result in st for a given // string s. static void generate(Set<String> st, String s) { if (s.length() == 0) { return; } // If current string is not already present. if (!st.contains(s)) { st.add(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.length(); i++) { String t = s; t = t.substring(0, i) + t.substring(i + 1); generate(st, t); } } return; } // Driver code public static void main(String args[]) { String s = "xyz"; TreeSet<String> st = new TreeSet<>(); generate(st, s); for (String str : st) { System.out.println(str); } }} // This code has been contributed by 29AjayKumar// modified by rahul_107 # Python program to print all distinct# subsequences of a string. # Finds and stores result in st for a given# string s.def generate(st, s): if len(s) == 0: return # If current string is not already present. if s not in st: st.add(s) # Traverse current string, one by one # remove every character and recur. for i in range(len(s)): t = list(s).copy() t.remove(s[i]) t = ''.join(t) generate(st, t) return # Driver Codeif __name__ == "__main__": s = "xyz" st = set() generate(st, s) for i in st: print(i) # This code is contributed by# sanjeev2552 // C# program to print all distinct subsequences// of a string.using System;using System.Collections.Generic; class GFG { // Finds and stores result in st for a given // string s. static void generate(HashSet<String> st, String s) { if (s.Length == 0) { return; } // If current string is not already present. if (!st.Contains(s)) { st.Add(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.Length; i++) { String t = s; t = t.Substring(0, i) + t.Substring(i + 1); generate(st, t); } } return; } // Driver code public static void Main(String[] args) { String s = "xyz"; HashSet<String> st = new HashSet<String>(); generate(st, s); foreach(String str in st) { Console.WriteLine(str); } }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to print// all distinct subsequences// of a string. // Finds and stores result in st for a given// string s.function generate(st,s){ if (s.length == 0) return st; // If current string is not already present. if (!st.has(s)) { st.add(s); // Traverse current string, one by one // remove every character and recur. for (let i = 0; i < s.length; i++) { let t = s; t = t.substr(0, i) + t.substr(i + 1); st = generate(st, t); } } return st;} // Driver codelet s = "xyz"; let st = new Set();st = generate(st, s); let str = '';console.log(st)for(item of st.values()) str += item + '<br> ' document.write(str); </script> Output: x xy xyz xz y yz z Time Complexity: O(nn) Auxiliary Space: O(n) This article is contributed by Aarti_Rathi and SANDEEP GAUR MNNIT. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar princiraj1992 sanjeev2552 rahul_107 rohitsingh07052 adi1212 lexicographic-ordering Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Convert string to char array in C++ Check whether two strings are anagram of each other
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 364, "s": 52, "text": "Given a string s, make a list of all possible combinations of letters of a given string S. If there are two strings with the same set of characters, print the lexicographically smallest arrangement of the two stringsFor string abc, the list in lexicographic order subsequences are, a ab abc ac b bc cExamples: " }, { "code": null, "e": 475, "s": 364, "text": "Input : s = \"ab\"\nOutput : a ab b\n\nInput : xyzx\nOutput : x xx xy xyx xyz xyzx xz xzx y\n yx yz yzx z zx" }, { "code": null, "e": 706, "s": 477, "text": "The idea is to use a set (which is implemented using self balancing BST) to store subsequences so that duplicates can be tested.To generate all subsequences, we one by one remove every character and recur for remaining string. " }, { "code": null, "e": 710, "s": 706, "text": "C++" }, { "code": null, "e": 715, "s": 710, "text": "Java" }, { "code": null, "e": 724, "s": 715, "text": "Python 3" }, { "code": null, "e": 727, "s": 724, "text": "C#" }, { "code": null, "e": 738, "s": 727, "text": "Javascript" }, { "code": "// C++ program to print all distinct subsequences// of a string.#include <bits/stdc++.h>using namespace std; // Finds and stores result in st for a given// string s.void generate(set<string>& st, string s){ if (s.size() == 0) return; // If current string is not already present. if (st.find(s) == st.end()) { st.insert(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.size(); i++) { string t = s; t.erase(i, 1); generate(st, t); } } return;} // Driver codeint main(){ string s = \"xyz\"; set<string> st; set<string>::iterator it; generate(st, s); for (auto it = st.begin(); it != st.end(); it++) cout << *it << endl; return 0;}", "e": 1534, "s": 738, "text": null }, { "code": "// Java program to print all distinct subsequences// of a string.import java.util.*; class GFG { // Finds and stores result in st for a given // string s. static void generate(Set<String> st, String s) { if (s.length() == 0) { return; } // If current string is not already present. if (!st.contains(s)) { st.add(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.length(); i++) { String t = s; t = t.substring(0, i) + t.substring(i + 1); generate(st, t); } } return; } // Driver code public static void main(String args[]) { String s = \"xyz\"; TreeSet<String> st = new TreeSet<>(); generate(st, s); for (String str : st) { System.out.println(str); } }} // This code has been contributed by 29AjayKumar// modified by rahul_107", "e": 2540, "s": 1534, "text": null }, { "code": "# Python program to print all distinct# subsequences of a string. # Finds and stores result in st for a given# string s.def generate(st, s): if len(s) == 0: return # If current string is not already present. if s not in st: st.add(s) # Traverse current string, one by one # remove every character and recur. for i in range(len(s)): t = list(s).copy() t.remove(s[i]) t = ''.join(t) generate(st, t) return # Driver Codeif __name__ == \"__main__\": s = \"xyz\" st = set() generate(st, s) for i in st: print(i) # This code is contributed by# sanjeev2552", "e": 3200, "s": 2540, "text": null }, { "code": "// C# program to print all distinct subsequences// of a string.using System;using System.Collections.Generic; class GFG { // Finds and stores result in st for a given // string s. static void generate(HashSet<String> st, String s) { if (s.Length == 0) { return; } // If current string is not already present. if (!st.Contains(s)) { st.Add(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.Length; i++) { String t = s; t = t.Substring(0, i) + t.Substring(i + 1); generate(st, t); } } return; } // Driver code public static void Main(String[] args) { String s = \"xyz\"; HashSet<String> st = new HashSet<String>(); generate(st, s); foreach(String str in st) { Console.WriteLine(str); } }} /* This code contributed by PrinciRaj1992 */", "e": 4219, "s": 3200, "text": null }, { "code": "<script> // JavaScript program to print// all distinct subsequences// of a string. // Finds and stores result in st for a given// string s.function generate(st,s){ if (s.length == 0) return st; // If current string is not already present. if (!st.has(s)) { st.add(s); // Traverse current string, one by one // remove every character and recur. for (let i = 0; i < s.length; i++) { let t = s; t = t.substr(0, i) + t.substr(i + 1); st = generate(st, t); } } return st;} // Driver codelet s = \"xyz\"; let st = new Set();st = generate(st, s); let str = '';console.log(st)for(item of st.values()) str += item + '<br> ' document.write(str); </script>", "e": 4961, "s": 4219, "text": null }, { "code": null, "e": 4971, "s": 4961, "text": "Output: " }, { "code": null, "e": 4990, "s": 4971, "text": "x\nxy\nxyz\nxz\ny\nyz\nz" }, { "code": null, "e": 5013, "s": 4990, "text": "Time Complexity: O(nn)" }, { "code": null, "e": 5035, "s": 5013, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 5478, "s": 5035, "text": "This article is contributed by Aarti_Rathi and SANDEEP GAUR MNNIT. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5490, "s": 5478, "text": "29AjayKumar" }, { "code": null, "e": 5504, "s": 5490, "text": "princiraj1992" }, { "code": null, "e": 5516, "s": 5504, "text": "sanjeev2552" }, { "code": null, "e": 5526, "s": 5516, "text": "rahul_107" }, { "code": null, "e": 5542, "s": 5526, "text": "rohitsingh07052" }, { "code": null, "e": 5550, "s": 5542, "text": "adi1212" }, { "code": null, "e": 5573, "s": 5550, "text": "lexicographic-ordering" }, { "code": null, "e": 5581, "s": 5573, "text": "Strings" }, { "code": null, "e": 5589, "s": 5581, "text": "Strings" }, { "code": null, "e": 5687, "s": 5589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5762, "s": 5687, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 5807, "s": 5762, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5864, "s": 5807, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 5900, "s": 5864, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 5938, "s": 5900, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 5999, "s": 5938, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 6044, "s": 5999, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 6108, "s": 6044, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6144, "s": 6108, "text": "Convert string to char array in C++" } ]
How to change Bootstrap datepicker with specific date format ?
23 Jul, 2021 DatePicker is a component of Bootstrap Framework that allows users to select the date by providing a user-friendly interface. Using DatePicker, we can select a date from the DatePicker dialog which is far better than manually typing the date in the input field. Also, we can format the DatePicker as per the requirements. DatePicker provides various date formats like dd/mm/yyyy, yyyy-mm-dd, dd/mm/yyyy, dd-mm-yyyy, etc out of which one can be selected which best fits the requirements. To use this custom date formats we need to set this format in jQuery DatePicker. Below are some examples with different date formats. Example 1:The following is the DatePicker with dd-mm-yyyy format. HTML <!DOCTYPE html><html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"> </script> </head> <body> <input type="text" class="date form-control" style="width: 200px" /> <script type="text/javascript"> $(".date").datepicker({ format: "dd-mm-yyyy", }); </script> </body></html> Output: Example 2: The following is the datePicker with yyyy-mm-dd format. HTML <!DOCTYPE html><html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"> </script> </head> <body> <input type="text" class="date form-control" style="width: 200px" /> <script type="text/javascript"> $(".date").datepicker({ format: "yyyy-mm-dd", }); </script> </body></html> Output: Example 3: The following is the datePicker with dd/mm/yyyy format. HTML <!DOCTYPE html><html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"> </script> </head> <body> <input type="text" class="date form-control" style="width: 200px" /> <script type="text/javascript"> $(".date").datepicker({ format: "dd/mm/yyyy", }); </script> </body></html> Output: Example 4: The following is the datePicker with yyyy/mm/dd format. HTML <!DOCTYPE html><html> <head> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"> </script> </head> <body> <input type="text" class="date form-control" style="width: 200px" /> <script type="text/javascript"> $(".date").datepicker({ format: "yyyy/mm/dd", }); </script> </body></html> Output: vrushaket Bootstrap-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2021" }, { "code": null, "e": 290, "s": 28, "text": "DatePicker is a component of Bootstrap Framework that allows users to select the date by providing a user-friendly interface. Using DatePicker, we can select a date from the DatePicker dialog which is far better than manually typing the date in the input field." }, { "code": null, "e": 597, "s": 290, "text": "Also, we can format the DatePicker as per the requirements. DatePicker provides various date formats like dd/mm/yyyy, yyyy-mm-dd, dd/mm/yyyy, dd-mm-yyyy, etc out of which one can be selected which best fits the requirements. To use this custom date formats we need to set this format in jQuery DatePicker." }, { "code": null, "e": 650, "s": 597, "text": "Below are some examples with different date formats." }, { "code": null, "e": 716, "s": 650, "text": "Example 1:The following is the DatePicker with dd-mm-yyyy format." }, { "code": null, "e": 721, "s": 716, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css\" rel=\"stylesheet\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js\"> </script> </head> <body> <input type=\"text\" class=\"date form-control\" style=\"width: 200px\" /> <script type=\"text/javascript\"> $(\".date\").datepicker({ format: \"dd-mm-yyyy\", }); </script> </body></html>", "e": 1550, "s": 721, "text": null }, { "code": null, "e": 1558, "s": 1550, "text": "Output:" }, { "code": null, "e": 1625, "s": 1558, "text": "Example 2: The following is the datePicker with yyyy-mm-dd format." }, { "code": null, "e": 1630, "s": 1625, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css\" rel=\"stylesheet\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js\"> </script> </head> <body> <input type=\"text\" class=\"date form-control\" style=\"width: 200px\" /> <script type=\"text/javascript\"> $(\".date\").datepicker({ format: \"yyyy-mm-dd\", }); </script> </body></html>", "e": 2459, "s": 1630, "text": null }, { "code": null, "e": 2467, "s": 2459, "text": "Output:" }, { "code": null, "e": 2534, "s": 2467, "text": "Example 3: The following is the datePicker with dd/mm/yyyy format." }, { "code": null, "e": 2539, "s": 2534, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css\" rel=\"stylesheet\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js\"> </script> </head> <body> <input type=\"text\" class=\"date form-control\" style=\"width: 200px\" /> <script type=\"text/javascript\"> $(\".date\").datepicker({ format: \"dd/mm/yyyy\", }); </script> </body></html>", "e": 3368, "s": 2539, "text": null }, { "code": null, "e": 3377, "s": 3368, "text": " Output:" }, { "code": null, "e": 3445, "s": 3377, "text": "Example 4: The following is the datePicker with yyyy/mm/dd format. " }, { "code": null, "e": 3450, "s": 3445, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\" /> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css\" rel=\"stylesheet\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js\"> </script> </head> <body> <input type=\"text\" class=\"date form-control\" style=\"width: 200px\" /> <script type=\"text/javascript\"> $(\".date\").datepicker({ format: \"yyyy/mm/dd\", }); </script> </body></html>", "e": 4279, "s": 3450, "text": null }, { "code": null, "e": 4287, "s": 4279, "text": "Output:" }, { "code": null, "e": 4297, "s": 4287, "text": "vrushaket" }, { "code": null, "e": 4317, "s": 4297, "text": "Bootstrap-Questions" }, { "code": null, "e": 4324, "s": 4317, "text": "Picked" }, { "code": null, "e": 4334, "s": 4324, "text": "Bootstrap" }, { "code": null, "e": 4351, "s": 4334, "text": "Web Technologies" } ]
Class Factories: A powerful pattern in Python
25 Oct, 2020 A Class Factory is a function that creates and returns a class. It is one of the powerful patterns in Python. In this section, we will cover how to design class factories and the use cases of it. As mentioned, class factories are functions that create and return a class. It can create a class at the coding time (using class keyword) and as well as during run time (using the type). Let’s start with how to design a class factory and create a class at the coding time, then we look into the scenario of creating a class during run time. Designing a class factory using the class keyword is nothing but creating a function that holds a class. Let’s see the below code: Python3 def apple_function(): """Return an Apple class, built using the class keyword""" class Apple(object): def __init__(self, color): self.color = color def getColor(self): return self.color return Apple # invoking class factory functionApple = apple_function()appleObj = Apple('red')print(appleObj.getColor()) red Using type we can create classes dynamically. But doing so will leave the functions in the namespace along with the class. Let’s look into the code to understand it better. Python3 def init(self, color): self.color = color def getColor(self): return self.color Apple = type('Apple', (object,), { '__init__': init, 'getColor': getColor,}) appleRed = Apple(color='red')print(appleRed.getColor()) red The above code shows how to create class dynamically. But the problem is that the functions such as init and getColor are cluttering the namespace and also we won’t be able to reuse the functionality. Whereas, by using a class factory, you can minimize the clutter and can reuse the function when in need. Let’s look at the below code. Python3 def create_apple_class(): def init(self, color): self.color = color def getColor(self): return self.color return type('Apple', (object,), { '__init__': init, 'getColor': getColor, }) Apple = create_apple_class()appleObj = Apple('red')print(appleObj.getColor()) red It is important to note that multiple calls to create_apple_class will return distinct classes. Let’s have a look at some of the use cases of class factories. Class Factories are useful when you do not know what attributes to be assigned at the time of coding Class Factories are necessary when attributes of the class differ based on the requirement. Let’s consider the case of a login process. Here, we will consider two scenarios, either traditional login or using an OpenId service. If we look into traditional login, the parameters are username and password, and additionally, it may have two-factor authentication. And, for OpenId service, the parameters are service name and email address. This two login scenario points to the fact that attributes of a class differ based on the login service. Let’s look in the below sample code: Python3 def credentials_cls(need_proxy=False, tfa=False): # need proxy for openId services if need_proxy: print("Open Id Service") keys = ['service_name', 'email_address'] else: print("Traditional Login") keys = ['username', 'password'] # two factor authentication for traditional login if tfa: keys.append('auth_token') class CredentialCheck(object): required_keys = set(keys) def __init__(self, **kwargs): # checking whether key matches based on login service if self.required_keys != set(kwargs.keys()): raise ValueError('Mismatch') # storing the keys and values to the credential object for k, v in kwargs.items(): setattr(self, k, v) return CredentialCheck CredCheck = credentials_cls(False, False)crdTraditional = CredCheck(username='uname', password='******') OpenIDCheck = credentials_cls(True, False)crdOpenID = OpenIDCheck(service_name='sname', email_address='email@gmail.com') Traditional Login Open Id Service Another advantage of using class attributes is that it can deal with class attributes and can distinguish them from class instances. Let’s consider the scenario where a class defines a class method. Class methods are methods that require the class itself for execution rather than the instance of a class. You can design a class method by decorating a method using @classmethod decorator. Let’s look at the below code. Python3 class Apple(object): color = 'red' @classmethod def classapple(cls): return cls.color appleRed = Apple()appleYellow = Apple()appleGreen = Apple() print("Apple Red: ", appleRed.classapple()) appleYellow.color = 'Yellow'print("Apple Yellow: ", appleYellow.classapple()) appleGreen.color = 'Green'print("Apple Green: ", appleGreen.classapple()) Apple Red: red Apple Yellow: red Apple Green: red In the above code, we have designed a class called Apple that has color as an attribute. In addition to this, we have declared a class method called classapple using the decorator @classmethod. The functionality of classapple method is to return the color of the apple. But, you can note that even after setting the color of apple to Yellow and Green, the object returns the default color red. This limitation can be overcome using a class factory. Let’s see the below code that defines a class factory called create_Apple_subclass. Here we will create a subclass of Apple, subApple, to set the color. Finally, the class factory returns the subclass. Python3 class Apple(object): color = 'red' @classmethod def classapple(cls): return cls.color def create_Apple_subclass(new_color): class SubApple(Apple): color = new_color return SubApple sappleYellow = create_Apple_subclass('Yellow')print("Apple Color: ", sappleYellow.classapple()) sappleGreen = create_Apple_subclass('Green')print("Apple Color: ", sappleGreen.classapple()) Apple Color: Yellow Apple Color: Green Class factories are powerful design patterns that ensure a dynamic class creation process is readable, organized, and reusable. And, also class factories allow attribute switching based on the parameter sent to the function. Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2020" }, { "code": null, "e": 224, "s": 28, "text": "A Class Factory is a function that creates and returns a class. It is one of the powerful patterns in Python. In this section, we will cover how to design class factories and the use cases of it." }, { "code": null, "e": 566, "s": 224, "text": "As mentioned, class factories are functions that create and return a class. It can create a class at the coding time (using class keyword) and as well as during run time (using the type). Let’s start with how to design a class factory and create a class at the coding time, then we look into the scenario of creating a class during run time." }, { "code": null, "e": 697, "s": 566, "text": "Designing a class factory using the class keyword is nothing but creating a function that holds a class. Let’s see the below code:" }, { "code": null, "e": 705, "s": 697, "text": "Python3" }, { "code": "def apple_function(): \"\"\"Return an Apple class, built using the class keyword\"\"\" class Apple(object): def __init__(self, color): self.color = color def getColor(self): return self.color return Apple # invoking class factory functionApple = apple_function()appleObj = Apple('red')print(appleObj.getColor())", "e": 1065, "s": 705, "text": null }, { "code": null, "e": 1070, "s": 1065, "text": "red\n" }, { "code": null, "e": 1243, "s": 1070, "text": "Using type we can create classes dynamically. But doing so will leave the functions in the namespace along with the class. Let’s look into the code to understand it better." }, { "code": null, "e": 1251, "s": 1243, "text": "Python3" }, { "code": "def init(self, color): self.color = color def getColor(self): return self.color Apple = type('Apple', (object,), { '__init__': init, 'getColor': getColor,}) appleRed = Apple(color='red')print(appleRed.getColor())", "e": 1483, "s": 1251, "text": null }, { "code": null, "e": 1488, "s": 1483, "text": "red\n" }, { "code": null, "e": 1824, "s": 1488, "text": "The above code shows how to create class dynamically. But the problem is that the functions such as init and getColor are cluttering the namespace and also we won’t be able to reuse the functionality. Whereas, by using a class factory, you can minimize the clutter and can reuse the function when in need. Let’s look at the below code." }, { "code": null, "e": 1832, "s": 1824, "text": "Python3" }, { "code": "def create_apple_class(): def init(self, color): self.color = color def getColor(self): return self.color return type('Apple', (object,), { '__init__': init, 'getColor': getColor, }) Apple = create_apple_class()appleObj = Apple('red')print(appleObj.getColor())", "e": 2140, "s": 1832, "text": null }, { "code": null, "e": 2145, "s": 2140, "text": "red\n" }, { "code": null, "e": 2241, "s": 2145, "text": "It is important to note that multiple calls to create_apple_class will return distinct classes." }, { "code": null, "e": 2406, "s": 2241, "text": "Let’s have a look at some of the use cases of class factories. Class Factories are useful when you do not know what attributes to be assigned at the time of coding " }, { "code": null, "e": 2988, "s": 2406, "text": "Class Factories are necessary when attributes of the class differ based on the requirement. Let’s consider the case of a login process. Here, we will consider two scenarios, either traditional login or using an OpenId service. If we look into traditional login, the parameters are username and password, and additionally, it may have two-factor authentication. And, for OpenId service, the parameters are service name and email address. This two login scenario points to the fact that attributes of a class differ based on the login service. Let’s look in the below sample code: " }, { "code": null, "e": 2996, "s": 2988, "text": "Python3" }, { "code": "def credentials_cls(need_proxy=False, tfa=False): # need proxy for openId services if need_proxy: print(\"Open Id Service\") keys = ['service_name', 'email_address'] else: print(\"Traditional Login\") keys = ['username', 'password'] # two factor authentication for traditional login if tfa: keys.append('auth_token') class CredentialCheck(object): required_keys = set(keys) def __init__(self, **kwargs): # checking whether key matches based on login service if self.required_keys != set(kwargs.keys()): raise ValueError('Mismatch') # storing the keys and values to the credential object for k, v in kwargs.items(): setattr(self, k, v) return CredentialCheck CredCheck = credentials_cls(False, False)crdTraditional = CredCheck(username='uname', password='******') OpenIDCheck = credentials_cls(True, False)crdOpenID = OpenIDCheck(service_name='sname', email_address='email@gmail.com')", "e": 4046, "s": 2996, "text": null }, { "code": null, "e": 4081, "s": 4046, "text": "Traditional Login\nOpen Id Service\n" }, { "code": null, "e": 4500, "s": 4081, "text": "Another advantage of using class attributes is that it can deal with class attributes and can distinguish them from class instances. Let’s consider the scenario where a class defines a class method. Class methods are methods that require the class itself for execution rather than the instance of a class. You can design a class method by decorating a method using @classmethod decorator. Let’s look at the below code." }, { "code": null, "e": 4508, "s": 4500, "text": "Python3" }, { "code": "class Apple(object): color = 'red' @classmethod def classapple(cls): return cls.color appleRed = Apple()appleYellow = Apple()appleGreen = Apple() print(\"Apple Red: \", appleRed.classapple()) appleYellow.color = 'Yellow'print(\"Apple Yellow: \", appleYellow.classapple()) appleGreen.color = 'Green'print(\"Apple Green: \", appleGreen.classapple())", "e": 4874, "s": 4508, "text": null }, { "code": null, "e": 4928, "s": 4874, "text": "Apple Red: red\nApple Yellow: red\nApple Green: red\n" }, { "code": null, "e": 5378, "s": 4928, "text": "In the above code, we have designed a class called Apple that has color as an attribute. In addition to this, we have declared a class method called classapple using the decorator @classmethod. The functionality of classapple method is to return the color of the apple. But, you can note that even after setting the color of apple to Yellow and Green, the object returns the default color red. This limitation can be overcome using a class factory. " }, { "code": null, "e": 5581, "s": 5378, "text": "Let’s see the below code that defines a class factory called create_Apple_subclass. Here we will create a subclass of Apple, subApple, to set the color. Finally, the class factory returns the subclass. " }, { "code": null, "e": 5589, "s": 5581, "text": "Python3" }, { "code": "class Apple(object): color = 'red' @classmethod def classapple(cls): return cls.color def create_Apple_subclass(new_color): class SubApple(Apple): color = new_color return SubApple sappleYellow = create_Apple_subclass('Yellow')print(\"Apple Color: \", sappleYellow.classapple()) sappleGreen = create_Apple_subclass('Green')print(\"Apple Color: \", sappleGreen.classapple())", "e": 5997, "s": 5589, "text": null }, { "code": null, "e": 6039, "s": 5997, "text": "Apple Color: Yellow\nApple Color: Green\n" }, { "code": null, "e": 6264, "s": 6039, "text": "Class factories are powerful design patterns that ensure a dynamic class creation process is readable, organized, and reusable. And, also class factories allow attribute switching based on the parameter sent to the function." }, { "code": null, "e": 6275, "s": 6264, "text": "Python-OOP" }, { "code": null, "e": 6282, "s": 6275, "text": "Python" } ]
Largest subsequence having GCD greater than 1
11 Aug, 2021 Given an array, arr[], find the largest subsequence such that GCD of all those subsequences are greater than 1. Examples: Input: 3, 6, 2, 5, 4 Output: 3 Explanation: There are only three elements(6, 2, 4) having GCD greater than 1 i.e., 2. So the largest subsequence will be 3 Input: 10, 15, 7, 25, 9, 35 Output: 4 Naive Approach(Method 1) Simple approach is to generate all the subsequence one by one and then find the GCD of all such generated set. Problem of this approach is that it grows exponentially in 2N Iterative Approach(Method 2) If we observe then we will found that to make gcd greater than 1, all such elements must contain common factor greater than 1 which evenly divides all these values. So in order to get that factor we will iterate from 2 to Maximum element of array and then check for divisibility. C++ Java Python3 C# PHP Javascript // Simple C++ program to find length of// the largest subsequence with GCD greater// than 1.#include<bits/stdc++.h> using namespace std; // Returns length of the largest subsequence// with GCD more than 1.int largestGCDSubsequence(int arr[], int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = *max_element(arr, arr+n); // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = max(ans, count); } return ans;} // Driver codeint main(){ int arr[] = {3, 6, 2, 5, 4}; int size = sizeof(arr) / sizeof(arr[0]); cout << largestGCDSubsequence(arr, size); return 0;} // Efficient Java program to find length of// the largest subsequence with GCD greater// than 1.import java.util.Arrays; class GFG {// Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int arr[], int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = Arrays.stream(arr).max().getAsInt();; // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = Math.max(ans, count); } return ans;}// Driver program to test above public static void main(String[] args) { int arr[] = {3, 6, 2, 5, 4}; int size = arr.length; System.out.println(largestGCDSubsequence(arr, size)); }} //this code contributed by Rajput-Ji # Simple Python 3 program to find length of# the largest subsequence with GCD greater# than 1. # Returns length of the largest subsequence# with GCD more than 1.def largestGCDSubsequence(arr, n): ans = 0 # Finding the Maximum value in arr[] maxele = max(arr) # Iterate from 2 to maximum possible # divisor of all give values for i in range(2, maxele + 1): count = 0 for j in range(n): # If we found divisor, # increment count if (arr[j] % i == 0): count += 1 ans = max(ans, count) return ans # Driver codeif __name__ == '__main__': arr = [3, 6, 2, 5, 4] size = len(arr) print(largestGCDSubsequence(arr, size)) # This code is contributed by Rajput-Ji // Efficient C# program to find length of// the largest subsequence with GCD greater// than 1.using System;using System.Linq;public class GFG {// Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int []arr, int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = arr.Max(); // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = Math.Max(ans, count); } return ans;}// Driver program to test above public static void Main() { int []arr = {3, 6, 2, 5, 4}; int size = arr.Length; Console.Write(largestGCDSubsequence(arr, size)); }} //this code contributed by Rajput-Ji <?php// Simple PHP program to find length of// the largest subsequence with GCD greater// than 1. // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence($arr, $n){ $ans = 0; // Finding the Maximum value in arr[] $maxele = max($arr); // Iterate from 2 to maximum possible // divisor of all give values for ($i = 2; $i <= $maxele; ++$i) { $count = 0; for ($j = 0; $j < $n; ++$j) { // If we found divisor, // increment count if ($arr[$j] % $i == 0) ++$count; } $ans = max($ans, $count); } return $ans;} // Driver code$arr = array(3, 6, 2, 5, 4);$size = count($arr);echo largestGCDSubsequence($arr, $size); // This code is contributed by mits?> <script>// Efficient javascript program to find length of// the largest subsequence with GCD greater// than 1. // Returns length of the largest subsequence // with GCD more than 1. function largestGCDSubsequence(arr , n) { var ans = 0; // Finding the Maximum value in arr var maxele =Math.max(...arr); // Iterate from 2 to maximum possible // divisor of all give values for ( var i = 2; i <= maxele; ++i) { var count = 0; for (j = 0; j < n; ++j) { // If we found divisor, // increment count if (arr[j] % i == 0) ++count; } ans = Math.max(ans, count); } return ans; } // Driver program to test above var arr = [ 3, 6, 2, 5, 4 ]; var size = arr.length; document.write(largestGCDSubsequence(arr, size)); // This code is contributed by aashish1995</script> Output: 3 Time Complexity: O(n * max(arr[i])) where n is size of array. Auxiliary Space: O(1) Best Approach(Method 3) An efficient approach is to use prime factorization method with the help of Sieve of Eratosthenes. First of all we will find the smallest prime divisor of all elements by pre-computed sieve. After that we will mark all the prime divisor of every element of arr[] by factorizing it with the help of pre-computed prime[] array. Now we have all the marked primes occurring in all the array elements. The last step is to find the maximum count of all such prime factors. C++ Java Python3 C# PHP Javascript // Efficient C++ program to find length of// the largest subsequence with GCD greater// than 1.#include<bits/stdc++.h> using namespace std; #define MAX 100001 // prime[] for storing smallest prime divisor of element// count[] for storing the number of times a particular// divisor occurs in a subsequenceint prime[MAX], countdiv[MAX]; // Simple sieve to find smallest prime factors of numbers// smaller than MAXvoid SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (!prime[i]) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (!prime[i]) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.int largestGCDSubsequence(int arr[], int n){ int ans = 0; for (int i=0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = max(ans, countdiv[div]); while (element % div==0) element /= div; } } return ans;} // Driver codeint main(){ // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); int arr[] = {10, 15, 7, 25, 9, 35}; int size = sizeof(arr) / sizeof(arr[0]); cout << largestGCDSubsequence(arr, size); return 0;} // Efficient Java program to find length of// the largest subsequence with GCD greater// than 1. class GFG{static int MAX = 100001; // prime[] for storing smallest prime divisor// of element count[] for storing the number// of times a particular divisor occurs// in a subsequencestatic int[] prime = new int[MAX + 1];static int[] countdiv = new int[MAX + 1]; // Simple sieve to find smallest prime// factors of numbers smaller than MAXstatic void SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int arr[], int n){ int ans = 0; for (int i = 0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.max(ans, countdiv[div]); while (element % div == 0) element /= div; } } return ans;} // Driver codepublic static void main (String[] args){ // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); int arr[] = {10, 15, 7, 25, 9, 35}; int size = arr.length; System.out.println(largestGCDSubsequence(arr, size));}} // This code is contributed by mits # Efficient Python3 program to find length# of the largest subsequence with GCD# greater than 1.import math as mt MAX = 100001 # prime[] for storing smallest# prime divisor of element# count[] for storing the number# of times a particular divisor# occurs in a subsequenceprime = [0 for i in range(MAX + 1)]countdiv = [0 for i in range(MAX + 1)] # Simple sieve to find smallest prime# factors of numbers smaller than MAXdef SieveOfEratosthenes(): for i in range(2, mt.ceil(mt.sqrt(MAX + 1))): if (prime[i] == 0): for j in range(i * 2, MAX + 1, i): prime[j] = i # Prime number will have same divisor for i in range(1, MAX): if (prime[i] == 0): prime[i] = i # Returns length of the largest# subsequence with GCD more than 1.def largestGCDSubsequence(arr, n): ans = 0 for i in range(n): element = arr[i] # Fetch total unique prime # divisor of element while (element > 1): div = prime[element] # Increment count[] of Every # unique divisor we get till now countdiv[div] += 1 # Find maximum frequency of divisor ans = max(ans, countdiv[div]) while (element % div == 0): element = element // div return ans # Driver code # Pre-compute smallest divisor# of all numbersSieveOfEratosthenes() arr= [10, 15, 7, 25, 9, 35]size = len(arr)print(largestGCDSubsequence(arr, size)) # This code is contributed# by Mohit kumar 29 // Efficient C# program to find length of// the largest subsequence with GCD greater// than 1.using System; class GFG{ static int MAX=100001; // prime[] for storing smallest// prime divisor of element count[]// for storing the number of times// a particular divisor occurs in a subsequencestatic int[] prime = new int[MAX + 1];static int[] countdiv = new int[MAX + 1]; // Simple sieve to find smallest prime// factors of numbers smaller than MAXstatic void SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int []arr, int n){ int ans = 0; for (int i = 0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.Max(ans, countdiv[div]); while (element % div==0) element /= div; } } return ans;} // Driver codepublic static void Main(){ // Pre-compute smallest // divisor of all numbers SieveOfEratosthenes(); int []arr = {10, 15, 7, 25, 9, 35}; int size = arr.Length; Console.WriteLine(largestGCDSubsequence(arr, size));}} // This code is contributed by mits <?php// Efficient PHP program to find length of// the largest subsequence with GCD greater// than 1. $MAX = 10001; // prime[] for storing smallest prime divisor of element// count[] for storing the number of times a particular// divisor occurs in a subsequence$prime = array_fill(0, $MAX, 0);$countdiv = array_fill(0, $MAX, 0); // Simple sieve to find smallest prime factors of numbers// smaller than MAXfunction SieveOfEratosthenes(){ global $MAX,$prime; for ($i = 2; $i * $i <= $MAX; ++$i) { if ($prime[$i] == 0) for ($j = $i * 2; $j <= $MAX; $j += $i) $prime[$j] = $i; } // Prime number will have same divisor for ($i = 1; $i < $MAX; ++$i) if ($prime[$i] == 0) $prime[$i] = $i;} // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence($arr, $n){ global $countdiv,$prime; $ans = 0; for ($i = 0; $i < $n; ++$i) { $element = $arr[$i]; // Fetch total unique prime divisor of element while ($element > 1) { $div = $prime[$element]; // Increment count[] of Every unique divisor // we get till now ++$countdiv[$div]; // Find maximum frequency of divisor $ans = max($ans, $countdiv[$div]); while ($element % $div == 0) $element = (int)($element/$div); } } return $ans;} // Driver code // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); $arr = array(10, 15, 7, 25, 9, 35); $size = count($arr); echo largestGCDSubsequence($arr, $size); // This code is contributed by mits?> <script>// Efficient Javascript program to find length of// the largest subsequence with GCD greater// than 1. let MAX = 100001;// prime[] for storing smallest prime divisor// of element count[] for storing the number// of times a particular divisor occurs// in a subsequencelet prime = new Array(MAX + 1);let countdiv = new Array(MAX + 1);for(let i=0;i<MAX+1;i++){ prime[i]=0; countdiv[i]=0;} // Simple sieve to find smallest prime// factors of numbers smaller than MAXfunction SieveOfEratosthenes(){ for (let i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (let j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (let i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence(arr,n){ let ans = 0; for (let i = 0; i < n; ++i) { let element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { let div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.max(ans, countdiv[div]); while (element % div == 0) element /= div; } } return ans;} // Driver code// Pre-compute smallest divisor of all numbersSieveOfEratosthenes();let arr=[10, 15, 7, 25, 9, 35];let size = arr.length;document.write(largestGCDSubsequence(arr, size)); // This code is contributed by unknown2108</script> Output: 4 Time complexity: O( n*log(max(arr[i])) ) + MAX*log(log(MAX)) Auxiliary space: O(MAX)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SHREYAS_SINGH Rajput-Ji Mithun Kumar mohit kumar 29 aashish1995 unknown2108 surindertarika1234 GCD-LCM prime-factor Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Aug, 2021" }, { "code": null, "e": 178, "s": 54, "text": "Given an array, arr[], find the largest subsequence such that GCD of all those subsequences are greater than 1. Examples: " }, { "code": null, "e": 374, "s": 178, "text": "Input: 3, 6, 2, 5, 4\nOutput: 3\nExplanation: There are only three elements(6, \n2, 4) having GCD greater than 1 i.e., 2. So the \nlargest subsequence will be 3\n\nInput: 10, 15, 7, 25, 9, 35\nOutput: 4" }, { "code": null, "e": 403, "s": 378, "text": "Naive Approach(Method 1)" }, { "code": null, "e": 577, "s": 403, "text": "Simple approach is to generate all the subsequence one by one and then find the GCD of all such generated set. Problem of this approach is that it grows exponentially in 2N " }, { "code": null, "e": 606, "s": 577, "text": "Iterative Approach(Method 2)" }, { "code": null, "e": 888, "s": 606, "text": "If we observe then we will found that to make gcd greater than 1, all such elements must contain common factor greater than 1 which evenly divides all these values. So in order to get that factor we will iterate from 2 to Maximum element of array and then check for divisibility. " }, { "code": null, "e": 892, "s": 888, "text": "C++" }, { "code": null, "e": 897, "s": 892, "text": "Java" }, { "code": null, "e": 905, "s": 897, "text": "Python3" }, { "code": null, "e": 908, "s": 905, "text": "C#" }, { "code": null, "e": 912, "s": 908, "text": "PHP" }, { "code": null, "e": 923, "s": 912, "text": "Javascript" }, { "code": "// Simple C++ program to find length of// the largest subsequence with GCD greater// than 1.#include<bits/stdc++.h> using namespace std; // Returns length of the largest subsequence// with GCD more than 1.int largestGCDSubsequence(int arr[], int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = *max_element(arr, arr+n); // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = max(ans, count); } return ans;} // Driver codeint main(){ int arr[] = {3, 6, 2, 5, 4}; int size = sizeof(arr) / sizeof(arr[0]); cout << largestGCDSubsequence(arr, size); return 0;}", "e": 1789, "s": 923, "text": null }, { "code": "// Efficient Java program to find length of// the largest subsequence with GCD greater// than 1.import java.util.Arrays; class GFG {// Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int arr[], int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = Arrays.stream(arr).max().getAsInt();; // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = Math.max(ans, count); } return ans;}// Driver program to test above public static void main(String[] args) { int arr[] = {3, 6, 2, 5, 4}; int size = arr.length; System.out.println(largestGCDSubsequence(arr, size)); }} //this code contributed by Rajput-Ji", "e": 2764, "s": 1789, "text": null }, { "code": "# Simple Python 3 program to find length of# the largest subsequence with GCD greater# than 1. # Returns length of the largest subsequence# with GCD more than 1.def largestGCDSubsequence(arr, n): ans = 0 # Finding the Maximum value in arr[] maxele = max(arr) # Iterate from 2 to maximum possible # divisor of all give values for i in range(2, maxele + 1): count = 0 for j in range(n): # If we found divisor, # increment count if (arr[j] % i == 0): count += 1 ans = max(ans, count) return ans # Driver codeif __name__ == '__main__': arr = [3, 6, 2, 5, 4] size = len(arr) print(largestGCDSubsequence(arr, size)) # This code is contributed by Rajput-Ji", "e": 3529, "s": 2764, "text": null }, { "code": " // Efficient C# program to find length of// the largest subsequence with GCD greater// than 1.using System;using System.Linq;public class GFG {// Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int []arr, int n){ int ans = 0; // Finding the Maximum value in arr[] int maxele = arr.Max(); // Iterate from 2 to maximum possible // divisor of all give values for (int i=2; i<=maxele; ++i) { int count = 0; for (int j=0; j<n; ++j) { // If we found divisor, // increment count if (arr[j]%i == 0) ++count; } ans = Math.Max(ans, count); } return ans;}// Driver program to test above public static void Main() { int []arr = {3, 6, 2, 5, 4}; int size = arr.Length; Console.Write(largestGCDSubsequence(arr, size)); }} //this code contributed by Rajput-Ji", "e": 4482, "s": 3529, "text": null }, { "code": "<?php// Simple PHP program to find length of// the largest subsequence with GCD greater// than 1. // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence($arr, $n){ $ans = 0; // Finding the Maximum value in arr[] $maxele = max($arr); // Iterate from 2 to maximum possible // divisor of all give values for ($i = 2; $i <= $maxele; ++$i) { $count = 0; for ($j = 0; $j < $n; ++$j) { // If we found divisor, // increment count if ($arr[$j] % $i == 0) ++$count; } $ans = max($ans, $count); } return $ans;} // Driver code$arr = array(3, 6, 2, 5, 4);$size = count($arr);echo largestGCDSubsequence($arr, $size); // This code is contributed by mits?>", "e": 5284, "s": 4482, "text": null }, { "code": "<script>// Efficient javascript program to find length of// the largest subsequence with GCD greater// than 1. // Returns length of the largest subsequence // with GCD more than 1. function largestGCDSubsequence(arr , n) { var ans = 0; // Finding the Maximum value in arr var maxele =Math.max(...arr); // Iterate from 2 to maximum possible // divisor of all give values for ( var i = 2; i <= maxele; ++i) { var count = 0; for (j = 0; j < n; ++j) { // If we found divisor, // increment count if (arr[j] % i == 0) ++count; } ans = Math.max(ans, count); } return ans; } // Driver program to test above var arr = [ 3, 6, 2, 5, 4 ]; var size = arr.length; document.write(largestGCDSubsequence(arr, size)); // This code is contributed by aashish1995</script>", "e": 6284, "s": 5284, "text": null }, { "code": null, "e": 6294, "s": 6284, "text": "Output: " }, { "code": null, "e": 6296, "s": 6294, "text": "3" }, { "code": null, "e": 6381, "s": 6296, "text": "Time Complexity: O(n * max(arr[i])) where n is size of array. Auxiliary Space: O(1) " }, { "code": null, "e": 6405, "s": 6381, "text": "Best Approach(Method 3)" }, { "code": null, "e": 6874, "s": 6405, "text": "An efficient approach is to use prime factorization method with the help of Sieve of Eratosthenes. First of all we will find the smallest prime divisor of all elements by pre-computed sieve. After that we will mark all the prime divisor of every element of arr[] by factorizing it with the help of pre-computed prime[] array. Now we have all the marked primes occurring in all the array elements. The last step is to find the maximum count of all such prime factors. " }, { "code": null, "e": 6878, "s": 6874, "text": "C++" }, { "code": null, "e": 6883, "s": 6878, "text": "Java" }, { "code": null, "e": 6891, "s": 6883, "text": "Python3" }, { "code": null, "e": 6894, "s": 6891, "text": "C#" }, { "code": null, "e": 6898, "s": 6894, "text": "PHP" }, { "code": null, "e": 6909, "s": 6898, "text": "Javascript" }, { "code": "// Efficient C++ program to find length of// the largest subsequence with GCD greater// than 1.#include<bits/stdc++.h> using namespace std; #define MAX 100001 // prime[] for storing smallest prime divisor of element// count[] for storing the number of times a particular// divisor occurs in a subsequenceint prime[MAX], countdiv[MAX]; // Simple sieve to find smallest prime factors of numbers// smaller than MAXvoid SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (!prime[i]) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (!prime[i]) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.int largestGCDSubsequence(int arr[], int n){ int ans = 0; for (int i=0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = max(ans, countdiv[div]); while (element % div==0) element /= div; } } return ans;} // Driver codeint main(){ // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); int arr[] = {10, 15, 7, 25, 9, 35}; int size = sizeof(arr) / sizeof(arr[0]); cout << largestGCDSubsequence(arr, size); return 0;}", "e": 8491, "s": 6909, "text": null }, { "code": "// Efficient Java program to find length of// the largest subsequence with GCD greater// than 1. class GFG{static int MAX = 100001; // prime[] for storing smallest prime divisor// of element count[] for storing the number// of times a particular divisor occurs// in a subsequencestatic int[] prime = new int[MAX + 1];static int[] countdiv = new int[MAX + 1]; // Simple sieve to find smallest prime// factors of numbers smaller than MAXstatic void SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int arr[], int n){ int ans = 0; for (int i = 0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.max(ans, countdiv[div]); while (element % div == 0) element /= div; } } return ans;} // Driver codepublic static void main (String[] args){ // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); int arr[] = {10, 15, 7, 25, 9, 35}; int size = arr.length; System.out.println(largestGCDSubsequence(arr, size));}} // This code is contributed by mits", "e": 10174, "s": 8491, "text": null }, { "code": "# Efficient Python3 program to find length# of the largest subsequence with GCD# greater than 1.import math as mt MAX = 100001 # prime[] for storing smallest# prime divisor of element# count[] for storing the number# of times a particular divisor# occurs in a subsequenceprime = [0 for i in range(MAX + 1)]countdiv = [0 for i in range(MAX + 1)] # Simple sieve to find smallest prime# factors of numbers smaller than MAXdef SieveOfEratosthenes(): for i in range(2, mt.ceil(mt.sqrt(MAX + 1))): if (prime[i] == 0): for j in range(i * 2, MAX + 1, i): prime[j] = i # Prime number will have same divisor for i in range(1, MAX): if (prime[i] == 0): prime[i] = i # Returns length of the largest# subsequence with GCD more than 1.def largestGCDSubsequence(arr, n): ans = 0 for i in range(n): element = arr[i] # Fetch total unique prime # divisor of element while (element > 1): div = prime[element] # Increment count[] of Every # unique divisor we get till now countdiv[div] += 1 # Find maximum frequency of divisor ans = max(ans, countdiv[div]) while (element % div == 0): element = element // div return ans # Driver code # Pre-compute smallest divisor# of all numbersSieveOfEratosthenes() arr= [10, 15, 7, 25, 9, 35]size = len(arr)print(largestGCDSubsequence(arr, size)) # This code is contributed# by Mohit kumar 29", "e": 11701, "s": 10174, "text": null }, { "code": "// Efficient C# program to find length of// the largest subsequence with GCD greater// than 1.using System; class GFG{ static int MAX=100001; // prime[] for storing smallest// prime divisor of element count[]// for storing the number of times// a particular divisor occurs in a subsequencestatic int[] prime = new int[MAX + 1];static int[] countdiv = new int[MAX + 1]; // Simple sieve to find smallest prime// factors of numbers smaller than MAXstatic void SieveOfEratosthenes(){ for (int i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (int i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.static int largestGCDSubsequence(int []arr, int n){ int ans = 0; for (int i = 0; i < n; ++i) { int element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { int div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.Max(ans, countdiv[div]); while (element % div==0) element /= div; } } return ans;} // Driver codepublic static void Main(){ // Pre-compute smallest // divisor of all numbers SieveOfEratosthenes(); int []arr = {10, 15, 7, 25, 9, 35}; int size = arr.Length; Console.WriteLine(largestGCDSubsequence(arr, size));}} // This code is contributed by mits", "e": 13388, "s": 11701, "text": null }, { "code": "<?php// Efficient PHP program to find length of// the largest subsequence with GCD greater// than 1. $MAX = 10001; // prime[] for storing smallest prime divisor of element// count[] for storing the number of times a particular// divisor occurs in a subsequence$prime = array_fill(0, $MAX, 0);$countdiv = array_fill(0, $MAX, 0); // Simple sieve to find smallest prime factors of numbers// smaller than MAXfunction SieveOfEratosthenes(){ global $MAX,$prime; for ($i = 2; $i * $i <= $MAX; ++$i) { if ($prime[$i] == 0) for ($j = $i * 2; $j <= $MAX; $j += $i) $prime[$j] = $i; } // Prime number will have same divisor for ($i = 1; $i < $MAX; ++$i) if ($prime[$i] == 0) $prime[$i] = $i;} // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence($arr, $n){ global $countdiv,$prime; $ans = 0; for ($i = 0; $i < $n; ++$i) { $element = $arr[$i]; // Fetch total unique prime divisor of element while ($element > 1) { $div = $prime[$element]; // Increment count[] of Every unique divisor // we get till now ++$countdiv[$div]; // Find maximum frequency of divisor $ans = max($ans, $countdiv[$div]); while ($element % $div == 0) $element = (int)($element/$div); } } return $ans;} // Driver code // Pre-compute smallest divisor of all numbers SieveOfEratosthenes(); $arr = array(10, 15, 7, 25, 9, 35); $size = count($arr); echo largestGCDSubsequence($arr, $size); // This code is contributed by mits?>", "e": 15058, "s": 13388, "text": null }, { "code": "<script>// Efficient Javascript program to find length of// the largest subsequence with GCD greater// than 1. let MAX = 100001;// prime[] for storing smallest prime divisor// of element count[] for storing the number// of times a particular divisor occurs// in a subsequencelet prime = new Array(MAX + 1);let countdiv = new Array(MAX + 1);for(let i=0;i<MAX+1;i++){ prime[i]=0; countdiv[i]=0;} // Simple sieve to find smallest prime// factors of numbers smaller than MAXfunction SieveOfEratosthenes(){ for (let i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (let j = i * 2; j <= MAX; j += i) prime[j] = i; } // Prime number will have same divisor for (let i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i;} // Returns length of the largest subsequence// with GCD more than 1.function largestGCDSubsequence(arr,n){ let ans = 0; for (let i = 0; i < n; ++i) { let element = arr[i]; // Fetch total unique prime divisor of element while (element > 1) { let div = prime[element]; // Increment count[] of Every unique divisor // we get till now ++countdiv[div]; // Find maximum frequency of divisor ans = Math.max(ans, countdiv[div]); while (element % div == 0) element /= div; } } return ans;} // Driver code// Pre-compute smallest divisor of all numbersSieveOfEratosthenes();let arr=[10, 15, 7, 25, 9, 35];let size = arr.length;document.write(largestGCDSubsequence(arr, size)); // This code is contributed by unknown2108</script>", "e": 16725, "s": 15058, "text": null }, { "code": null, "e": 16735, "s": 16725, "text": "Output: " }, { "code": null, "e": 16738, "s": 16735, "text": " 4" }, { "code": null, "e": 17244, "s": 16738, "text": "Time complexity: O( n*log(max(arr[i])) ) + MAX*log(log(MAX)) Auxiliary space: O(MAX)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 17258, "s": 17244, "text": "SHREYAS_SINGH" }, { "code": null, "e": 17268, "s": 17258, "text": "Rajput-Ji" }, { "code": null, "e": 17281, "s": 17268, "text": "Mithun Kumar" }, { "code": null, "e": 17296, "s": 17281, "text": "mohit kumar 29" }, { "code": null, "e": 17308, "s": 17296, "text": "aashish1995" }, { "code": null, "e": 17320, "s": 17308, "text": "unknown2108" }, { "code": null, "e": 17339, "s": 17320, "text": "surindertarika1234" }, { "code": null, "e": 17347, "s": 17339, "text": "GCD-LCM" }, { "code": null, "e": 17360, "s": 17347, "text": "prime-factor" }, { "code": null, "e": 17373, "s": 17360, "text": "Mathematical" }, { "code": null, "e": 17386, "s": 17373, "text": "Mathematical" }, { "code": null, "e": 17484, "s": 17386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17514, "s": 17484, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 17557, "s": 17514, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 17617, "s": 17557, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 17632, "s": 17617, "text": "C++ Data Types" }, { "code": null, "e": 17656, "s": 17632, "text": "Merge two sorted arrays" }, { "code": null, "e": 17675, "s": 17656, "text": "Coin Change | DP-7" }, { "code": null, "e": 17696, "s": 17675, "text": "Operators in C / C++" }, { "code": null, "e": 17710, "s": 17696, "text": "Prime Numbers" }, { "code": null, "e": 17752, "s": 17710, "text": "Program to find GCD or HCF of two numbers" } ]
Print all full nodes in a Binary Tree
08 Jul, 2022 Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty. Examples: Input : 10 / \ 8 2 / \ / 3 5 7 Output : 10 8 Input : 1 / \ 2 3 / \ 4 6 Output : 1 3 This is a simple problem. We do any of the tra­ver­sals (Inorder, Pre­order, Pos­torder, level order traversal) and keep printing nodes that have mode left and right children as non-NULL. Implementation: C++ Java Python3 C# Javascript // A C++ program to find the all full nodes in// a given binary tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; Node *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Traverses given tree in Inorder fashion and// prints all nodes that have both children as// non-empty.void findFullNode(Node *root){ if (root != NULL) { findFullNode(root->left); if (root->left != NULL && root->right != NULL) cout << root->data << " "; findFullNode(root->right); }} // Driver program to test above functionint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); findFullNode(root); return 0;} // Java program to find the all full nodes in// a given binary treepublic class FullNodes { // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty. public static void findFullNode(Node root) { if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) System.out.print(root.data+" "); findFullNode(root.right); } } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); findFullNode(root); }} /* A binary tree node */class Node{ int data; Node left, right; Node(int data) { left=right=null; this.data=data; }};//This code is contributed by Gaurav Tiwari # Python3 program to find the all# full nodes in a given binary tree # Binary Tree Node""" utility that allocates a newNodewith the given key """class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # Traverses given tree in Inorder# fashion and prints all nodes that# have both children as non-empty.def findFullNode(root) : if (root != None) : findFullNode(root.left) if (root.left != None and root.right != None) : print(root.data, end = " ") findFullNode(root.right) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(5) root.right.right = newNode(6) root.right.left.right = newNode(7) root.right.right.right = newNode(8) root.right.left.right.left = newNode(9) findFullNode(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find the all full nodes in// a given binary treeusing System; public class FullNodes{ // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty. static void findFullNode(Node root) { if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) Console.Write(root.data + " "); findFullNode(root.right); } } public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); findFullNode(root); }} /* A binary tree node */class Node{ public int data; public Node left, right; public Node(int data) { left = right = null; this.data = data; }}; // This code is contributed by 29AjayKumar <script> // JavaScript program to find the all full nodes in// a given binary tree /* A binary tree node */class Node{ constructor(data) { this.left=this.right=null; this.data=data; }} // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty.function findFullNode(root){ if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) document.write(root.data+" "); findFullNode(root.right); }} let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.left = new Node(5);root.right.right = new Node(6);root.right.left.right = new Node(7);root.right.right.right = new Node(8);root.right.left.right.left = new Node(9);findFullNode(root); // This code is contributed by rag2127 </script> 1 3 Time Complexity : O(n)Space complexity: O(n) for Recursive Stack Space in case of Skewed Tree This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. _Gaurav_Tiwari 29AjayKumar SHUBHAMSINGH10 rag2127 prasanna1995 hardikkoriintern Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Introduction to Tree Data Structure Inorder Tree Traversal without Recursion What is Data Structure: Types, Classifications and Applications Binary Tree | Set 3 (Types of Binary Tree) Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree | Set 2 (Properties) Diameter of a Binary Tree Decision Tree Construct Tree from given Inorder and Preorder traversals
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 184, "s": 52, "text": "Given a binary tree, print all nodes will are full nodes. Full Nodes are nodes which has both left and right children as non-empty." }, { "code": null, "e": 195, "s": 184, "text": "Examples: " }, { "code": null, "e": 374, "s": 195, "text": "Input : 10\n / \\\n 8 2\n / \\ /\n 3 5 7\nOutput : 10 8\n\nInput : 1\n / \\\n 2 3\n / \\\n 4 6 \nOutput : 1 3" }, { "code": null, "e": 562, "s": 374, "text": "This is a simple problem. We do any of the tra­ver­sals (Inorder, Pre­order, Pos­torder, level order traversal) and keep printing nodes that have mode left and right children as non-NULL." }, { "code": null, "e": 578, "s": 562, "text": "Implementation:" }, { "code": null, "e": 582, "s": 578, "text": "C++" }, { "code": null, "e": 587, "s": 582, "text": "Java" }, { "code": null, "e": 595, "s": 587, "text": "Python3" }, { "code": null, "e": 598, "s": 595, "text": "C#" }, { "code": null, "e": 609, "s": 598, "text": "Javascript" }, { "code": "// A C++ program to find the all full nodes in// a given binary tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; Node *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Traverses given tree in Inorder fashion and// prints all nodes that have both children as// non-empty.void findFullNode(Node *root){ if (root != NULL) { findFullNode(root->left); if (root->left != NULL && root->right != NULL) cout << root->data << \" \"; findFullNode(root->right); }} // Driver program to test above functionint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); findFullNode(root); return 0;}", "e": 1645, "s": 609, "text": null }, { "code": "// Java program to find the all full nodes in// a given binary treepublic class FullNodes { // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty. public static void findFullNode(Node root) { if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) System.out.print(root.data+\" \"); findFullNode(root.right); } } public static void main(String args[]) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); findFullNode(root); }} /* A binary tree node */class Node{ int data; Node left, right; Node(int data) { left=right=null; this.data=data; }};//This code is contributed by Gaurav Tiwari", "e": 2748, "s": 1645, "text": null }, { "code": "# Python3 program to find the all# full nodes in a given binary tree # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\"class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # Traverses given tree in Inorder# fashion and prints all nodes that# have both children as non-empty.def findFullNode(root) : if (root != None) : findFullNode(root.left) if (root.left != None and root.right != None) : print(root.data, end = \" \") findFullNode(root.right) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.right.left = newNode(5) root.right.right = newNode(6) root.right.left.right = newNode(7) root.right.right.right = newNode(8) root.right.left.right.left = newNode(9) findFullNode(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 3782, "s": 2748, "text": null }, { "code": "// C# program to find the all full nodes in// a given binary treeusing System; public class FullNodes{ // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty. static void findFullNode(Node root) { if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) Console.Write(root.data + \" \"); findFullNode(root.right); } } public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); root.right.left.right = new Node(7); root.right.right.right = new Node(8); root.right.left.right.left = new Node(9); findFullNode(root); }} /* A binary tree node */class Node{ public int data; public Node left, right; public Node(int data) { left = right = null; this.data = data; }}; // This code is contributed by 29AjayKumar", "e": 4918, "s": 3782, "text": null }, { "code": "<script> // JavaScript program to find the all full nodes in// a given binary tree /* A binary tree node */class Node{ constructor(data) { this.left=this.right=null; this.data=data; }} // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty.function findFullNode(root){ if (root != null) { findFullNode(root.left); if (root.left != null && root.right != null) document.write(root.data+\" \"); findFullNode(root.right); }} let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.left = new Node(5);root.right.right = new Node(6);root.right.left.right = new Node(7);root.right.right.right = new Node(8);root.right.left.right.left = new Node(9);findFullNode(root); // This code is contributed by rag2127 </script>", "e": 5829, "s": 4918, "text": null }, { "code": null, "e": 5834, "s": 5829, "text": "1 3 " }, { "code": null, "e": 5928, "s": 5834, "text": "Time Complexity : O(n)Space complexity: O(n) for Recursive Stack Space in case of Skewed Tree" }, { "code": null, "e": 6225, "s": 5928, "text": "This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 6240, "s": 6225, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 6252, "s": 6240, "text": "29AjayKumar" }, { "code": null, "e": 6267, "s": 6252, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 6275, "s": 6267, "text": "rag2127" }, { "code": null, "e": 6288, "s": 6275, "text": "prasanna1995" }, { "code": null, "e": 6305, "s": 6288, "text": "hardikkoriintern" }, { "code": null, "e": 6310, "s": 6305, "text": "Tree" }, { "code": null, "e": 6315, "s": 6310, "text": "Tree" }, { "code": null, "e": 6413, "s": 6315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6445, "s": 6413, "text": "Introduction to Data Structures" }, { "code": null, "e": 6481, "s": 6445, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 6522, "s": 6481, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 6586, "s": 6522, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6629, "s": 6586, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 6677, "s": 6629, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 6710, "s": 6677, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 6736, "s": 6710, "text": "Diameter of a Binary Tree" }, { "code": null, "e": 6750, "s": 6736, "text": "Decision Tree" } ]
LeafletJS – Interacting with Maps using JavaScript
11 Sep, 2021 Maps have become an integral part of our everyday lives. From driving to a location to finding some restaurants or stores nearby or while planning travel, almost every type of app uses maps. Using maps helps us to add location-based services in our application. One way to add maps in a web application is using Leaflet JS. Leaflet JS is an open-source JavaScript library for adding simple and interactive web maps. It can add the map data to the map layers and has features like panning, zooming, etc that most of the applications require. Though leaflet provides some core features required in any map application, an easy way to increase the functionality of maps is using third-party plugins. As leaflet is an open-source library i.e. its source code is available on GitHub, there have been a lot of contributions and there are a lot of plugins available. You can get the list of the plugins here. So, Leaflet is a map API and it helps us to interact with the map data but it is not providing any data. Nor does it provide the map itself as it is not a mapping service. So how do we get the map? The answer is that Leaflet depends on third parties to provide the basemap i.e Leaflet is built in such a way that it can be used with multiple base map layers. Generally, Leaflet is used with OpenStreetMaps but we can even use other map providers like Mapbox, Ersi, Bing Map Layers, etc. You can check different basemap providers here. So, let us understand how leaflet can be used to interact with maps step-by-step: 1. The Directory Structure This is the directory structure that will be followed during this example. You can have a different directory structure as well but make sure it reflects in your code as well. 2. HTML Boilerplate and adding Leaflet References HTML <!DOCTYPE html><html> <head> <title> Playing Around With Leaflet JS </title> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- Leaflet CSS --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" /> <!-- Leaflet JS --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script></head> <body></body> </html> To add map to our web page, simple web technologies like HTML, CSS and JavaScript are required. To use Leaflet in your code, you need to add the Leaflet CSS and Leaflet JS. You can either download them or use them by including their CDNs (see above code sample). 3. Create a Map container and create a Map object <div id="mymap"> </div> We first define a container element where we want to load the map and provide it an id “mymap”. let map = L.map('mymap').setView([19.5937, 78.9629], 5); Now, we create a map object using which we’ll create a map and manipulate it. We instantiate the map object with the id of the container element created above i.e. “mymap”. The setview method is used to set the center of the map and the zoom level. 4. Add Map Tiles using TileLayer Javascript L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors', maxZoom: 20, minZoom: 2, tileSize: 512, zoomOffset: -1}).addTo(map); To load and display our map, we use TileLayer class to create a layer and specify the URL of the map tiles. The map is divided into multiple tiles and we are using OpenStreetMap for displaying the map tiles. You can get the list of tile providers here. We do specify some additional parameters like min zoom level, max zoom level, tile size. As we are using the map tiles of OpenStreetMap, we need to provide proper attribution (or credits) to OpenStreetMap (or whichever map tile provider you are using) for using their map tiles. To add this layer on our map, we use the addTo() method. 5. Making our dataset for including markers https://github.com/OptimalLearner/Leaflet-JS-Example-Code/blob/master/assets/location-data.json Now, we need to add some markers to the map which point to some location. We have saved the data in a different file named “location-data.json”. This file contains the marker details like latitude and longitude coordinates, etc. You can access the data from the above link provided and save it along with your code. If you want to keep the data in your JS file itself, you can create a variable and assign it to the above data. 6. Creating marker, binding popups and event handling Javascript let marker = L.marker([latitude, longitude]).bindPopup(`<h3> ${title} </h3> <p> ${description} </p>`).on('click', () => { map.flyTo([latitude, longitude], zoomLevel);}).addTo(map); A marker is used to identify and highlight a location on a map. To add a marker in Leaflet, we initialize the marker class and pass the coordinates of the location we need the marker to point to. You may add as many markers as you want. Now to identify which location is marked by the marker, we can add a popup to the marker which will tell us the location information. We add a popup using bindPopup method to display the location name and a little description of the location. Leaflet also has the ability to react to events generated by us. We can add an event listener using “on” function for a particular event (in our case “click”) which listens to a function containing some set of operations. At the end, we add this marker to our map. 7. Customizing the marker icon Javascript let iconOption = { iconUrl: './assets/location-marker.svg', iconSize: [30, 30]};let ourCustomIcon = L.icon(iconOption); let marker = L.marker([latitude, longitude], {icon: ourCustomIcon}).bindPopup(`<h3> ${title} </h3> <p> ${description} </p>`).on('click', () => { map.flyTo([latitude, longitude], zoomLevel);}).addTo(map); Not everyone would like to use the same default marker icon. So, here comes the feature of custom marker icons to the rescue. You need to use the Icon class and pass the URL of the icon which you want to use as the marker and add the size of icon [width, height] in pixels(px). Now we need to add the icon to the marker. In the Marker class after adding the coordinates, we can pass the custom marker icon for rendering the marker. 8. What’s best for you: flyTo or setView? Javascript map.setView([latitude, longitude], zoomLevel);map.flyTo([latitude, longitude], zoomLevel); Both are doing the same work of changing the location to specific coordinates but flyTo() method provides some animation that will fly to the location specified using coordinates. If you need some animation then you can use flyTo() method else setView() also works to change the location. There is another method called panTo([latitude, longitude]) which is just calling setView() keeping the zoom level to current map’s zoom level. setView() method allows you to even set the zoom level but that’s not the case with panTo(). 9. Complete Code and Result HTML CSS Javascript <!DOCTYPE html><html> <head> <title> Playing Around With LeafletJS </title> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- Leaflet CSS --> <link rel="stylesheet" href= "https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" /> <!-- Leaflet JS --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script> <!-- Custom Styles --> <link rel="stylesheet" type="text/css" href="css/styles.css"></head> <body> <h2 class="heading"> Some Indian Monuments </h2> <div id="mymap"> </div> <div class="button-group flex-style"> <div class="component1"> <button class="map-zoom-out-btn">Map Zoom Out</button> </div> <div class="component2"> <select class="select-dropdown" name="dropdown"> <option> Select any monument </option> </select> <button class="search-btn"> Search </button> </div> </div> <footer class="footer flex-style"> Made Using Leaflet JS | <a href="https://github.com/OptimalLearner/Leaflet-JS-Example-Code" target="_blank"> Source Code</a> <a href="" target="_blank"> <img src="assets/github-icon.png" /> </a> </footer> <script type="text/javascript" src="js/script.js"></script></body> </html> body { margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif;}.heading { font-family: monospace; font-size: 40px; text-align: center; margin: 2.5vh 0;}#mymap { width: 90vw; height: 70vh; margin: 0 5vw 2vh; border: 3px solid #888;}.button-group { justify-content: space-evenly !important;}.map-zoom-out-btn, .search-btn { background-color: #0072B5; color: #FFF; padding: 10px 35px; border: none; font-size: 17px; border-radius: 5px; cursor: pointer;}.select-dropdown { display: inline-block; margin: 0 15px 0 0; padding: 10px 35px; border: 1px solid #AAA; font: inherit; -webkit-appearance: none; -moz-appearance: none; -ms-appearance: none; appearance: none; background: #FFF; background-repeat: no-repeat; background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%); background-position: right 15px top 1em, right 10px top 1em; background-size: 5px 5px, 5px 5px;}.footer { position: fixed; left: 0; bottom: 0; width: 100%; display: flex; justify-content: center; align-items: center; text-align: center; font-size: 17px; padding-bottom: 8px;}.footer a { padding: 0 5px 0 5px; color: #000; cursor: pointer;}.flex-style { display: flex; justify-content: center; align-items: center;} let map = L.map("mymap").setView([19.5937, 78.9629], 5);let ourData = []; L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: "© OpenStreetMap contributors", maxZoom: 20, minZoom: 2, tileSize: 512, zoomOffset: -1,}).addTo(map); let iconOption = { iconUrl: "./assets/location-marker.svg", iconSize: [30, 30],};let ourCustomIcon = L.icon(iconOption); fetch("./assets/location-data.json") .then((response) => response.json()) .then((data) => { ourData = data; for (let i = 0; i < data.length; i++) { let option = document.createElement("option"); option.value = i + 1; option.text = data[i].title; document.querySelector(".select-dropdown").appendChild(option); let marker = L.marker([data[i].latitude, data[i].longitude], { icon: ourCustomIcon, }) .bindPopup( `<h3> ${data[i].title} </h3> <p> ${data[i].description} </p>` ) .on("click", () => { map.flyTo([data[i].latitude, data[i].longitude], data[i].zoomLevel); }) .addTo(map); } }) .catch((error) => alert(error)); document.querySelector(".map-zoom-out-btn").addEventListener("click", () => { map.flyTo([19.5937, 78.9629], 5);}); document.querySelector(".search-btn").addEventListener("click", () => { let select = document.querySelector(".select-dropdown"); let value = select.options[select.selectedIndex].value; map.flyTo( [ourData[value - 1].latitude, ourData[value - 1].longitude], ourData[value - 1].zoomLevel );}); Using the HTML Boilerplate, we have added a map container, a button for zooming out the map, and a dropdown that will contain the locations marked on the map. We have applied some styles to our components using external CSS by adding references to the external style sheet. In the script file, we create a map object and add map tiles to the object. Then we create our custom icon object and add the size and the URL of the icon to the icon options which we will add to the marker while creating the marker for each location. Using Fetch API, we request our data by providing the URL of data. We get the response object which is then converted to json. Using this json data which contains the information about locations, we dynamically add the options for the locations to the dropdown list using DOM and we create markers for every location along with popups and onclick event listener. In case of any errors, the error message is alerted to the user. We added an onclick event listener on the Zoom Out button which flies us to the initial coordinates and zoom level. We also added an event listener on the Search button which gets the value of the dropdown list and using the value we select the location and zoom the map to that selected location. The result of the above example can be seen below: To run your webpage locally, you need to run the webpage through local server. You can either use WAMP or XAMPP or simpleNode.js http-server. If you get stuck somewhere in between, you can refer this GitHub Repository. Blogathon-2021 JavaScript-Questions Blogathon JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2021" }, { "code": null, "e": 290, "s": 28, "text": "Maps have become an integral part of our everyday lives. From driving to a location to finding some restaurants or stores nearby or while planning travel, almost every type of app uses maps. Using maps helps us to add location-based services in our application." }, { "code": null, "e": 930, "s": 290, "text": "One way to add maps in a web application is using Leaflet JS. Leaflet JS is an open-source JavaScript library for adding simple and interactive web maps. It can add the map data to the map layers and has features like panning, zooming, etc that most of the applications require. Though leaflet provides some core features required in any map application, an easy way to increase the functionality of maps is using third-party plugins. As leaflet is an open-source library i.e. its source code is available on GitHub, there have been a lot of contributions and there are a lot of plugins available. You can get the list of the plugins here." }, { "code": null, "e": 1465, "s": 930, "text": "So, Leaflet is a map API and it helps us to interact with the map data but it is not providing any data. Nor does it provide the map itself as it is not a mapping service. So how do we get the map? The answer is that Leaflet depends on third parties to provide the basemap i.e Leaflet is built in such a way that it can be used with multiple base map layers. Generally, Leaflet is used with OpenStreetMaps but we can even use other map providers like Mapbox, Ersi, Bing Map Layers, etc. You can check different basemap providers here." }, { "code": null, "e": 1547, "s": 1465, "text": "So, let us understand how leaflet can be used to interact with maps step-by-step:" }, { "code": null, "e": 1576, "s": 1549, "text": "1. The Directory Structure" }, { "code": null, "e": 1752, "s": 1576, "text": "This is the directory structure that will be followed during this example. You can have a different directory structure as well but make sure it reflects in your code as well." }, { "code": null, "e": 1802, "s": 1752, "text": "2. HTML Boilerplate and adding Leaflet References" }, { "code": null, "e": 1807, "s": 1802, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> Playing Around With Leaflet JS </title> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- Leaflet CSS --> <link rel=\"stylesheet\" href=\"https://unpkg.com/leaflet@1.7.1/dist/leaflet.css\" integrity=\"sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==\" crossorigin=\"\" /> <!-- Leaflet JS --> <script src=\"https://unpkg.com/leaflet@1.7.1/dist/leaflet.js\" integrity=\"sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==\" crossorigin=\"\"></script></head> <body></body> </html>", "e": 2512, "s": 1807, "text": null }, { "code": null, "e": 2775, "s": 2512, "text": "To add map to our web page, simple web technologies like HTML, CSS and JavaScript are required. To use Leaflet in your code, you need to add the Leaflet CSS and Leaflet JS. You can either download them or use them by including their CDNs (see above code sample)." }, { "code": null, "e": 2825, "s": 2775, "text": "3. Create a Map container and create a Map object" }, { "code": null, "e": 2849, "s": 2825, "text": "<div id=\"mymap\"> </div>" }, { "code": null, "e": 2945, "s": 2849, "text": "We first define a container element where we want to load the map and provide it an id “mymap”." }, { "code": null, "e": 3002, "s": 2945, "text": "let map = L.map('mymap').setView([19.5937, 78.9629], 5);" }, { "code": null, "e": 3251, "s": 3002, "text": "Now, we create a map object using which we’ll create a map and manipulate it. We instantiate the map object with the id of the container element created above i.e. “mymap”. The setview method is used to set the center of the map and the zoom level." }, { "code": null, "e": 3284, "s": 3251, "text": "4. Add Map Tiles using TileLayer" }, { "code": null, "e": 3295, "s": 3284, "text": "Javascript" }, { "code": "L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors', maxZoom: 20, minZoom: 2, tileSize: 512, zoomOffset: -1}).addTo(map);", "e": 3492, "s": 3295, "text": null }, { "code": null, "e": 4082, "s": 3492, "text": "To load and display our map, we use TileLayer class to create a layer and specify the URL of the map tiles. The map is divided into multiple tiles and we are using OpenStreetMap for displaying the map tiles. You can get the list of tile providers here. We do specify some additional parameters like min zoom level, max zoom level, tile size. As we are using the map tiles of OpenStreetMap, we need to provide proper attribution (or credits) to OpenStreetMap (or whichever map tile provider you are using) for using their map tiles. To add this layer on our map, we use the addTo() method. " }, { "code": null, "e": 4126, "s": 4082, "text": "5. Making our dataset for including markers" }, { "code": null, "e": 4222, "s": 4126, "text": "https://github.com/OptimalLearner/Leaflet-JS-Example-Code/blob/master/assets/location-data.json" }, { "code": null, "e": 4651, "s": 4222, "text": "Now, we need to add some markers to the map which point to some location. We have saved the data in a different file named “location-data.json”. This file contains the marker details like latitude and longitude coordinates, etc. You can access the data from the above link provided and save it along with your code. If you want to keep the data in your JS file itself, you can create a variable and assign it to the above data." }, { "code": null, "e": 4705, "s": 4651, "text": "6. Creating marker, binding popups and event handling" }, { "code": null, "e": 4716, "s": 4705, "text": "Javascript" }, { "code": "let marker = L.marker([latitude, longitude]).bindPopup(`<h3> ${title} </h3> <p> ${description} </p>`).on('click', () => { map.flyTo([latitude, longitude], zoomLevel);}).addTo(map);", "e": 4900, "s": 4716, "text": null }, { "code": null, "e": 5380, "s": 4900, "text": "A marker is used to identify and highlight a location on a map. To add a marker in Leaflet, we initialize the marker class and pass the coordinates of the location we need the marker to point to. You may add as many markers as you want. Now to identify which location is marked by the marker, we can add a popup to the marker which will tell us the location information. We add a popup using bindPopup method to display the location name and a little description of the location." }, { "code": null, "e": 5645, "s": 5380, "text": "Leaflet also has the ability to react to events generated by us. We can add an event listener using “on” function for a particular event (in our case “click”) which listens to a function containing some set of operations. At the end, we add this marker to our map." }, { "code": null, "e": 5676, "s": 5645, "text": "7. Customizing the marker icon" }, { "code": null, "e": 5687, "s": 5676, "text": "Javascript" }, { "code": "let iconOption = { iconUrl: './assets/location-marker.svg', iconSize: [30, 30]};let ourCustomIcon = L.icon(iconOption); let marker = L.marker([latitude, longitude], {icon: ourCustomIcon}).bindPopup(`<h3> ${title} </h3> <p> ${description} </p>`).on('click', () => { map.flyTo([latitude, longitude], zoomLevel);}).addTo(map);", "e": 6023, "s": 5687, "text": null }, { "code": null, "e": 6455, "s": 6023, "text": "Not everyone would like to use the same default marker icon. So, here comes the feature of custom marker icons to the rescue. You need to use the Icon class and pass the URL of the icon which you want to use as the marker and add the size of icon [width, height] in pixels(px). Now we need to add the icon to the marker. In the Marker class after adding the coordinates, we can pass the custom marker icon for rendering the marker." }, { "code": null, "e": 6497, "s": 6455, "text": "8. What’s best for you: flyTo or setView?" }, { "code": null, "e": 6508, "s": 6497, "text": "Javascript" }, { "code": "map.setView([latitude, longitude], zoomLevel);map.flyTo([latitude, longitude], zoomLevel);", "e": 6599, "s": 6508, "text": null }, { "code": null, "e": 6888, "s": 6599, "text": "Both are doing the same work of changing the location to specific coordinates but flyTo() method provides some animation that will fly to the location specified using coordinates. If you need some animation then you can use flyTo() method else setView() also works to change the location." }, { "code": null, "e": 7125, "s": 6888, "text": "There is another method called panTo([latitude, longitude]) which is just calling setView() keeping the zoom level to current map’s zoom level. setView() method allows you to even set the zoom level but that’s not the case with panTo()." }, { "code": null, "e": 7153, "s": 7125, "text": "9. Complete Code and Result" }, { "code": null, "e": 7158, "s": 7153, "text": "HTML" }, { "code": null, "e": 7162, "s": 7158, "text": "CSS" }, { "code": null, "e": 7173, "s": 7162, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <title> Playing Around With LeafletJS </title> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- Leaflet CSS --> <link rel=\"stylesheet\" href= \"https://unpkg.com/leaflet@1.7.1/dist/leaflet.css\" integrity=\"sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==\" crossorigin=\"\" /> <!-- Leaflet JS --> <script src=\"https://unpkg.com/leaflet@1.7.1/dist/leaflet.js\" integrity=\"sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==\" crossorigin=\"\"></script> <!-- Custom Styles --> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/styles.css\"></head> <body> <h2 class=\"heading\"> Some Indian Monuments </h2> <div id=\"mymap\"> </div> <div class=\"button-group flex-style\"> <div class=\"component1\"> <button class=\"map-zoom-out-btn\">Map Zoom Out</button> </div> <div class=\"component2\"> <select class=\"select-dropdown\" name=\"dropdown\"> <option> Select any monument </option> </select> <button class=\"search-btn\"> Search </button> </div> </div> <footer class=\"footer flex-style\"> Made Using Leaflet JS | <a href=\"https://github.com/OptimalLearner/Leaflet-JS-Example-Code\" target=\"_blank\"> Source Code</a> <a href=\"\" target=\"_blank\"> <img src=\"assets/github-icon.png\" /> </a> </footer> <script type=\"text/javascript\" src=\"js/script.js\"></script></body> </html>", "e": 8824, "s": 7173, "text": null }, { "code": "body { margin: 0; padding: 0; box-sizing: border-box; font-family: sans-serif;}.heading { font-family: monospace; font-size: 40px; text-align: center; margin: 2.5vh 0;}#mymap { width: 90vw; height: 70vh; margin: 0 5vw 2vh; border: 3px solid #888;}.button-group { justify-content: space-evenly !important;}.map-zoom-out-btn, .search-btn { background-color: #0072B5; color: #FFF; padding: 10px 35px; border: none; font-size: 17px; border-radius: 5px; cursor: pointer;}.select-dropdown { display: inline-block; margin: 0 15px 0 0; padding: 10px 35px; border: 1px solid #AAA; font: inherit; -webkit-appearance: none; -moz-appearance: none; -ms-appearance: none; appearance: none; background: #FFF; background-repeat: no-repeat; background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%); background-position: right 15px top 1em, right 10px top 1em; background-size: 5px 5px, 5px 5px;}.footer { position: fixed; left: 0; bottom: 0; width: 100%; display: flex; justify-content: center; align-items: center; text-align: center; font-size: 17px; padding-bottom: 8px;}.footer a { padding: 0 5px 0 5px; color: #000; cursor: pointer;}.flex-style { display: flex; justify-content: center; align-items: center;}", "e": 10266, "s": 8824, "text": null }, { "code": "let map = L.map(\"mymap\").setView([19.5937, 78.9629], 5);let ourData = []; L.tileLayer(\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\", { attribution: \"© OpenStreetMap contributors\", maxZoom: 20, minZoom: 2, tileSize: 512, zoomOffset: -1,}).addTo(map); let iconOption = { iconUrl: \"./assets/location-marker.svg\", iconSize: [30, 30],};let ourCustomIcon = L.icon(iconOption); fetch(\"./assets/location-data.json\") .then((response) => response.json()) .then((data) => { ourData = data; for (let i = 0; i < data.length; i++) { let option = document.createElement(\"option\"); option.value = i + 1; option.text = data[i].title; document.querySelector(\".select-dropdown\").appendChild(option); let marker = L.marker([data[i].latitude, data[i].longitude], { icon: ourCustomIcon, }) .bindPopup( `<h3> ${data[i].title} </h3> <p> ${data[i].description} </p>` ) .on(\"click\", () => { map.flyTo([data[i].latitude, data[i].longitude], data[i].zoomLevel); }) .addTo(map); } }) .catch((error) => alert(error)); document.querySelector(\".map-zoom-out-btn\").addEventListener(\"click\", () => { map.flyTo([19.5937, 78.9629], 5);}); document.querySelector(\".search-btn\").addEventListener(\"click\", () => { let select = document.querySelector(\".select-dropdown\"); let value = select.options[select.selectedIndex].value; map.flyTo( [ourData[value - 1].latitude, ourData[value - 1].longitude], ourData[value - 1].zoomLevel );});", "e": 11796, "s": 10266, "text": null }, { "code": null, "e": 12322, "s": 11796, "text": "Using the HTML Boilerplate, we have added a map container, a button for zooming out the map, and a dropdown that will contain the locations marked on the map. We have applied some styles to our components using external CSS by adding references to the external style sheet. In the script file, we create a map object and add map tiles to the object. Then we create our custom icon object and add the size and the URL of the icon to the icon options which we will add to the marker while creating the marker for each location." }, { "code": null, "e": 12750, "s": 12322, "text": "Using Fetch API, we request our data by providing the URL of data. We get the response object which is then converted to json. Using this json data which contains the information about locations, we dynamically add the options for the locations to the dropdown list using DOM and we create markers for every location along with popups and onclick event listener. In case of any errors, the error message is alerted to the user." }, { "code": null, "e": 13048, "s": 12750, "text": "We added an onclick event listener on the Zoom Out button which flies us to the initial coordinates and zoom level. We also added an event listener on the Search button which gets the value of the dropdown list and using the value we select the location and zoom the map to that selected location." }, { "code": null, "e": 13099, "s": 13048, "text": "The result of the above example can be seen below:" }, { "code": null, "e": 13318, "s": 13099, "text": "To run your webpage locally, you need to run the webpage through local server. You can either use WAMP or XAMPP or simpleNode.js http-server. If you get stuck somewhere in between, you can refer this GitHub Repository." }, { "code": null, "e": 13333, "s": 13318, "text": "Blogathon-2021" }, { "code": null, "e": 13354, "s": 13333, "text": "JavaScript-Questions" }, { "code": null, "e": 13364, "s": 13354, "text": "Blogathon" }, { "code": null, "e": 13375, "s": 13364, "text": "JavaScript" }, { "code": null, "e": 13392, "s": 13375, "text": "Web Technologies" } ]
File getCanonicalFile() method in Java with Examples
30 Jan, 2019 The getCanonicalFile() method is a part of File class. This function returns the Canonical File of the given file object.If the File path of the file object is Canonical then it simply returns the File of the current file object.The Canonical File is always absolute and unique, the function removes the ‘.’ ‘..’ from the path of the File, if present. For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using an IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete). The function getCanonicalFile() will return a file whose path will be an absolute and unique path from the root directories. The canonical form of an existing file may be different from the canonical form of a same non-existing file and the canonical form of an existing file may be different from the canonical form of the same file when it is deleted.Function Signature: public File getCanonicalFile() Function Syntax: file.getCanonicalFile() Parameters: This function does not accept any parameters. Return value: This function returns File object, the Canonical File of the given File object. Exception This method throws following exceptions Security Exception: if the required property value cannot be accessed. I/O Exception: if I/O exception occurs. Below program will illustrate the use of getCanonicalFile() method: Example 1: Here “program.txt” is a file present in the present working directory // Java program to demonstrate the// use of getCanonicalFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("program.txt"); // Get the Canonical file // of the given file f File canonical = f.getCanonicalFile(); // Display the file path of the file object // and also the file path of Canonical file System.out.println("Original file path: " + f.getPath()); System.out.println("Canonical file path: " + canonical.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output: Original file path: program.txt Canonical file path: C:\Users\pc\eclipse-workspace1\arnab\program.txt Example 2: We are given a File object we have to create the canonical file from that file object. // Java program to demonstrate the// use of getCanonicalFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("c:\\users\\..\\program"); // Get the Canonical file // of the given file f File canonical = f.getCanonicalFile(); // Display the file path of the file object // and also the file path of Canonical file System.out.println("Original file path: " + f.getPath()); System.out.println("Canonical file path: " + canonical.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output: Original file path: c:\users\..\program Canonical file path: C:\program The programs might not run in an online IDE. please use an offline IDE and set the path of the file Java-File Class Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2019" }, { "code": null, "e": 380, "s": 28, "text": "The getCanonicalFile() method is a part of File class. This function returns the Canonical File of the given file object.If the File path of the file object is Canonical then it simply returns the File of the current file object.The Canonical File is always absolute and unique, the function removes the ‘.’ ‘..’ from the path of the File, if present." }, { "code": null, "e": 1112, "s": 380, "text": "For Example: if we create a file object using the path as “program.txt”, it points to the file present in the same directory where the executable program is kept (if you are using an IDE it will point to the file where you have saved the program ). Here the path of the file mentioned above is “program.txt” but this path is not absolute (i.e. not complete). The function getCanonicalFile() will return a file whose path will be an absolute and unique path from the root directories. The canonical form of an existing file may be different from the canonical form of a same non-existing file and the canonical form of an existing file may be different from the canonical form of the same file when it is deleted.Function Signature:" }, { "code": null, "e": 1143, "s": 1112, "text": "public File getCanonicalFile()" }, { "code": null, "e": 1160, "s": 1143, "text": "Function Syntax:" }, { "code": null, "e": 1184, "s": 1160, "text": "file.getCanonicalFile()" }, { "code": null, "e": 1242, "s": 1184, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 1336, "s": 1242, "text": "Return value: This function returns File object, the Canonical File of the given File object." }, { "code": null, "e": 1386, "s": 1336, "text": "Exception This method throws following exceptions" }, { "code": null, "e": 1457, "s": 1386, "text": "Security Exception: if the required property value cannot be accessed." }, { "code": null, "e": 1497, "s": 1457, "text": "I/O Exception: if I/O exception occurs." }, { "code": null, "e": 1565, "s": 1497, "text": "Below program will illustrate the use of getCanonicalFile() method:" }, { "code": null, "e": 1646, "s": 1565, "text": "Example 1: Here “program.txt” is a file present in the present working directory" }, { "code": "// Java program to demonstrate the// use of getCanonicalFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"program.txt\"); // Get the Canonical file // of the given file f File canonical = f.getCanonicalFile(); // Display the file path of the file object // and also the file path of Canonical file System.out.println(\"Original file path: \" + f.getPath()); System.out.println(\"Canonical file path: \" + canonical.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 2495, "s": 1646, "text": null }, { "code": null, "e": 2503, "s": 2495, "text": "Output:" }, { "code": null, "e": 2606, "s": 2503, "text": "Original file path: program.txt\nCanonical file path: C:\\Users\\pc\\eclipse-workspace1\\arnab\\program.txt\n" }, { "code": null, "e": 2704, "s": 2606, "text": "Example 2: We are given a File object we have to create the canonical file from that file object." }, { "code": "// Java program to demonstrate the// use of getCanonicalFile() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"c:\\\\users\\\\..\\\\program\"); // Get the Canonical file // of the given file f File canonical = f.getCanonicalFile(); // Display the file path of the file object // and also the file path of Canonical file System.out.println(\"Original file path: \" + f.getPath()); System.out.println(\"Canonical file path: \" + canonical.getPath()); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 3579, "s": 2704, "text": null }, { "code": null, "e": 3587, "s": 3579, "text": "Output:" }, { "code": null, "e": 3660, "s": 3587, "text": "Original file path: c:\\users\\..\\program\nCanonical file path: C:\\program\n" }, { "code": null, "e": 3760, "s": 3660, "text": "The programs might not run in an online IDE. please use an offline IDE and set the path of the file" }, { "code": null, "e": 3776, "s": 3760, "text": "Java-File Class" }, { "code": null, "e": 3791, "s": 3776, "text": "Java-Functions" }, { "code": null, "e": 3807, "s": 3791, "text": "Java-IO package" }, { "code": null, "e": 3812, "s": 3807, "text": "Java" }, { "code": null, "e": 3817, "s": 3812, "text": "Java" }, { "code": null, "e": 3915, "s": 3817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3934, "s": 3915, "text": "Interfaces in Java" }, { "code": null, "e": 3952, "s": 3934, "text": "ArrayList in Java" }, { "code": null, "e": 3967, "s": 3952, "text": "Stream In Java" }, { "code": null, "e": 3987, "s": 3967, "text": "Collections in Java" }, { "code": null, "e": 4011, "s": 3987, "text": "Singleton Class in Java" }, { "code": null, "e": 4043, "s": 4011, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4055, "s": 4043, "text": "Set in Java" }, { "code": null, "e": 4075, "s": 4055, "text": "Stack Class in Java" }, { "code": null, "e": 4096, "s": 4075, "text": "Introduction to Java" } ]
Reshaping array dimensions in Julia | Array reshape() Method
23 Mar, 2020 The reshape() is an inbuilt function in julia which is used to return an array with the same data as the specified array, but with different specified dimension sizes. Syntax:reshape(A, dims) Parameters: A: Specified array. dims: Specified dimension. Returns: It returns an array with the same data as the specified array, but with different specified dimension sizes. Example 1: # Julia program to illustrate # the use of Array reshape() method # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = [1, 2, 3, 4];println(reshape(A, (2, 2))) # Getting an array with the same data# as the specified 2D array, but with# (4 * 4) dimension sizes.B = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];println(reshape(B, (4, 4))) # Getting an array with the same data# as the specified 2D array, but with# (2 * 8) dimension sizes.C = [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16];println(reshape(C, 2, :)) Output: Example 2: # Julia program to illustrate # the use of Array reshape() method # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = ["a", "b", "c", "d"];println(reshape(A, (2, 2))) # Getting an array with the same data# as the specified 2D array, but with# (2 * 2) dimension sizes.B = ["a" "b"; "c" "d"];println(reshape(B, (2, 2))) # Getting an array with the same data# as the specified 3D array, but with# (2 * 2*3) dimension sizes.C = cat(["a" "b"; "c" "d"], ["e" "f"; "g" "h"], ["i" "j"; "k" "l"], dims = 3);println(reshape(C, (2, 2, 3))) Output: Julia Array-functions Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2020" }, { "code": null, "e": 196, "s": 28, "text": "The reshape() is an inbuilt function in julia which is used to return an array with the same data as the specified array, but with different specified dimension sizes." }, { "code": null, "e": 220, "s": 196, "text": "Syntax:reshape(A, dims)" }, { "code": null, "e": 232, "s": 220, "text": "Parameters:" }, { "code": null, "e": 252, "s": 232, "text": "A: Specified array." }, { "code": null, "e": 279, "s": 252, "text": "dims: Specified dimension." }, { "code": null, "e": 397, "s": 279, "text": "Returns: It returns an array with the same data as the specified array, but with different specified dimension sizes." }, { "code": null, "e": 408, "s": 397, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of Array reshape() method # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = [1, 2, 3, 4];println(reshape(A, (2, 2))) # Getting an array with the same data# as the specified 2D array, but with# (4 * 4) dimension sizes.B = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];println(reshape(B, (4, 4))) # Getting an array with the same data# as the specified 2D array, but with# (2 * 8) dimension sizes.C = [1 5 9 13; 2 6 10 14; 3 7 11 15; 4 8 12 16];println(reshape(C, 2, :))", "e": 997, "s": 408, "text": null }, { "code": null, "e": 1005, "s": 997, "text": "Output:" }, { "code": null, "e": 1016, "s": 1005, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of Array reshape() method # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = [\"a\", \"b\", \"c\", \"d\"];println(reshape(A, (2, 2))) # Getting an array with the same data# as the specified 2D array, but with# (2 * 2) dimension sizes.B = [\"a\" \"b\"; \"c\" \"d\"];println(reshape(B, (2, 2))) # Getting an array with the same data# as the specified 3D array, but with# (2 * 2*3) dimension sizes.C = cat([\"a\" \"b\"; \"c\" \"d\"], [\"e\" \"f\"; \"g\" \"h\"], [\"i\" \"j\"; \"k\" \"l\"], dims = 3);println(reshape(C, (2, 2, 3)))", "e": 1600, "s": 1016, "text": null }, { "code": null, "e": 1608, "s": 1600, "text": "Output:" }, { "code": null, "e": 1630, "s": 1608, "text": "Julia Array-functions" }, { "code": null, "e": 1636, "s": 1630, "text": "Julia" } ]
Flutter Development in Ubuntu 20.04
30 Aug, 2020 In this article, let’s look at how you can set up a development environment for Flutter, if you’re using Ubuntu 20.04. It was difficult earlier and was kind of a nightmare to get it done. But now, it has changed and anyone can easily set up a flutter development environment on their Ubuntu system in a few minutes. Flutter on Ubuntu Let’s break down the things that we have to do. Before moving any further, please make a note that, we will be setting up flutter in VS Code since it allows a much smoother performance on almost any system (even if your system is having 4GB of Ram or low). I personally have experienced the advantage of using VS Code, where I got my overall time taken for various tasks reduced nearly by 75% when compared to the time taken while using Android Studio. The process involved in the setting up process are : VS Code or Visual Studio Code is an amazing all-in-one code editor developed by the team at Microsoft. It is free and open-sourced. You can download VS Code from here. It doesn’t have much download size and is easy to set up. You can also use the terminal to install the VS Code on your system, by running the following code : $ sudo apt install code After installing VS Code, we need to install Flutter SDK so that it will enable VS Code to build flutter applications. In order to install the flutter SDK, you have to open your terminal again and run the following line of code (or follow similar instructions from the Flutter Website : $ sudo apt install code Once you’re done installing the VS Code and Flutter SDK, let’s try opening VS Code. If there hadn’t been any installation errors, VS Code will open without any issue. After loading up, we need to enable Git which is a version control system (VCS) which will be really helpful in the later stages. For this, select VCS Option from the left side of the VS Code. Please refer to the below image if you’re new to VS Code. VCS in VS Code After selecting that, you will find an option to install Git. Once you click on that, you will be taken to the website from which you can download Git for your system. You can also install Git by running the following code on your terminal. $ sudo apt update $ sudo apt install git After Installing Git, come back to the VS Code and select the Extensions (the icon present at two down the position with that of VCS). Extension Shortcut From that, you have to search for flutter and install that extension. Also, make sure that Dart is also installed in the same method. Installing Flutter Extension Now you’re nearly ready to go. There is one more final installation that you need to perform before you’re all set to go. You will have to install Android Studio for all the essential packages like ADB Manager or if you need to add any virtual devices via AVD Manager. As said above, though we may be able to download all the packages separately, it may lead on to some errors. To avoid that, let’s install Android Studio so that all the essential packages will get added correctly. You can install Android Studio by running the following command on the terminal. First install JDK : $ sudo apt install openjdk-11-jdk Now, you can install Android Studio : $ sudo snap install android-studio --classic After installing Android Studio, open it from the Applications directory and run it. You will be asked whether to import any settings and select ‘Do not import’ for that. Move ahead with the installation flow and finally, all the installation will be over. After the installation is over, you will reach the starting page. From there select the ‘Configure’ option present on the right side bottom. Configure option Now, you have to select ‘SDK Manager’ from the list and you will be redirected to a page where you can install the required Android SDKs for various Android OS Versions. Please make sure that you’re installing the SDK of the same version as that of your phone or the virtual device which you will be setting up later. Select them and click on ‘Apply’. After that, you will be prompted to install them and follow the procedure. Select the required SDKs Once everything is complete, close everything including Android Studio as well as VS Code. You can restart VS Code now. Within VS Code, you can create a new workspace folder (where your project files will be stored). After that, click on View from the top Tool Bar and select the Command Panel. In that type in Flutter New Project and select it. If everything has been set up correctly, you will be asked to type in your project name. Sometimes, you will be asked to locate the Flutter SDK. In that case, provide the location where you installed the Flutter SDK. If there were no errors, a project of the name that you provided will load up in a moment. The same can also be achieved by running the following command on the terminal present on VS Code (select Terminal from the toolbar on the top and run the following command. flutter create $projectname where $projectname can be changed with the name of your preference. Once the project loads completely, all the files can be accessed from the Files section of VS Code present on the left side tool bar (2 positions above that of the VCS). You may connect your physical device (android) for installing the application or you may install a new Android Virtual Device from the AVD Manager, just like how we installed the SDKs from SDK Manager. The Run option can be found just below VCS and it can be used to run and debug your application. Now, you’re all set to develop flutter application using VS Code. Happy Coding. android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Checkbox Widget Flutter - Custom Bottom Navigation Bar Flutter - Asset Image Flutter - DropDownButton Widget Flutter - Checkbox Widget How to Install Flutter App on Android? Flutter - File Structure Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Aug, 2020" }, { "code": null, "e": 371, "s": 54, "text": "In this article, let’s look at how you can set up a development environment for Flutter, if you’re using Ubuntu 20.04. It was difficult earlier and was kind of a nightmare to get it done. But now, it has changed and anyone can easily set up a flutter development environment on their Ubuntu system in a few minutes. " }, { "code": null, "e": 389, "s": 371, "text": "Flutter on Ubuntu" }, { "code": null, "e": 895, "s": 389, "text": "Let’s break down the things that we have to do. Before moving any further, please make a note that, we will be setting up flutter in VS Code since it allows a much smoother performance on almost any system (even if your system is having 4GB of Ram or low). I personally have experienced the advantage of using VS Code, where I got my overall time taken for various tasks reduced nearly by 75% when compared to the time taken while using Android Studio. The process involved in the setting up process are :" }, { "code": null, "e": 1122, "s": 895, "text": "VS Code or Visual Studio Code is an amazing all-in-one code editor developed by the team at Microsoft. It is free and open-sourced. You can download VS Code from here. It doesn’t have much download size and is easy to set up. " }, { "code": null, "e": 1224, "s": 1122, "text": "You can also use the terminal to install the VS Code on your system, by running the following code : " }, { "code": null, "e": 1248, "s": 1224, "text": "$ sudo apt install code" }, { "code": null, "e": 1536, "s": 1248, "text": "After installing VS Code, we need to install Flutter SDK so that it will enable VS Code to build flutter applications. In order to install the flutter SDK, you have to open your terminal again and run the following line of code (or follow similar instructions from the Flutter Website : " }, { "code": null, "e": 1560, "s": 1536, "text": "$ sudo apt install code" }, { "code": null, "e": 1858, "s": 1560, "text": "Once you’re done installing the VS Code and Flutter SDK, let’s try opening VS Code. If there hadn’t been any installation errors, VS Code will open without any issue. After loading up, we need to enable Git which is a version control system (VCS) which will be really helpful in the later stages. " }, { "code": null, "e": 1980, "s": 1858, "text": "For this, select VCS Option from the left side of the VS Code. Please refer to the below image if you’re new to VS Code. " }, { "code": null, "e": 1995, "s": 1980, "text": "VCS in VS Code" }, { "code": null, "e": 2236, "s": 1995, "text": "After selecting that, you will find an option to install Git. Once you click on that, you will be taken to the website from which you can download Git for your system. You can also install Git by running the following code on your terminal." }, { "code": null, "e": 2278, "s": 2236, "text": "$ sudo apt update\n\n$ sudo apt install git" }, { "code": null, "e": 2413, "s": 2278, "text": "After Installing Git, come back to the VS Code and select the Extensions (the icon present at two down the position with that of VCS)." }, { "code": null, "e": 2432, "s": 2413, "text": "Extension Shortcut" }, { "code": null, "e": 2567, "s": 2432, "text": "From that, you have to search for flutter and install that extension. Also, make sure that Dart is also installed in the same method. " }, { "code": null, "e": 2596, "s": 2567, "text": "Installing Flutter Extension" }, { "code": null, "e": 2866, "s": 2596, "text": "Now you’re nearly ready to go. There is one more final installation that you need to perform before you’re all set to go. You will have to install Android Studio for all the essential packages like ADB Manager or if you need to add any virtual devices via AVD Manager. " }, { "code": null, "e": 3162, "s": 2866, "text": "As said above, though we may be able to download all the packages separately, it may lead on to some errors. To avoid that, let’s install Android Studio so that all the essential packages will get added correctly. You can install Android Studio by running the following command on the terminal. " }, { "code": null, "e": 3184, "s": 3162, "text": "First install JDK : " }, { "code": null, "e": 3218, "s": 3184, "text": "$ sudo apt install openjdk-11-jdk" }, { "code": null, "e": 3257, "s": 3218, "text": "Now, you can install Android Studio :" }, { "code": null, "e": 3302, "s": 3257, "text": "$ sudo snap install android-studio --classic" }, { "code": null, "e": 3700, "s": 3302, "text": "After installing Android Studio, open it from the Applications directory and run it. You will be asked whether to import any settings and select ‘Do not import’ for that. Move ahead with the installation flow and finally, all the installation will be over. After the installation is over, you will reach the starting page. From there select the ‘Configure’ option present on the right side bottom." }, { "code": null, "e": 3717, "s": 3700, "text": "Configure option" }, { "code": null, "e": 4144, "s": 3717, "text": "Now, you have to select ‘SDK Manager’ from the list and you will be redirected to a page where you can install the required Android SDKs for various Android OS Versions. Please make sure that you’re installing the SDK of the same version as that of your phone or the virtual device which you will be setting up later. Select them and click on ‘Apply’. After that, you will be prompted to install them and follow the procedure." }, { "code": null, "e": 4169, "s": 4144, "text": "Select the required SDKs" }, { "code": null, "e": 4467, "s": 4171, "text": "Once everything is complete, close everything including Android Studio as well as VS Code. You can restart VS Code now. Within VS Code, you can create a new workspace folder (where your project files will be stored). After that, click on View from the top Tool Bar and select the Command Panel. " }, { "code": null, "e": 4735, "s": 4467, "text": "In that type in Flutter New Project and select it. If everything has been set up correctly, you will be asked to type in your project name. Sometimes, you will be asked to locate the Flutter SDK. In that case, provide the location where you installed the Flutter SDK." }, { "code": null, "e": 5001, "s": 4735, "text": "If there were no errors, a project of the name that you provided will load up in a moment. The same can also be achieved by running the following command on the terminal present on VS Code (select Terminal from the toolbar on the top and run the following command. " }, { "code": null, "e": 5030, "s": 5001, "text": "flutter create $projectname " }, { "code": null, "e": 5268, "s": 5030, "text": "where $projectname can be changed with the name of your preference. Once the project loads completely, all the files can be accessed from the Files section of VS Code present on the left side tool bar (2 positions above that of the VCS)." }, { "code": null, "e": 5568, "s": 5268, "text": "You may connect your physical device (android) for installing the application or you may install a new Android Virtual Device from the AVD Manager, just like how we installed the SDKs from SDK Manager. The Run option can be found just below VCS and it can be used to run and debug your application. " }, { "code": null, "e": 5649, "s": 5568, "text": "Now, you’re all set to develop flutter application using VS Code. Happy Coding. " }, { "code": null, "e": 5657, "s": 5649, "text": "android" }, { "code": null, "e": 5665, "s": 5657, "text": "Flutter" }, { "code": null, "e": 5670, "s": 5665, "text": "Dart" }, { "code": null, "e": 5678, "s": 5670, "text": "Flutter" }, { "code": null, "e": 5776, "s": 5678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5804, "s": 5776, "text": "Listview.builder in Flutter" }, { "code": null, "e": 5836, "s": 5804, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 5862, "s": 5836, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 5901, "s": 5862, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5923, "s": 5901, "text": "Flutter - Asset Image" }, { "code": null, "e": 5955, "s": 5923, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 5981, "s": 5955, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 6020, "s": 5981, "text": "How to Install Flutter App on Android?" }, { "code": null, "e": 6045, "s": 6020, "text": "Flutter - File Structure" } ]
Side of a regular n-sided polygon circumscribed in a circle
24 Jun, 2022 Given two integers r and n where n is the number of sides of a regular polygon and r is the radius of the circle this polygon is circumscribed in. The task is to find the length of the side of polygon. Examples: Input: n = 5, r = 11 Output: 12.9256Input: n = 3, r = 5 Output: 8.6576 Approach: Consider the image above and let angle AOB be theta then theta = 360 / n. In right angled triangle , angle ACO = 90 degrees and angle AOC = theta / 2. So, AC = OA * sin(theta / 2) = r * sin(theta / 2) Therefore, side of the polygon, AB = 2 * AC i.e. 2 * r * sin(theta / 2). Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to calculate the side of the polygon// circumscribed in a circlefloat calculateSide(float n, float r){ float theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * sin(theta_in_radians / 2);} // Driver Codeint main(){ // Total sides of the polygon float n = 3; // Radius of the circumscribing circle float r = 5; cout << calculateSide(n, r);} // Java implementation of the approachimport java.lang.Math;import java.io.*; class GFG { // Function to calculate the side of the polygon// circumscribed in a circlestatic double calculateSide(double n, double r){ double theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * Math.sin(theta_in_radians / 2);} // Driver Code public static void main (String[] args) { // Total sides of the polygon double n = 3; // Radius of the circumscribing circle double r = 5; System.out.println (calculateSide(n, r)); }//This code is contributed by akt_mit } # Python 3 implementation of the approachfrom math import sin # Function to calculate the side of# the polygon circumscribed in a circledef calculateSide(n, r): theta = 360 / n theta_in_radians = theta * 3.14 / 180 return 2 * r * sin(theta_in_radians / 2) # Driver Codeif __name__ == '__main__': # Total sides of the polygon n = 3 # Radius of the circumscribing circle r = 5 print('{0:.5}'.format(calculateSide(n, r))) # This code is contributed by# Sanjit_Prasad // C# implementation of the approach using System; class GFG { // Function to calculate the side of the polygon // circumscribed in a circle static double calculateSide(double n, double r) { double theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return Math.Round(2 * r * Math.Sin(theta_in_radians / 2),4); } // Driver Code public static void Main () { // Total sides of the polygon double n = 3; // Radius of the circumscribing circle double r = 5; Console.WriteLine(calculateSide(n, r)); } // This code is contributed by Ryuga} <?php// PHP implementation of the approach // Function to calculate the side of the// polygon circumscribed in a circlefunction calculateSide($n, $r){ $theta; $theta_in_radians; $theta = 360 / $n; $theta_in_radians = $theta * 3.14 / 180; return 2 * $r * sin($theta_in_radians / 2);} // Driver Code // Total sides of the polygon$n = 3; // Radius of the circumscribing circle$r = 5; echo calculateSide($n, $r); // This code is contributed by inder_verma..?> <script> // javascript implementation of the approach // Function to calculate the side of the polygon// circumscribed in a circlefunction calculateSide( n , r){ var theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * Math.sin(theta_in_radians / 2);} // Driver Code // Total sides of the polygonvar n = 3; // Radius of the circumscribing circlevar r = 5;document.write(calculateSide(n, r).toFixed(5)); // This code contributed by Princi Singh </script> 8.6576 Time Complexity: O(1), since there is no loop or recursion.Auxiliary Space: O(1), since no extra space has been taken. jit_t ankthon inderDuMCA Sanjit_Prasad princi singh singhh3010 souravkumar29 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2022" }, { "code": null, "e": 232, "s": 28, "text": "Given two integers r and n where n is the number of sides of a regular polygon and r is the radius of the circle this polygon is circumscribed in. The task is to find the length of the side of polygon. " }, { "code": null, "e": 244, "s": 232, "text": "Examples: " }, { "code": null, "e": 316, "s": 244, "text": "Input: n = 5, r = 11 Output: 12.9256Input: n = 3, r = 5 Output: 8.6576 " }, { "code": null, "e": 600, "s": 316, "text": "Approach: Consider the image above and let angle AOB be theta then theta = 360 / n. In right angled triangle , angle ACO = 90 degrees and angle AOC = theta / 2. So, AC = OA * sin(theta / 2) = r * sin(theta / 2) Therefore, side of the polygon, AB = 2 * AC i.e. 2 * r * sin(theta / 2)." }, { "code": null, "e": 652, "s": 600, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 656, "s": 652, "text": "C++" }, { "code": null, "e": 661, "s": 656, "text": "Java" }, { "code": null, "e": 669, "s": 661, "text": "Python3" }, { "code": null, "e": 672, "s": 669, "text": "C#" }, { "code": null, "e": 676, "s": 672, "text": "PHP" }, { "code": null, "e": 687, "s": 676, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to calculate the side of the polygon// circumscribed in a circlefloat calculateSide(float n, float r){ float theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * sin(theta_in_radians / 2);} // Driver Codeint main(){ // Total sides of the polygon float n = 3; // Radius of the circumscribing circle float r = 5; cout << calculateSide(n, r);}", "e": 1197, "s": 687, "text": null }, { "code": "// Java implementation of the approachimport java.lang.Math;import java.io.*; class GFG { // Function to calculate the side of the polygon// circumscribed in a circlestatic double calculateSide(double n, double r){ double theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * Math.sin(theta_in_radians / 2);} // Driver Code public static void main (String[] args) { // Total sides of the polygon double n = 3; // Radius of the circumscribing circle double r = 5; System.out.println (calculateSide(n, r)); }//This code is contributed by akt_mit }", "e": 1830, "s": 1197, "text": null }, { "code": "# Python 3 implementation of the approachfrom math import sin # Function to calculate the side of# the polygon circumscribed in a circledef calculateSide(n, r): theta = 360 / n theta_in_radians = theta * 3.14 / 180 return 2 * r * sin(theta_in_radians / 2) # Driver Codeif __name__ == '__main__': # Total sides of the polygon n = 3 # Radius of the circumscribing circle r = 5 print('{0:.5}'.format(calculateSide(n, r))) # This code is contributed by# Sanjit_Prasad", "e": 2326, "s": 1830, "text": null }, { "code": "// C# implementation of the approach using System; class GFG { // Function to calculate the side of the polygon // circumscribed in a circle static double calculateSide(double n, double r) { double theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return Math.Round(2 * r * Math.Sin(theta_in_radians / 2),4); } // Driver Code public static void Main () { // Total sides of the polygon double n = 3; // Radius of the circumscribing circle double r = 5; Console.WriteLine(calculateSide(n, r)); } // This code is contributed by Ryuga}", "e": 2990, "s": 2326, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to calculate the side of the// polygon circumscribed in a circlefunction calculateSide($n, $r){ $theta; $theta_in_radians; $theta = 360 / $n; $theta_in_radians = $theta * 3.14 / 180; return 2 * $r * sin($theta_in_radians / 2);} // Driver Code // Total sides of the polygon$n = 3; // Radius of the circumscribing circle$r = 5; echo calculateSide($n, $r); // This code is contributed by inder_verma..?>", "e": 3460, "s": 2990, "text": null }, { "code": "<script> // javascript implementation of the approach // Function to calculate the side of the polygon// circumscribed in a circlefunction calculateSide( n , r){ var theta, theta_in_radians; theta = 360 / n; theta_in_radians = theta * 3.14 / 180; return 2 * r * Math.sin(theta_in_radians / 2);} // Driver Code // Total sides of the polygonvar n = 3; // Radius of the circumscribing circlevar r = 5;document.write(calculateSide(n, r).toFixed(5)); // This code contributed by Princi Singh </script>", "e": 3976, "s": 3460, "text": null }, { "code": null, "e": 3983, "s": 3976, "text": "8.6576" }, { "code": null, "e": 4102, "s": 3983, "text": "Time Complexity: O(1), since there is no loop or recursion.Auxiliary Space: O(1), since no extra space has been taken." }, { "code": null, "e": 4108, "s": 4102, "text": "jit_t" }, { "code": null, "e": 4116, "s": 4108, "text": "ankthon" }, { "code": null, "e": 4127, "s": 4116, "text": "inderDuMCA" }, { "code": null, "e": 4141, "s": 4127, "text": "Sanjit_Prasad" }, { "code": null, "e": 4154, "s": 4141, "text": "princi singh" }, { "code": null, "e": 4165, "s": 4154, "text": "singhh3010" }, { "code": null, "e": 4179, "s": 4165, "text": "souravkumar29" }, { "code": null, "e": 4189, "s": 4179, "text": "Geometric" }, { "code": null, "e": 4202, "s": 4189, "text": "Mathematical" }, { "code": null, "e": 4215, "s": 4202, "text": "Mathematical" }, { "code": null, "e": 4225, "s": 4215, "text": "Geometric" }, { "code": null, "e": 4323, "s": 4225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4376, "s": 4323, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 4427, "s": 4376, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 4485, "s": 4427, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 4532, "s": 4485, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 4607, "s": 4532, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 4650, "s": 4607, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4710, "s": 4650, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4725, "s": 4710, "text": "C++ Data Types" }, { "code": null, "e": 4749, "s": 4725, "text": "Merge two sorted arrays" } ]
Square root of a number without using sqrt() function
22 Apr, 2021 Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach: Start iterating from i = 1. If i * i = n, then print i as n is a perfect square whose square root is i. Else find the smallest i for which i * i is strictly greater than n. Now we know square root of n lies in the interval i – 1 and i and we can use Binary Search algorithm to find the square root. Find mid of i – 1 and i and compare mid * mid with n, with precision upto 5 decimal places. If mid * mid = n then return mid.If mid * mid < n then recur for the second half.If mid * mid > n then recur for the first half. If mid * mid = n then return mid.If mid * mid < n then recur for the second half.If mid * mid > n then recur for the first half. If mid * mid = n then return mid. If mid * mid < n then recur for the second half. If mid * mid > n then recur for the first half. 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; // Recursive function that returns square root// of a number with precision upto 5 decimal placesdouble Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (abs(mul - n) < 0.00001)) return mid; // If mul is less than n, recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nvoid findSqrt(double n){ double i = 1; // While the square root is not found bool found = false; while (!found) { // If n is a perfect square if (i * i == n) { cout << fixed << setprecision(0) << i; found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); cout << fixed << setprecision(5) << res; found = true; } i++; }} // Driver codeint main(){ double n = 3; findSqrt(n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Recursive function that returns// square root of a number with// precision upto 5 decimal placesstatic double Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nstatic void findSqrt(double n){ double i = 1; // While the square root is not found boolean found = false; while (!found) { // If n is a perfect square if (i * i == n) { System.out.println(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); System.out.printf("%.5f", res); found = true; } i++; }} // Driver codepublic static void main(String[] args){ double n = 3; findSqrt(n);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approachimport math # Recursive function that returns square root# of a number with precision upto 5 decimal placesdef Square(n, i, j): mid = (i + j) / 2; mul = mid * mid; # If mid itself is the square root, # return mid if ((mul == n) or (abs(mul - n) < 0.00001)): return mid; # If mul is less than n, recur second half elif (mul < n): return Square(n, mid, j); # Else recur first half else: return Square(n, i, mid); # Function to find the square root of ndef findSqrt(n): i = 1; # While the square root is not found found = False; while (found == False): # If n is a perfect square if (i * i == n): print(i); found = True; elif (i * i > n): # Square root will lie in the # interval i-1 and i res = Square(n, i - 1, i); print ("{0:.5f}".format(res)) found = True i += 1; # Driver codeif __name__ == '__main__': n = 3; findSqrt(n); # This code is contributed by 29AjayKumar // C# implementation of the approachusing System; class GFG{ // Recursive function that returns// square root of a number with// precision upto 5 decimal placesstatic double Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.Abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nstatic void findSqrt(double n){ double i = 1; // While the square root is not found Boolean found = false; while (!found) { // If n is a perfect square if (i * i == n) { Console.WriteLine(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); Console.Write("{0:F5}", res); found = true; } i++; }} // Driver codepublic static void Main(String[] args){ double n = 3; findSqrt(n);}} // This code is contributed by Princi Singh <script> // Javascript implementation of the approach // Recursive function that returns// square root of a number with// precision upto 5 decimal placesfunction Square(n, i, j){ var mid = ((i + j) / 2); var mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nfunction findSqrt(n){ var i = 1; // While the square root is not found var found = false; while (!found) { // If n is a perfect square if (i * i == n) { document.write(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i var res = Square(n, i - 1, i); document.write(res.toFixed(5)); found = true; } i++; }} // Driver codevar n = 3; findSqrt(n); // This code is contributed by todaysgaurav </script> 1.73205 princiraj1992 princi singh 29AjayKumar todaysgaurav Mathematical Searching Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Maximum and minimum of an array using minimum number of comparisons K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Find the Missing Number Search, insert and delete in an unsorted array
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2021" }, { "code": null, "e": 142, "s": 52, "text": "Given a number N, the task is to find the square root of N without using sqrt() function." }, { "code": null, "e": 153, "s": 142, "text": "Examples: " }, { "code": null, "e": 177, "s": 153, "text": "Input: N = 25 Output: 5" }, { "code": null, "e": 206, "s": 177, "text": "Input: N = 3 Output: 1.73205" }, { "code": null, "e": 239, "s": 206, "text": "Input: N = 2.5 Output: 1.58114 " }, { "code": null, "e": 251, "s": 239, "text": "Approach: " }, { "code": null, "e": 355, "s": 251, "text": "Start iterating from i = 1. If i * i = n, then print i as n is a perfect square whose square root is i." }, { "code": null, "e": 424, "s": 355, "text": "Else find the smallest i for which i * i is strictly greater than n." }, { "code": null, "e": 550, "s": 424, "text": "Now we know square root of n lies in the interval i – 1 and i and we can use Binary Search algorithm to find the square root." }, { "code": null, "e": 771, "s": 550, "text": "Find mid of i – 1 and i and compare mid * mid with n, with precision upto 5 decimal places. If mid * mid = n then return mid.If mid * mid < n then recur for the second half.If mid * mid > n then recur for the first half." }, { "code": null, "e": 900, "s": 771, "text": "If mid * mid = n then return mid.If mid * mid < n then recur for the second half.If mid * mid > n then recur for the first half." }, { "code": null, "e": 934, "s": 900, "text": "If mid * mid = n then return mid." }, { "code": null, "e": 983, "s": 934, "text": "If mid * mid < n then recur for the second half." }, { "code": null, "e": 1031, "s": 983, "text": "If mid * mid > n then recur for the first half." }, { "code": null, "e": 1084, "s": 1031, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1088, "s": 1084, "text": "C++" }, { "code": null, "e": 1093, "s": 1088, "text": "Java" }, { "code": null, "e": 1101, "s": 1093, "text": "Python3" }, { "code": null, "e": 1104, "s": 1101, "text": "C#" }, { "code": null, "e": 1115, "s": 1104, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Recursive function that returns square root// of a number with precision upto 5 decimal placesdouble Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (abs(mul - n) < 0.00001)) return mid; // If mul is less than n, recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nvoid findSqrt(double n){ double i = 1; // While the square root is not found bool found = false; while (!found) { // If n is a perfect square if (i * i == n) { cout << fixed << setprecision(0) << i; found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); cout << fixed << setprecision(5) << res; found = true; } i++; }} // Driver codeint main(){ double n = 3; findSqrt(n); return 0;}", "e": 2333, "s": 1115, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Recursive function that returns// square root of a number with// precision upto 5 decimal placesstatic double Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nstatic void findSqrt(double n){ double i = 1; // While the square root is not found boolean found = false; while (!found) { // If n is a perfect square if (i * i == n) { System.out.println(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); System.out.printf(\"%.5f\", res); found = true; } i++; }} // Driver codepublic static void main(String[] args){ double n = 3; findSqrt(n);}} // This code is contributed by PrinciRaj1992", "e": 3658, "s": 2333, "text": null }, { "code": "# Python3 implementation of the approachimport math # Recursive function that returns square root# of a number with precision upto 5 decimal placesdef Square(n, i, j): mid = (i + j) / 2; mul = mid * mid; # If mid itself is the square root, # return mid if ((mul == n) or (abs(mul - n) < 0.00001)): return mid; # If mul is less than n, recur second half elif (mul < n): return Square(n, mid, j); # Else recur first half else: return Square(n, i, mid); # Function to find the square root of ndef findSqrt(n): i = 1; # While the square root is not found found = False; while (found == False): # If n is a perfect square if (i * i == n): print(i); found = True; elif (i * i > n): # Square root will lie in the # interval i-1 and i res = Square(n, i - 1, i); print (\"{0:.5f}\".format(res)) found = True i += 1; # Driver codeif __name__ == '__main__': n = 3; findSqrt(n); # This code is contributed by 29AjayKumar", "e": 4753, "s": 3658, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Recursive function that returns// square root of a number with// precision upto 5 decimal placesstatic double Square(double n, double i, double j){ double mid = (i + j) / 2; double mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.Abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nstatic void findSqrt(double n){ double i = 1; // While the square root is not found Boolean found = false; while (!found) { // If n is a perfect square if (i * i == n) { Console.WriteLine(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i double res = Square(n, i - 1, i); Console.Write(\"{0:F5}\", res); found = true; } i++; }} // Driver codepublic static void Main(String[] args){ double n = 3; findSqrt(n);}} // This code is contributed by Princi Singh", "e": 6068, "s": 4753, "text": null }, { "code": "<script> // Javascript implementation of the approach // Recursive function that returns// square root of a number with// precision upto 5 decimal placesfunction Square(n, i, j){ var mid = ((i + j) / 2); var mul = mid * mid; // If mid itself is the square root, // return mid if ((mul == n) || (Math.abs(mul - n) < 0.00001)) return mid; // If mul is less than n, // recur second half else if (mul < n) return Square(n, mid, j); // Else recur first half else return Square(n, i, mid);} // Function to find the square root of nfunction findSqrt(n){ var i = 1; // While the square root is not found var found = false; while (!found) { // If n is a perfect square if (i * i == n) { document.write(i); found = true; } else if (i * i > n) { // Square root will lie in the // interval i-1 and i var res = Square(n, i - 1, i); document.write(res.toFixed(5)); found = true; } i++; }} // Driver codevar n = 3; findSqrt(n); // This code is contributed by todaysgaurav </script>", "e": 7264, "s": 6068, "text": null }, { "code": null, "e": 7272, "s": 7264, "text": "1.73205" }, { "code": null, "e": 7288, "s": 7274, "text": "princiraj1992" }, { "code": null, "e": 7301, "s": 7288, "text": "princi singh" }, { "code": null, "e": 7313, "s": 7301, "text": "29AjayKumar" }, { "code": null, "e": 7326, "s": 7313, "text": "todaysgaurav" }, { "code": null, "e": 7339, "s": 7326, "text": "Mathematical" }, { "code": null, "e": 7349, "s": 7339, "text": "Searching" }, { "code": null, "e": 7359, "s": 7349, "text": "Searching" }, { "code": null, "e": 7372, "s": 7359, "text": "Mathematical" }, { "code": null, "e": 7470, "s": 7372, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7494, "s": 7470, "text": "Merge two sorted arrays" }, { "code": null, "e": 7515, "s": 7494, "text": "Operators in C / C++" }, { "code": null, "e": 7529, "s": 7515, "text": "Prime Numbers" }, { "code": null, "e": 7582, "s": 7529, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7619, "s": 7582, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7687, "s": 7619, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7743, "s": 7687, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 7791, "s": 7743, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 7815, "s": 7791, "text": "Find the Missing Number" } ]
G-Fact 21 | Collatz Sequence
07 Jul, 2021 Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations: N → N/2 ( if N is even) N → 3N + 1 (if N is odd) i.e. If N is even, divide it by 2 to get N/2. If N is odd, multiply it by 3 and add 1 to obtain 3N + 1. It is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1. For example, 10 → 5 → 16 → 8 → 4 → 2 → 1 A Coding Practice Question on Collatz Sequence If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Dynamic Programming GFacts Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Find if there is a path between two vertices in an undirected graph Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Return values of printf() and scanf() in C/C++ How are variables scoped in C - Static or Dynamic? What are the Operators that Can be and Cannot be Overloaded in C++? Difference between YOLO and SSD G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2021" }, { "code": null, "e": 191, "s": 52, "text": "Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations:" }, { "code": null, "e": 347, "s": 191, "text": "N → N/2 ( if N is even)\nN → 3N + 1 (if N is odd)\n\ni.e. If N is even, divide it by 2 to get N/2. \nIf N is odd, multiply it by 3 and add 1 to obtain 3N + 1.\n" }, { "code": null, "e": 462, "s": 347, "text": "It is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1." }, { "code": null, "e": 503, "s": 462, "text": "For example, 10 → 5 → 16 → 8 → 4 → 2 → 1" }, { "code": null, "e": 550, "s": 503, "text": "A Coding Practice Question on Collatz Sequence" }, { "code": null, "e": 772, "s": 550, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 792, "s": 772, "text": "Dynamic Programming" }, { "code": null, "e": 799, "s": 792, "text": "GFacts" }, { "code": null, "e": 812, "s": 799, "text": "Mathematical" }, { "code": null, "e": 832, "s": 812, "text": "Dynamic Programming" }, { "code": null, "e": 845, "s": 832, "text": "Mathematical" }, { "code": null, "e": 943, "s": 845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 970, "s": 943, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 1008, "s": 970, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 1076, "s": 1008, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 1109, "s": 1076, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 1128, "s": 1109, "text": "Coin Change | DP-7" }, { "code": null, "e": 1175, "s": 1128, "text": "Return values of printf() and scanf() in C/C++" }, { "code": null, "e": 1226, "s": 1175, "text": "How are variables scoped in C - Static or Dynamic?" }, { "code": null, "e": 1294, "s": 1226, "text": "What are the Operators that Can be and Cannot be Overloaded in C++?" }, { "code": null, "e": 1326, "s": 1294, "text": "Difference between YOLO and SSD" } ]
help_text – Django Form Field Validation
13 Feb, 2020 Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments. The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. The default help_text for a Field is empty. Let’s check how to use help_text in a field using a project. Syntax field_name = models.Field(option = value) Illustration of help_text using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options. from django import forms class GeeksForm(forms.Form): geeks_field = forms.CharField(help_text = "Enter your Name") Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form if request.POST: if form.is_valid(): temp = form.cleaned_data.get("geeks_field") print(temp) return render(request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method = "POST"> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view URLpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field CharField is created with help_text “Enter your Name”. NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2020" }, { "code": null, "e": 273, "s": 28, "text": "Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments." }, { "code": null, "e": 583, "s": 273, "text": "The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. The default help_text for a Field is empty. Let’s check how to use help_text in a field using a project." }, { "code": null, "e": 590, "s": 583, "text": "Syntax" }, { "code": null, "e": 632, "s": 590, "text": "field_name = models.Field(option = value)" }, { "code": null, "e": 742, "s": 632, "text": "Illustration of help_text using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 829, "s": 742, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 880, "s": 829, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 913, "s": 880, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1039, "s": 913, "text": "Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options." }, { "code": "from django import forms class GeeksForm(forms.Form): geeks_field = forms.CharField(help_text = \"Enter your Name\")", "e": 1158, "s": 1039, "text": null }, { "code": null, "e": 1194, "s": 1158, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 1432, "s": 1194, "text": null }, { "code": null, "e": 1566, "s": 1432, "text": "Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} form = GeeksForm(request.POST or None) context['form'] = form if request.POST: if form.is_valid(): temp = form.cleaned_data.get(\"geeks_field\") print(temp) return render(request, \"home.html\", context)", "e": 1937, "s": 1566, "text": null }, { "code": null, "e": 2223, "s": 1937, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method = \"POST\"> {% csrf_token %} {{ form }} <input type = \"submit\" value = \"Submit\"></form>", "e": 2331, "s": 2223, "text": null }, { "code": null, "e": 2377, "s": 2331, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view URLpatterns = [ path('', home_view ),]", "e": 2511, "s": 2377, "text": null }, { "code": null, "e": 2574, "s": 2511, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 2601, "s": 2574, "text": "Python manage.py runserver" }, { "code": null, "e": 2677, "s": 2601, "text": "Thus, an geeks_field CharField is created with help_text “Enter your Name”." }, { "code": null, "e": 2689, "s": 2677, "text": "NaveenArora" }, { "code": null, "e": 2702, "s": 2689, "text": "Django-forms" }, { "code": null, "e": 2716, "s": 2702, "text": "Python Django" }, { "code": null, "e": 2723, "s": 2716, "text": "Python" } ]
Node.js console.trace() Method - GeeksforGeeks
13 Jul, 2020 The console.trace() method is an inbuilt application programming interface of the console module which is used to print stack trace messages to stderr in a newline. Similar to console.error() method. Syntax: console.trace(message, args); Parameters: This method has two parameters as mentioned above and described below: message: This parameter specifies the message to be printed.args: It is optional parameter that specifies the parameters to be passed as substitution values in the message. All passed args are sent to util.format(). message: This parameter specifies the message to be printed. args: It is optional parameter that specifies the parameters to be passed as substitution values in the message. All passed args are sent to util.format(). Return Value: This method doesn’t return anything but print ‘Trace:’ string followed by the formatted message to stderr in a newline and stack trace to the current position in the code. Below examples illustrate the use of console.trace() method in Node.js: Example 1:Filename: app.js // Node.js program to demonstrate the // console.trace() method // Accessing console moduleconst console = require('console'); // Calling console.trace() methodconsole.trace("stack teace sample"); console.trace( "stack trace sample with args: %d", 39); Run the app.js file using the following command: node app.js Output: Trace: stack teace sampleat Object. (C:\nodejs\g\console\console_trace.js:4:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)Trace: stack trace sample with args: 39at Object. (C:\nodejs\g\console\console_trace.js:5:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3) Example 2:Filename: app.js // Node.js program to demonstrate the // console.trace() method // Accessing console moduleconst console = require('console'); // Calling console.trace() methodconsole.trace("stack trace message: " + "at %s: line no: %d ", "ff()", 96); var isTrace = true; console.custom_trace = function(message) { if (isTrace) { console.trace(message); }} console.custom_trace("custom trace message"); Run the app.js file using the following command: node app.js Output: Trace: stack trace message: at ff(): line no: 96at Object. (C:\nodejs\g\console\console_trace_1.js:4:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)Trace: custom trace messageat Console.console.custom_trace (C:\nodejs\g\console\console_trace_1.js:11:13)at Object. (C:\nodejs\g\console\console_trace_1.js:14:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3) Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/console.html#console_console_trace_data_args Node.js-console-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.writeFile() Method Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function Mongoose | findByIdAndUpdate() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills 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": 25049, "s": 25021, "text": "\n13 Jul, 2020" }, { "code": null, "e": 25249, "s": 25049, "text": "The console.trace() method is an inbuilt application programming interface of the console module which is used to print stack trace messages to stderr in a newline. Similar to console.error() method." }, { "code": null, "e": 25257, "s": 25249, "text": "Syntax:" }, { "code": null, "e": 25287, "s": 25257, "text": "console.trace(message, args);" }, { "code": null, "e": 25370, "s": 25287, "text": "Parameters: This method has two parameters as mentioned above and described below:" }, { "code": null, "e": 25586, "s": 25370, "text": "message: This parameter specifies the message to be printed.args: It is optional parameter that specifies the parameters to be passed as substitution values in the message. All passed args are sent to util.format()." }, { "code": null, "e": 25647, "s": 25586, "text": "message: This parameter specifies the message to be printed." }, { "code": null, "e": 25803, "s": 25647, "text": "args: It is optional parameter that specifies the parameters to be passed as substitution values in the message. All passed args are sent to util.format()." }, { "code": null, "e": 25989, "s": 25803, "text": "Return Value: This method doesn’t return anything but print ‘Trace:’ string followed by the formatted message to stderr in a newline and stack trace to the current position in the code." }, { "code": null, "e": 26061, "s": 25989, "text": "Below examples illustrate the use of console.trace() method in Node.js:" }, { "code": null, "e": 26088, "s": 26061, "text": "Example 1:Filename: app.js" }, { "code": "// Node.js program to demonstrate the // console.trace() method // Accessing console moduleconst console = require('console'); // Calling console.trace() methodconsole.trace(\"stack teace sample\"); console.trace( \"stack trace sample with args: %d\", 39);", "e": 26348, "s": 26088, "text": null }, { "code": null, "e": 26397, "s": 26348, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 26409, "s": 26397, "text": "node app.js" }, { "code": null, "e": 26417, "s": 26409, "text": "Output:" }, { "code": null, "e": 27532, "s": 26417, "text": "Trace: stack teace sampleat Object. (C:\\nodejs\\g\\console\\console_trace.js:4:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)Trace: stack trace sample with args: 39at Object. (C:\\nodejs\\g\\console\\console_trace.js:5:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)" }, { "code": null, "e": 27559, "s": 27532, "text": "Example 2:Filename: app.js" }, { "code": "// Node.js program to demonstrate the // console.trace() method // Accessing console moduleconst console = require('console'); // Calling console.trace() methodconsole.trace(\"stack trace message: \" + \"at %s: line no: %d \", \"ff()\", 96); var isTrace = true; console.custom_trace = function(message) { if (isTrace) { console.trace(message); }} console.custom_trace(\"custom trace message\");", "e": 27964, "s": 27559, "text": null }, { "code": null, "e": 28013, "s": 27964, "text": "Run the app.js file using the following command:" }, { "code": null, "e": 28025, "s": 28013, "text": "node app.js" }, { "code": null, "e": 28033, "s": 28025, "text": "Output:" }, { "code": null, "e": 29242, "s": 28033, "text": "Trace: stack trace message: at ff(): line no: 96at Object. (C:\\nodejs\\g\\console\\console_trace_1.js:4:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)Trace: custom trace messageat Console.console.custom_trace (C:\\nodejs\\g\\console\\console_trace_1.js:11:13)at Object. (C:\\nodejs\\g\\console\\console_trace_1.js:14:9)at Module._compile (internal/modules/cjs/loader.js:776:30)at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)at Module.load (internal/modules/cjs/loader.js:653:32)at tryModuleLoad (internal/modules/cjs/loader.js:593:12)at Function.Module._load (internal/modules/cjs/loader.js:585:3)at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)at startup (internal/bootstrap/node.js:283:19)at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)" }, { "code": null, "e": 29326, "s": 29242, "text": "Note: The above program will compile and run by using the node filename.js command." }, { "code": null, "e": 29405, "s": 29326, "text": "Reference: https://nodejs.org/api/console.html#console_console_trace_data_args" }, { "code": null, "e": 29428, "s": 29405, "text": "Node.js-console-module" }, { "code": null, "e": 29436, "s": 29428, "text": "Node.js" }, { "code": null, "e": 29453, "s": 29436, "text": "Web Technologies" }, { "code": null, "e": 29551, "s": 29453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29560, "s": 29551, "text": "Comments" }, { "code": null, "e": 29573, "s": 29560, "text": "Old Comments" }, { "code": null, "e": 29603, "s": 29573, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 29657, "s": 29603, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 29694, "s": 29657, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29729, "s": 29694, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 29769, "s": 29729, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 29825, "s": 29769, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29887, "s": 29825, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29930, "s": 29887, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29980, "s": 29930, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Forensics - Dshell and Scapy
Dshell is a Python-based network forensic analysis toolkit. This toolkit was developed by the US Army Research Laboratory. The release of this open source toolkit was in the year 2014. The major focus of this toolkit is to make forensic investigations with ease. The toolkit consists of large number of decoders which are listed in the following table. dns This is used to extract DNS related queries reservedips Identifies the solutions for DNS problems large-flows Listing of the netflows rip-http It is used extract the files from the HTTP traffic Protocols Used for identification of non-standard protocols The US Army Laboratory has maintained the clone repository in GitHub in the following link − https://github.com/USArmyResearchLab/Dshell The clone consists of a script install-ubuntu.py () used for installation of this toolkit. Once the installation is successful, it will automatically build the executables and dependencies that will be used later. The dependencies are as follows − dependencies = { "Crypto": "crypto", "dpkt": "dpkt", "IPy": "ipy", "pcap": "pypcap" } This toolkit can be used against the pcap (packet capture) files, which is usually recorded during the incidents or during the alert. These pcap files is either created by libpcap on Linux platform or WinPcap on Windows platform. Scapy is a Python-based tool used to analyze and manipulate the network traffic. Following is the link for Scapy toolkit − http://www.secdev.org/projects/scapy/ This toolkit is used to analyze packet manipulation. It is very capable to decode packets of a wide number of protocols and capture them. Scapy differs from the Dshell toolkit by providing a detailed description to the investigator about network traffic. These descriptions have been recorded in real time. Scapy has the ability to plot using third-party tools or OS fingerprinting. Consider the following example. import scapy, GeoIP #Imports scapy and GeoIP toolkit from scapy import * geoIp = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) #locates the Geo IP address def locatePackage(pkg): src = pkg.getlayer(IP).src #gets source IP address dst = pkg.getlayer(IP).dst #gets destination IP address srcCountry = geoIp.country_code_by_addr(src) #gets Country details of source dstCountry = geoIp.country_code_by_addr(dst) #gets country details of destination print src+"("+srcCountry+") >> "+dst+"("+dstCountry+")\n" This script gives the detailed description of the country details in the network packet, who are communicating with each other. The above script will produce the following output. 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": 2255, "s": 1992, "text": "Dshell is a Python-based network forensic analysis toolkit. This toolkit was developed by the US Army Research Laboratory. The release of this open source toolkit was in the year 2014. The major focus of this toolkit is to make forensic investigations with ease." }, { "code": null, "e": 2345, "s": 2255, "text": "The toolkit consists of large number of decoders which are listed in the following table." }, { "code": null, "e": 2349, "s": 2345, "text": "dns" }, { "code": null, "e": 2393, "s": 2349, "text": "This is used to extract DNS related queries" }, { "code": null, "e": 2405, "s": 2393, "text": "reservedips" }, { "code": null, "e": 2447, "s": 2405, "text": "Identifies the solutions for DNS problems" }, { "code": null, "e": 2459, "s": 2447, "text": "large-flows" }, { "code": null, "e": 2483, "s": 2459, "text": "Listing of the netflows" }, { "code": null, "e": 2492, "s": 2483, "text": "rip-http" }, { "code": null, "e": 2543, "s": 2492, "text": "It is used extract the files from the HTTP traffic" }, { "code": null, "e": 2553, "s": 2543, "text": "Protocols" }, { "code": null, "e": 2603, "s": 2553, "text": "Used for identification of non-standard protocols" }, { "code": null, "e": 2696, "s": 2603, "text": "The US Army Laboratory has maintained the clone repository in GitHub in the following link −" }, { "code": null, "e": 2740, "s": 2696, "text": "https://github.com/USArmyResearchLab/Dshell" }, { "code": null, "e": 2831, "s": 2740, "text": "The clone consists of a script install-ubuntu.py () used for installation of this toolkit." }, { "code": null, "e": 2954, "s": 2831, "text": "Once the installation is successful, it will automatically build the executables and dependencies that will be used later." }, { "code": null, "e": 2988, "s": 2954, "text": "The dependencies are as follows −" }, { "code": null, "e": 3091, "s": 2988, "text": "dependencies = { \n \"Crypto\": \"crypto\", \n \"dpkt\": \"dpkt\", \n \"IPy\": \"ipy\", \n \"pcap\": \"pypcap\" \n}" }, { "code": null, "e": 3321, "s": 3091, "text": "This toolkit can be used against the pcap (packet capture) files, which is usually recorded during the incidents or during the alert. These pcap files is either created by libpcap on Linux platform or WinPcap on Windows platform." }, { "code": null, "e": 3444, "s": 3321, "text": "Scapy is a Python-based tool used to analyze and manipulate the network traffic. Following is the link for Scapy toolkit −" }, { "code": null, "e": 3482, "s": 3444, "text": "http://www.secdev.org/projects/scapy/" }, { "code": null, "e": 3789, "s": 3482, "text": "This toolkit is used to analyze packet manipulation. It is very capable to decode packets of a wide number of protocols and capture them. Scapy differs from the Dshell toolkit by providing a detailed description to the investigator about network traffic. These descriptions have been recorded in real time." }, { "code": null, "e": 3865, "s": 3789, "text": "Scapy has the ability to plot using third-party tools or OS fingerprinting." }, { "code": null, "e": 3897, "s": 3865, "text": "Consider the following example." }, { "code": null, "e": 4398, "s": 3897, "text": "import scapy, GeoIP #Imports scapy and GeoIP toolkit \nfrom scapy import * \ngeoIp = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) #locates the Geo IP address \ndef locatePackage(pkg): \nsrc = pkg.getlayer(IP).src #gets source IP address \ndst = pkg.getlayer(IP).dst #gets destination IP address \nsrcCountry = geoIp.country_code_by_addr(src) #gets Country details of source \ndstCountry = geoIp.country_code_by_addr(dst) #gets country details of destination \nprint src+\"(\"+srcCountry+\") >> \"+dst+\"(\"+dstCountry+\")\\n\"" }, { "code": null, "e": 4526, "s": 4398, "text": "This script gives the detailed description of the country details in the network packet, who are communicating with each other." }, { "code": null, "e": 4578, "s": 4526, "text": "The above script will produce the following output." }, { "code": null, "e": 4615, "s": 4578, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4631, "s": 4615, "text": " Malhar Lathkar" }, { "code": null, "e": 4664, "s": 4631, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4683, "s": 4664, "text": " Arnab Chakraborty" }, { "code": null, "e": 4718, "s": 4683, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4740, "s": 4718, "text": " In28Minutes Official" }, { "code": null, "e": 4774, "s": 4740, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4802, "s": 4774, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4837, "s": 4802, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4851, "s": 4837, "text": " Lets Kode It" }, { "code": null, "e": 4884, "s": 4851, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4901, "s": 4884, "text": " Abhilash Nelson" }, { "code": null, "e": 4908, "s": 4901, "text": " Print" }, { "code": null, "e": 4919, "s": 4908, "text": " Add Notes" } ]
Activity Selection Problem | Greedy Algo-1 - GeeksforGeeks
12 Jan, 2022 Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. If a Greedy Algorithm can solve a problem, then it generally becomes the best method to solve that problem as the Greedy algorithms are in general more efficient than other techniques like Dynamic Programming. But Greedy algorithms cannot always be applied. For example, the Fractional Knapsack problem can be solved using Greedy, but 0-1 Knapsack cannot be solved using Greedy.Following are some standard algorithms that are Greedy algorithms. 1) Kruskal’s Minimum Spanning Tree (MST): In Kruskal’s algorithm, we create a MST by picking edges one by one. The Greedy Choice is to pick the smallest weight edge that doesn’t cause a cycle in the MST constructed so far. 2) Prim’s Minimum Spanning Tree: In Prim’s algorithm also, we create a MST by picking edges one by one. We maintain two sets: a set of the vertices already included in MST and the set of the vertices not yet included. The Greedy Choice is to pick the smallest weight edge that connects the two sets. 3) Dijkstra’s Shortest Path: Dijkstra’s algorithm is very similar to Prim’s algorithm. The shortest-path tree is built up, edge by edge. We maintain two sets: a set of the vertices already included in the tree and the set of the vertices not yet included. The Greedy Choice is to pick the edge that connects the two sets and is on the smallest weight path from source to the set that contains not yet included vertices. 4) Huffman Coding: Huffman Coding is a loss-less compression technique. It assigns variable-length bit codes to different characters. The Greedy Choice is to assign the least bit length code to the most frequent character.The greedy algorithms are sometimes also used to get an approximation for Hard optimization problems. For example, Traveling Salesman Problem is an NP-Hard problem. A Greedy choice for this problem is to pick the nearest unvisited city from the current city at every step. These solutions don’t always produce the best optimal solution but can be used to get an approximately optimal solution.Let us consider the Activity Selection problem as our first example of Greedy algorithms. Following is the problem statement. You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example: Example 1 : Consider the following 3 activities sorted by by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person can perform at most two activities. The maximum set of activities that can be executed is {0, 2} [ These are indexes in start[] and finish[] ] Example 2 : Consider the following 6 activities sorted by by finish time. start[] = {1, 3, 0, 5, 8, 5}; finish[] = {2, 4, 6, 7, 9, 9}; A person can perform at most four activities. The maximum set of activities that can be executed is {0, 1, 3, 4} [ These are indexes in start[] and finish[] ] The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of the previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.1) Sort the activities according to their finishing time 2) Select the first activity from the sorted array and print it. 3) Do the following for the remaining activities in the sorted array. .......a) If the start time of this activity is greater than or equal to the finish time of the previously selected activity then select this activity and print it.In the following C implementation, it is assumed that the activities are already sorted according to their finish time. C++ C Java C# Python3 PHP Javascript // C++ program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include <bits/stdc++.h>using namespace std; // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; cout <<"Following activities are selected "<< endl; // The first activity always gets selected i = 0; cout <<" "<< i; // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { cout <<" " << j; i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;}//this code contributed by shivanisinghss2110 // C program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include<stdio.h> // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; printf ("Following activities are selected n"); // The first activity always gets selected i = 0; printf("%d ", i); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { printf ("%d ", j); i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;} // The following implementation assumes that the activities// are already sorted according to their finish timeimport java.util.*;import java.lang.*;import java.io.*; class ActivitySelection{ // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities public static void printMaxActivities(int s[], int f[], int n) { int i, j; System.out.print("Following activities are selected : n"); // The first activity always gets selected i = 0; System.out.print(i+" "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { System.out.print(j+" "); i = j; } } } // driver program to test above function public static void main(String[] args) { int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = s.length; printMaxActivities(s, f, n); } } // The following implementation assumes// that the activities are already sorted// according to their finish timeusing System; class GFG{// Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiespublic static void printMaxActivities(int[] s, int[] f, int n){int i, j; Console.Write("Following activities are selected : "); // The first activity always gets selectedi = 0;Console.Write(i + " "); // Consider rest of the activitiesfor (j = 1; j < n; j++){ // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { Console.Write(j + " "); i = j; }}} // Driver Codepublic static void Main(){ int[] s = {1, 3, 0, 5, 8, 5}; int[] f = {2, 4, 6, 7, 9, 9}; int n = s.Length; printMaxActivities(s, f, n);}} // This code is contributed// by ChitraNayal """The following implementation assumes that the activitiesare already sorted according to their finish time""" """Prints a maximum set of activities that can be done by asingle person, one at a time"""# n --> Total number of activities# s[]--> An array that contains start time of all activities# f[] --> An array that contains finish time of all activities def printMaxActivities(s , f ): n = len(f) print ("The following activities are selected") # The first activity is always selected i = 0 print (i,end=' ') # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if s[j] >= f[i]: print (j,end=' ') i = j # Driver program to test above functions = [1 , 3 , 0 , 5 , 8 , 5]f = [2 , 4 , 6 , 7 , 9 , 9]printMaxActivities(s , f) # This code is contributed by Nikhil Kumar Singh <?php// PHP program for activity selection problem.// The following implementation assumes that// the activities are already sorted according// to their finish time // Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiesfunction printMaxActivities($s, $f, $n){ echo "Following activities are selected " . "\n"; // The first activity always gets selected $i = 0; echo $i . " "; // Consider rest of the activities for ($j = 1; $j < $n; $j++) { // If this activity has start time greater // than or equal to the finish time of // previously selected activity, then select it if ($s[$j] >= $f[$i]) { echo $j . " "; $i = $j; } }} // Driver Code$s = array(1, 3, 0, 5, 8, 5);$f = array(2, 4, 6, 7, 9, 9);$n = sizeof($s);printMaxActivities($s, $f, $n); // This code is contributed// by Akanksha Rai?> <script>// The following implementation assumes that the activities// are already sorted according to their finish time // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities function printMaxActivities(s,f,n) { let i, j; document.write("Following activities are selected : n"); // The first activity always gets selected i = 0; document.write(i+" "); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { document.write(j+" "); i = j; } } } // Driver program to test above function let s = [1, 3, 0, 5, 8, 5] let f = [2, 4, 6, 7, 9, 9] let n = s.length; printMaxActivities(s, f, n); // This code is contributed by avanitrachhadiya2155</script> Following activities are selected n0 1 3 4 How does Greedy Choice work for Activities sorted according to finish time? Let the given set of activities be S = {1, 2, 3, ...n} and activities are sorted by finish time. The greedy choice is to always pick activity 1. How come activity 1 always provides one of the optimal solutions. We can prove it by showing that if there is another solution B with the first activity other than 1, then there is also a solution A of the same size with activity 1 as the first activity. Let the first activity selected by B be k, then there always exist A = {B – {k}} U {1}. (Note that the activities in B are independent and k has the smallest finishing time among all. Since k is not 1, finish(k) >= finish(1)). How to implement when given activities are not sorted? We create a structure/class for activities. We sort all activities by finish time (Refer sort in C++ STL). Once we have activities sorted, we apply the same algorithm.Below image is an illustration of the above approach: Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; // A job has a start time, finish time and profit.struct Activitiy{ int start, finish;}; // A utility function that is used for sorting// activities according to finish timebool activityCompare(Activitiy s1, Activitiy s2){ return (s1.finish < s2.finish);} // Returns count of the maximum set of activities that can// be done by a single person, one at a time.void printMaxActivities(Activitiy arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, activityCompare); cout << "Following activities are selected n"; // The first activity always gets selected int i = 0; cout << "(" << arr[i].start << ", " << arr[i].finish << "), "; // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (arr[j].start >= arr[i].finish) { cout << "(" << arr[j].start << ", " << arr[j].finish << "), "; i = j; } }} // Driver programint main(){ Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}}; int n = sizeof(arr)/sizeof(arr[0]); printMaxActivities(arr, n); return 0;} // Java program for activity selection problem// when input activities may not be sorted.import java.io.*;import java.util.*; // A job has a start time, finish time and profit.class Activity{ int start, finish; // Constructor public Activity(int start, int finish) { this.start = start; this.finish = finish; }} // class to define user defined comparatorclass Compare{ // A utility function that is used for sorting // activities according to finish time static void compare(Activity arr[], int n) { Arrays.sort(arr, new Comparator<Activity>() { @Override public int compare(Activity s1, Activity s2) { return s1.finish - s2.finish; } }); }} // Driver classclass GFG { // Returns count of the maximum set of activities that // can // be done by a single person, one at a time. static void printMaxActivities(Activity arr[], int n) { // Sort jobs according to finish time Compare obj = new Compare(); obj.compare(arr, n); System.out.println( "Following activities are selected :"); // The first activity always gets selected int i = 0; System.out.print("(" + arr[i].start + ", " + arr[i].finish + "), "); // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than // or equal to the finish time of previously // selected activity, then select it if (arr[j].start >= arr[i].finish) { System.out.print("(" + arr[j].start + ", " + arr[j].finish + "), "); i = j; } } } // Driver code public static void main(String[] args) { int n = 6; Activity arr[] = new Activity[n]; arr[0] = new Activity(5, 9); arr[1] = new Activity(1, 2); arr[2] = new Activity(3, 4); arr[3] = new Activity(0, 6); arr[4] = new Activity(5, 7); arr[5] = new Activity(8, 9); printMaxActivities(arr, n); }} // This code is contributed by Dharanendra L V. ''' Python program for activity selection problem when input activities may not be sorted.'''def MaxActivities(arr, n): selected = [] # Sort jobs according to finish time Activity.sort(key = lambda x : x[1]) # The first activity always gets selected i = 0 selected.append(arr[i]) for j in range(1, n): '''If this activity has start time greater than or equal to the finish time of previously selected activity, then select it''' if arr[j][0] >= arr[i][1]: selected.append(arr[j]) i = j return selected # Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]]n = len(Activity)selected = MaxActivities(Activity, n)print("Following activities are selected :")print(selected) # This cde is contributed by kshitijjainm <script>/* JavaScript program for activity selection problem when input activities may not be sorted.*/function MaxActivities(arr, n){ let selected = []; // Sort jobs according to finish time Activity = Activity.sort(function(a,b) { return a[1] - b[1]; }); // The first activity always gets selected let i = 0 selected.push(arr[i]); for(let j=1;j<n;j++){ /*If this activity has start time greater than or equal to the finish time of previously selected activity, then select it*/ if( arr[j][0] >= arr[i][1]){ selected.push(arr[j]); i = j; } } return selected;}// Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]];n = Activity.length;selected = MaxActivities(Activity, n);document.write("Following activities are selected : <br>")console.log(selected)for(let i = 0;i<selected.length;i++) document.write("("+selected[i]+"), ")</script> Output: Following activities are selected (1, 2), (3, 4), (5, 7), (8, 9), Time Complexity: It takes O(n log n) time if input activities may not be sorted. It takes O(n) time when it is given that input activities are always sorted.Using STL we can solve it as follows: CPP Java Javascript // C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; void SelectActivities(vector<int>s,vector<int>f){// Vector to store results. vector<pair<int,int>>ans; // Minimum Priority Queue to sort activities in ascending order of finishing time (f[i]). priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>p; for(int i=0;i<s.size();i++){ // Pushing elements in priority queue where the key is f[i] p.push(make_pair(f[i],s[i])); } auto it = p.top(); int start = it.second; int end = it.first; p.pop(); ans.push_back(make_pair(start,end)); while(!p.empty()){ auto itr = p.top(); p.pop(); if(itr.second >= end){ start = itr.second; end = itr.first; ans.push_back(make_pair(start,end)); } } cout << "Following Activities should be selected. " << endl << endl; for(auto itr=ans.begin();itr!=ans.end();itr++){ cout << "Activity started at: " << (*itr).first << " and ends at " << (*itr).second << endl; }} // Driver programint main(){ vector<int>s = {1, 3, 0, 5, 8, 5}; vector<int>f = {2, 4, 6, 7, 9, 9}; SelectActivities(s,f); return 0;} // java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Pair class static class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } static void SelectActivities(int s[], int f[]) { // Vector to store results. ArrayList<Pair> ans = new ArrayList<>(); // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). PriorityQueue<Pair> p = new PriorityQueue<>( (p1, p2) -> p1.first - p2.first); for (int i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.add(new Pair(f[i], s[i])); } Pair it = p.poll(); int start = it.second; int end = it.first; ans.add(new Pair(start, end)); while (!p.isEmpty()) { Pair itr = p.poll(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.add(new Pair(start, end)); } } System.out.println( "Following Activities should be selected. \n"); for (Pair itr : ans) { System.out.println( "Activity started at: " + itr.first + " and ends at " + itr.second); } } // Driver Code public static void main(String[] args) { int s[] = { 1, 3, 0, 5, 8, 5 }; int f[] = { 2, 4, 6, 7, 9, 9 }; // Function call SelectActivities(s, f); }} // This code is contributed by Kingash. <script>// javascript program for the above approach // Pair classclass Pair{ constructor(first,second) { this.first = first; this.second = second; }} function SelectActivities(s,f){ // Vector to store results. let ans = []; // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). let p = []; for (let i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.push(new Pair(f[i], s[i])); } p.sort(function(a,b){return a.first-b.first;}); let it = p.shift(); let start = it.second; let end = it.first; ans.push(new Pair(start, end)); while (p.length!=0) { let itr = p.shift(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.push(new Pair(start, end)); } } document.write( "Following Activities should be selected. <br>"); for(let itr of ans.values()) { document.write( "Activity started at: " + itr.first + " and ends at " + itr.second+"<br>"); }} // Driver Codelet s=[1, 3, 0, 5, 8, 5 ];let f=[2, 4, 6, 7, 9, 9 ];// Function callSelectActivities(s, f); // This code is contributed by rag2127</script> Following Activities should be selected. Activity started at: 1 and ends at 2 Activity started at: 3 and ends at 4 Activity started at: 5 and ends at 7 Activity started at: 8 and ends at 9 ukasp Akanksha_Rai zafir_ahmad kshitijjainm shivanisinghss2110 dharanendralv23 Kingash avanitrachhadiya2155 rohitsingh07052 rag2127 surajv tejaskanikdaley1996 amartyaghoshgfg Activity Selection Problem Amazon Facebook Flipkart MakeMyTrip Morgan Stanley Visa Greedy Flipkart Morgan Stanley Amazon MakeMyTrip Visa Facebook Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for array rotation Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Fractional Knapsack Problem Minimum Number of Platforms Required for a Railway/Bus Station Delete an element from array (Using two traversals and one traversal) 3 Different ways to print Fibonacci series in Java Program for Shortest Job First (SJF) scheduling | Set 2 (Preemptive) Greedy Algorithm to find Minimum number of Coins Difference between Prim's and Kruskal's algorithm for MST Minimum Count of Bit flips required to make a Binary String Palindromic
[ { "code": null, "e": 30545, "s": 30517, "text": "\n12 Jan, 2022" }, { "code": null, "e": 33320, "s": 30545, "text": "Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. If a Greedy Algorithm can solve a problem, then it generally becomes the best method to solve that problem as the Greedy algorithms are in general more efficient than other techniques like Dynamic Programming. But Greedy algorithms cannot always be applied. For example, the Fractional Knapsack problem can be solved using Greedy, but 0-1 Knapsack cannot be solved using Greedy.Following are some standard algorithms that are Greedy algorithms. 1) Kruskal’s Minimum Spanning Tree (MST): In Kruskal’s algorithm, we create a MST by picking edges one by one. The Greedy Choice is to pick the smallest weight edge that doesn’t cause a cycle in the MST constructed so far. 2) Prim’s Minimum Spanning Tree: In Prim’s algorithm also, we create a MST by picking edges one by one. We maintain two sets: a set of the vertices already included in MST and the set of the vertices not yet included. The Greedy Choice is to pick the smallest weight edge that connects the two sets. 3) Dijkstra’s Shortest Path: Dijkstra’s algorithm is very similar to Prim’s algorithm. The shortest-path tree is built up, edge by edge. We maintain two sets: a set of the vertices already included in the tree and the set of the vertices not yet included. The Greedy Choice is to pick the edge that connects the two sets and is on the smallest weight path from source to the set that contains not yet included vertices. 4) Huffman Coding: Huffman Coding is a loss-less compression technique. It assigns variable-length bit codes to different characters. The Greedy Choice is to assign the least bit length code to the most frequent character.The greedy algorithms are sometimes also used to get an approximation for Hard optimization problems. For example, Traveling Salesman Problem is an NP-Hard problem. A Greedy choice for this problem is to pick the nearest unvisited city from the current city at every step. These solutions don’t always produce the best optimal solution but can be used to get an approximately optimal solution.Let us consider the Activity Selection problem as our first example of Greedy algorithms. Following is the problem statement. You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. " }, { "code": null, "e": 33331, "s": 33320, "text": "Example: " }, { "code": null, "e": 33934, "s": 33331, "text": "Example 1 : Consider the following 3 activities sorted by\nby finish time.\n start[] = {10, 12, 20};\n finish[] = {20, 25, 30};\nA person can perform at most two activities. The \nmaximum set of activities that can be executed \nis {0, 2} [ These are indexes in start[] and \nfinish[] ]\n\nExample 2 : Consider the following 6 activities \nsorted by by finish time.\n start[] = {1, 3, 0, 5, 8, 5};\n finish[] = {2, 4, 6, 7, 9, 9};\nA person can perform at most four activities. The \nmaximum set of activities that can be executed \nis {0, 1, 3, 4} [ These are indexes in start[] and \nfinish[] ]" }, { "code": null, "e": 34761, "s": 33934, "text": "The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of the previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.1) Sort the activities according to their finishing time 2) Select the first activity from the sorted array and print it. 3) Do the following for the remaining activities in the sorted array. .......a) If the start time of this activity is greater than or equal to the finish time of the previously selected activity then select this activity and print it.In the following C implementation, it is assumed that the activities are already sorted according to their finish time. " }, { "code": null, "e": 34765, "s": 34761, "text": "C++" }, { "code": null, "e": 34767, "s": 34765, "text": "C" }, { "code": null, "e": 34772, "s": 34767, "text": "Java" }, { "code": null, "e": 34775, "s": 34772, "text": "C#" }, { "code": null, "e": 34783, "s": 34775, "text": "Python3" }, { "code": null, "e": 34787, "s": 34783, "text": "PHP" }, { "code": null, "e": 34798, "s": 34787, "text": "Javascript" }, { "code": "// C++ program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include <bits/stdc++.h>using namespace std; // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; cout <<\"Following activities are selected \"<< endl; // The first activity always gets selected i = 0; cout <<\" \"<< i; // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { cout <<\" \" << j; i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;}//this code contributed by shivanisinghss2110", "e": 36001, "s": 34798, "text": null }, { "code": "// C program for activity selection problem.// The following implementation assumes that the activities// are already sorted according to their finish time#include<stdio.h> // Prints a maximum set of activities that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start time of all activities// f[] --> An array that contains finish time of all activitiesvoid printMaxActivities(int s[], int f[], int n){ int i, j; printf (\"Following activities are selected n\"); // The first activity always gets selected i = 0; printf(\"%d \", i); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { printf (\"%d \", j); i = j; } }} // driver program to test above functionint main(){ int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = sizeof(s)/sizeof(s[0]); printMaxActivities(s, f, n); return 0;}", "e": 37130, "s": 36001, "text": null }, { "code": "// The following implementation assumes that the activities// are already sorted according to their finish timeimport java.util.*;import java.lang.*;import java.io.*; class ActivitySelection{ // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities public static void printMaxActivities(int s[], int f[], int n) { int i, j; System.out.print(\"Following activities are selected : n\"); // The first activity always gets selected i = 0; System.out.print(i+\" \"); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { System.out.print(j+\" \"); i = j; } } } // driver program to test above function public static void main(String[] args) { int s[] = {1, 3, 0, 5, 8, 5}; int f[] = {2, 4, 6, 7, 9, 9}; int n = s.length; printMaxActivities(s, f, n); } }", "e": 38426, "s": 37130, "text": null }, { "code": "// The following implementation assumes// that the activities are already sorted// according to their finish timeusing System; class GFG{// Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiespublic static void printMaxActivities(int[] s, int[] f, int n){int i, j; Console.Write(\"Following activities are selected : \"); // The first activity always gets selectedi = 0;Console.Write(i + \" \"); // Consider rest of the activitiesfor (j = 1; j < n; j++){ // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { Console.Write(j + \" \"); i = j; }}} // Driver Codepublic static void Main(){ int[] s = {1, 3, 0, 5, 8, 5}; int[] f = {2, 4, 6, 7, 9, 9}; int n = s.Length; printMaxActivities(s, f, n);}} // This code is contributed// by ChitraNayal", "e": 39565, "s": 38426, "text": null }, { "code": "\"\"\"The following implementation assumes that the activitiesare already sorted according to their finish time\"\"\" \"\"\"Prints a maximum set of activities that can be done by asingle person, one at a time\"\"\"# n --> Total number of activities# s[]--> An array that contains start time of all activities# f[] --> An array that contains finish time of all activities def printMaxActivities(s , f ): n = len(f) print (\"The following activities are selected\") # The first activity is always selected i = 0 print (i,end=' ') # Consider rest of the activities for j in range(n): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if s[j] >= f[i]: print (j,end=' ') i = j # Driver program to test above functions = [1 , 3 , 0 , 5 , 8 , 5]f = [2 , 4 , 6 , 7 , 9 , 9]printMaxActivities(s , f) # This code is contributed by Nikhil Kumar Singh", "e": 40542, "s": 39565, "text": null }, { "code": "<?php// PHP program for activity selection problem.// The following implementation assumes that// the activities are already sorted according// to their finish time // Prints a maximum set of activities// that can be done by a single// person, one at a time.// n --> Total number of activities// s[] --> An array that contains start// time of all activities// f[] --> An array that contains finish// time of all activitiesfunction printMaxActivities($s, $f, $n){ echo \"Following activities are selected \" . \"\\n\"; // The first activity always gets selected $i = 0; echo $i . \" \"; // Consider rest of the activities for ($j = 1; $j < $n; $j++) { // If this activity has start time greater // than or equal to the finish time of // previously selected activity, then select it if ($s[$j] >= $f[$i]) { echo $j . \" \"; $i = $j; } }} // Driver Code$s = array(1, 3, 0, 5, 8, 5);$f = array(2, 4, 6, 7, 9, 9);$n = sizeof($s);printMaxActivities($s, $f, $n); // This code is contributed// by Akanksha Rai?>", "e": 41621, "s": 40542, "text": null }, { "code": "<script>// The following implementation assumes that the activities// are already sorted according to their finish time // Prints a maximum set of activities that can be done by a single // person, one at a time. // n --> Total number of activities // s[] --> An array that contains start time of all activities // f[] --> An array that contains finish time of all activities function printMaxActivities(s,f,n) { let i, j; document.write(\"Following activities are selected : n\"); // The first activity always gets selected i = 0; document.write(i+\" \"); // Consider rest of the activities for (j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (s[j] >= f[i]) { document.write(j+\" \"); i = j; } } } // Driver program to test above function let s = [1, 3, 0, 5, 8, 5] let f = [2, 4, 6, 7, 9, 9] let n = s.length; printMaxActivities(s, f, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 42882, "s": 41621, "text": null }, { "code": null, "e": 42929, "s": 42885, "text": "Following activities are selected n0 1 3 4 " }, { "code": null, "e": 43495, "s": 42931, "text": "How does Greedy Choice work for Activities sorted according to finish time? Let the given set of activities be S = {1, 2, 3, ...n} and activities are sorted by finish time. The greedy choice is to always pick activity 1. How come activity 1 always provides one of the optimal solutions. We can prove it by showing that if there is another solution B with the first activity other than 1, then there is also a solution A of the same size with activity 1 as the first activity. Let the first activity selected by B be k, then there always exist A = {B – {k}} U {1}." }, { "code": null, "e": 43636, "s": 43497, "text": "(Note that the activities in B are independent and k has the smallest finishing time among all. Since k is not 1, finish(k) >= finish(1))." }, { "code": null, "e": 43917, "s": 43638, "text": "How to implement when given activities are not sorted? We create a structure/class for activities. We sort all activities by finish time (Refer sort in C++ STL). Once we have activities sorted, we apply the same algorithm.Below image is an illustration of the above approach: " }, { "code": null, "e": 43972, "s": 43921, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 43978, "s": 43974, "text": "C++" }, { "code": null, "e": 43983, "s": 43978, "text": "Java" }, { "code": null, "e": 43991, "s": 43983, "text": "Python3" }, { "code": null, "e": 44002, "s": 43991, "text": "Javascript" }, { "code": "// C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; // A job has a start time, finish time and profit.struct Activitiy{ int start, finish;}; // A utility function that is used for sorting// activities according to finish timebool activityCompare(Activitiy s1, Activitiy s2){ return (s1.finish < s2.finish);} // Returns count of the maximum set of activities that can// be done by a single person, one at a time.void printMaxActivities(Activitiy arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, activityCompare); cout << \"Following activities are selected n\"; // The first activity always gets selected int i = 0; cout << \"(\" << arr[i].start << \", \" << arr[i].finish << \"), \"; // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than or // equal to the finish time of previously selected // activity, then select it if (arr[j].start >= arr[i].finish) { cout << \"(\" << arr[j].start << \", \" << arr[j].finish << \"), \"; i = j; } }} // Driver programint main(){ Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}}; int n = sizeof(arr)/sizeof(arr[0]); printMaxActivities(arr, n); return 0;}", "e": 45409, "s": 44002, "text": null }, { "code": "// Java program for activity selection problem// when input activities may not be sorted.import java.io.*;import java.util.*; // A job has a start time, finish time and profit.class Activity{ int start, finish; // Constructor public Activity(int start, int finish) { this.start = start; this.finish = finish; }} // class to define user defined comparatorclass Compare{ // A utility function that is used for sorting // activities according to finish time static void compare(Activity arr[], int n) { Arrays.sort(arr, new Comparator<Activity>() { @Override public int compare(Activity s1, Activity s2) { return s1.finish - s2.finish; } }); }} // Driver classclass GFG { // Returns count of the maximum set of activities that // can // be done by a single person, one at a time. static void printMaxActivities(Activity arr[], int n) { // Sort jobs according to finish time Compare obj = new Compare(); obj.compare(arr, n); System.out.println( \"Following activities are selected :\"); // The first activity always gets selected int i = 0; System.out.print(\"(\" + arr[i].start + \", \" + arr[i].finish + \"), \"); // Consider rest of the activities for (int j = 1; j < n; j++) { // If this activity has start time greater than // or equal to the finish time of previously // selected activity, then select it if (arr[j].start >= arr[i].finish) { System.out.print(\"(\" + arr[j].start + \", \" + arr[j].finish + \"), \"); i = j; } } } // Driver code public static void main(String[] args) { int n = 6; Activity arr[] = new Activity[n]; arr[0] = new Activity(5, 9); arr[1] = new Activity(1, 2); arr[2] = new Activity(3, 4); arr[3] = new Activity(0, 6); arr[4] = new Activity(5, 7); arr[5] = new Activity(8, 9); printMaxActivities(arr, n); }} // This code is contributed by Dharanendra L V.", "e": 47489, "s": 45409, "text": null }, { "code": "''' Python program for activity selection problem when input activities may not be sorted.'''def MaxActivities(arr, n): selected = [] # Sort jobs according to finish time Activity.sort(key = lambda x : x[1]) # The first activity always gets selected i = 0 selected.append(arr[i]) for j in range(1, n): '''If this activity has start time greater than or equal to the finish time of previously selected activity, then select it''' if arr[j][0] >= arr[i][1]: selected.append(arr[j]) i = j return selected # Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]]n = len(Activity)selected = MaxActivities(Activity, n)print(\"Following activities are selected :\")print(selected) # This cde is contributed by kshitijjainm", "e": 48304, "s": 47489, "text": null }, { "code": "<script>/* JavaScript program for activity selection problem when input activities may not be sorted.*/function MaxActivities(arr, n){ let selected = []; // Sort jobs according to finish time Activity = Activity.sort(function(a,b) { return a[1] - b[1]; }); // The first activity always gets selected let i = 0 selected.push(arr[i]); for(let j=1;j<n;j++){ /*If this activity has start time greater than or equal to the finish time of previously selected activity, then select it*/ if( arr[j][0] >= arr[i][1]){ selected.push(arr[j]); i = j; } } return selected;}// Driver codeActivity = [[5, 9], [1, 2], [3, 4], [0, 6],[5, 7], [8, 9]];n = Activity.length;selected = MaxActivities(Activity, n);document.write(\"Following activities are selected : <br>\")console.log(selected)for(let i = 0;i<selected.length;i++) document.write(\"(\"+selected[i]+\"), \")</script>", "e": 49257, "s": 48304, "text": null }, { "code": null, "e": 49269, "s": 49260, "text": "Output: " }, { "code": null, "e": 49338, "s": 49271, "text": "Following activities are selected \n(1, 2), (3, 4), (5, 7), (8, 9)," }, { "code": null, "e": 49536, "s": 49340, "text": "Time Complexity: It takes O(n log n) time if input activities may not be sorted. It takes O(n) time when it is given that input activities are always sorted.Using STL we can solve it as follows: " }, { "code": null, "e": 49542, "s": 49538, "text": "CPP" }, { "code": null, "e": 49547, "s": 49542, "text": "Java" }, { "code": null, "e": 49558, "s": 49547, "text": "Javascript" }, { "code": "// C++ program for activity selection problem// when input activities may not be sorted.#include <bits/stdc++.h>using namespace std; void SelectActivities(vector<int>s,vector<int>f){// Vector to store results. vector<pair<int,int>>ans; // Minimum Priority Queue to sort activities in ascending order of finishing time (f[i]). priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>p; for(int i=0;i<s.size();i++){ // Pushing elements in priority queue where the key is f[i] p.push(make_pair(f[i],s[i])); } auto it = p.top(); int start = it.second; int end = it.first; p.pop(); ans.push_back(make_pair(start,end)); while(!p.empty()){ auto itr = p.top(); p.pop(); if(itr.second >= end){ start = itr.second; end = itr.first; ans.push_back(make_pair(start,end)); } } cout << \"Following Activities should be selected. \" << endl << endl; for(auto itr=ans.begin();itr!=ans.end();itr++){ cout << \"Activity started at: \" << (*itr).first << \" and ends at \" << (*itr).second << endl; }} // Driver programint main(){ vector<int>s = {1, 3, 0, 5, 8, 5}; vector<int>f = {2, 4, 6, 7, 9, 9}; SelectActivities(s,f); return 0;}", "e": 50828, "s": 49558, "text": null }, { "code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Pair class static class Pair { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } } static void SelectActivities(int s[], int f[]) { // Vector to store results. ArrayList<Pair> ans = new ArrayList<>(); // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). PriorityQueue<Pair> p = new PriorityQueue<>( (p1, p2) -> p1.first - p2.first); for (int i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.add(new Pair(f[i], s[i])); } Pair it = p.poll(); int start = it.second; int end = it.first; ans.add(new Pair(start, end)); while (!p.isEmpty()) { Pair itr = p.poll(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.add(new Pair(start, end)); } } System.out.println( \"Following Activities should be selected. \\n\"); for (Pair itr : ans) { System.out.println( \"Activity started at: \" + itr.first + \" and ends at \" + itr.second); } } // Driver Code public static void main(String[] args) { int s[] = { 1, 3, 0, 5, 8, 5 }; int f[] = { 2, 4, 6, 7, 9, 9 }; // Function call SelectActivities(s, f); }} // This code is contributed by Kingash.", "e": 52300, "s": 50828, "text": null }, { "code": "<script>// javascript program for the above approach // Pair classclass Pair{ constructor(first,second) { this.first = first; this.second = second; }} function SelectActivities(s,f){ // Vector to store results. let ans = []; // Minimum Priority Queue to sort activities in // ascending order of finishing time (f[i]). let p = []; for (let i = 0; i < s.length; i++) { // Pushing elements in priority queue where the // key is f[i] p.push(new Pair(f[i], s[i])); } p.sort(function(a,b){return a.first-b.first;}); let it = p.shift(); let start = it.second; let end = it.first; ans.push(new Pair(start, end)); while (p.length!=0) { let itr = p.shift(); if (itr.second >= end) { start = itr.second; end = itr.first; ans.push(new Pair(start, end)); } } document.write( \"Following Activities should be selected. <br>\"); for(let itr of ans.values()) { document.write( \"Activity started at: \" + itr.first + \" and ends at \" + itr.second+\"<br>\"); }} // Driver Codelet s=[1, 3, 0, 5, 8, 5 ];let f=[2, 4, 6, 7, 9, 9 ];// Function callSelectActivities(s, f); // This code is contributed by rag2127</script>", "e": 53561, "s": 52300, "text": null }, { "code": null, "e": 53756, "s": 53561, "text": "Following Activities should be selected. \n\nActivity started at: 1 and ends at 2\nActivity started at: 3 and ends at 4\nActivity started at: 5 and ends at 7\nActivity started at: 8 and ends at 9" }, { "code": null, "e": 53762, "s": 53756, "text": "ukasp" }, { "code": null, "e": 53775, "s": 53762, "text": "Akanksha_Rai" }, { "code": null, "e": 53787, "s": 53775, "text": "zafir_ahmad" }, { "code": null, "e": 53800, "s": 53787, "text": "kshitijjainm" }, { "code": null, "e": 53819, "s": 53800, "text": "shivanisinghss2110" }, { "code": null, "e": 53835, "s": 53819, "text": "dharanendralv23" }, { "code": null, "e": 53843, "s": 53835, "text": "Kingash" }, { "code": null, "e": 53864, "s": 53843, "text": "avanitrachhadiya2155" }, { "code": null, "e": 53880, "s": 53864, "text": "rohitsingh07052" }, { "code": null, "e": 53888, "s": 53880, "text": "rag2127" }, { "code": null, "e": 53895, "s": 53888, "text": "surajv" }, { "code": null, "e": 53915, "s": 53895, "text": "tejaskanikdaley1996" }, { "code": null, "e": 53931, "s": 53915, "text": "amartyaghoshgfg" }, { "code": null, "e": 53958, "s": 53931, "text": "Activity Selection Problem" }, { "code": null, "e": 53965, "s": 53958, "text": "Amazon" }, { "code": null, "e": 53974, "s": 53965, "text": "Facebook" }, { "code": null, "e": 53983, "s": 53974, "text": "Flipkart" }, { "code": null, "e": 53994, "s": 53983, "text": "MakeMyTrip" }, { "code": null, "e": 54009, "s": 53994, "text": "Morgan Stanley" }, { "code": null, "e": 54014, "s": 54009, "text": "Visa" }, { "code": null, "e": 54021, "s": 54014, "text": "Greedy" }, { "code": null, "e": 54030, "s": 54021, "text": "Flipkart" }, { "code": null, "e": 54045, "s": 54030, "text": "Morgan Stanley" }, { "code": null, "e": 54052, "s": 54045, "text": "Amazon" }, { "code": null, "e": 54063, "s": 54052, "text": "MakeMyTrip" }, { "code": null, "e": 54068, "s": 54063, "text": "Visa" }, { "code": null, "e": 54077, "s": 54068, "text": "Facebook" }, { "code": null, "e": 54084, "s": 54077, "text": "Greedy" }, { "code": null, "e": 54182, "s": 54084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54209, "s": 54182, "text": "Program for array rotation" }, { "code": null, "e": 54290, "s": 54209, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 54318, "s": 54290, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 54381, "s": 54318, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 54451, "s": 54381, "text": "Delete an element from array (Using two traversals and one traversal)" }, { "code": null, "e": 54502, "s": 54451, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 54571, "s": 54502, "text": "Program for Shortest Job First (SJF) scheduling | Set 2 (Preemptive)" }, { "code": null, "e": 54620, "s": 54571, "text": "Greedy Algorithm to find Minimum number of Coins" }, { "code": null, "e": 54678, "s": 54620, "text": "Difference between Prim's and Kruskal's algorithm for MST" } ]
How to create Python dictionary from JSON input?
You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } You can load it in your python program and loop over its keys in the following way: import json f = open('data.json') data = json.load(f) f.close() # Now you can use data as a normal dict: for (k, v) in data.items(): print("Key: " + k) print("Value: " + str(v)) This will give the output: Key: id Value: file Key: value Value: File Key: popup Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
[ { "code": null, "e": 1288, "s": 1062, "text": "You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content" }, { "code": null, "e": 1537, "s": 1288, "text": "{\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [\n {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n ]\n }\n}" }, { "code": null, "e": 1621, "s": 1537, "text": "You can load it in your python program and loop over its keys in the following way:" }, { "code": null, "e": 1685, "s": 1621, "text": "import json\nf = open('data.json')\ndata = json.load(f)\nf.close()" }, { "code": null, "e": 1726, "s": 1685, "text": "# Now you can use data as a normal dict:" }, { "code": null, "e": 1799, "s": 1726, "text": "for (k, v) in data.items():\nprint(\"Key: \" + k)\nprint(\"Value: \" + str(v))" }, { "code": null, "e": 1826, "s": 1799, "text": "This will give the output:" }, { "code": null, "e": 2037, "s": 1826, "text": "Key: id\nValue: file\nKey: value\nValue: File\nKey: popup\nValue: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}" } ]
Submit a form data using PHP, AJAX and Javascript
Theory of Computation In this article, you will learn how to submit a form data without refreshing the web page using PHP, Ajax and Javascript. Generally, we have all seen that when we submit some form or fetch some records, the page refreshing or reloading may take some time. We can do the same process without refreshing the web page using Ajax. Ajax is a technique to provide fast and dynamic web services. It updates or retrieves data asynchronously by exchanging data over the server. It has the ability to perform tasks on a web page without page refresh. To store the form data in the back-end, we must have a database. In this article, we have used the MySQL database. So, let's first create a database name Company in MySQL and a table name employee using the following MySQL statement. You can either use your existing database or copy paste the following command in your database. CREATE TABLE IF NOT EXISTS `employee` ( `emp_id` int(11) NOT NULL AUTO_INCREMENT, `emp_name` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `phone` int(11) NOT NULL, `address` varchar(50) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`emp_id`) ) Next, create a simple form 'employee_form.php' to get information from employee. This form contains all the fields that the employee table has. In this, we have included jQuery and Bootstrap libraries. <!DOCTYPE html> <html> <head> <title>Submit Form Using AJAX, PHP and javascript</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <link href="style.css" rel="stylesheet"> <script type="text/javascript" src="formscript.js"></script> </head> <body> <form id="emp_form" name="form"> <h3>New Employee Registration Form</h3> <div> <label>Employee Name* :</label> <input type="text" name="emp_name" id="emp_name" /> <label>Email* :</label> <input type="text" name="email" id="email" /> <label>Phone :</label> <input type="text" name="phone" id="phone" /> <label>Address :</label> <input type="text" name="address" id="address" /> <label>Username* :</label> <input type="text" name="username" id="username" /> <label>Password* : </label> <input type="password" name="password" id="password" /> <label> </label> <input id="submit" class="submit" onclick="formsubmit()" type="button" value="Submit"> </div> </form> <div id="clear"></div> </body> </html> The above file includes a css file name style.css and a javascript file name formscript.js. On click the submit button, formsubmit() method will be called which is defined in formscript.js file. The style.css file contains basic styles of the form. #emp_form{ width: 320px; height: 300px; border: 2px solid #4AD1E2; padding: 10px; margin-left:auto; margin-right: auto; font-family: sans-serif; } label { width: 150px; float: left; margin-right: 0.5em; display: block; margin-bottom: 7px; } input { color: #781351; background: #A2E7F0; border: 2px solid #4AD1E2; margin-bottom: 7px; } .submit { color: #000; background: #A2E7F0; border: 2px outset #4AD1E2; font-weight: bold; } #clear{clear:both; } The formscript.js file contains validation code and the else part of this code contains ajax codes which send the request to the PHP script with the form data and returns notification of a successful data submission. It sends the request without reloading the form. function formsubmit() { var empname = document.getElementById('emp_name').value; var email = document.getElementById('email').value; var phone = document.getElementById('phone').value; var address = document.getElementById('address').value; var username = document.getElementById('username').value; var pwd = document.getElementById('password').value; //store all the submitted data in astring. var formdata = 'empname=' + empname + '&emailid=' + email + '&phn=' + phone + '&address=' + address +'&uname=' + username+ '&password=' + pwd; // validate the form input if (empname == '' ) { alert("Please Enter Employee Name"); return false; } if(email == '') { alert("Please Enter Email id"); return false; } if(username == '') { alert("Please Enter Username"); return false; } if(pwd == '') { alert("Please Enter Password"); return false; } else { // AJAX code to submit form. $.ajax({ type: "POST", url: "storeempdata.php", //call storeemdata.php to store form data data: formdata, cache: false, success: function(html) { alert(html); } }); } return false; } In the above code, ajax code calls the storeemdata.php file to store the form data. Generally, we would send data to a server using POST request, the server handles it and sends a response back to the front-end. Instead of this, we have established the back-end connection here and captured the form data using Javascript and then, send an asynchronous request to the server for handling the response. We have used the improved version of MySQL, make sure to replace database credentials from yours. <?php $name = $_POST['empname']; $email = $_POST['emailid']; $phn = $_POST['phn']; $address = $_POST['address']; $uname = $_POST['uname']; $password = $_POST['password']; // Establishing Connection with Server.. $conn = new mysqli('localhost', 'root', '', 'company'); //Check for connection error if($conn->connect_error){ die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error); } // Selecting Database $db = mysql_select_db("company", $connection); // Selecting Database if (isset($_POST['empname'])) { //Insert Query $insert= "insert into employee(emp_id, emp_name , email, phone, address, username, password) values ('','$name', '$email', '$phn', '$address','$uname', '$password')"; if($conn->query($insert)){ echo 'Data inserted successfully'; } else{ echo 'Error '.$conn->error; } mysql_close($connection); // Connection Closed ?> The above code submits the form data to the employee table without reloading the page. After submitting the data, it returns 'Data inserted successfully' message and in case of failure, it returns an error message.
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 439, "s": 112, "text": "In this article, you will learn how to submit a form data without refreshing the web page using PHP, Ajax and Javascript. Generally, we have all seen that when we submit some form or fetch some records, the page refreshing or reloading may take some time. We can do the same process without refreshing the web page using Ajax." }, { "code": null, "e": 654, "s": 439, "text": "Ajax is a technique to provide fast and dynamic web services. It updates or retrieves data asynchronously by exchanging data over the server. It has the ability to perform tasks on a web page without page refresh. " }, { "code": null, "e": 984, "s": 654, "text": "To store the form data in the back-end, we must have a database. In this article, we have used the MySQL database. So, let's first create a database name Company in MySQL and a table name employee using the following MySQL statement. You can either use your existing database or copy paste the following command in your database." }, { "code": null, "e": 1296, "s": 984, "text": "\nCREATE TABLE IF NOT EXISTS `employee` (\n `emp_id` int(11) NOT NULL AUTO_INCREMENT,\n `emp_name` varchar(50) NOT NULL,\n `email` varchar(50) NOT NULL,\n `phone` int(11) NOT NULL,\n `address` varchar(50) NOT NULL,\n `username` varchar(50) NOT NULL,\n `password` varchar(50) NOT NULL,\n PRIMARY KEY (`emp_id`)\n)\n" }, { "code": null, "e": 1500, "s": 1296, "text": "Next, create a simple form 'employee_form.php' to get information from employee. This form contains all the fields that the employee table has. In this, we have included jQuery and Bootstrap libraries. " }, { "code": null, "e": 2561, "s": 1500, "text": "\n<!DOCTYPE html>\n<html>\n <head>\n <title>Submit Form Using AJAX, PHP and javascript</title>\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"></script>\n <link href=\"style.css\" rel=\"stylesheet\"> <script type=\"text/javascript\" src=\"formscript.js\"></script>\n </head>\n <body>\n <form id=\"emp_form\" name=\"form\">\n <h3>New Employee Registration Form</h3>\n <div>\n <label>Employee Name* :</label> \n <input type=\"text\" name=\"emp_name\" id=\"emp_name\" />\n <label>Email* :</label> \n <input type=\"text\" name=\"email\" id=\"email\" />\n <label>Phone :</label> \n <input type=\"text\" name=\"phone\" id=\"phone\" />\n <label>Address :</label> \n <input type=\"text\" name=\"address\" id=\"address\" />\n <label>Username* :</label> \n <input type=\"text\" name=\"username\" id=\"username\" />\n <label>Password* : </label> \n <input type=\"password\" name=\"password\" id=\"password\" /> <label> </label> \n <input id=\"submit\" class=\"submit\" onclick=\"formsubmit()\" type=\"button\" value=\"Submit\">\n </div>\n </form>\n <div id=\"clear\"></div>\n</body>\n</html>\n" }, { "code": null, "e": 2757, "s": 2561, "text": "The above file includes a css file name style.css and a javascript file name formscript.js. On click the submit button, formsubmit() method will be called which is defined in formscript.js file. " }, { "code": null, "e": 2811, "s": 2757, "text": "The style.css file contains basic styles of the form." }, { "code": null, "e": 3339, "s": 2811, "text": "\n#emp_form{\n width: 320px;\n height: 300px; \n border: 2px solid #4AD1E2;\n padding: 10px;\n margin-left:auto;\n margin-right: auto;\n font-family: sans-serif;\n}\nlabel\n{\n width: 150px;\n float: left;\n margin-right: 0.5em;\n display: block;\n margin-bottom: 7px; \n}\ninput\n{\n color: #781351;\n background: #A2E7F0;\n border: 2px solid #4AD1E2;\n margin-bottom: 7px; \n}\n.submit\n{\n color: #000;\n background: #A2E7F0;\n border: 2px outset #4AD1E2;\n font-weight: bold;\n} \n#clear{clear:both; }\n" }, { "code": null, "e": 3605, "s": 3339, "text": "The formscript.js file contains validation code and the else part of this code contains ajax codes which send the request to the PHP script with the form data and returns notification of a successful data submission. It sends the request without reloading the form." }, { "code": null, "e": 4750, "s": 3605, "text": "\nfunction formsubmit() {\n var empname = document.getElementById('emp_name').value;\n var email = document.getElementById('email').value;\n var phone = document.getElementById('phone').value;\n var address = document.getElementById('address').value;\n var username = document.getElementById('username').value;\n var pwd = document.getElementById('password').value;\n //store all the submitted data in astring.\n var formdata = 'empname=' + empname + '&emailid=' + email + '&phn=' + phone + '&address=' + address +'&uname=' + username+ '&password=' + pwd;\n\t// validate the form input\n\tif (empname == '' ) {\n\t\talert(\"Please Enter Employee Name\");\n\t\treturn false;\n\t}\n\tif(email == '') {\n\t\talert(\"Please Enter Email id\");\n\t\treturn false;\n\t}\n\tif(username == '') {\n\t\talert(\"Please Enter Username\");\n\t\treturn false;\n\t}\n\tif(pwd == '') {\n\t\talert(\"Please Enter Password\");\n\t\treturn false;\n\t}\n\telse {\n\t// AJAX code to submit form.\n\t$.ajax({\n\t\t type: \"POST\",\n\t\t url: \"storeempdata.php\", //call storeemdata.php to store form data\n\t\t data: formdata,\n\t\t cache: false,\n\t\t success: function(html) {\n\t\t alert(html);\n\t\t }\n\t});\n\t}\n\treturn false;\n}\n" }, { "code": null, "e": 5251, "s": 4750, "text": "In the above code, ajax code calls the storeemdata.php file to store the form data. Generally, we would send data to a server using POST request, the server handles it and sends a response back to the front-end. Instead of this, we have established the back-end connection here and captured the form data using Javascript and then, send an asynchronous request to the server for handling the response. We have used the improved version of MySQL, make sure to replace database credentials from yours. " }, { "code": null, "e": 6135, "s": 5251, "text": "<?php\n$name = $_POST['empname'];\n$email = $_POST['emailid'];\n$phn = $_POST['phn'];\n$address = $_POST['address'];\n$uname = $_POST['uname'];\n$password = $_POST['password'];\n\n// Establishing Connection with Server..\n$conn = new mysqli('localhost', 'root', '', 'company');\n\n//Check for connection error\nif($conn->connect_error){\n die(\"Error in DB connection: \".$conn->connect_errno.\" : \".$conn->connect_error); \n}\n// Selecting Database\n$db = mysql_select_db(\"company\", $connection); // Selecting Database\n\nif (isset($_POST['empname'])) {\n\n//Insert Query\n$insert= \"insert into employee(emp_id, emp_name , email, phone, address, username, password) \nvalues ('','$name', '$email', '$phn', '$address','$uname', '$password')\"; \n\nif($conn->query($insert)){\n echo 'Data inserted successfully';\n}\nelse{\n echo 'Error '.$conn->error; \n}\n\nmysql_close($connection); // Connection Closed\n?> \n" } ]
How to extract the attribute value of an element in Selenium?
We can extract the attribute value of an element in Selenium with the help of getAttribute() method. Once we locate the element, this method is used to get the attribute value of the element and assigned to a variable. import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class AttributeType { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); //Using id tagname attribute combination for css expression WebElement button = driver.findElement(By.cssSelector("input[name=’search’]")); // getting the type attribute and printing in console String buttontype = button.getAttribute(“type”); System.out.println(“Attribute value is “ + buttontype); driver.close(); } }
[ { "code": null, "e": 1281, "s": 1062, "text": "We can extract the attribute value of an element in Selenium with the help of getAttribute() method. Once we locate the element, this method is used to get the attribute value of the element and assigned to a variable." }, { "code": null, "e": 2272, "s": 1281, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class AttributeType {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n //Using id tagname attribute combination for css expression\n WebElement button = driver.findElement(By.cssSelector(\"input[name=’search’]\"));\n // getting the type attribute and printing in console\n String buttontype = button.getAttribute(“type”);\n System.out.println(“Attribute value is “ + buttontype);\n driver.close();\n }\n}" } ]
AngularJS | angular.bind() Function - GeeksforGeeks
30 Mar, 2021 The angular.bind() Function in AngularJS is used to bind the current context to a function, but actually execute it at a later time. It can also be used in Partial Applications. Partial Applications is when you want to make a function but some of the arguments have been passed already.Syntax: angular.bind(self, function, args); Parameter Values: self: This refers to the context in which the function should be evaluated. function: It refers to the function to be bound. args: It is used to prebound to the function at the time of function call. It is an optional argument. Example 1: html <html> <head> <title>angular.bind()</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:Center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.bind()</h2> <p>Input number to sum with 5: <div ng-controller="geek"> <input type="number" ng-model="num" ng-change="Func()" /> <br>Sum = {{Add}} </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.num = 0; $scope.Func = function () { var add = angular.bind(this, function (a, b) { return a + b; }); $scope.Add = add(5, $scope.num); } }]); </script> </body></html> Output: Before Input: After Input: Example 2: html <html> <head> <title>angular.bind()</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:Center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.bind()</h2> <div ng-controller="geek"> Input A: <input type="number" ng-model="val1" ng-change="GetResult()" /> <br><br> Input B: <input type="number" ng-model="val2" ng-change="GetResult()" /> <br /><br> {{result}} </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { function isEqual(a, b) { if (a == b) { return "Inputs are equal." } else if (a >= b) { return "A is greater than B." } else if (a <= b) { return "A is lesser than B." } } $scope.GetResult = function () { var result = angular.bind(this, isEqual); $scope.result = result($scope.val1, $scope.val2); } }]); </script> </body></html> Output: Before Input: After Input: simranarora5sos AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n30 Mar, 2021" }, { "code": null, "e": 26650, "s": 26354, "text": "The angular.bind() Function in AngularJS is used to bind the current context to a function, but actually execute it at a later time. It can also be used in Partial Applications. Partial Applications is when you want to make a function but some of the arguments have been passed already.Syntax: " }, { "code": null, "e": 26686, "s": 26650, "text": "angular.bind(self, function, args);" }, { "code": null, "e": 26706, "s": 26686, "text": "Parameter Values: " }, { "code": null, "e": 26782, "s": 26706, "text": "self: This refers to the context in which the function should be evaluated." }, { "code": null, "e": 26831, "s": 26782, "text": "function: It refers to the function to be bound." }, { "code": null, "e": 26934, "s": 26831, "text": "args: It is used to prebound to the function at the time of function call. It is an optional argument." }, { "code": null, "e": 26947, "s": 26934, "text": "Example 1: " }, { "code": null, "e": 26952, "s": 26947, "text": "html" }, { "code": "<html> <head> <title>angular.bind()</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:Center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.bind()</h2> <p>Input number to sum with 5: <div ng-controller=\"geek\"> <input type=\"number\" ng-model=\"num\" ng-change=\"Func()\" /> <br>Sum = {{Add}} </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.num = 0; $scope.Func = function () { var add = angular.bind(this, function (a, b) { return a + b; }); $scope.Add = add(5, $scope.num); } }]); </script> </body></html>", "e": 27853, "s": 26952, "text": null }, { "code": null, "e": 27877, "s": 27853, "text": "Output: Before Input: " }, { "code": null, "e": 27892, "s": 27877, "text": "After Input: " }, { "code": null, "e": 27904, "s": 27892, "text": "Example 2: " }, { "code": null, "e": 27909, "s": 27904, "text": "html" }, { "code": "<html> <head> <title>angular.bind()</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:Center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.bind()</h2> <div ng-controller=\"geek\"> Input A: <input type=\"number\" ng-model=\"val1\" ng-change=\"GetResult()\" /> <br><br> Input B: <input type=\"number\" ng-model=\"val2\" ng-change=\"GetResult()\" /> <br /><br> {{result}} </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { function isEqual(a, b) { if (a == b) { return \"Inputs are equal.\" } else if (a >= b) { return \"A is greater than B.\" } else if (a <= b) { return \"A is lesser than B.\" } } $scope.GetResult = function () { var result = angular.bind(this, isEqual); $scope.result = result($scope.val1, $scope.val2); } }]); </script> </body></html>", "e": 29201, "s": 27909, "text": null }, { "code": null, "e": 29225, "s": 29201, "text": "Output: Before Input: " }, { "code": null, "e": 29240, "s": 29225, "text": "After Input: " }, { "code": null, "e": 29258, "s": 29242, "text": "simranarora5sos" }, { "code": null, "e": 29268, "s": 29258, "text": "AngularJS" }, { "code": null, "e": 29285, "s": 29268, "text": "Web Technologies" }, { "code": null, "e": 29383, "s": 29285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29418, "s": 29383, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29453, "s": 29418, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29477, "s": 29453, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29512, "s": 29477, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29565, "s": 29512, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29605, "s": 29565, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29638, "s": 29605, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29683, "s": 29638, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29726, "s": 29683, "text": "How to fetch data from an API in ReactJS ?" } ]
Minimum operations to convert an Array into a Permutation of 1 to N by replacing with remainder from some d - GeeksforGeeks
12 Jan, 2022 Given an array arr[] of size N, the task is to find the minimum number of operations to convert the array into a permutation of [1, n], in each operation, an element a[i] can be replaced by a[i] % d where d can be different in each operation performed. If it is not possible print -1. Examples: Input: arr[] = {5, 4, 10, 8, 1}Output: 2 Explanation: In first operation choosing d = 7 , 10 can be replaced by 10 % 7 , In second operation d = 6, 8 can be replaced by 8 %6 so two operations. Input : arr[] = {1, 2, 3, 7}Output: -1 Approach: The task can be solved using the greedy approach. This approach is based on the fact that when remainder r is to be obtained, then a[i] > 2*r i.e r lies between the range [0, a[i]-1 /2] Let us take an example: 8 for different d Taking, 8 % 7= 1 8%6 = 2 8%5 = 3 8%4 = 0 8%3 = 2 8%2 = 0 8%1=0 So maximum number that can be obtained is 3 using mod operation, so when we want to obtain a number i in a permutation then the number should a[i] > 2* i+1 Follow these steps to solve this problem: Initialize a set s Traverse through the array arr[] & insert all the elements of arr[] into the set. Initialize a variable ops = 0 Now iterate from n to 1 Check if s has i already if it has removed it from the set. Else increment ops and check if the largest element of the set < 2* i +1 If the largest of the set is < 2* i +1 then set ops = -1 and break out of the loop. Else erase it from the set because we can make it i using mod operation. Print the ops `Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum operations// to convert the array into a permutation of [1, n]void minimum_operations(int arr[], int n){ // Initialize the set set<int> s; // Insert all the elements into the set for (int i = 0; i < n; i++) { s.insert(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.find(i) != s.end()) { s.erase(s.find(i)); } // count the ops because there is no element else { ops++; // Check the largest element of the set auto it = s.end(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (*it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.erase(it); } } // Print the result cout << ops << endl;} // Driver Codeint main(){ // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); minimum_operations(arr, n); return 0;} // Java code for the above approachimport java.util.*; class GFG{ // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int arr[], int n) { // Initialize the set SortedSet<Integer> s = new TreeSet<Integer>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.contains(i)) { s.remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set Integer it = s.last(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.remove(it); } } // Print the result System.out.print(ops +"\n"); } // Driver Code public static void main(String[] args) { // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = arr.length; minimum_operations(arr, n); }} // This code is contributed by 29AjayKumar # Python 3 code for the above approach # Function to find the minimum operations# to convert the array into a permutation of [1, n]def minimum_operations(arr, n): # Initialize the set s = set([]) # Insert all the elements into the set for i in range(n): s.add(arr[i]) # Initialize ops to count the operations ops = 0 # Traverse from [n to 1] for i in range(n, 0, -1): # If we already have i in our # array erase it from the set if (i in s): list(s).remove(i) # count the ops because there is no element else: ops += 1 # Check the largest element of the set it = len(s) it -= 1 # If it is < 2*i +1 we cant get that i # using % operation so there is no way to # create a permutation if (list(s)[it] < 2 * i + 1): ops = -1 break # Erase it if we have processed # it to i by % operation list(s).pop(it) # Print the result print(ops) # Driver Codeif __name__ == "__main__": # Initialize the value n arr = [5, 4, 10, 8, 1] n = len(arr) minimum_operations(arr, n) # This code is contributed by ukasp. // C# code for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int []arr, int n) { // Initialize the set SortedSet<int> s = new SortedSet<int>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.Add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.Contains(i)) { s.Remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set int it = s.Max; it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.Remove(it); } } // Print the result Console.Write(ops +"\n"); } // Driver Code public static void Main(String[] args) { // Initialize the value n int []arr = { 5, 4, 10, 8, 1 }; int n = arr.Length; minimum_operations(arr, n); }} // This code is contributed by 29AjayKumar <script>// Javascript code for the above approach // Function to find the minimum operations// to convert the array into a permutation of [1, n]function minimum_operations(arr, n){ // Initialize the set var s = new Set(); // Insert all the elements into the set for (var i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations var ops = 0; // Traverse from [n to 1] for (var i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.has(i)) { s.delete(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set var it = Math.max(...Array.from(s.values())); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.delete(it); } } // Print the result document.write(ops +"<br>");} // Driver Code // Initialize the value nvar arr = [ 5, 4, 10, 8, 1 ];var n = arr.length;minimum_operations(arr, n); // This code is contributed by Shubham Singh</script> 2 Time Complexity: O(nlogn)Auxiliary Space: O(n) ukasp 29AjayKumar shikhasingrajput SHUBHAMSINGH10 Algo-Geek 2021 permutation Algo Geek Arrays Greedy Arrays Greedy permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Lexicographically smallest string formed by concatenating any prefix and its mirrored form Check if the given string is valid English word or not Divide given number into two even parts Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Check if an edge is a part of any Minimum Spanning Tree Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 26352, "s": 26324, "text": "\n12 Jan, 2022" }, { "code": null, "e": 26637, "s": 26352, "text": "Given an array arr[] of size N, the task is to find the minimum number of operations to convert the array into a permutation of [1, n], in each operation, an element a[i] can be replaced by a[i] % d where d can be different in each operation performed. If it is not possible print -1." }, { "code": null, "e": 26647, "s": 26637, "text": "Examples:" }, { "code": null, "e": 26842, "s": 26647, "text": "Input: arr[] = {5, 4, 10, 8, 1}Output: 2 Explanation: In first operation choosing d = 7 , 10 can be replaced by 10 % 7 , In second operation d = 6, 8 can be replaced by 8 %6 so two operations." }, { "code": null, "e": 26881, "s": 26842, "text": "Input : arr[] = {1, 2, 3, 7}Output: -1" }, { "code": null, "e": 27081, "s": 26881, "text": "Approach: The task can be solved using the greedy approach. This approach is based on the fact that when remainder r is to be obtained, then a[i] > 2*r i.e r lies between the range [0, a[i]-1 /2] " }, { "code": null, "e": 27123, "s": 27081, "text": "Let us take an example: 8 for different d" }, { "code": null, "e": 27140, "s": 27123, "text": "Taking, 8 % 7= 1" }, { "code": null, "e": 27159, "s": 27140, "text": " 8%6 = 2" }, { "code": null, "e": 27178, "s": 27159, "text": " 8%5 = 3" }, { "code": null, "e": 27196, "s": 27178, "text": " 8%4 = 0" }, { "code": null, "e": 27214, "s": 27196, "text": " 8%3 = 2" }, { "code": null, "e": 27232, "s": 27214, "text": " 8%2 = 0" }, { "code": null, "e": 27248, "s": 27232, "text": " 8%1=0" }, { "code": null, "e": 27404, "s": 27248, "text": "So maximum number that can be obtained is 3 using mod operation, so when we want to obtain a number i in a permutation then the number should a[i] > 2* i+1" }, { "code": null, "e": 27446, "s": 27404, "text": "Follow these steps to solve this problem:" }, { "code": null, "e": 27466, "s": 27446, "text": "Initialize a set s " }, { "code": null, "e": 27548, "s": 27466, "text": "Traverse through the array arr[] & insert all the elements of arr[] into the set." }, { "code": null, "e": 27578, "s": 27548, "text": "Initialize a variable ops = 0" }, { "code": null, "e": 27602, "s": 27578, "text": "Now iterate from n to 1" }, { "code": null, "e": 27662, "s": 27602, "text": "Check if s has i already if it has removed it from the set." }, { "code": null, "e": 27736, "s": 27662, "text": "Else increment ops and check if the largest element of the set < 2* i +1" }, { "code": null, "e": 27820, "s": 27736, "text": "If the largest of the set is < 2* i +1 then set ops = -1 and break out of the loop." }, { "code": null, "e": 27893, "s": 27820, "text": "Else erase it from the set because we can make it i using mod operation." }, { "code": null, "e": 27907, "s": 27893, "text": "Print the ops" }, { "code": null, "e": 27959, "s": 27907, "text": "`Below is the implementation of the above approach:" }, { "code": null, "e": 27963, "s": 27959, "text": "C++" }, { "code": null, "e": 27968, "s": 27963, "text": "Java" }, { "code": null, "e": 27976, "s": 27968, "text": "Python3" }, { "code": null, "e": 27979, "s": 27976, "text": "C#" }, { "code": null, "e": 27990, "s": 27979, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum operations// to convert the array into a permutation of [1, n]void minimum_operations(int arr[], int n){ // Initialize the set set<int> s; // Insert all the elements into the set for (int i = 0; i < n; i++) { s.insert(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.find(i) != s.end()) { s.erase(s.find(i)); } // count the ops because there is no element else { ops++; // Check the largest element of the set auto it = s.end(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (*it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.erase(it); } } // Print the result cout << ops << endl;} // Driver Codeint main(){ // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); minimum_operations(arr, n); return 0;}", "e": 29396, "s": 27990, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int arr[], int n) { // Initialize the set SortedSet<Integer> s = new TreeSet<Integer>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.contains(i)) { s.remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set Integer it = s.last(); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.remove(it); } } // Print the result System.out.print(ops +\"\\n\"); } // Driver Code public static void main(String[] args) { // Initialize the value n int arr[] = { 5, 4, 10, 8, 1 }; int n = arr.length; minimum_operations(arr, n); }} // This code is contributed by 29AjayKumar", "e": 30805, "s": 29396, "text": null }, { "code": "# Python 3 code for the above approach # Function to find the minimum operations# to convert the array into a permutation of [1, n]def minimum_operations(arr, n): # Initialize the set s = set([]) # Insert all the elements into the set for i in range(n): s.add(arr[i]) # Initialize ops to count the operations ops = 0 # Traverse from [n to 1] for i in range(n, 0, -1): # If we already have i in our # array erase it from the set if (i in s): list(s).remove(i) # count the ops because there is no element else: ops += 1 # Check the largest element of the set it = len(s) it -= 1 # If it is < 2*i +1 we cant get that i # using % operation so there is no way to # create a permutation if (list(s)[it] < 2 * i + 1): ops = -1 break # Erase it if we have processed # it to i by % operation list(s).pop(it) # Print the result print(ops) # Driver Codeif __name__ == \"__main__\": # Initialize the value n arr = [5, 4, 10, 8, 1] n = len(arr) minimum_operations(arr, n) # This code is contributed by ukasp.", "e": 32060, "s": 30805, "text": null }, { "code": "// C# code for the above approachusing System;using System.Collections.Generic; public class GFG{ // Function to find the minimum operations // to convert the array into a permutation of [1, n] static void minimum_operations(int []arr, int n) { // Initialize the set SortedSet<int> s = new SortedSet<int>(); // Insert all the elements into the set for (int i = 0; i < n; i++) { s.Add(arr[i]); } // Initialize ops to count the operations int ops = 0; // Traverse from [n to 1] for (int i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.Contains(i)) { s.Remove(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set int it = s.Max; it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.Remove(it); } } // Print the result Console.Write(ops +\"\\n\"); } // Driver Code public static void Main(String[] args) { // Initialize the value n int []arr = { 5, 4, 10, 8, 1 }; int n = arr.Length; minimum_operations(arr, n); }} // This code is contributed by 29AjayKumar", "e": 33486, "s": 32060, "text": null }, { "code": "<script>// Javascript code for the above approach // Function to find the minimum operations// to convert the array into a permutation of [1, n]function minimum_operations(arr, n){ // Initialize the set var s = new Set(); // Insert all the elements into the set for (var i = 0; i < n; i++) { s.add(arr[i]); } // Initialize ops to count the operations var ops = 0; // Traverse from [n to 1] for (var i = n; i >= 1; i--) { // If we already have i in our // array erase it from the set if (s.has(i)) { s.delete(i); } // count the ops because there is no element else { ops++; // Check the largest element of the set var it = Math.max(...Array.from(s.values())); it--; // If it is < 2*i +1 we cant get that i // using % operation so there is no way to // create a permutation if (it < 2 * i + 1) { ops = -1; break; } // Erase it if we have processed // it to i by % operation s.delete(it); } } // Print the result document.write(ops +\"<br>\");} // Driver Code // Initialize the value nvar arr = [ 5, 4, 10, 8, 1 ];var n = arr.length;minimum_operations(arr, n); // This code is contributed by Shubham Singh</script>", "e": 34911, "s": 33486, "text": null }, { "code": null, "e": 34916, "s": 34914, "text": "2" }, { "code": null, "e": 34965, "s": 34918, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(n)" }, { "code": null, "e": 34973, "s": 34967, "text": "ukasp" }, { "code": null, "e": 34985, "s": 34973, "text": "29AjayKumar" }, { "code": null, "e": 35002, "s": 34985, "text": "shikhasingrajput" }, { "code": null, "e": 35017, "s": 35002, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 35032, "s": 35017, "text": "Algo-Geek 2021" }, { "code": null, "e": 35044, "s": 35032, "text": "permutation" }, { "code": null, "e": 35054, "s": 35044, "text": "Algo Geek" }, { "code": null, "e": 35061, "s": 35054, "text": "Arrays" }, { "code": null, "e": 35068, "s": 35061, "text": "Greedy" }, { "code": null, "e": 35075, "s": 35068, "text": "Arrays" }, { "code": null, "e": 35082, "s": 35075, "text": "Greedy" }, { "code": null, "e": 35094, "s": 35082, "text": "permutation" }, { "code": null, "e": 35192, "s": 35094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35201, "s": 35192, "text": "Comments" }, { "code": null, "e": 35214, "s": 35201, "text": "Old Comments" }, { "code": null, "e": 35305, "s": 35214, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 35360, "s": 35305, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 35400, "s": 35360, "text": "Divide given number into two even parts" }, { "code": null, "e": 35480, "s": 35400, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 35536, "s": 35480, "text": "Check if an edge is a part of any Minimum Spanning Tree" }, { "code": null, "e": 35551, "s": 35536, "text": "Arrays in Java" }, { "code": null, "e": 35567, "s": 35551, "text": "Arrays in C/C++" }, { "code": null, "e": 35594, "s": 35567, "text": "Program for array rotation" }, { "code": null, "e": 35642, "s": 35594, "text": "Stack Data Structure (Introduction and Program)" } ]
Convert decimal point numbers to percentage using filters in Vue.js - GeeksforGeeks
17 Mar, 2021 Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template. The conversion from a decimal number to percentage values can be done using filters. The logic of the filter will first check if the number is less than or equal to 1. When the user provides a number that is greater than 1, a message is displayed asking the user to enter a valid number, otherwise, we will multiply the number by 100 and return it by appending a percentage sign (%). index.html <html><head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script></head><body> <div id='parent'> <p><strong>Decimal1: </strong> {{dec1}} </p> <p><strong>Percentage : </strong> {{ dec1 | percent }} </p> <p><strong>Decimal2: </strong> {{dec2}} </p> <p><strong>Percentage : </strong> {{ dec2 | percent }} </p> <p><strong>Decimal3: </strong> {{dec3}} </p> <p><strong>Percentage : </strong> {{ dec3 | percent }} </p> <p><strong>Decimal4: </strong> {{dec4}} </p> <p><strong>Percentage : </strong> {{ dec4 | percent }} </p> </div> <script src='app.js'></script></body></html> app.js const parent = new Vue({ el: '#parent', data: { dec1: 0.1, dec2: 0.023, dec3: 0.47, dec4: 13 }, filters: { percent: function(dec) { if (dec <= 1) { return dec * 100 + "%"; } return 'Please enter number less than or equal to 1' } }}) Output: Decimal to percentage using filter Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26858, "s": 26545, "text": "Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries." }, { "code": null, "e": 27213, "s": 26858, "text": "Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template." }, { "code": null, "e": 27597, "s": 27213, "text": "The conversion from a decimal number to percentage values can be done using filters. The logic of the filter will first check if the number is less than or equal to 1. When the user provides a number that is greater than 1, a message is displayed asking the user to enter a valid number, otherwise, we will multiply the number by 100 and return it by appending a percentage sign (%)." }, { "code": null, "e": 27608, "s": 27597, "text": "index.html" }, { "code": "<html><head> <script src=\"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js\"> </script></head><body> <div id='parent'> <p><strong>Decimal1: </strong> {{dec1}} </p> <p><strong>Percentage : </strong> {{ dec1 | percent }} </p> <p><strong>Decimal2: </strong> {{dec2}} </p> <p><strong>Percentage : </strong> {{ dec2 | percent }} </p> <p><strong>Decimal3: </strong> {{dec3}} </p> <p><strong>Percentage : </strong> {{ dec3 | percent }} </p> <p><strong>Decimal4: </strong> {{dec4}} </p> <p><strong>Percentage : </strong> {{ dec4 | percent }} </p> </div> <script src='app.js'></script></body></html>", "e": 28397, "s": 27608, "text": null }, { "code": null, "e": 28404, "s": 28397, "text": "app.js" }, { "code": "const parent = new Vue({ el: '#parent', data: { dec1: 0.1, dec2: 0.023, dec3: 0.47, dec4: 13 }, filters: { percent: function(dec) { if (dec <= 1) { return dec * 100 + \"%\"; } return 'Please enter number less than or equal to 1' } }})", "e": 28744, "s": 28404, "text": null }, { "code": null, "e": 28752, "s": 28744, "text": "Output:" }, { "code": null, "e": 28787, "s": 28752, "text": "Decimal to percentage using filter" }, { "code": null, "e": 28794, "s": 28787, "text": "Vue.JS" }, { "code": null, "e": 28805, "s": 28794, "text": "JavaScript" }, { "code": null, "e": 28822, "s": 28805, "text": "Web Technologies" }, { "code": null, "e": 28920, "s": 28822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28960, "s": 28920, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29021, "s": 28960, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29062, "s": 29021, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29084, "s": 29062, "text": "JavaScript | Promises" }, { "code": null, "e": 29138, "s": 29084, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29178, "s": 29138, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29211, "s": 29178, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29254, "s": 29211, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29304, "s": 29254, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create Password Protected Zip of a file using Python - GeeksforGeeks
24 Jan, 2021 ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together. In this article, we will learn how to Create Password-Protected Zip of a file using Python. For this, we are using pyminizip module from python. The pyminizip module can be installed using the below command: pip install pyminizip For creating zip, we are using compress() method from pyminizip. So, we discuss first its syntax and arguments. pyminizip.compress(“/srcfile/path.txt”, “file_path_prefix”, “/distfile/path.zip”, “password”, int(compress_level)) Arguments: src file path (string) src file prefix path (string) or None (path to prepend to file) dst file path (string) password (string) or None (to create no-password zip) compress_level(int) between 1 to 9, 1 (more fast) <—> 9 (more compress) or 0 (default) Return value: Always returns None Input file: Program: Python3 # importing moduleimport pyminizip # input file pathinpt = "./Text.txt" # prefix pathpre = None # output zip file pathoupt = "./output.zip" # set password valuepassword = "GFG" # compress levelcom_lvl = 5 # compressing filepyminizip.compress(inpt, None, oupt, password, com_lvl) Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24664, "s": 24292, "text": "ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together." }, { "code": null, "e": 24809, "s": 24664, "text": "In this article, we will learn how to Create Password-Protected Zip of a file using Python. For this, we are using pyminizip module from python." }, { "code": null, "e": 24873, "s": 24809, "text": " The pyminizip module can be installed using the below command:" }, { "code": null, "e": 24895, "s": 24873, "text": "pip install pyminizip" }, { "code": null, "e": 25007, "s": 24895, "text": "For creating zip, we are using compress() method from pyminizip. So, we discuss first its syntax and arguments." }, { "code": null, "e": 25122, "s": 25007, "text": "pyminizip.compress(“/srcfile/path.txt”, “file_path_prefix”, “/distfile/path.zip”, “password”, int(compress_level))" }, { "code": null, "e": 25133, "s": 25122, "text": "Arguments:" }, { "code": null, "e": 25156, "s": 25133, "text": "src file path (string)" }, { "code": null, "e": 25220, "s": 25156, "text": "src file prefix path (string) or None (path to prepend to file)" }, { "code": null, "e": 25243, "s": 25220, "text": "dst file path (string)" }, { "code": null, "e": 25297, "s": 25243, "text": "password (string) or None (to create no-password zip)" }, { "code": null, "e": 25385, "s": 25297, "text": "compress_level(int) between 1 to 9, 1 (more fast) <—> 9 (more compress) or 0 (default) " }, { "code": null, "e": 25419, "s": 25385, "text": "Return value: Always returns None" }, { "code": null, "e": 25431, "s": 25419, "text": "Input file:" }, { "code": null, "e": 25440, "s": 25431, "text": "Program:" }, { "code": null, "e": 25448, "s": 25440, "text": "Python3" }, { "code": "# importing moduleimport pyminizip # input file pathinpt = \"./Text.txt\" # prefix pathpre = None # output zip file pathoupt = \"./output.zip\" # set password valuepassword = \"GFG\" # compress levelcom_lvl = 5 # compressing filepyminizip.compress(inpt, None, oupt, password, com_lvl)", "e": 25751, "s": 25448, "text": null }, { "code": null, "e": 25759, "s": 25751, "text": "Output:" }, { "code": null, "e": 25774, "s": 25759, "text": "python-utility" }, { "code": null, "e": 25781, "s": 25774, "text": "Python" }, { "code": null, "e": 25879, "s": 25781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25911, "s": 25879, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25953, "s": 25911, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26009, "s": 25953, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26051, "s": 26009, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26082, "s": 26051, "text": "Python | os.path.join() method" }, { "code": null, "e": 26137, "s": 26082, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26159, "s": 26137, "text": "Defaultdict in Python" }, { "code": null, "e": 26198, "s": 26159, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26227, "s": 26198, "text": "Create a directory in Python" } ]
MySQL query to get the current date records wherein one of the columns displays current date
To achieve this, following is the syntax wherein we have used DATE(NOW()) − select *from yourTableName where DATE(yourColumnName)=DATE(NOW()); Let us first create a table − mysql> create table DemoTable706 ( UserId varchar(100), UserName varchar(100), UserSignupDate datetime ); Query OK, 0 rows affected (0.57 sec) Insert some records in the table using insert command − mysql> insert into DemoTable706 values('John1@gmail.com','John','2019-01-31 12:45:22'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable706 values('Chris123@gmail.com','Chris','2019-07-22 10:05:02'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable706 values('12Robert@gmail.com','Robert','2019-06-22 11:25:22'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable706 values('DavidM@gmail.com','David','2019-07-22 00:00:02'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable706; This will produce the following output - +--------------------+----------+---------------------+ | UserId | UserName | UserSignupDate | +--------------------+----------+---------------------+ | John1@gmail.com | John | 2019-01-31 12:45:22 | | Chris123@gmail.com | Chris | 2019-07-22 10:05:02 | | 12Robert@gmail.com | Robert | 2019-06-22 11:25:22 | | DavidM@gmail.com | David | 2019-07-22 00:00:02 | +--------------------+----------+---------------------+ 4 rows in set (0.00 sec) Following is the query to get records wherein one of the columns displays current date − mysql> select *from DemoTable706 where DATE(UserSignupDate)=DATE(NOW()); This will produce the following output - +--------------------+----------+---------------------+ | UserId | UserName | UserSignupDate | +--------------------+----------+---------------------+ | Chris123@gmail.com | Chris | 2019-07-22 10:05:02 | | DavidM@gmail.com | David | 2019-07-22 00:00:02 | +--------------------+----------+---------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "To achieve this, following is the syntax wherein we have used DATE(NOW()) −" }, { "code": null, "e": 1205, "s": 1138, "text": "select *from yourTableName where DATE(yourColumnName)=DATE(NOW());" }, { "code": null, "e": 1235, "s": 1205, "text": "Let us first create a table −" }, { "code": null, "e": 1387, "s": 1235, "text": "mysql> create table DemoTable706 (\n UserId varchar(100),\n UserName varchar(100),\n UserSignupDate datetime\n);\nQuery OK, 0 rows affected (0.57 sec)" }, { "code": null, "e": 1443, "s": 1387, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1950, "s": 1443, "text": "mysql> insert into DemoTable706 values('John1@gmail.com','John','2019-01-31 12:45:22');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable706 values('Chris123@gmail.com','Chris','2019-07-22 10:05:02');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable706 values('12Robert@gmail.com','Robert','2019-06-22 11:25:22');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable706 values('DavidM@gmail.com','David','2019-07-22 00:00:02');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2010, "s": 1950, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2044, "s": 2010, "text": "mysql> select *from DemoTable706;" }, { "code": null, "e": 2085, "s": 2044, "text": "This will produce the following output -" }, { "code": null, "e": 2558, "s": 2085, "text": "+--------------------+----------+---------------------+\n| UserId | UserName | UserSignupDate |\n+--------------------+----------+---------------------+\n| John1@gmail.com | John | 2019-01-31 12:45:22 |\n| Chris123@gmail.com | Chris | 2019-07-22 10:05:02 |\n| 12Robert@gmail.com | Robert | 2019-06-22 11:25:22 |\n| DavidM@gmail.com | David | 2019-07-22 00:00:02 |\n+--------------------+----------+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2647, "s": 2558, "text": "Following is the query to get records wherein one of the columns displays current date −" }, { "code": null, "e": 2720, "s": 2647, "text": "mysql> select *from DemoTable706 where DATE(UserSignupDate)=DATE(NOW());" }, { "code": null, "e": 2761, "s": 2720, "text": "This will produce the following output -" }, { "code": null, "e": 3122, "s": 2761, "text": "+--------------------+----------+---------------------+\n| UserId | UserName | UserSignupDate |\n+--------------------+----------+---------------------+\n| Chris123@gmail.com | Chris | 2019-07-22 10:05:02 |\n| DavidM@gmail.com | David | 2019-07-22 00:00:02 |\n+--------------------+----------+---------------------+\n2 rows in set (0.00 sec)" } ]
Extract all integers from string in C++
Here we will see how to extract all integers from strings in C++. We can put a string where numbers and no-numbers are present. We will extract all numeric values from it. To solve this problem, we will use the stringstream class in C++. We will cut the string word by word and then try to convert it into integer type data. if the conversion is done, then it is integer and print the value. Input: A string with some numbers “Hello 112 World 35 75” Output: 112 35 75 Step 1:Take a number string Step 2: Divide it into different words Step 3: If a word can be converted into integer type data, then it is printed Step 4: End Live Demo #include<iostream> #include<sstream> using namespace std; void getNumberFromString(string s) { stringstream str_strm; str_strm << s; //convert the string s into stringstream string temp_str; int temp_int; while(!str_strm.eof()) { str_strm >> temp_str; //take words into temp_str one by one if(stringstream(temp_str) >> temp_int) { //try to convert string to int cout << temp_int << " "; } temp_str = ""; //clear temp string } } main() { string my_str = "Hello 112 World 35 75"; getNumberFromString(my_str); } 112 35 75
[ { "code": null, "e": 1234, "s": 1062, "text": "Here we will see how to extract all integers from strings in C++. We can put a string where numbers and no-numbers are present. We will extract all numeric values from it." }, { "code": null, "e": 1454, "s": 1234, "text": "To solve this problem, we will use the stringstream class in C++. We will cut the string word by word and then try to convert it into integer type data. if the conversion is done, then it is integer and print the value." }, { "code": null, "e": 1530, "s": 1454, "text": "Input: A string with some numbers “Hello 112 World 35 75”\nOutput: 112 35 75" }, { "code": null, "e": 1687, "s": 1530, "text": "Step 1:Take a number string\nStep 2: Divide it into different words\nStep 3: If a word can be converted into integer type data, then it is printed\nStep 4: End" }, { "code": null, "e": 1698, "s": 1687, "text": " Live Demo" }, { "code": null, "e": 2264, "s": 1698, "text": "#include<iostream>\n#include<sstream>\nusing namespace std;\nvoid getNumberFromString(string s) {\n stringstream str_strm;\n str_strm << s; //convert the string s into stringstream\n string temp_str;\n int temp_int;\n while(!str_strm.eof()) {\n str_strm >> temp_str; //take words into temp_str one by one\n if(stringstream(temp_str) >> temp_int) { //try to convert string to int\n cout << temp_int << \" \";\n }\n temp_str = \"\"; //clear temp string\n }\n}\nmain() {\n string my_str = \"Hello 112 World 35 75\";\n getNumberFromString(my_str);\n}" }, { "code": null, "e": 2274, "s": 2264, "text": "112 35 75" } ]
Change Spacing of Axis Tick Marks in Base R Plot - GeeksforGeeks
28 Apr, 2021 In this article, we are going to see how to modify the space between axis tick marks of a Base R plot in R programming. It can be done in the following ways: Using xaxp & yaxp method.Using axis() Function. Using xaxp & yaxp method. Using axis() Function. Method 1: Using xaxp & yaxp method The first tick mark, last tick, and a number of tick mark parameters are given represented by a,b,c shown in the below syntax. These parameters are put into used to change in spacing between axis ticks in the base plot. Syntax: plot(x, y, xaxp = c(a,b,c), yaxp = c(a,b,c)) Parameters : a= first tick mark b= last tick mark c= Number of tick marks Example: R # Create example datay <- 1:80x <- 1:80 # Change axis ticks with xaxp & yaxpplot(x, y, xaxp = c(1, 80, 4), yaxp = c(1, 80, 10)) Output: Method 2: Using axis function. In this method, first, there is a need to create a plot without axis ticks. Then, add ticks by applying the axis() function. Different ticks are added in the way as represented by a, b, c parameters in syntax. So, this is one such method to change the spacing between axis ticks in Base R Plot. Syntax: plot(x, y, xaxt = “n”,yaxt = “n”) axis(side = 1, at = c(a, b, c....)) axis(side = 2, at = c(a, b, c.....)) Parameters: a, b, c = values of axis ticks Example: R # Create example datay <- 1:120x <- 1:120 # Change axis ticks with axis functionplot(x, y, xaxt = "n", yaxt = "n")axis(side = 1, at = c(10, 40, 80))axis(side = 2, at = c(15, 50, 75, 100)) Output: Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n28 Apr, 2021" }, { "code": null, "e": 24971, "s": 24851, "text": "In this article, we are going to see how to modify the space between axis tick marks of a Base R plot in R programming." }, { "code": null, "e": 25009, "s": 24971, "text": "It can be done in the following ways:" }, { "code": null, "e": 25057, "s": 25009, "text": "Using xaxp & yaxp method.Using axis() Function." }, { "code": null, "e": 25083, "s": 25057, "text": "Using xaxp & yaxp method." }, { "code": null, "e": 25106, "s": 25083, "text": "Using axis() Function." }, { "code": null, "e": 25142, "s": 25106, "text": "Method 1: Using xaxp & yaxp method" }, { "code": null, "e": 25362, "s": 25142, "text": "The first tick mark, last tick, and a number of tick mark parameters are given represented by a,b,c shown in the below syntax. These parameters are put into used to change in spacing between axis ticks in the base plot." }, { "code": null, "e": 25415, "s": 25362, "text": "Syntax: plot(x, y, xaxp = c(a,b,c), yaxp = c(a,b,c))" }, { "code": null, "e": 25428, "s": 25415, "text": "Parameters :" }, { "code": null, "e": 25447, "s": 25428, "text": "a= first tick mark" }, { "code": null, "e": 25466, "s": 25447, "text": "b= last tick mark" }, { "code": null, "e": 25490, "s": 25466, "text": "c= Number of tick marks" }, { "code": null, "e": 25499, "s": 25490, "text": "Example:" }, { "code": null, "e": 25501, "s": 25499, "text": "R" }, { "code": "# Create example datay <- 1:80x <- 1:80 # Change axis ticks with xaxp & yaxpplot(x, y, xaxp = c(1, 80, 4), yaxp = c(1, 80, 10)) ", "e": 25650, "s": 25501, "text": null }, { "code": null, "e": 25658, "s": 25650, "text": "Output:" }, { "code": null, "e": 25689, "s": 25658, "text": "Method 2: Using axis function." }, { "code": null, "e": 25984, "s": 25689, "text": "In this method, first, there is a need to create a plot without axis ticks. Then, add ticks by applying the axis() function. Different ticks are added in the way as represented by a, b, c parameters in syntax. So, this is one such method to change the spacing between axis ticks in Base R Plot." }, { "code": null, "e": 25992, "s": 25984, "text": "Syntax:" }, { "code": null, "e": 26026, "s": 25992, "text": "plot(x, y, xaxt = “n”,yaxt = “n”)" }, { "code": null, "e": 26062, "s": 26026, "text": "axis(side = 1, at = c(a, b, c....))" }, { "code": null, "e": 26099, "s": 26062, "text": "axis(side = 2, at = c(a, b, c.....))" }, { "code": null, "e": 26111, "s": 26099, "text": "Parameters:" }, { "code": null, "e": 26142, "s": 26111, "text": "a, b, c = values of axis ticks" }, { "code": null, "e": 26151, "s": 26142, "text": "Example:" }, { "code": null, "e": 26153, "s": 26151, "text": "R" }, { "code": "# Create example datay <- 1:120x <- 1:120 # Change axis ticks with axis functionplot(x, y, xaxt = \"n\", yaxt = \"n\")axis(side = 1, at = c(10, 40, 80))axis(side = 2, at = c(15, 50, 75, 100))", "e": 26359, "s": 26153, "text": null }, { "code": null, "e": 26367, "s": 26359, "text": "Output:" }, { "code": null, "e": 26374, "s": 26367, "text": "Picked" }, { "code": null, "e": 26383, "s": 26374, "text": "R-Charts" }, { "code": null, "e": 26392, "s": 26383, "text": "R-Graphs" }, { "code": null, "e": 26400, "s": 26392, "text": "R-plots" }, { "code": null, "e": 26411, "s": 26400, "text": "R Language" }, { "code": null, "e": 26509, "s": 26411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26518, "s": 26509, "text": "Comments" }, { "code": null, "e": 26531, "s": 26518, "text": "Old Comments" }, { "code": null, "e": 26583, "s": 26531, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26621, "s": 26583, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26656, "s": 26621, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26714, "s": 26656, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26763, "s": 26714, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26806, "s": 26763, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26856, "s": 26806, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26873, "s": 26856, "text": "R - if statement" }, { "code": null, "e": 26910, "s": 26873, "text": "How to import an Excel File into R ?" } ]
Write your own memcpy() in C
Here we will see how to implement memcpy() function in C. The memcpy() function is used to copy a block of data from one location to another. The syntax of the memcpy() is like below − void * memcpy(void * dest, const void * srd, size_t num); To make our own memcpy, we have to typecast the given address to char*, then copy data from source to destination byte by byte. Just go through the following code to get better idea. #include<stdio.h> #include<string.h> void custom_memcpy(void *dest, void *src, size_t n) { int i; //cast src and dest to char* char *src_char = (char *)src; char *dest_char = (char *)dest; for (i=0; i<n; i++) dest_char[i] = src_char[i]; //copy contents byte by byte } main() { char src[] = "Hello World"; char dest[100]; custom_memcpy(dest, src, strlen(src)+1); printf("The copied string is %s\n", dest); int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90}; int n = sizeof(arr)/sizeof(arr[0]); int dest_arr[n], i; custom_memcpy(dest_arr, arr, sizeof(arr)); printf("The copied array is "); for (i=0; i<n; i++) printf("%d ", dest_arr[i]); } The copied string is Hello World The copied array is 10 20 30 40 50 60 70 80 90
[ { "code": null, "e": 1247, "s": 1062, "text": "Here we will see how to implement memcpy() function in C. The memcpy() function is used to copy a block of data from one location to another. The syntax of the memcpy() is like below −" }, { "code": null, "e": 1305, "s": 1247, "text": "void * memcpy(void * dest, const void * srd, size_t num);" }, { "code": null, "e": 1488, "s": 1305, "text": "To make our own memcpy, we have to typecast the given address to char*, then copy data from source to destination byte by byte. Just go through the following code to get better idea." }, { "code": null, "e": 2181, "s": 1488, "text": "#include<stdio.h>\n#include<string.h>\nvoid custom_memcpy(void *dest, void *src, size_t n) {\n int i;\n //cast src and dest to char*\n char *src_char = (char *)src;\n char *dest_char = (char *)dest;\n for (i=0; i<n; i++)\n dest_char[i] = src_char[i]; //copy contents byte by byte\n}\nmain() {\n char src[] = \"Hello World\";\n char dest[100];\n custom_memcpy(dest, src, strlen(src)+1);\n printf(\"The copied string is %s\\n\", dest);\n int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};\n int n = sizeof(arr)/sizeof(arr[0]);\n int dest_arr[n], i;\n custom_memcpy(dest_arr, arr, sizeof(arr));\n printf(\"The copied array is \");\n for (i=0; i<n; i++)\n printf(\"%d \", dest_arr[i]);\n}" }, { "code": null, "e": 2261, "s": 2181, "text": "The copied string is Hello World\nThe copied array is 10 20 30 40 50 60 70 80 90" } ]
How to call an interface method in Java?
In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object. public interface InterfaceDemo{ default public void displayNameDefault(String name){ System.out.println("Your name is : " + name); } public void displayName(String name); public void displayNameAndDesignation(String name, String designation); } The above interface defines three methods for displaying a name and optionally a job title. One method is a default method that contains implementation logic. The remaining two methods do not include implementation logic. public class InterfaceDemoImpl implements InterfaceDemo{ public void displayName(String name) { System.out.println(name); } public void displayNameAndDesignation(String name, String designation) { System.out.println("Name:" + name + "\n"+ "Designation:" + designation); } } The above java program declares that it will implement the interface by using the implements keyword. The program is now obligated to provide java code for the two non-default methods. Accordingly, implementations of the methods are provided. public class CallInterfaceMethod { public static void main(String args[]){ InterfaceDemo demo = new InterfaceDemoImpl(); demo.displayName("Adithya"); demo.displayNameAndDesignation("Adithya", "Java Developer"); demo.displayNameDefault("Adithya"); } } The above program instantiates the interface implementation. Next, each of the methods defined in the interface is called. Adithya Name:Adithya Designation:Java Developer Your name is : Adithya
[ { "code": null, "e": 1248, "s": 1062, "text": "In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object." }, { "code": null, "e": 1515, "s": 1248, "text": "public interface InterfaceDemo{\n default public void displayNameDefault(String name){\n System.out.println(\"Your name is : \" + name);\n }\n public void displayName(String name);\n public void displayNameAndDesignation(String name, String designation);\n}" }, { "code": null, "e": 1737, "s": 1515, "text": "The above interface defines three methods for displaying a name and optionally a job title. One method is a default method that contains implementation logic. The remaining two methods do not include implementation logic." }, { "code": null, "e": 2052, "s": 1737, "text": "public class InterfaceDemoImpl implements InterfaceDemo{\n public void displayName(String name) {\n System.out.println(name);\n } \n public void displayNameAndDesignation(String name, String designation) {\n System.out.println(\"Name:\" + name + \"\\n\"+ \"Designation:\" + designation);\n }\n}" }, { "code": null, "e": 2295, "s": 2052, "text": "The above java program declares that it will implement the interface by using the implements keyword. The program is now obligated to provide java code for the two non-default methods. Accordingly, implementations of the methods are provided." }, { "code": null, "e": 2593, "s": 2295, "text": "public class CallInterfaceMethod {\n public static void main(String args[]){\n InterfaceDemo demo = new InterfaceDemoImpl();\n demo.displayName(\"Adithya\");\n demo.displayNameAndDesignation(\"Adithya\", \"Java Developer\");\n demo.displayNameDefault(\"Adithya\");\n }\n}" }, { "code": null, "e": 2716, "s": 2593, "text": "The above program instantiates the interface implementation. Next, each of the methods defined in the interface is called." }, { "code": null, "e": 2787, "s": 2716, "text": "Adithya\nName:Adithya\nDesignation:Java Developer\nYour name is : Adithya" } ]
H2 Database - Delete
The SQL DELETE query is used to delete the existing records from a table. We can use WHERE clause with DELETE query to delete selected records, otherwise all the records will be deleted. Following is the generic query syntax of the delete command. DELETE [ TOP term ] FROM tableName [ WHERE expression ] [ LIMIT term ] The above syntax deletes the rows from a table. If TOP or LIMIT is specified, at most the specified number of rows are deleted (no limit if null or smaller than zero). Consider the CUSTOMER table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The following command will delete the details of the customer, whose ID is 6. DELETE FROM CUSTOMERS WHERE ID = 6; After execution of the above command, check the Customer table by executing the following command. SELECT * FROM CUSTOMERS; The above command produces the following output − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If we want to DELETE all the records from CUSTOMERS table, we do not use WHERE clause. The DELETE query would be as follows. DELETE FROM CUSTOMER; After executing the above command, no records will be available in the Customer table. 14 Lectures 1 hours Mahesh Kumar 100 Lectures 9.5 hours Hari Om Singh 108 Lectures 8 hours Pavan Lalwani 10 Lectures 1 hours Deepti Trivedi 20 Lectures 2 hours Deepti Trivedi 14 Lectures 1 hours Deepti Trivedi Print Add Notes Bookmark this page
[ { "code": null, "e": 2294, "s": 2107, "text": "The SQL DELETE query is used to delete the existing records from a table. We can use WHERE clause with DELETE query to delete selected records, otherwise all the records will be deleted." }, { "code": null, "e": 2355, "s": 2294, "text": "Following is the generic query syntax of the delete command." }, { "code": null, "e": 2427, "s": 2355, "text": "DELETE [ TOP term ] FROM tableName [ WHERE expression ] [ LIMIT term ]\n" }, { "code": null, "e": 2595, "s": 2427, "text": "The above syntax deletes the rows from a table. If TOP or LIMIT is specified, at most the specified number of rows are deleted (no limit if null or smaller than zero)." }, { "code": null, "e": 2653, "s": 2595, "text": "Consider the CUSTOMER table having the following records." }, { "code": null, "e": 3181, "s": 2653, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 3259, "s": 3181, "text": "The following command will delete the details of the customer, whose ID is 6." }, { "code": null, "e": 3296, "s": 3259, "text": "DELETE FROM CUSTOMERS WHERE ID = 6;\n" }, { "code": null, "e": 3395, "s": 3296, "text": "After execution of the above command, check the Customer table by executing the following command." }, { "code": null, "e": 3421, "s": 3395, "text": "SELECT * FROM CUSTOMERS; " }, { "code": null, "e": 3471, "s": 3421, "text": "The above command produces the following output −" }, { "code": null, "e": 3952, "s": 3471, "text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n" }, { "code": null, "e": 4077, "s": 3952, "text": "If we want to DELETE all the records from CUSTOMERS table, we do not use WHERE clause. The DELETE query would be as follows." }, { "code": null, "e": 4101, "s": 4077, "text": "DELETE FROM CUSTOMER; \n" }, { "code": null, "e": 4188, "s": 4101, "text": "After executing the above command, no records will be available in the Customer table." }, { "code": null, "e": 4221, "s": 4188, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4235, "s": 4221, "text": " Mahesh Kumar" }, { "code": null, "e": 4271, "s": 4235, "text": "\n 100 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4286, "s": 4271, "text": " Hari Om Singh" }, { "code": null, "e": 4320, "s": 4286, "text": "\n 108 Lectures \n 8 hours \n" }, { "code": null, "e": 4335, "s": 4320, "text": " Pavan Lalwani" }, { "code": null, "e": 4368, "s": 4335, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 4384, "s": 4368, "text": " Deepti Trivedi" }, { "code": null, "e": 4417, "s": 4384, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 4433, "s": 4417, "text": " Deepti Trivedi" }, { "code": null, "e": 4466, "s": 4433, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 4482, "s": 4466, "text": " Deepti Trivedi" }, { "code": null, "e": 4489, "s": 4482, "text": " Print" }, { "code": null, "e": 4500, "s": 4489, "text": " Add Notes" } ]
C++ Program to Implement Gauss Jordan Elimination
This is a C++ Program to Implement Gauss Jordan Elimination. It is used to analyze linear system of simultaneous equations. It is mainly focused on reducing the system of equations to a diagonal matrix form by row operations such that the solution is obtained directly. Begin n = size of the input matrix To find the elements of the diagonal matrix: Make nested for loops j = 0 to n and i = 0 to n The element in the first row and the first column is made 1 and then the remaining elements in the first column are made 0. Similarly, the elements in the second row and the second column is made 1, and then the other elements in the second column are reduced to 0 and so on. Print all calculated solution values. End #include<iostream> using namespace std; int main() { int i,j,k,n; // declare variables and matrixes as input float a[10][10],b,x[10]; printf("\nEnter the size of matrix: "); scanf("%d",&n); printf("\nEnter the elements of augmented matrix (rowwise):\ n"); for(i=1; i<=n; i++) { for(j=1; j<=(n+1); j++) { cout << "A[" << i << ", " << j << " ]="; cin >> a[i][j]; } } //to find the elements of diagonal matrix for(j=1; j<=n; j++) { for(i=1; i<=n; i++) { if(i!=j) { b=a[i][j]/a[j][j]; for(k=1; k<=n+1; k++) { a[i][k]=a[i][k]-b*a[j][k]; } } } } cout<<"\nThe solution is:\n"; for(i=1; i<=n; i++) { x[i]=a[i][n+1]/a[i][i]; cout<<"x"<<i << "="<<x[i]<<" "; } return(0); } Enter the size of matrix: 3 Enter the elements of augmented matrix row-wise: A[1, 1 ]=1 A[1, 2 ]=2 A[1, 3 ]=-4 A[1, 4 ]=2 A[2, 1 ]=7 A[2, 2 ]=6 A[2, 3 ]=-2 A[2, 4 ]=-5 A[3, 1 ]=0 A[3, 2 ]=-3 A[3, 3 ]=-5 A[3, 4 ]=-8 The solution is: x1=-2.89831 x2=2.5678 x3=0.059322
[ { "code": null, "e": 1332, "s": 1062, "text": "This is a C++ Program to Implement Gauss Jordan Elimination. It is used to analyze linear system of simultaneous equations. It is mainly focused on reducing the system of equations to a diagonal matrix form by row operations such that the solution is obtained directly." }, { "code": null, "e": 1820, "s": 1332, "text": "Begin\n n = size of the input matrix\n To find the elements of the diagonal matrix:\n Make nested for loops j = 0 to n and i = 0 to n\n The element in the first row and the first column is made 1\n and then the remaining elements in the first column are made 0.\n Similarly, the elements in the second row and the second\n column is made 1, and then the other elements in the second\n column are reduced to 0 and so on.\n Print all calculated solution values.\nEnd" }, { "code": null, "e": 2652, "s": 1820, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int i,j,k,n; // declare variables and matrixes as\n input\n float a[10][10],b,x[10];\n printf(\"\\nEnter the size of matrix: \");\n scanf(\"%d\",&n);\n printf(\"\\nEnter the elements of augmented matrix (rowwise):\\ n\");\n for(i=1; i<=n; i++) {\n for(j=1; j<=(n+1); j++) {\n cout << \"A[\" << i << \", \" << j << \" ]=\";\n cin >> a[i][j];\n }\n }\n //to find the elements of diagonal matrix\n for(j=1; j<=n; j++) {\n for(i=1; i<=n; i++) {\n if(i!=j) {\n b=a[i][j]/a[j][j];\n for(k=1; k<=n+1; k++) { \n a[i][k]=a[i][k]-b*a[j][k];\n }\n }\n }\n }\n cout<<\"\\nThe solution is:\\n\";\n for(i=1; i<=n; i++) {\n x[i]=a[i][n+1]/a[i][i];\n cout<<\"x\"<<i << \"=\"<<x[i]<<\" \";\n }\n return(0);\n}" }, { "code": null, "e": 2918, "s": 2652, "text": "Enter the size of matrix: 3\nEnter the elements of augmented matrix row-wise:\nA[1, 1 ]=1\nA[1, 2 ]=2\nA[1, 3 ]=-4\nA[1, 4 ]=2\nA[2, 1 ]=7\nA[2, 2 ]=6\nA[2, 3 ]=-2\nA[2, 4 ]=-5\nA[3, 1 ]=0\nA[3, 2 ]=-3\nA[3, 3 ]=-5\nA[3, 4 ]=-8\nThe solution is:\nx1=-2.89831 x2=2.5678 x3=0.059322" } ]
Analyzing Employee Reviews: Google vs Amazon vs Apple vs Microsoft | by Andres Vourakis | Towards Data Science
Whether it is for their ability to offer high salaries, extravagant perks, or their exciting mission statements, it is clear that top companies like Google and Microsoft have become talent magnets. To put it into perspective, Google alone receives more than two million job applications each year. Working for a top tech company is many people’s dream, it was certainly mine for a long time, but shouldn’t we be asking ourselves “Is it really worth working for one of these companies?” Well, who better to help us answer this question than their own employees. In this article, I will walk you through my analysis of Employee Reviews for Google, Microsoft, Amazon and Apple and try to uncover some meaningful information that will hopefully illuminate us when deciding which company it’s worth working for. I will start by describing how I cleaned and processed the data, and then talk about my analysis with the help of some visualizations. Let’s get started!! The employee reviews data used for this analysis was downloaded from the Kaggle Datasets and it was sourced from Glassdoor — a website where current and former employees anonymously review companies and their management. The dataset contains over 67k employee reviews for Google, Amazon, Facebook, Apple and Microsoft. The reviews are separated into the following categories: Index: indexCompany: Company nameLocation : This dataset is global, as such it may include the country’s name in parenthesis [i.e “Toronto, ON(Canada)”]. However, if the location is in the USA then it will only include the city and state[i.e “Los Angeles, CA” ]Date Posted: in the following format MM DD, YYYYJob-Title: This string will also include whether the reviewer is a ‘Current’ or ‘Former’ Employee at the time of the reviewSummary: Short summary of employee reviewPros: ProsCons: ConsOverall Rating: 1–5Work/Life Balance Rating: 1–5Culture and Values Rating: 1–5Career Opportunities Rating: 1–5Comp & Benefits Rating: 1–5Senior Management Rating: 1–5Helpful Review Count: A count of how many people found the review to be helpfulLink to Review : This will provide you with a direct link to the page that contains the review. However it is likely that this link will be outdated Index: index Company: Company name Location : This dataset is global, as such it may include the country’s name in parenthesis [i.e “Toronto, ON(Canada)”]. However, if the location is in the USA then it will only include the city and state[i.e “Los Angeles, CA” ] Date Posted: in the following format MM DD, YYYY Job-Title: This string will also include whether the reviewer is a ‘Current’ or ‘Former’ Employee at the time of the review Summary: Short summary of employee review Pros: Pros Cons: Cons Overall Rating: 1–5 Work/Life Balance Rating: 1–5 Culture and Values Rating: 1–5 Career Opportunities Rating: 1–5 Comp & Benefits Rating: 1–5 Senior Management Rating: 1–5 Helpful Review Count: A count of how many people found the review to be helpful Link to Review : This will provide you with a direct link to the page that contains the review. However it is likely that this link will be outdated Here is what the data looks like in tabular form: After doing some basic data exploration, I decided to do the following to get the data ready for my analysis: Only include employee reviews for Google, Amazon, Microsoft and Apple. Although Facebook and Netflix had a good number of reviews, combined, they represented less than 4% of the dataset, so I decided to exclude them from this analysis for simplicity purposes. The “Link” and “Advice to Management” columns were dropped since I didn’t think they would be as insightful as the other columns. Rows with missing values in the “Date” column were dropped. A new column named “Year” was created containing the different years when the reviews were made. Rows with missing values in the following columns were dropped: “company”, ‘year’, “overall-ratings”, and “job-title”. Rows with missing values in all columns were dropped. Columns containing numeric values were converted to the appropriate data type. I began my analysis by visualizing the distribution of employee reviews for each of the 4 companies I selected. Interpretation: We can clearly see that Amazon has the most employee reviews (over 25,000). This is great since it probably means that we’ll see good mix of opinions. Although Google has the least amount of employee reviews, it is still large enough to be significant and be able to compare it to the other companies. Lets take a look at how these reviews are distributed throughout the years for each company. Interpretation: As we can see, there is a decade worth of employees reviews available, but they only go up to 2018. Microsoft: Most reviews are from the past 4–7 years Google: Most reviews are from the past 4 years Amazon: Most reviews are from the past 3–4 years Apple: Most reviews are from the past 2–4 years Based on these observations and considering how fast these companies are growing and changing every year, I decided to continue my analysis with employee reviews from the last 4 years available (2015 to 2018), since I believe they will be the most relevant. Now that we know how many reviews we are dealing with, let’s figure out who is writing them. This question can be answered in many different ways and my first approach was to figure out the job title of the reviewers, here is what the top 5 looks like: Anonymous Employee 21910Software Engineer 930Specialist 648Software Development Engineer 618Warehouse Associate 585 Unfortunately, most of the job titles are labeled “Anonymous Employee”. Considering that often times companies have a slightly different titles for the same job, I decided to not dig any deeper. Instead, let’s take a look at how many of the reviewers are current and former employees As we can see, most of the reviews come from current employees, but to get some more insight let’s see what this distribution looks like for each company: Interpretation: Once again, we see that most of the reviews for each company are from current employees. These are a few thoughts that came to mind when trying to interpret the data: Is having a large number of reviews from current employees a good thing or does it mean more bias? Perhaps, having more reviews from former employees could give us the type of insights that we don’t often read about these companies. Let’s continue... Let’s take a look at how the average overall rating for each company has changed over the past few years (2015–2018) Interpretation: We can see that the average overall rating for every company, except Apple, has not decreased since 2015. Google holds the highest average overall rating among the 4 and it has remained that way for the past couple of years. Lets talk about the trends for each company: Google: Seems to have started decreasing slightly since 2016. Microsoft: Increasing slowly since 2015 Apple: Seems to be decreasing slowly. Amazon: Has increased dramatically from 2015 to 2017. Let’s find out how good these companies are at allowing their employees to have a life outside of work: Interpretation: Google has the highest work-life balance rating (over 4 stars) and Microsoft comes as a close second. Amazon seems to fall short when it comes to providing good work-life balance. Let’s find out how the employees the rate core principals and ideals of their company: Interpretation: Google has the highest rating for culture values and Apple places second (over 4 stars). Amazon has the lowest rating of the 4, but with just over 3.5 stars. How good are they at helping you advance your career? Interpretation: Google has the highest rating for career opportunities (over 4 stars). This shouldn’t comes as a surprise considering how big the company is and how many different types of technologies they are working with. Apple has the lowest rating at just below 3.5 stars. Let’s find out how well these companies are doing in terms of benefits/perks for their employees. Interpretation: Google has the highest rating for benefits/perks with over 4.5 stars. Apple and Microsoft also seem to offer good benefits, but Amazon falls a bit short. Leadership is an important function of management, let’s see how Senior Management’s leadership is rated at these companies: Interpretation: Google has the highest rating for Senior Management, but at just below 4 stars which is its lowest when compared to its other ratings. Amazon has the lowest rating for senior management. Let’s explore the pros comments using word-clouds: The following words were common (and very frequent) among all 4 companies, but were not included in the word-clouds: benefit, company, culture, environment, good, great, lot, opportunity, people, work, and working. These words are all important in trying to figure out what makes these companies good, but I decided to leave them out in order to make room for other frequent keywords that may be more unique/insightful about each company. These are a few of the things employees like about their company: Google: The perks, smart people, free food, and good salary. Amazon: The ability to learn, their teams, smart people and management. Apple: The employee discounts, the products, their teams, the fun environment, and the good training. Microsoft: Smart people, the products, the salary, the technology, and their teams. Let’s explore the cons comments using word-clouds: The following words were common (and very frequent) among all 4 companies, but were not included in the word-clouds: company, get, lot, management, manager, people, time, and work. These words are all important in trying to figure out what makes these companies bad, but I decided to leave them out in order to make room for other frequent keywords that may be more unique/insightful about each company. These are a few of the things employees dislike about their company: Google: Their teams, the hard work, the projects, office politics and lack of work-life balance Amazon: Lack of work-life balance, the hours, and the culture. Apple: The lack of work-life balance, the retail store, the customers, and the pay. Microsoft: Office politics, the lack of work-life balance, their team, the hard work, and the culture Through the analysis we found out that Google not only has the highest overall average rating at just below 4.4 stars (as of 2018), but it also places first when it comes to work-life balance, benefits/perks, culture values, senior management and career opportunities. Microsoft comes second in terms of overall average rating at just above 4 stars but Apple seems to have better Senior Management and culture values and offer better benefits/perks. Amazon comes last at almost every category except for career opportunities. We also learned that despite the ratings, in general, employees find the lack of work-life balance at their companies problematic. In addition, the word-clouds reveal that the top cons among all 4 companies are management, people (other employees) and the work itself. These 3 cons are also among the top reasons why people quit their jobs. Something we should be asking ourselves is, knowing how popular Google is, how come it has the least amount of reviews available out of the 4 companies we analysed? Is it because it has the least amount of employees or is there something else we are missing? There are certainly a lot of other questions that come to mind and it is important to point out that this is by no means an exhaustive analysis. Nevertheless, I hope that this article was insightful and you feel inspired to extend on this analysis or use your Data Science skills to investigate a different topic of interest. if you would like to go over the code, all of it has been carefully documented on this Jupyter Notebook. Let me know your thoughts and feedback in the comments. Is there something you would’ve done differently? What other data could I use as part of this analysis?
[ { "code": null, "e": 345, "s": 47, "text": "Whether it is for their ability to offer high salaries, extravagant perks, or their exciting mission statements, it is clear that top companies like Google and Microsoft have become talent magnets. To put it into perspective, Google alone receives more than two million job applications each year." }, { "code": null, "e": 854, "s": 345, "text": "Working for a top tech company is many people’s dream, it was certainly mine for a long time, but shouldn’t we be asking ourselves “Is it really worth working for one of these companies?” Well, who better to help us answer this question than their own employees. In this article, I will walk you through my analysis of Employee Reviews for Google, Microsoft, Amazon and Apple and try to uncover some meaningful information that will hopefully illuminate us when deciding which company it’s worth working for." }, { "code": null, "e": 1009, "s": 854, "text": "I will start by describing how I cleaned and processed the data, and then talk about my analysis with the help of some visualizations. Let’s get started!!" }, { "code": null, "e": 1328, "s": 1009, "text": "The employee reviews data used for this analysis was downloaded from the Kaggle Datasets and it was sourced from Glassdoor — a website where current and former employees anonymously review companies and their management. The dataset contains over 67k employee reviews for Google, Amazon, Facebook, Apple and Microsoft." }, { "code": null, "e": 1385, "s": 1328, "text": "The reviews are separated into the following categories:" }, { "code": null, "e": 2272, "s": 1385, "text": "Index: indexCompany: Company nameLocation : This dataset is global, as such it may include the country’s name in parenthesis [i.e “Toronto, ON(Canada)”]. However, if the location is in the USA then it will only include the city and state[i.e “Los Angeles, CA” ]Date Posted: in the following format MM DD, YYYYJob-Title: This string will also include whether the reviewer is a ‘Current’ or ‘Former’ Employee at the time of the reviewSummary: Short summary of employee reviewPros: ProsCons: ConsOverall Rating: 1–5Work/Life Balance Rating: 1–5Culture and Values Rating: 1–5Career Opportunities Rating: 1–5Comp & Benefits Rating: 1–5Senior Management Rating: 1–5Helpful Review Count: A count of how many people found the review to be helpfulLink to Review : This will provide you with a direct link to the page that contains the review. However it is likely that this link will be outdated" }, { "code": null, "e": 2285, "s": 2272, "text": "Index: index" }, { "code": null, "e": 2307, "s": 2285, "text": "Company: Company name" }, { "code": null, "e": 2536, "s": 2307, "text": "Location : This dataset is global, as such it may include the country’s name in parenthesis [i.e “Toronto, ON(Canada)”]. However, if the location is in the USA then it will only include the city and state[i.e “Los Angeles, CA” ]" }, { "code": null, "e": 2585, "s": 2536, "text": "Date Posted: in the following format MM DD, YYYY" }, { "code": null, "e": 2709, "s": 2585, "text": "Job-Title: This string will also include whether the reviewer is a ‘Current’ or ‘Former’ Employee at the time of the review" }, { "code": null, "e": 2751, "s": 2709, "text": "Summary: Short summary of employee review" }, { "code": null, "e": 2762, "s": 2751, "text": "Pros: Pros" }, { "code": null, "e": 2773, "s": 2762, "text": "Cons: Cons" }, { "code": null, "e": 2793, "s": 2773, "text": "Overall Rating: 1–5" }, { "code": null, "e": 2823, "s": 2793, "text": "Work/Life Balance Rating: 1–5" }, { "code": null, "e": 2854, "s": 2823, "text": "Culture and Values Rating: 1–5" }, { "code": null, "e": 2887, "s": 2854, "text": "Career Opportunities Rating: 1–5" }, { "code": null, "e": 2915, "s": 2887, "text": "Comp & Benefits Rating: 1–5" }, { "code": null, "e": 2945, "s": 2915, "text": "Senior Management Rating: 1–5" }, { "code": null, "e": 3025, "s": 2945, "text": "Helpful Review Count: A count of how many people found the review to be helpful" }, { "code": null, "e": 3174, "s": 3025, "text": "Link to Review : This will provide you with a direct link to the page that contains the review. However it is likely that this link will be outdated" }, { "code": null, "e": 3224, "s": 3174, "text": "Here is what the data looks like in tabular form:" }, { "code": null, "e": 3334, "s": 3224, "text": "After doing some basic data exploration, I decided to do the following to get the data ready for my analysis:" }, { "code": null, "e": 3594, "s": 3334, "text": "Only include employee reviews for Google, Amazon, Microsoft and Apple. Although Facebook and Netflix had a good number of reviews, combined, they represented less than 4% of the dataset, so I decided to exclude them from this analysis for simplicity purposes." }, { "code": null, "e": 3724, "s": 3594, "text": "The “Link” and “Advice to Management” columns were dropped since I didn’t think they would be as insightful as the other columns." }, { "code": null, "e": 3784, "s": 3724, "text": "Rows with missing values in the “Date” column were dropped." }, { "code": null, "e": 3881, "s": 3784, "text": "A new column named “Year” was created containing the different years when the reviews were made." }, { "code": null, "e": 4000, "s": 3881, "text": "Rows with missing values in the following columns were dropped: “company”, ‘year’, “overall-ratings”, and “job-title”." }, { "code": null, "e": 4054, "s": 4000, "text": "Rows with missing values in all columns were dropped." }, { "code": null, "e": 4133, "s": 4054, "text": "Columns containing numeric values were converted to the appropriate data type." }, { "code": null, "e": 4245, "s": 4133, "text": "I began my analysis by visualizing the distribution of employee reviews for each of the 4 companies I selected." }, { "code": null, "e": 4563, "s": 4245, "text": "Interpretation: We can clearly see that Amazon has the most employee reviews (over 25,000). This is great since it probably means that we’ll see good mix of opinions. Although Google has the least amount of employee reviews, it is still large enough to be significant and be able to compare it to the other companies." }, { "code": null, "e": 4656, "s": 4563, "text": "Lets take a look at how these reviews are distributed throughout the years for each company." }, { "code": null, "e": 4772, "s": 4656, "text": "Interpretation: As we can see, there is a decade worth of employees reviews available, but they only go up to 2018." }, { "code": null, "e": 4824, "s": 4772, "text": "Microsoft: Most reviews are from the past 4–7 years" }, { "code": null, "e": 4871, "s": 4824, "text": "Google: Most reviews are from the past 4 years" }, { "code": null, "e": 4920, "s": 4871, "text": "Amazon: Most reviews are from the past 3–4 years" }, { "code": null, "e": 4968, "s": 4920, "text": "Apple: Most reviews are from the past 2–4 years" }, { "code": null, "e": 5226, "s": 4968, "text": "Based on these observations and considering how fast these companies are growing and changing every year, I decided to continue my analysis with employee reviews from the last 4 years available (2015 to 2018), since I believe they will be the most relevant." }, { "code": null, "e": 5479, "s": 5226, "text": "Now that we know how many reviews we are dealing with, let’s figure out who is writing them. This question can be answered in many different ways and my first approach was to figure out the job title of the reviewers, here is what the top 5 looks like:" }, { "code": null, "e": 5670, "s": 5479, "text": "Anonymous Employee 21910Software Engineer 930Specialist 648Software Development Engineer 618Warehouse Associate 585" }, { "code": null, "e": 5954, "s": 5670, "text": "Unfortunately, most of the job titles are labeled “Anonymous Employee”. Considering that often times companies have a slightly different titles for the same job, I decided to not dig any deeper. Instead, let’s take a look at how many of the reviewers are current and former employees" }, { "code": null, "e": 6109, "s": 5954, "text": "As we can see, most of the reviews come from current employees, but to get some more insight let’s see what this distribution looks like for each company:" }, { "code": null, "e": 6543, "s": 6109, "text": "Interpretation: Once again, we see that most of the reviews for each company are from current employees. These are a few thoughts that came to mind when trying to interpret the data: Is having a large number of reviews from current employees a good thing or does it mean more bias? Perhaps, having more reviews from former employees could give us the type of insights that we don’t often read about these companies. Let’s continue..." }, { "code": null, "e": 6660, "s": 6543, "text": "Let’s take a look at how the average overall rating for each company has changed over the past few years (2015–2018)" }, { "code": null, "e": 6946, "s": 6660, "text": "Interpretation: We can see that the average overall rating for every company, except Apple, has not decreased since 2015. Google holds the highest average overall rating among the 4 and it has remained that way for the past couple of years. Lets talk about the trends for each company:" }, { "code": null, "e": 7008, "s": 6946, "text": "Google: Seems to have started decreasing slightly since 2016." }, { "code": null, "e": 7048, "s": 7008, "text": "Microsoft: Increasing slowly since 2015" }, { "code": null, "e": 7086, "s": 7048, "text": "Apple: Seems to be decreasing slowly." }, { "code": null, "e": 7140, "s": 7086, "text": "Amazon: Has increased dramatically from 2015 to 2017." }, { "code": null, "e": 7244, "s": 7140, "text": "Let’s find out how good these companies are at allowing their employees to have a life outside of work:" }, { "code": null, "e": 7440, "s": 7244, "text": "Interpretation: Google has the highest work-life balance rating (over 4 stars) and Microsoft comes as a close second. Amazon seems to fall short when it comes to providing good work-life balance." }, { "code": null, "e": 7527, "s": 7440, "text": "Let’s find out how the employees the rate core principals and ideals of their company:" }, { "code": null, "e": 7701, "s": 7527, "text": "Interpretation: Google has the highest rating for culture values and Apple places second (over 4 stars). Amazon has the lowest rating of the 4, but with just over 3.5 stars." }, { "code": null, "e": 7755, "s": 7701, "text": "How good are they at helping you advance your career?" }, { "code": null, "e": 8033, "s": 7755, "text": "Interpretation: Google has the highest rating for career opportunities (over 4 stars). This shouldn’t comes as a surprise considering how big the company is and how many different types of technologies they are working with. Apple has the lowest rating at just below 3.5 stars." }, { "code": null, "e": 8131, "s": 8033, "text": "Let’s find out how well these companies are doing in terms of benefits/perks for their employees." }, { "code": null, "e": 8301, "s": 8131, "text": "Interpretation: Google has the highest rating for benefits/perks with over 4.5 stars. Apple and Microsoft also seem to offer good benefits, but Amazon falls a bit short." }, { "code": null, "e": 8426, "s": 8301, "text": "Leadership is an important function of management, let’s see how Senior Management’s leadership is rated at these companies:" }, { "code": null, "e": 8629, "s": 8426, "text": "Interpretation: Google has the highest rating for Senior Management, but at just below 4 stars which is its lowest when compared to its other ratings. Amazon has the lowest rating for senior management." }, { "code": null, "e": 8680, "s": 8629, "text": "Let’s explore the pros comments using word-clouds:" }, { "code": null, "e": 8895, "s": 8680, "text": "The following words were common (and very frequent) among all 4 companies, but were not included in the word-clouds: benefit, company, culture, environment, good, great, lot, opportunity, people, work, and working." }, { "code": null, "e": 9185, "s": 8895, "text": "These words are all important in trying to figure out what makes these companies good, but I decided to leave them out in order to make room for other frequent keywords that may be more unique/insightful about each company. These are a few of the things employees like about their company:" }, { "code": null, "e": 9246, "s": 9185, "text": "Google: The perks, smart people, free food, and good salary." }, { "code": null, "e": 9318, "s": 9246, "text": "Amazon: The ability to learn, their teams, smart people and management." }, { "code": null, "e": 9420, "s": 9318, "text": "Apple: The employee discounts, the products, their teams, the fun environment, and the good training." }, { "code": null, "e": 9504, "s": 9420, "text": "Microsoft: Smart people, the products, the salary, the technology, and their teams." }, { "code": null, "e": 9555, "s": 9504, "text": "Let’s explore the cons comments using word-clouds:" }, { "code": null, "e": 9736, "s": 9555, "text": "The following words were common (and very frequent) among all 4 companies, but were not included in the word-clouds: company, get, lot, management, manager, people, time, and work." }, { "code": null, "e": 10028, "s": 9736, "text": "These words are all important in trying to figure out what makes these companies bad, but I decided to leave them out in order to make room for other frequent keywords that may be more unique/insightful about each company. These are a few of the things employees dislike about their company:" }, { "code": null, "e": 10124, "s": 10028, "text": "Google: Their teams, the hard work, the projects, office politics and lack of work-life balance" }, { "code": null, "e": 10187, "s": 10124, "text": "Amazon: Lack of work-life balance, the hours, and the culture." }, { "code": null, "e": 10271, "s": 10187, "text": "Apple: The lack of work-life balance, the retail store, the customers, and the pay." }, { "code": null, "e": 10373, "s": 10271, "text": "Microsoft: Office politics, the lack of work-life balance, their team, the hard work, and the culture" }, { "code": null, "e": 10899, "s": 10373, "text": "Through the analysis we found out that Google not only has the highest overall average rating at just below 4.4 stars (as of 2018), but it also places first when it comes to work-life balance, benefits/perks, culture values, senior management and career opportunities. Microsoft comes second in terms of overall average rating at just above 4 stars but Apple seems to have better Senior Management and culture values and offer better benefits/perks. Amazon comes last at almost every category except for career opportunities." }, { "code": null, "e": 11240, "s": 10899, "text": "We also learned that despite the ratings, in general, employees find the lack of work-life balance at their companies problematic. In addition, the word-clouds reveal that the top cons among all 4 companies are management, people (other employees) and the work itself. These 3 cons are also among the top reasons why people quit their jobs." }, { "code": null, "e": 11499, "s": 11240, "text": "Something we should be asking ourselves is, knowing how popular Google is, how come it has the least amount of reviews available out of the 4 companies we analysed? Is it because it has the least amount of employees or is there something else we are missing?" }, { "code": null, "e": 11644, "s": 11499, "text": "There are certainly a lot of other questions that come to mind and it is important to point out that this is by no means an exhaustive analysis." }, { "code": null, "e": 11930, "s": 11644, "text": "Nevertheless, I hope that this article was insightful and you feel inspired to extend on this analysis or use your Data Science skills to investigate a different topic of interest. if you would like to go over the code, all of it has been carefully documented on this Jupyter Notebook." } ]
How to attach a Scrollbar to a Text widget in Tkinter?
Tkinter Text widget is used to accept multiline user Input. It is similar to Entry Widget but the only difference is that Text widget supports multiple line texts. In order to create a Text widget, we have to instantiate a text object. Adding multiple texts will require to add the ScrollBar. In order to add a scrollbar in the text widget, we can call the ScrolledText(root) function. This function generally creates a text field with a scrollbar. The ScrolledText(root) function resides in Tkinter ScrolledText Module. We can import it using the following command, from tkinter.scrolledtext import ScrolledText In this example, we will create a Text widget and then add a scrollbar to it. #Import the library from tkinter import * from tkinter.scrolledtext import ScrolledText #Create an object of tkinter window or frame win = Tk() #Define the geometry of window win.geometry("650x250") #Create an instance of Text Widget ScrolledText(win).pack() win.mainloop() Running the above code will display a window with a text widget that supports multiline user Input and a native scrollbar.
[ { "code": null, "e": 1298, "s": 1062, "text": "Tkinter Text widget is used to accept multiline user Input. It is similar to Entry Widget but the only difference is that Text widget supports multiple line texts. In order to create a Text widget, we have to instantiate a text object." }, { "code": null, "e": 1511, "s": 1298, "text": "Adding multiple texts will require to add the ScrollBar. In order to add a scrollbar in the text widget, we can call the ScrolledText(root) function. This function generally creates a text field with a scrollbar." }, { "code": null, "e": 1629, "s": 1511, "text": "The ScrolledText(root) function resides in Tkinter ScrolledText Module. We can import it using the following command," }, { "code": null, "e": 1675, "s": 1629, "text": "from tkinter.scrolledtext import ScrolledText" }, { "code": null, "e": 1753, "s": 1675, "text": "In this example, we will create a Text widget and then add a scrollbar to it." }, { "code": null, "e": 2031, "s": 1753, "text": "#Import the library\nfrom tkinter import *\nfrom tkinter.scrolledtext import ScrolledText\n\n#Create an object of tkinter window or frame\nwin = Tk()\n\n#Define the geometry of window\nwin.geometry(\"650x250\")\n\n#Create an instance of Text Widget\nScrolledText(win).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2154, "s": 2031, "text": "Running the above code will display a window with a text widget that supports multiline user Input and a native scrollbar." } ]
Count distinct elements in every window | Practice | GeeksforGeeks
Given an array of integers and a number K. Find the count of distinct elements in every window of size K in the array. Example 1: Input: N = 7, K = 4 A[] = {1,2,1,3,4,2,3} Output: 3 4 4 3 Explanation: Window 1 of size k = 4 is 1 2 1 3. Number of distinct elements in this window are 3. Window 2 of size k = 4 is 2 1 3 4. Number of distinct elements in this window are 4. Window 3 of size k = 4 is 1 3 4 2. Number of distinct elements in this window are 4. Window 4 of size k = 4 is 3 4 2 3. Number of distinct elements in this window are 3. Example 2: Input: N = 3, K = 2 A[] = {4,1,1} Output: 2 1 Your Task: Your task is to complete the function countDistinct() which takes the array A[], the size of the array(N) and the window size(K) as inputs and returns an array containing the count of distinct elements in every contiguous window of size K in the array A[]. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= K <= N <= 105 1 <= A[i] <= 105 , for each valid i 0 venkatesh_naidu2 weeks ago C++ Solution → O(n) Time, O(k) space class Solution{ public: vector <int> countDistinct (int arr[], int n, int k) { //code here. unordered_map<int, int> f; vector<int> res; // create map for the first window of k items for(int i = 0; i < k; i++) { if(f.find(arr[i]) == f.end()) f[arr[i]] = 1; else f[arr[i]]++; } // distinct numbers count for first window int count = f.size(); res.push_back(count); for(int i = k; i < n; i++) { // decrement count if item is being removed from map if(f[arr[i-k]] == 1) { f.erase(arr[i-k]); count--; } else { f[arr[i-k]]--; } // increment count if item is being freshly added to map if(f.find(arr[i]) == f.end()) { f[arr[i]] = 1; count++; } else { f[arr[i]]++; } // append the count for current window res.push_back(count); } return res; } }; 0 19bcs13142 weeks ago Using HashMap class Solution { ArrayList<Integer> countDistinct(int arr[], int n, int k) { // code here ArrayList<Integer> ans=new ArrayList<Integer>(); Map<Integer,Integer> map=new HashMap<>(); int j=0,i=0; while(j<n){ map.put(arr[j],map.getOrDefault(arr[j],0)+1); if(j-i+1<k){ j++; }else if(j-i+1==k){ ans.add(map.size()); if(map.get(arr[i])==1){ map.remove(arr[i]); } else if(map.get(arr[i])>1){ map.replace(arr[i],map.get(arr[i])-1); } i++; j++; } } return ans; } } +1 kartikeyashokgautam1 month ago JAVA Solution :- ArrayList<Integer> countDistinct(int A[], int n, int k) { ArrayList<Integer> al = new ArrayList<>(); HashMap<Integer,Integer> hm = new HashMap<>(); for(int i=0;i<=k-2;i++) { hm.put(A[i],hm.getOrDefault(A[i],0)+1); } for(int j=0, i=k-1;i<A.length;) // Acquire { hm.put(A[i],hm.getOrDefault(A[i],0)+1); al.add(hm.size()); // work int freq = hm.get(A[j]); // Release if(freq == 1) { hm.remove(A[j]); } else { hm.put(A[j],freq-1); } i++; j++; } return al; } +1 mayank20211 month ago C++ : 1.5/3.2vector <int> countDistinct (int A[], int n, int k) { vector<int> vec; map<int, int>mp; // if(k>n) return vec; for(int i=0; i<k ; i++) { mp[A[i]]++; } vec.push_back(mp.size()); for(int i=k; i<n ; i++) { if(mp[A[i-k]]==1) mp.erase(A[i-k]); else mp[A[i-k]]--; mp[A[i]]++; vec.push_back(mp.size()); } return vec; } 0 mummadiug1 month ago only 200 test cases are passing suggests some changes from collections import Counterclass Solution: def countDistinct(self, A, N, K): m=[] for i in range(N-K+1): z=Counter(A[i:i+K]) m.append(len(z)) return m +1 sagrikasoni This comment was deleted. +2 dipeshmakwane1 month ago Easy C++ Solution : vector <int> countDistinct (int A[], int n, int k) { //code here. unordered_map<int,int>um; vector<int>v; for(int i=0;i<k;i++){ um[A[i]]++; } v.push_back(um.size()); int j=0; for(int i=k;i<n;i++){ um[A[j]]--; um[A[i]]++; if(um[A[j]]==0){ um.erase(A[j]); } j++; v.push_back(um.size()); } return v; } 0 avipanwar65651 month ago vector <int> countDistinct (int A[], int n, int k) { vector<int> v; unordered_map<int, int> m; for(int i=0; i<k; i++) { m[A[i]]++; } v.push_back(m.size()); for(int i=k; i<n; i++) { if(m[A[i-k]]==1) { m.erase(A[i-k]); } else { m[A[i-k]]--; } m[A[i]]++; v.push_back(m.size()); } return v; } 0 vishwajeetpawar191 month ago class Solution{ public: vector <int> countDistinct (int A[], int n, int k) { //code here. map<int,int>mp ; vector <int> res ; int count = 0 ; for(int i=0;i<k;i++) { if(mp.find(A[i])!=mp.end()) { mp[A[i]]++ ; continue ; } mp[A[i]]++ ; count++ ; } res.push_back(count) ; int left = 0 ; for(int i=k;i<n;i++) { mp[A[left]]-- ; if( mp[A[left]] == 0 ) count-- ; mp[A[i]]++ ; if( mp[A[i]] == 1 ) count++ ; res.push_back(count) ; left++ ; } return res ; } }; +1 dronzerdracel1 month ago Sliding window concept of Aditya Verma vector <int> countDistinct (int arr[], int n, int k) { //code here. unordered_map<int,int>mp; int i=0,j=0; vector<int>v; while(j<n){ mp[arr[j]]++; if(j-i+1<k) j++; else if(j-i+1==k){ v.push_back(mp.size()); mp[arr[i]]--; if(mp[arr[i]]==0) mp.erase(arr[i]); i++; j++; } } return v; 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": 357, "s": 238, "text": "Given an array of integers and a number K. Find the count of distinct elements in every window of size K in the array." }, { "code": null, "e": 368, "s": 357, "text": "Example 1:" }, { "code": null, "e": 781, "s": 368, "text": "Input:\nN = 7, K = 4\nA[] = {1,2,1,3,4,2,3}\nOutput: 3 4 4 3\nExplanation: Window 1 of size k = 4 is\n1 2 1 3. Number of distinct elements in\nthis window are 3. \nWindow 2 of size k = 4 is 2 1 3 4. Number\nof distinct elements in this window are 4.\nWindow 3 of size k = 4 is 1 3 4 2. Number\nof distinct elements in this window are 4.\nWindow 4 of size k = 4 is 3 4 2 3. Number\nof distinct elements in this window are 3.\n" }, { "code": null, "e": 792, "s": 781, "text": "Example 2:" }, { "code": null, "e": 838, "s": 792, "text": "Input:\nN = 3, K = 2\nA[] = {4,1,1}\nOutput: 2 1" }, { "code": null, "e": 1106, "s": 838, "text": "Your Task:\nYour task is to complete the function countDistinct() which takes the array A[], the size of the array(N) and the window size(K) as inputs and returns an array containing the count of distinct elements in every contiguous window of size K in the array A[]." }, { "code": null, "e": 1170, "s": 1106, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1238, "s": 1170, "text": "Constraints:\n1 <= K <= N <= 105\n1 <= A[i] <= 105 , for each valid i" }, { "code": null, "e": 1240, "s": 1238, "text": "0" }, { "code": null, "e": 1267, "s": 1240, "text": "venkatesh_naidu2 weeks ago" }, { "code": null, "e": 1304, "s": 1267, "text": "C++ Solution → O(n) Time, O(k) space" }, { "code": null, "e": 2487, "s": 1304, "text": "class Solution{\n public:\n vector <int> countDistinct (int arr[], int n, int k)\n {\n //code here.\n unordered_map<int, int> f;\n vector<int> res;\n \n // create map for the first window of k items\n for(int i = 0; i < k; i++) {\n if(f.find(arr[i]) == f.end())\n f[arr[i]] = 1;\n else\n f[arr[i]]++;\n }\n \n // distinct numbers count for first window\n int count = f.size();\n res.push_back(count);\n \n for(int i = k; i < n; i++) {\n // decrement count if item is being removed from map\n if(f[arr[i-k]] == 1) {\n f.erase(arr[i-k]);\n count--;\n }\n else {\n f[arr[i-k]]--;\n }\n\n // increment count if item is being freshly added to map\n if(f.find(arr[i]) == f.end()) {\n f[arr[i]] = 1;\n count++;\n } else {\n f[arr[i]]++;\n }\n \n // append the count for current window\n res.push_back(count);\n }\n \n return res;\n }\n};" }, { "code": null, "e": 2489, "s": 2487, "text": "0" }, { "code": null, "e": 2510, "s": 2489, "text": "19bcs13142 weeks ago" }, { "code": null, "e": 2525, "s": 2510, "text": "Using HashMap " }, { "code": null, "e": 3310, "s": 2525, "text": "class Solution\n{\n ArrayList<Integer> countDistinct(int arr[], int n, int k)\n {\n // code here \n ArrayList<Integer> ans=new ArrayList<Integer>();\n \n Map<Integer,Integer> map=new HashMap<>();\n \n int j=0,i=0;\n \n while(j<n){\n map.put(arr[j],map.getOrDefault(arr[j],0)+1);\n if(j-i+1<k){\n j++;\n }else if(j-i+1==k){\n ans.add(map.size());\n if(map.get(arr[i])==1){\n map.remove(arr[i]);\n }\n else if(map.get(arr[i])>1){\n map.replace(arr[i],map.get(arr[i])-1);\n }\n \n i++;\n j++;\n }\n }\n return ans;\n }\n}" }, { "code": null, "e": 3317, "s": 3314, "text": "+1" }, { "code": null, "e": 3348, "s": 3317, "text": "kartikeyashokgautam1 month ago" }, { "code": null, "e": 3365, "s": 3348, "text": "JAVA Solution :-" }, { "code": null, "e": 3867, "s": 3367, "text": " ArrayList<Integer> countDistinct(int A[], int n, int k) { ArrayList<Integer> al = new ArrayList<>(); HashMap<Integer,Integer> hm = new HashMap<>(); for(int i=0;i<=k-2;i++) { hm.put(A[i],hm.getOrDefault(A[i],0)+1); } for(int j=0, i=k-1;i<A.length;) // Acquire { hm.put(A[i],hm.getOrDefault(A[i],0)+1); al.add(hm.size()); // work int freq = hm.get(A[j]); " }, { "code": null, "e": 4108, "s": 3867, "text": "// Release if(freq == 1) { hm.remove(A[j]); } else { hm.put(A[j],freq-1); } i++; j++; } return al; }" }, { "code": null, "e": 4111, "s": 4108, "text": "+1" }, { "code": null, "e": 4133, "s": 4111, "text": "mayank20211 month ago" }, { "code": null, "e": 4646, "s": 4133, "text": "C++ : 1.5/3.2vector <int> countDistinct (int A[], int n, int k) { vector<int> vec; map<int, int>mp; // if(k>n) return vec; for(int i=0; i<k ; i++) { mp[A[i]]++; } vec.push_back(mp.size()); for(int i=k; i<n ; i++) { if(mp[A[i-k]]==1) mp.erase(A[i-k]); else mp[A[i-k]]--; mp[A[i]]++; vec.push_back(mp.size()); } return vec; }" }, { "code": null, "e": 4648, "s": 4646, "text": "0" }, { "code": null, "e": 4669, "s": 4648, "text": "mummadiug1 month ago" }, { "code": null, "e": 4723, "s": 4669, "text": "only 200 test cases are passing suggests some changes" }, { "code": null, "e": 4918, "s": 4723, "text": "from collections import Counterclass Solution: def countDistinct(self, A, N, K): m=[] for i in range(N-K+1): z=Counter(A[i:i+K]) m.append(len(z)) return m" }, { "code": null, "e": 4921, "s": 4918, "text": "+1" }, { "code": null, "e": 4933, "s": 4921, "text": "sagrikasoni" }, { "code": null, "e": 4959, "s": 4933, "text": "This comment was deleted." }, { "code": null, "e": 4962, "s": 4959, "text": "+2" }, { "code": null, "e": 4987, "s": 4962, "text": "dipeshmakwane1 month ago" }, { "code": null, "e": 5007, "s": 4987, "text": "Easy C++ Solution :" }, { "code": null, "e": 5509, "s": 5007, "text": " vector <int> countDistinct (int A[], int n, int k)\n {\n //code here.\n unordered_map<int,int>um;\n vector<int>v;\n for(int i=0;i<k;i++){\n um[A[i]]++;\n }\n v.push_back(um.size());\n int j=0;\n for(int i=k;i<n;i++){\n um[A[j]]--;\n um[A[i]]++;\n if(um[A[j]]==0){\n um.erase(A[j]);\n }\n j++;\n v.push_back(um.size());\n }\n \n return v;\n }\n " }, { "code": null, "e": 5511, "s": 5509, "text": "0" }, { "code": null, "e": 5536, "s": 5511, "text": "avipanwar65651 month ago" }, { "code": null, "e": 6018, "s": 5536, "text": "vector <int> countDistinct (int A[], int n, int k) { vector<int> v; unordered_map<int, int> m; for(int i=0; i<k; i++) { m[A[i]]++; } v.push_back(m.size()); for(int i=k; i<n; i++) { if(m[A[i-k]]==1) { m.erase(A[i-k]); } else { m[A[i-k]]--; } m[A[i]]++; v.push_back(m.size()); } return v; }" }, { "code": null, "e": 6020, "s": 6018, "text": "0" }, { "code": null, "e": 6049, "s": 6020, "text": "vishwajeetpawar191 month ago" }, { "code": null, "e": 6923, "s": 6049, "text": "class Solution{\n \n public:\n \n vector <int> countDistinct (int A[], int n, int k)\n {\n //code here.\n map<int,int>mp ;\n vector <int> res ;\n int count = 0 ;\n \n for(int i=0;i<k;i++)\n {\n if(mp.find(A[i])!=mp.end())\n {\n mp[A[i]]++ ;\n continue ;\n }\n mp[A[i]]++ ;\n count++ ;\n }\n res.push_back(count) ;\n \n int left = 0 ;\n \n for(int i=k;i<n;i++)\n {\n mp[A[left]]-- ;\n \n if( mp[A[left]] == 0 )\n count-- ;\n \n mp[A[i]]++ ;\n \n if( mp[A[i]] == 1 )\n count++ ;\n \n res.push_back(count) ;\n left++ ;\n }\n \n return res ;\n }\n \n};" }, { "code": null, "e": 6926, "s": 6923, "text": "+1" }, { "code": null, "e": 6951, "s": 6926, "text": "dronzerdracel1 month ago" }, { "code": null, "e": 6990, "s": 6951, "text": "Sliding window concept of Aditya Verma" }, { "code": null, "e": 7492, "s": 6990, "text": "vector <int> countDistinct (int arr[], int n, int k)\n {\n //code here.\n unordered_map<int,int>mp;\n int i=0,j=0;\n vector<int>v;\n while(j<n){\n mp[arr[j]]++;\n if(j-i+1<k)\n j++;\n else if(j-i+1==k){\n v.push_back(mp.size());\n mp[arr[i]]--;\n if(mp[arr[i]]==0)\n mp.erase(arr[i]);\n i++;\n j++;\n } \n }\n return v;" }, { "code": null, "e": 7638, "s": 7492, "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": 7674, "s": 7638, "text": " Login to access your submissions. " }, { "code": null, "e": 7684, "s": 7674, "text": "\nProblem\n" }, { "code": null, "e": 7694, "s": 7684, "text": "\nContest\n" }, { "code": null, "e": 7757, "s": 7694, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7905, "s": 7757, "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": 8113, "s": 7905, "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": 8219, "s": 8113, "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 a date spinner in Java?
To create a date spinner, use the SpinnerDateModel class. Within that set the date format − Date today = new Date(); JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH)); JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy"); spinner2.setEditor(editor); Above, we have set the Date format to be − dd/MM/yy The following is an example to create a date spinner in Java − package my; import java.awt.GridBagLayout; import java.util.Calendar; import java.util.Date; import javax.swing.*; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Spinner Demo"); JPanel panel = new JPanel(); JLabel label = new JLabel("Exam No."); JLabel label2 = new JLabel(" Appeared On"); panel.setLayout(new GridBagLayout()); int min = 0; int max = 10; int step = 1; int i = 5; SpinnerModel value = new SpinnerNumberModel(i, min, max, step); JSpinner spinner = new JSpinner(value); spinner.setBounds(50, 80, 70, 100); Date today = new Date(); JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH)); JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy"); spinner2.setEditor(editor); panel.add(label); panel.add(spinner); panel.add(label2); panel.add(spinner2); frame.add(panel); frame.setSize(550,300); frame.setVisible(true); } }
[ { "code": null, "e": 1154, "s": 1062, "text": "To create a date spinner, use the SpinnerDateModel class. Within that set the date format −" }, { "code": null, "e": 1374, "s": 1154, "text": "Date today = new Date();\nJSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));\nJSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, \"dd/MM/yy\");\nspinner2.setEditor(editor);" }, { "code": null, "e": 1417, "s": 1374, "text": "Above, we have set the Date format to be −" }, { "code": null, "e": 1426, "s": 1417, "text": "dd/MM/yy" }, { "code": null, "e": 1489, "s": 1426, "text": "The following is an example to create a date spinner in Java −" }, { "code": null, "e": 2567, "s": 1489, "text": "package my;\nimport java.awt.GridBagLayout;\nimport java.util.Calendar;\nimport java.util.Date;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Spinner Demo\");\n JPanel panel = new JPanel();\n JLabel label = new JLabel(\"Exam No.\");\n JLabel label2 = new JLabel(\" Appeared On\");\n panel.setLayout(new GridBagLayout());\n int min = 0;\n int max = 10;\n int step = 1;\n int i = 5;\n SpinnerModel value = new SpinnerNumberModel(i, min, max, step);\n JSpinner spinner = new JSpinner(value);\n spinner.setBounds(50, 80, 70, 100);\n Date today = new Date();\n JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH));\n JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, \"dd/MM/yy\");\n spinner2.setEditor(editor);\n panel.add(label);\n panel.add(spinner);\n panel.add(label2);\n panel.add(spinner2);\n frame.add(panel);\n frame.setSize(550,300);\n frame.setVisible(true);\n }\n}" } ]
A demonstration of carrying data analysis (New York City Airbnb Open Data) | by WY Fok | Towards Data Science
In this article, I will perform data analysis by using Python and record down every finding and thought during the analysis. Practicing with real data can not only help me have more experience in analyzing different data but also help me discover more techniques and skills when compared with others’ works. The dataset used in this article is “New York City Airbnb Open Data” which is from Kaggle. Here is the download link https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data After importing modules and csv file, normally my first step is to explore the dataset. This step includes studying the format of the overall dataset, types of all variables, checking and cleaning the dataset. data = pd.read_csv('AB_NYC_2019.csv')data.info()class 'pandas.core.frame.DataFrame'>RangeIndex: 48895 entries, 0 to 48894Data columns (total 16 columns):id 48895 non-null int64name 48879 non-null objecthost_id 48895 non-null int64host_name 48874 non-null objectneighbourhood_group 48895 non-null objectneighbourhood 48895 non-null objectlatitude 48895 non-null float64longitude 48895 non-null float64room_type 48895 non-null objectprice 48895 non-null int64minimum_nights 48895 non-null int64number_of_reviews 48895 non-null int64last_review 38843 non-null objectreviews_per_month 38843 non-null float64calculated_host_listings_count 48895 non-null int64availability_365 48895 non-null int64dtypes: float64(3), int64(7), object(6)memory usage: 6.0+ MB So there are in total of 16 columns and some columns have missing values. data.isnull().sum()id 0name 16host_id 0host_name 21neighbourhood_group 0neighbourhood 0latitude 0longitude 0room_type 0price 0minimum_nights 0number_of_reviews 0last_review 10052reviews_per_month 10052calculated_host_listings_count 0availability_365 0dtype: int64 Both last_review and reviews_per_month have over 10k missing values in the dataset. And they also have the same numbers of missing values. Based on the names and numbers of missing values, I suspect that these two columns are related and so have the same numbers of missing values. (data['last_review'].isnull()==data['reviews_per_month'].isnull()).all()True So they should be handled together. At this moment, I don’t know how to handle missing values in “last_review” column as this normally shows a date string indicating the date of the last review. So at this moment, I will just leave it first. However, for missing values in reviews_per_month, I will assign them as zero. data.loc[data['reviews_per_month'].isnull(),'reviews_per_month']=0 Remaining columns with missing values are name and host_name. However, I don’t think there is any predictive power from either name or host_name. So instead of handling missing values, I will directly remove from the dataset. There are two columns, id and host_id, indicating the Airbnb house and host. After checking, id is unique in the dataset but not host_id. Therefore, id can be removed but not host_id. Also, it can be meaningful if there is any relationship between the number of listing house and price. So host_id will be kept. Next step is to check numeric variables by using data.describe() Using describe() can help me understand the range of possible values for each variable. I can know the distribution of values. Also, it is possible to discover any unrealistic records from the dataset. For example in this dataset, there are some abnormalities. The first one is that there are records with “price” = 0 which is unrealistic as this means no need to pay to stay. So these records should be removed. The second is that the maximum of “minimum_nights” is 1250 which I believe is unrealistic (is this still an Airbnb or just another rental contract?). I put a threshold as 365 days. Any records with “minimum_nights” larger than 365 will also be removed. Dataset after cleaning: data.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 48870 entries, 0 to 48869Data columns (total 12 columns):host_id 48870 non-null int64neighbourhood_group 48870 non-null objectneighbourhood 48870 non-null objectlatitude 48870 non-null float64longitude 48870 non-null float64room_type 48870 non-null objectprice 48870 non-null int64minimum_nights 48870 non-null int64number_of_reviews 48870 non-null int64reviews_per_month 48870 non-null float64calculated_host_listings_count 48870 non-null int64availability_365 48870 non-null int64dtypes: float64(3), int64(6), object(3)memory usage: 4.5+ MB 48870 rows and 12 columns Now I can have a look at the dataset. Each column at a time The first is neighbourhood_group set(data['neighbourhood_group']){'Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island'}data.groupby('neighbourhood_group')['price'].describe() This table easily shows the distribution of price in each neighbourhood_group and across all. The numbers of Airbnb is not even. Most Airbnb houses are in either Manhattan or Brooklyn. However, these two regions are also the highest prices among the five regions. A possible reason is that because the demands in these regions are high, causing more hosts to rent out their rooms or apartments. To show more accurately on the price, a further breakdown with consideration of room type is carried. data.pivot_table(index='neighbourhood_group',columns='room_type',values='price',aggfunc='mean') In average, you can get a private room in Brooklyn but you can’t even afford a shared room in Manhattan. Next is the location of Airbnb. As already known there are more Airbnb in Manhattan and Brooklyn. Here I use a heat map to present. ny_map = folium.Map(location=[40.7, -74],zoom_start =10)data_loc= data[['latitude','longitude']].valuesdata_loc =data_loc.tolist()hm = plugins.HeatMap(data_loc)hm.add_to(ny_map)ny_map There is a large red area in Manhattan and Brooklyn. It’s time to further breakdown in each small neighborhood. for gp in set(data['neighbourhood_group']): print(data.loc[data['neighbourhood_group']==gp,].groupby(['neighbour hood_group','neighbourhood']).agg({'price':['count','mean']}).sort_values(by=('price', 'mean'),ascending=False).head())print() The above table shows the top 5 most expensive neighborhood in each group. Except for Staten Island which there is only 1 record in some neighbors for top 5 neighbors, others have enough records to correctly represent the average price in each region. Riverdale in Bronx is as expensive as in Manhattan. Next variable to be studied is “minimum_nights” The first is to breakdown by “neighbourhood_group” data.groupby('neighbourhood_group')['minimum_nights'].describe() As all records with ‘minimum_nights’ larger than 365 were removed already, the max is only 365. As shown, over 25% of Airbnb place only require 1 night and over half only require 2 or 3 nights which fits in the original principle of Airbnb service, a short term accommodation. Now we can move to the next variable, views. Instead of using number_of_reviews, I would use reviews_per_month since this can eliminate the effect of duration listing on Airbnb. for gp in set(data['neighbourhood_group']):print(gp)print(data[data['neighbourhood_group']==gp] ['price','reviews_per_month']].corr())print() Apparently there is no relationship between price and number of reviews per month. Instead, almost all houses only get few reviews per month. Here is the end of the analysis. Hope you enjoy and please share your comment to me so I can keep improving and demonstrate more data analysis using Python in the future. See you next time. Full code can be found in https://github.com/wyfok/New_York_City_Airbnb_Open_Data
[ { "code": null, "e": 480, "s": 172, "text": "In this article, I will perform data analysis by using Python and record down every finding and thought during the analysis. Practicing with real data can not only help me have more experience in analyzing different data but also help me discover more techniques and skills when compared with others’ works." }, { "code": null, "e": 660, "s": 480, "text": "The dataset used in this article is “New York City Airbnb Open Data” which is from Kaggle. Here is the download link https://www.kaggle.com/dgomonov/new-york-city-airbnb-open-data" }, { "code": null, "e": 870, "s": 660, "text": "After importing modules and csv file, normally my first step is to explore the dataset. This step includes studying the format of the overall dataset, types of all variables, checking and cleaning the dataset." }, { "code": null, "e": 1960, "s": 870, "text": "data = pd.read_csv('AB_NYC_2019.csv')data.info()class 'pandas.core.frame.DataFrame'>RangeIndex: 48895 entries, 0 to 48894Data columns (total 16 columns):id 48895 non-null int64name 48879 non-null objecthost_id 48895 non-null int64host_name 48874 non-null objectneighbourhood_group 48895 non-null objectneighbourhood 48895 non-null objectlatitude 48895 non-null float64longitude 48895 non-null float64room_type 48895 non-null objectprice 48895 non-null int64minimum_nights 48895 non-null int64number_of_reviews 48895 non-null int64last_review 38843 non-null objectreviews_per_month 38843 non-null float64calculated_host_listings_count 48895 non-null int64availability_365 48895 non-null int64dtypes: float64(3), int64(7), object(6)memory usage: 6.0+ MB" }, { "code": null, "e": 2034, "s": 1960, "text": "So there are in total of 16 columns and some columns have missing values." }, { "code": null, "e": 2690, "s": 2034, "text": "data.isnull().sum()id 0name 16host_id 0host_name 21neighbourhood_group 0neighbourhood 0latitude 0longitude 0room_type 0price 0minimum_nights 0number_of_reviews 0last_review 10052reviews_per_month 10052calculated_host_listings_count 0availability_365 0dtype: int64" }, { "code": null, "e": 2972, "s": 2690, "text": "Both last_review and reviews_per_month have over 10k missing values in the dataset. And they also have the same numbers of missing values. Based on the names and numbers of missing values, I suspect that these two columns are related and so have the same numbers of missing values." }, { "code": null, "e": 3049, "s": 2972, "text": "(data['last_review'].isnull()==data['reviews_per_month'].isnull()).all()True" }, { "code": null, "e": 3085, "s": 3049, "text": "So they should be handled together." }, { "code": null, "e": 3291, "s": 3085, "text": "At this moment, I don’t know how to handle missing values in “last_review” column as this normally shows a date string indicating the date of the last review. So at this moment, I will just leave it first." }, { "code": null, "e": 3369, "s": 3291, "text": "However, for missing values in reviews_per_month, I will assign them as zero." }, { "code": null, "e": 3436, "s": 3369, "text": "data.loc[data['reviews_per_month'].isnull(),'reviews_per_month']=0" }, { "code": null, "e": 3662, "s": 3436, "text": "Remaining columns with missing values are name and host_name. However, I don’t think there is any predictive power from either name or host_name. So instead of handling missing values, I will directly remove from the dataset." }, { "code": null, "e": 3974, "s": 3662, "text": "There are two columns, id and host_id, indicating the Airbnb house and host. After checking, id is unique in the dataset but not host_id. Therefore, id can be removed but not host_id. Also, it can be meaningful if there is any relationship between the number of listing house and price. So host_id will be kept." }, { "code": null, "e": 4023, "s": 3974, "text": "Next step is to check numeric variables by using" }, { "code": null, "e": 4039, "s": 4023, "text": "data.describe()" }, { "code": null, "e": 4241, "s": 4039, "text": "Using describe() can help me understand the range of possible values for each variable. I can know the distribution of values. Also, it is possible to discover any unrealistic records from the dataset." }, { "code": null, "e": 4452, "s": 4241, "text": "For example in this dataset, there are some abnormalities. The first one is that there are records with “price” = 0 which is unrealistic as this means no need to pay to stay. So these records should be removed." }, { "code": null, "e": 4705, "s": 4452, "text": "The second is that the maximum of “minimum_nights” is 1250 which I believe is unrealistic (is this still an Airbnb or just another rental contract?). I put a threshold as 365 days. Any records with “minimum_nights” larger than 365 will also be removed." }, { "code": null, "e": 4729, "s": 4705, "text": "Dataset after cleaning:" }, { "code": null, "e": 5564, "s": 4729, "text": "data.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 48870 entries, 0 to 48869Data columns (total 12 columns):host_id 48870 non-null int64neighbourhood_group 48870 non-null objectneighbourhood 48870 non-null objectlatitude 48870 non-null float64longitude 48870 non-null float64room_type 48870 non-null objectprice 48870 non-null int64minimum_nights 48870 non-null int64number_of_reviews 48870 non-null int64reviews_per_month 48870 non-null float64calculated_host_listings_count 48870 non-null int64availability_365 48870 non-null int64dtypes: float64(3), int64(6), object(3)memory usage: 4.5+ MB" }, { "code": null, "e": 5590, "s": 5564, "text": "48870 rows and 12 columns" }, { "code": null, "e": 5650, "s": 5590, "text": "Now I can have a look at the dataset. Each column at a time" }, { "code": null, "e": 5683, "s": 5650, "text": "The first is neighbourhood_group" }, { "code": null, "e": 5832, "s": 5683, "text": "set(data['neighbourhood_group']){'Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island'}data.groupby('neighbourhood_group')['price'].describe()" }, { "code": null, "e": 6227, "s": 5832, "text": "This table easily shows the distribution of price in each neighbourhood_group and across all. The numbers of Airbnb is not even. Most Airbnb houses are in either Manhattan or Brooklyn. However, these two regions are also the highest prices among the five regions. A possible reason is that because the demands in these regions are high, causing more hosts to rent out their rooms or apartments." }, { "code": null, "e": 6329, "s": 6227, "text": "To show more accurately on the price, a further breakdown with consideration of room type is carried." }, { "code": null, "e": 6425, "s": 6329, "text": "data.pivot_table(index='neighbourhood_group',columns='room_type',values='price',aggfunc='mean')" }, { "code": null, "e": 6530, "s": 6425, "text": "In average, you can get a private room in Brooklyn but you can’t even afford a shared room in Manhattan." }, { "code": null, "e": 6662, "s": 6530, "text": "Next is the location of Airbnb. As already known there are more Airbnb in Manhattan and Brooklyn. Here I use a heat map to present." }, { "code": null, "e": 6846, "s": 6662, "text": "ny_map = folium.Map(location=[40.7, -74],zoom_start =10)data_loc= data[['latitude','longitude']].valuesdata_loc =data_loc.tolist()hm = plugins.HeatMap(data_loc)hm.add_to(ny_map)ny_map" }, { "code": null, "e": 6899, "s": 6846, "text": "There is a large red area in Manhattan and Brooklyn." }, { "code": null, "e": 6958, "s": 6899, "text": "It’s time to further breakdown in each small neighborhood." }, { "code": null, "e": 7201, "s": 6958, "text": "for gp in set(data['neighbourhood_group']): print(data.loc[data['neighbourhood_group']==gp,].groupby(['neighbour hood_group','neighbourhood']).agg({'price':['count','mean']}).sort_values(by=('price', 'mean'),ascending=False).head())print()" }, { "code": null, "e": 7505, "s": 7201, "text": "The above table shows the top 5 most expensive neighborhood in each group. Except for Staten Island which there is only 1 record in some neighbors for top 5 neighbors, others have enough records to correctly represent the average price in each region. Riverdale in Bronx is as expensive as in Manhattan." }, { "code": null, "e": 7604, "s": 7505, "text": "Next variable to be studied is “minimum_nights” The first is to breakdown by “neighbourhood_group”" }, { "code": null, "e": 7669, "s": 7604, "text": "data.groupby('neighbourhood_group')['minimum_nights'].describe()" }, { "code": null, "e": 7946, "s": 7669, "text": "As all records with ‘minimum_nights’ larger than 365 were removed already, the max is only 365. As shown, over 25% of Airbnb place only require 1 night and over half only require 2 or 3 nights which fits in the original principle of Airbnb service, a short term accommodation." }, { "code": null, "e": 8124, "s": 7946, "text": "Now we can move to the next variable, views. Instead of using number_of_reviews, I would use reviews_per_month since this can eliminate the effect of duration listing on Airbnb." }, { "code": null, "e": 8269, "s": 8124, "text": "for gp in set(data['neighbourhood_group']):print(gp)print(data[data['neighbourhood_group']==gp] ['price','reviews_per_month']].corr())print()" }, { "code": null, "e": 8352, "s": 8269, "text": "Apparently there is no relationship between price and number of reviews per month." }, { "code": null, "e": 8411, "s": 8352, "text": "Instead, almost all houses only get few reviews per month." }, { "code": null, "e": 8601, "s": 8411, "text": "Here is the end of the analysis. Hope you enjoy and please share your comment to me so I can keep improving and demonstrate more data analysis using Python in the future. See you next time." } ]
Python String isalpha() Method - GeeksforGeeks
12 Aug, 2021 Python String isalpha() method is a built-in method used for string handling. The isalpha() methods returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. This function is used to check if the argument includes only alphabet characters (mentioned below). ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz Syntax: string.isalpha() Parameters: isalpha() does not take any parameters Returns: True: If all characters in the string are alphabet. False: If the string contains 1 or more non-alphabets. Errors and Exceptions: It contains no arguments, therefore an error occurs if a parameter is passedBoth uppercase and lowercase alphabets return “True”Space is not considered to be the alphabet, therefore it returns “False” It contains no arguments, therefore an error occurs if a parameter is passed Both uppercase and lowercase alphabets return “True” Space is not considered to be the alphabet, therefore it returns “False” Input : string = 'Ayush' Output : True Input : string = 'Ayush Saxena' Output : False Input : string = 'Ayush0212' Output : False Python3 # Python code for implementation of isalpha() # checking for alphabetsstring = 'Ayush'print(string.isalpha()) string = 'Ayush0212'print(string.isalpha()) # checking if space is an alphabetstring = 'Ayush Saxena'print( string.isalpha()) Output: True False False Given a string in python, count number of alphabets in the string and print the alphabets. Input : string = 'Ayush Saxena' Output : 11 AyushSaxena Input : string = 'Ayush0212' Output : 5 Ayush Algorithm: Initialize a new string and variable counter to 0. Traverse the given string character by character upto its length, check if character is an alphabet. If it is an alphabet, increment the counter by 1 and add it to a the new string, else traverse to the next character. Print the value of the counter and the new string. Initialize a new string and variable counter to 0. Traverse the given string character by character upto its length, check if character is an alphabet. If it is an alphabet, increment the counter by 1 and add it to a the new string, else traverse to the next character. Print the value of the counter and the new string. Python3 # Python program to illustrate# counting number of alphabets # using isalpha() # Given stringstring='Ayush Saxena'count=0 # Initialising new stringsnewstring1 =""newstring2 ="" # Iterating the string and checking for alphabets# Incrementing the counter if an alphabet is found# Finally printing the countfor a in string: if (a.isalpha()) == True: count+=1 newstring1+=aprint(count)print(newstring1) # Given stringstring='Ayush0212'count=0for a in string: if (a.isalpha()) == True: count+=1 newstring2+=aprint(count)print(newstring2) Output: 11 AyushSaxena 5 Ayush roozbeh AmiyaRanjanRout Python-Built-in-functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python
[ { "code": null, "e": 23894, "s": 23866, "text": "\n12 Aug, 2021" }, { "code": null, "e": 24189, "s": 23894, "text": "Python String isalpha() method is a built-in method used for string handling. The isalpha() methods returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. This function is used to check if the argument includes only alphabet characters (mentioned below). " }, { "code": null, "e": 24242, "s": 24189, "text": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 24251, "s": 24242, "text": "Syntax: " }, { "code": null, "e": 24268, "s": 24251, "text": "string.isalpha()" }, { "code": null, "e": 24280, "s": 24268, "text": "Parameters:" }, { "code": null, "e": 24319, "s": 24280, "text": "isalpha() does not take any parameters" }, { "code": null, "e": 24328, "s": 24319, "text": "Returns:" }, { "code": null, "e": 24380, "s": 24328, "text": "True: If all characters in the string are alphabet." }, { "code": null, "e": 24435, "s": 24380, "text": "False: If the string contains 1 or more non-alphabets." }, { "code": null, "e": 24458, "s": 24435, "text": "Errors and Exceptions:" }, { "code": null, "e": 24659, "s": 24458, "text": "It contains no arguments, therefore an error occurs if a parameter is passedBoth uppercase and lowercase alphabets return “True”Space is not considered to be the alphabet, therefore it returns “False”" }, { "code": null, "e": 24736, "s": 24659, "text": "It contains no arguments, therefore an error occurs if a parameter is passed" }, { "code": null, "e": 24789, "s": 24736, "text": "Both uppercase and lowercase alphabets return “True”" }, { "code": null, "e": 24862, "s": 24789, "text": "Space is not considered to be the alphabet, therefore it returns “False”" }, { "code": null, "e": 24994, "s": 24862, "text": "Input : string = 'Ayush'\nOutput : True\n\nInput : string = 'Ayush Saxena'\nOutput : False\n\nInput : string = 'Ayush0212'\nOutput : False" }, { "code": null, "e": 25002, "s": 24994, "text": "Python3" }, { "code": "# Python code for implementation of isalpha() # checking for alphabetsstring = 'Ayush'print(string.isalpha()) string = 'Ayush0212'print(string.isalpha()) # checking if space is an alphabetstring = 'Ayush Saxena'print( string.isalpha())", "e": 25244, "s": 25002, "text": null }, { "code": null, "e": 25253, "s": 25244, "text": "Output: " }, { "code": null, "e": 25270, "s": 25253, "text": "True\nFalse\nFalse" }, { "code": null, "e": 25362, "s": 25270, "text": "Given a string in python, count number of alphabets in the string and print the alphabets. " }, { "code": null, "e": 25483, "s": 25362, "text": "Input : string = 'Ayush Saxena'\nOutput : 11\n AyushSaxena\n\nInput : string = 'Ayush0212'\nOutput : 5\n Ayush" }, { "code": null, "e": 25494, "s": 25483, "text": "Algorithm:" }, { "code": null, "e": 25815, "s": 25494, "text": "Initialize a new string and variable counter to 0. Traverse the given string character by character upto its length, check if character is an alphabet. If it is an alphabet, increment the counter by 1 and add it to a the new string, else traverse to the next character. Print the value of the counter and the new string." }, { "code": null, "e": 25867, "s": 25815, "text": "Initialize a new string and variable counter to 0. " }, { "code": null, "e": 25969, "s": 25867, "text": "Traverse the given string character by character upto its length, check if character is an alphabet. " }, { "code": null, "e": 26088, "s": 25969, "text": "If it is an alphabet, increment the counter by 1 and add it to a the new string, else traverse to the next character. " }, { "code": null, "e": 26139, "s": 26088, "text": "Print the value of the counter and the new string." }, { "code": null, "e": 26147, "s": 26139, "text": "Python3" }, { "code": "# Python program to illustrate# counting number of alphabets # using isalpha() # Given stringstring='Ayush Saxena'count=0 # Initialising new stringsnewstring1 =\"\"newstring2 =\"\" # Iterating the string and checking for alphabets# Incrementing the counter if an alphabet is found# Finally printing the countfor a in string: if (a.isalpha()) == True: count+=1 newstring1+=aprint(count)print(newstring1) # Given stringstring='Ayush0212'count=0for a in string: if (a.isalpha()) == True: count+=1 newstring2+=aprint(count)print(newstring2)", "e": 26718, "s": 26147, "text": null }, { "code": null, "e": 26727, "s": 26718, "text": "Output: " }, { "code": null, "e": 26750, "s": 26727, "text": "11\nAyushSaxena\n5\nAyush" }, { "code": null, "e": 26758, "s": 26750, "text": "roozbeh" }, { "code": null, "e": 26774, "s": 26758, "text": "AmiyaRanjanRout" }, { "code": null, "e": 26800, "s": 26774, "text": "Python-Built-in-functions" }, { "code": null, "e": 26814, "s": 26800, "text": "python-string" }, { "code": null, "e": 26821, "s": 26814, "text": "Python" }, { "code": null, "e": 26919, "s": 26821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26947, "s": 26919, "text": "Read JSON file using Python" }, { "code": null, "e": 26997, "s": 26947, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27019, "s": 26997, "text": "Python map() function" }, { "code": null, "e": 27063, "s": 27019, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27081, "s": 27063, "text": "Python Dictionary" }, { "code": null, "e": 27104, "s": 27081, "text": "Taking input in Python" }, { "code": null, "e": 27139, "s": 27104, "text": "Read a file line by line in Python" }, { "code": null, "e": 27171, "s": 27139, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27213, "s": 27171, "text": "Different ways to create Pandas Dataframe" } ]
Apache Oozie - CLI and Extensions
By this time, you have a good understanding of Oozie workflows, coordinators and bundles. In the last part of this tutorial, let’s touch base some of the other important concepts in Oozie. We have seen a few commands earlier to run the jobs of workflow, coordinator and bundle. Oozie provides a command line utility, Oozie, to perform job and admin tasks. oozie version : show client version Following are some of the other job operations − oozie job <OPTIONS> : -action <arg> coordinator rerun on action ids (requires -rerun); coordinator log retrieval on action ids (requires -log) -auth <arg> select authentication type [SIMPLE|KERBEROS] -change <arg> change a coordinator/bundle job -config <arg> job configuration file '.xml' or '.properties' -D <property = value> set/override value for given property -date <arg> coordinator/bundle rerun on action dates (requires -rerun) -definition <arg> job definition -doas <arg> doAs user, impersonates as the specified user -dryrun Supported in Oozie-2.0 or later versions ONLY - dryrun or test run a coordinator job, job is not queued -info <arg> info of a job -kill <arg> kill a job -len <arg> number of actions (default TOTAL ACTIONS, requires -info) -localtime use local time (default GMT) -log <arg> job log -nocleanup do not clean up output-events of the coordinator rerun actions (requires -rerun) -offset <arg> job info offset of actions (default '1', requires -info) -oozie <arg> Oozie URL -refresh re-materialize the coordinator rerun actions (requires -rerun) -rerun <arg> rerun a job (coordinator requires -action or -date; bundle requires -coordinator or -date) -resume <arg> resume a job -run run a job -start <arg> start a job -submit submit a job -suspend <arg> suspend a job -value <arg> new endtime/concurrency/pausetime value for changing a coordinator job;new pausetime value for changing a bundle job -verbose verbose mode To check the status of the job, following commands can be used. -auth <arg> select authentication type [SIMPLE|KERBEROS] -doas <arg> doAs user, impersonates as the specified user. -filter <arg> user = <U>; name = <N>; group = <G>; status = <S>; ... -jobtype <arg> job type ('Supported in Oozie-2.0 or later versions ONLY - coordinator' or 'wf' (default)) -len <arg> number of jobs (default '100') -localtime use local time (default GMT) -offset <arg> jobs offset (default '1') -oozie <arg> Oozie URL -verbose verbose mode For example − To check the status of the Oozie system you can run the following command − oozie admin -oozie http://localhost:8080/oozie -status Validating a Workflow XML − oozie validate myApp/workflow.xml It performs an XML Schema validation on the specified workflow XML file. We have seen hive extensions. Similarly, Oozie provides more action extensions few of them are as below − The email action allows sending emails in Oozie from a workflow application. An email action must provide to addresses, cc addresses (optional), a subject and a body. Multiple recipients of an email can be provided as comma separated addresses. All the values specified in the email action can be parameterized (templated) using EL expressions. <workflow-app name = "sample-wf" xmlns = "uri:oozie:workflow:0.1"> ... <action name = "an-email"> <email xmlns = "uri:oozie:email-action:0.1"> <to>julie@xyz.com,max@abc.com</to> <cc>jax@xyz.com</cc> <subject>Email notifications for ${wf:id()}</subject> <body>The wf ${wf:id()} successfully completed.</body> </email> <ok to = "main_job"/> <error to = "kill_job"/> </action> ... </workflow-app> The shell action runs a Shell command. The workflow job will wait until the Shell command completes before continuing to the next action. To run the Shell job, you have to configure the shell action with the =job-tracker=, name-node and Shell exec elements as well as the necessary arguments and configuration. A shell action can be configured to create or delete HDFS directories before starting the Shell job. The shell launcher configuration can be specified with a file, using the job-xml element, and inline, using the configuration elements. How to run any shell script? <workflow-app xmlns = 'uri:oozie:workflow:0.3' name = 'shell-wf'> <start to = 'shell1' /> <action name = 'shell1'> <shell xmlns = "uri:oozie:shell-action:0.1"> <job-tracker>${jobTracker}</job-tracker> <name-node>${nameNode}</name-node> <file>path_of_file_name</file> </shell> <ok to = "end" /> <error to = "fail" /> </action> <kill name = "fail"> <message>Script failed, error message[${wf:errorMessage(wf:lastErrorNode())}] </message> </kill> <end name = 'end' /> </workflow-app> Similarly, we can have many more actions like ssh, sqoop, java action, etc. Oozie official documentation website is the best resource to understand Oozie in detail. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1964, "s": 1775, "text": "By this time, you have a good understanding of Oozie workflows, coordinators and bundles. In the last part of this tutorial, let’s touch base some of the other important concepts in Oozie." }, { "code": null, "e": 2131, "s": 1964, "text": "We have seen a few commands earlier to run the jobs of workflow, coordinator and bundle. Oozie provides a command line utility, Oozie, to perform job and admin tasks." }, { "code": null, "e": 2168, "s": 2131, "text": "oozie version : show client version\n" }, { "code": null, "e": 2217, "s": 2168, "text": "Following are some of the other job operations −" }, { "code": null, "e": 3686, "s": 2217, "text": "oozie job <OPTIONS> :\n-action <arg> coordinator rerun on action ids (requires -rerun); coordinator log\n retrieval on action ids (requires -log)\n-auth <arg> select authentication type [SIMPLE|KERBEROS]\n-change <arg> change a coordinator/bundle job\n-config <arg> job configuration file '.xml' or '.properties'\n-D <property = value> set/override value for given property\n-date <arg> coordinator/bundle rerun on action dates (requires -rerun)\n-definition <arg> job definition\n-doas <arg> doAs user, impersonates as the specified user\n-dryrun Supported in Oozie-2.0 or later versions ONLY - dryrun or test run a\n coordinator job, job is not queued\n-info <arg> info of a job\n-kill <arg> kill a job\n-len <arg> number of actions (default TOTAL ACTIONS, requires -info)\n-localtime use local time (default GMT)\n-log <arg> job log\n-nocleanup do not clean up output-events of the coordinator rerun actions (requires\n -rerun)\n-offset <arg> job info offset of actions (default '1', requires -info)\n-oozie <arg> Oozie URL\n-refresh re-materialize the coordinator rerun actions (requires -rerun)\n-rerun <arg> rerun a job (coordinator requires -action or -date; bundle requires \n -coordinator or -date)\n-resume <arg> resume a job\n-run run a job\n-start <arg> start a job\n-submit submit a job\n-suspend <arg> suspend a job\n-value <arg> new endtime/concurrency/pausetime value for changing a coordinator \n job;new pausetime value for changing a bundle job\n-verbose verbose mode\n" }, { "code": null, "e": 3750, "s": 3686, "text": "To check the status of the job, following commands can be used." }, { "code": null, "e": 4213, "s": 3750, "text": "-auth <arg> select authentication type [SIMPLE|KERBEROS]\n-doas <arg> doAs user, impersonates as the specified user.\n-filter <arg> user = <U>; name = <N>; group = <G>; status = <S>; ...\n-jobtype <arg> job type ('Supported in Oozie-2.0 or later versions ONLY - \n coordinator' or 'wf' (default))\n-len <arg> number of jobs (default '100')\n-localtime use local time (default GMT)\n-offset <arg> jobs offset (default '1')\n-oozie <arg> Oozie URL\n-verbose verbose mode\n" }, { "code": null, "e": 4303, "s": 4213, "text": "For example − To check the status of the Oozie system you can run the following command −" }, { "code": null, "e": 4359, "s": 4303, "text": "oozie admin -oozie http://localhost:8080/oozie -status\n" }, { "code": null, "e": 4387, "s": 4359, "text": "Validating a Workflow XML −" }, { "code": null, "e": 4422, "s": 4387, "text": "oozie validate myApp/workflow.xml\n" }, { "code": null, "e": 4495, "s": 4422, "text": "It performs an XML Schema validation on the specified workflow XML file." }, { "code": null, "e": 4601, "s": 4495, "text": "We have seen hive extensions. Similarly, Oozie provides more action extensions few of them are as below −" }, { "code": null, "e": 4846, "s": 4601, "text": "The email action allows sending emails in Oozie from a workflow application. An email action must provide to addresses, cc addresses (optional), a subject and a body. Multiple recipients of an email can be provided as comma separated addresses." }, { "code": null, "e": 4946, "s": 4846, "text": "All the values specified in the email action can be parameterized (templated) using EL expressions." }, { "code": null, "e": 5406, "s": 4946, "text": "<workflow-app name = \"sample-wf\" xmlns = \"uri:oozie:workflow:0.1\">\n...\n <action name = \"an-email\">\n <email xmlns = \"uri:oozie:email-action:0.1\">\n <to>julie@xyz.com,max@abc.com</to>\n <cc>jax@xyz.com</cc>\n <subject>Email notifications for ${wf:id()}</subject>\n <body>The wf ${wf:id()} successfully completed.</body>\n </email>\n <ok to = \"main_job\"/>\n <error to = \"kill_job\"/>\n </action>\n...\n</workflow-app>" }, { "code": null, "e": 5544, "s": 5406, "text": "The shell action runs a Shell command. The workflow job will wait until the Shell command completes before continuing to the next action." }, { "code": null, "e": 5818, "s": 5544, "text": "To run the Shell job, you have to configure the shell action with the =job-tracker=, name-node and Shell exec elements as well as the necessary arguments and configuration. A shell action can be configured to create or delete HDFS directories before starting the Shell job." }, { "code": null, "e": 5954, "s": 5818, "text": "The shell launcher configuration can be specified with a file, using the job-xml element, and inline, using the configuration elements." }, { "code": null, "e": 5983, "s": 5954, "text": "How to run any shell script?" }, { "code": null, "e": 6558, "s": 5983, "text": "<workflow-app xmlns = 'uri:oozie:workflow:0.3' name = 'shell-wf'>\n <start to = 'shell1' />\n \n <action name = 'shell1'>\n <shell xmlns = \"uri:oozie:shell-action:0.1\">\n <job-tracker>${jobTracker}</job-tracker>\n <name-node>${nameNode}</name-node>\n <file>path_of_file_name</file>\n </shell>\n <ok to = \"end\" />\n <error to = \"fail\" />\n </action>\n \n <kill name = \"fail\">\n <message>Script failed, error message[${wf:errorMessage(wf:lastErrorNode())}]\n </message>\n </kill>\n\t\n <end name = 'end' />\n</workflow-app>" }, { "code": null, "e": 6634, "s": 6558, "text": "Similarly, we can have many more actions like ssh, sqoop, java action, etc." }, { "code": null, "e": 6723, "s": 6634, "text": "Oozie official documentation website is the best resource to understand Oozie in detail." }, { "code": null, "e": 6758, "s": 6723, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6777, "s": 6758, "text": " Arnab Chakraborty" }, { "code": null, "e": 6812, "s": 6777, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6833, "s": 6812, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 6866, "s": 6833, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6879, "s": 6866, "text": " Nilay Mehta" }, { "code": null, "e": 6914, "s": 6879, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6932, "s": 6914, "text": " Bigdata Engineer" }, { "code": null, "e": 6965, "s": 6932, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6983, "s": 6965, "text": " Bigdata Engineer" }, { "code": null, "e": 7016, "s": 6983, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7034, "s": 7016, "text": " Bigdata Engineer" }, { "code": null, "e": 7041, "s": 7034, "text": " Print" }, { "code": null, "e": 7052, "s": 7041, "text": " Add Notes" } ]
Console.SetWindowSize() Method in C# - GeeksforGeeks
20 Feb, 2019 Console.SetWindowSize(Int32, Int32) Method is used to change the height and width of the console window to the specified values. Syntax: public static void SetWindowSize (int width, int height); Parameters:width: The width of the console window measured in columns.height: The height of the console window measured in rows. Exceptions: ArgumentOutOfRangeException:If the width or height is less than or equal to zerowidth plus WindowLeft or height plus WindowTop is greater than or equal to MaxValuewidth or height is greater than the largest possible window width or height for the current screen resolution and console font. If the width or height is less than or equal to zero width plus WindowLeft or height plus WindowTop is greater than or equal to MaxValue width or height is greater than the largest possible window width or height for the current screen resolution and console font. IOException: If an I/O error occured. Example 1: Getting the current dimensions of the window. // C# program to get the current// window width and Heightusing System; namespace GFG { class Program { static void Main(string[] args) { Console.WriteLine(Console.WindowWidth); Console.WriteLine(Console.WindowHeight); }}} Output: Example 2: Setting the value of SetWindowSize // C# program to illustrate the// Console.SetWindowSize Propertyusing System; namespace GFG { class Program { static void Main(string[] args) { // Passed 40, 40 to SetWindowSize to // change window size to 40 by 40 Console.SetWindowSize(40, 40);. // Printing the current dimensions Console.WriteLine(Console.WindowWidth); Console.WriteLine(Console.WindowHeight); }}} Output: Note: See the Horizontal Scroll Bar at the bottom of the Window in both the images. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.setwindowsize?view=netframework-4.7.2 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Method Overriding C# | Abstract Classes Extension Method in C# C# | Replace() Method Difference between Ref and Out keywords in C# C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 C# | Constructors Introduction to .NET Framework
[ { "code": null, "e": 26830, "s": 26802, "text": "\n20 Feb, 2019" }, { "code": null, "e": 26959, "s": 26830, "text": "Console.SetWindowSize(Int32, Int32) Method is used to change the height and width of the console window to the specified values." }, { "code": null, "e": 27025, "s": 26959, "text": "Syntax: public static void SetWindowSize (int width, int height);" }, { "code": null, "e": 27154, "s": 27025, "text": "Parameters:width: The width of the console window measured in columns.height: The height of the console window measured in rows." }, { "code": null, "e": 27166, "s": 27154, "text": "Exceptions:" }, { "code": null, "e": 27457, "s": 27166, "text": "ArgumentOutOfRangeException:If the width or height is less than or equal to zerowidth plus WindowLeft or height plus WindowTop is greater than or equal to MaxValuewidth or height is greater than the largest possible window width or height for the current screen resolution and console font." }, { "code": null, "e": 27510, "s": 27457, "text": "If the width or height is less than or equal to zero" }, { "code": null, "e": 27594, "s": 27510, "text": "width plus WindowLeft or height plus WindowTop is greater than or equal to MaxValue" }, { "code": null, "e": 27722, "s": 27594, "text": "width or height is greater than the largest possible window width or height for the current screen resolution and console font." }, { "code": null, "e": 27760, "s": 27722, "text": "IOException: If an I/O error occured." }, { "code": null, "e": 27817, "s": 27760, "text": "Example 1: Getting the current dimensions of the window." }, { "code": "// C# program to get the current// window width and Heightusing System; namespace GFG { class Program { static void Main(string[] args) { Console.WriteLine(Console.WindowWidth); Console.WriteLine(Console.WindowHeight); }}}", "e": 28067, "s": 27817, "text": null }, { "code": null, "e": 28075, "s": 28067, "text": "Output:" }, { "code": null, "e": 28121, "s": 28075, "text": "Example 2: Setting the value of SetWindowSize" }, { "code": "// C# program to illustrate the// Console.SetWindowSize Propertyusing System; namespace GFG { class Program { static void Main(string[] args) { // Passed 40, 40 to SetWindowSize to // change window size to 40 by 40 Console.SetWindowSize(40, 40);. // Printing the current dimensions Console.WriteLine(Console.WindowWidth); Console.WriteLine(Console.WindowHeight); }}}", "e": 28546, "s": 28121, "text": null }, { "code": null, "e": 28554, "s": 28546, "text": "Output:" }, { "code": null, "e": 28638, "s": 28554, "text": "Note: See the Horizontal Scroll Bar at the bottom of the Window in both the images." }, { "code": null, "e": 28649, "s": 28638, "text": "Reference:" }, { "code": null, "e": 28746, "s": 28649, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.setwindowsize?view=netframework-4.7.2" }, { "code": null, "e": 28767, "s": 28746, "text": "CSharp-Console-Class" }, { "code": null, "e": 28781, "s": 28767, "text": "CSharp-method" }, { "code": null, "e": 28788, "s": 28781, "text": "Picked" }, { "code": null, "e": 28791, "s": 28788, "text": "C#" }, { "code": null, "e": 28889, "s": 28791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28904, "s": 28889, "text": "C# | Delegates" }, { "code": null, "e": 28927, "s": 28904, "text": "C# | Method Overriding" }, { "code": null, "e": 28949, "s": 28927, "text": "C# | Abstract Classes" }, { "code": null, "e": 28972, "s": 28949, "text": "Extension Method in C#" }, { "code": null, "e": 28994, "s": 28972, "text": "C# | Replace() Method" }, { "code": null, "e": 29040, "s": 28994, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29062, "s": 29040, "text": "C# | Class and Object" }, { "code": null, "e": 29102, "s": 29062, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29120, "s": 29102, "text": "C# | Constructors" } ]
How to get all combinations of some arrays in JavaScript?
You can use your own function to get all combinations. Following is the code − function combination(values) { function * combinationRepeat(size, v) { if (size) for (var chr of values) yield * combinationRepeat(size - 1, v + chr); else yield v; } return [...combinationRepeat(values.length, "")]; } var output = combination([4,5]); console.log(output); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo306.js. This will produce the following output − PS C:\Users\Amit\javascript-code> node demo306.js [ '44', '45', '54', '55' ]
[ { "code": null, "e": 1117, "s": 1062, "text": "You can use your own function to get all combinations." }, { "code": null, "e": 1141, "s": 1117, "text": "Following is the code −" }, { "code": null, "e": 1450, "s": 1141, "text": "function combination(values) {\n function * combinationRepeat(size, v) {\n if (size)\n for (var chr of values)\n yield * combinationRepeat(size - 1, v + chr);\n else yield v;\n }\n return [...combinationRepeat(values.length, \"\")];\n}\nvar output = combination([4,5]);\nconsole.log(output);" }, { "code": null, "e": 1516, "s": 1450, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1534, "s": 1516, "text": "node fileName.js." }, { "code": null, "e": 1568, "s": 1534, "text": "Here, my file name is demo306.js." }, { "code": null, "e": 1609, "s": 1568, "text": "This will produce the following output −" }, { "code": null, "e": 1686, "s": 1609, "text": "PS C:\\Users\\Amit\\javascript-code> node demo306.js\n[ '44', '45', '54', '55' ]" } ]
Count of common subarrays in two different permutations of 1 to N - GeeksforGeeks
17 Aug, 2021 Given two arrays A and B of the same length N, filled with a permutation of natural numbers from 1 to N, the task is to count the number of common subarrays in A and B.Examples: Input: A = [1, 2, 3], B = [2, 3, 1] Output: 4 Explanation: The common subarrays are [1], [2], [3], [2, 3] Hence, total count = 4Input: A = [1, 2, 3, 4, 5], B = [2, 3, 1, 4, 5] Output: 7 Explanation: The common subarrays are [1], [2], [3], [4], [5], [2, 3], [4, 5] Hence, total count = 7 Naive Approach: The idea is to generate all subarrays of A and B separately, which would take O(N2) for each array. Now, compare all subarrays of A with all subarrays of B and count common subarrays. It would take O(N4).Efficient Approach: The idea is to use Hashing to solve this problem efficiently. Create a Hash array H of size N+1.Represent all elements of A by their respective indices: Create a Hash array H of size N+1. Represent all elements of A by their respective indices: Element Representation A[0] 0 A[1] 1 A[2] 2 . . and so on. 3. Use array H to store this representation, H[ A[ i ] ] = i 4. Update the elements of B according to this new representation using H, B[ i ] = H[ B[ i ] ] 5. Now, array A can be represented as [0, 1, 2, ..N], so simply count number of subarrays in B which have consecutive elements. Once we get length K of subarray of consecutive elements, count total possible subarray using following relation: Total number of subarrays = (K * (K + 1)) / 2 Look at this example to understand this approach in detail: Example: A = [4, 3, 1, 2, 5] B = [3, 1, 2, 4, 5] Common subarrays are [1], [2], [3], [4], [5], [3, 1], [1, 2], [3, 1, 2] = 81. Represent A[i] as i, and store in H as H[A[i]] = i, Now array H from index 1 to N is, H = [2, 3, 1, 0, 4]2. Update B according to H, B[i] = H[B[i]] B = [1, 2, 3, 0, 4]3. Look for subarray in B with consecutive elements, Subarray from index 0 to 2 is [1, 2, 3], consisting of consecutive elements with length K = 3 Element at index 3 forms a subarray [0] of length K = 1 Element at index 4 forms a subarray [4] of length K = 14. Total number of common subarrays = (3*(3+1))/2 + (1*(1+1))/2 + (1*(1+1))/2 = 6 + 1 + 1 = 8 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach#include<bits/stdc++.h>using namespace std; int commonSubarrays(int *A, int *B, int N){ // Initialising Map for // Index Mapping int Map[N + 1]; // Mapping elements of A for(int i = 0 ; i< N; i++) Map[*(A + i)] = i; // Modify elements of B // according to Map for (int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A *(B + i) = Map[*(B + i)]; } // Count of common subarrays int count = 0; // Traversing array B int i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codeint main(){ int N = 3; int A[] = {1, 2, 3}; int B[] = {2, 3, 1}; cout << (commonSubarrays(A, B, N)) << endl; N = 5; int C[] = {1, 2, 3, 4, 5}; int D[] = {2, 3, 1, 4, 5}; cout << (commonSubarrays(C, D, N));} // This code is contributed by chitranayal // Java implementation of the above approachclass GFG{ static int commonSubarrays(int []A, int []B, int N){ // Initialising Map for // Index Mapping int []Map = new int[N + 1]; // Mapping elements of A for(int i = 0; i< N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays int count = 0; // Traversing array B int i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codepublic static void main(String[] args){ int N = 3; int A[] = {1, 2, 3}; int B[] = {2, 3, 1}; System.out.print(commonSubarrays(A, B, N)); System.out.print("\n"); N = 5; int C[] = {1, 2, 3, 4, 5}; int D[] = {2, 3, 1, 4, 5}; System.out.print(commonSubarrays(C, D, N));}} // This code is contributed by gauravrajput1 # Python3 implementation of above approach def commonSubarrays(A, B, N): # Initialising Map for # Index Mapping Map = [0 for i in range(N + 1)] # Mapping elements of A for i in range(N): Map[A[i]]= i # Modify elements of B # according to Map for i in range(N) : # Changing B[i] as # the index of B[i] in A B[i]= Map[B[i]] # Count of common subarrays count = 0 # Traversing array B i = 0 while i<N: K = 1 i+= 1 # While consecutive elements # are found, we increment K while i<N and B[i]== B[i-1]+1: i+= 1 K+= 1 # Add number of subarrays # with length K # to total count count = count + ( (K)*(K + 1))//2 return count # Driver codeN = 3A =[1, 2, 3]B =[2, 3, 1]print(commonSubarrays(A, B, N)) N = 5A =[1, 2, 3, 4, 5]B =[2, 3, 1, 4, 5]print(commonSubarrays(A, B, N)) // C# implementation of the above approachusing System;class GFG{ static int commonSubarrays(int []A, int []B, int N){ // Initialising Map for // Index Mapping int []Map = new int[N + 1]; // Mapping elements of A for(int i = 0; i < N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays int count = 0; // Traversing array B int a = 0, K; while (a < N) { K = 1; a += 1; // While consecutive elements // are found, we increment K while (a < N && B[a] == B[a - 1] + 1) { a += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codepublic static void Main(){ int N = 3; int []A = {1, 2, 3}; int []B = {2, 3, 1}; Console.Write(commonSubarrays(A, B, N)); Console.Write("\n"); N = 5; int []C = {1, 2, 3, 4, 5}; int []D = {2, 3, 1, 4, 5}; Console.Write(commonSubarrays(C, D, N));}} // This code is contributed by Code_Mech <script>// Javascript implementation of the above approach function commonSubarrays(A, B, N){ // Initialising Map for // Index Mapping let Map = Array.from({length: N+1}, (_, i) => 0); // Mapping elements of A for(let i = 0; i< N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(let i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays let count = 0; // Traversing array B let i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver Code let N = 3; let A = [1, 2, 3]; let B = [2, 3, 1]; document.write(commonSubarrays(A, B, N)); document.write("<br/>"); N = 5; let C = [1, 2, 3, 4, 5]; let D = [2, 3, 1, 4, 5]; document.write(commonSubarrays(C, D, N)); // This code is contributed by target_2.</script> 4 7 Time complexity: O(N) Auxiliary Space: O(N) ukasp GauravRajput1 Code_Mech target_2 sagar0719kumar pankajsharmagfg permutation subarray Algorithms Arrays Combinatorial Data Structures Mathematical Data Structures Arrays Mathematical permutation Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to Start Learning DSA? Understanding Time Complexity with Simple Examples How to write a Pseudo Code? Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26675, "s": 26647, "text": "\n17 Aug, 2021" }, { "code": null, "e": 26854, "s": 26675, "text": "Given two arrays A and B of the same length N, filled with a permutation of natural numbers from 1 to N, the task is to count the number of common subarrays in A and B.Examples: " }, { "code": null, "e": 27143, "s": 26854, "text": "Input: A = [1, 2, 3], B = [2, 3, 1] Output: 4 Explanation: The common subarrays are [1], [2], [3], [2, 3] Hence, total count = 4Input: A = [1, 2, 3, 4, 5], B = [2, 3, 1, 4, 5] Output: 7 Explanation: The common subarrays are [1], [2], [3], [4], [5], [2, 3], [4, 5] Hence, total count = 7 " }, { "code": null, "e": 27449, "s": 27145, "text": "Naive Approach: The idea is to generate all subarrays of A and B separately, which would take O(N2) for each array. Now, compare all subarrays of A with all subarrays of B and count common subarrays. It would take O(N4).Efficient Approach: The idea is to use Hashing to solve this problem efficiently. " }, { "code": null, "e": 27541, "s": 27449, "text": "Create a Hash array H of size N+1.Represent all elements of A by their respective indices: " }, { "code": null, "e": 27576, "s": 27541, "text": "Create a Hash array H of size N+1." }, { "code": null, "e": 27634, "s": 27576, "text": "Represent all elements of A by their respective indices: " }, { "code": null, "e": 27713, "s": 27634, "text": "Element Representation\nA[0] 0\nA[1] 1\nA[2] 2\n.\n.\nand so on." }, { "code": null, "e": 27781, "s": 27713, "text": " 3. Use array H to store this representation, H[ A[ i ] ] = i" }, { "code": null, "e": 27883, "s": 27781, "text": " 4. Update the elements of B according to this new representation using H, B[ i ] = H[ B[ i ] ]" }, { "code": null, "e": 28134, "s": 27883, "text": " 5. Now, array A can be represented as [0, 1, 2, ..N], so simply count number of subarrays in B which have consecutive elements. Once we get length K of subarray of consecutive elements, count total possible subarray using following relation: " }, { "code": null, "e": 28181, "s": 28134, "text": "Total number of subarrays = (K * (K + 1)) / 2 " }, { "code": null, "e": 28242, "s": 28181, "text": "Look at this example to understand this approach in detail: " }, { "code": null, "e": 28890, "s": 28242, "text": "Example: A = [4, 3, 1, 2, 5] B = [3, 1, 2, 4, 5] Common subarrays are [1], [2], [3], [4], [5], [3, 1], [1, 2], [3, 1, 2] = 81. Represent A[i] as i, and store in H as H[A[i]] = i, Now array H from index 1 to N is, H = [2, 3, 1, 0, 4]2. Update B according to H, B[i] = H[B[i]] B = [1, 2, 3, 0, 4]3. Look for subarray in B with consecutive elements, Subarray from index 0 to 2 is [1, 2, 3], consisting of consecutive elements with length K = 3 Element at index 3 forms a subarray [0] of length K = 1 Element at index 4 forms a subarray [4] of length K = 14. Total number of common subarrays = (3*(3+1))/2 + (1*(1+1))/2 + (1*(1+1))/2 = 6 + 1 + 1 = 8 " }, { "code": null, "e": 28942, "s": 28890, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28946, "s": 28942, "text": "C++" }, { "code": null, "e": 28951, "s": 28946, "text": "Java" }, { "code": null, "e": 28959, "s": 28951, "text": "Python3" }, { "code": null, "e": 28962, "s": 28959, "text": "C#" }, { "code": null, "e": 28973, "s": 28962, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; int commonSubarrays(int *A, int *B, int N){ // Initialising Map for // Index Mapping int Map[N + 1]; // Mapping elements of A for(int i = 0 ; i< N; i++) Map[*(A + i)] = i; // Modify elements of B // according to Map for (int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A *(B + i) = Map[*(B + i)]; } // Count of common subarrays int count = 0; // Traversing array B int i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codeint main(){ int N = 3; int A[] = {1, 2, 3}; int B[] = {2, 3, 1}; cout << (commonSubarrays(A, B, N)) << endl; N = 5; int C[] = {1, 2, 3, 4, 5}; int D[] = {2, 3, 1, 4, 5}; cout << (commonSubarrays(C, D, N));} // This code is contributed by chitranayal", "e": 30214, "s": 28973, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ static int commonSubarrays(int []A, int []B, int N){ // Initialising Map for // Index Mapping int []Map = new int[N + 1]; // Mapping elements of A for(int i = 0; i< N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays int count = 0; // Traversing array B int i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codepublic static void main(String[] args){ int N = 3; int A[] = {1, 2, 3}; int B[] = {2, 3, 1}; System.out.print(commonSubarrays(A, B, N)); System.out.print(\"\\n\"); N = 5; int C[] = {1, 2, 3, 4, 5}; int D[] = {2, 3, 1, 4, 5}; System.out.print(commonSubarrays(C, D, N));}} // This code is contributed by gauravrajput1", "e": 31531, "s": 30214, "text": null }, { "code": "# Python3 implementation of above approach def commonSubarrays(A, B, N): # Initialising Map for # Index Mapping Map = [0 for i in range(N + 1)] # Mapping elements of A for i in range(N): Map[A[i]]= i # Modify elements of B # according to Map for i in range(N) : # Changing B[i] as # the index of B[i] in A B[i]= Map[B[i]] # Count of common subarrays count = 0 # Traversing array B i = 0 while i<N: K = 1 i+= 1 # While consecutive elements # are found, we increment K while i<N and B[i]== B[i-1]+1: i+= 1 K+= 1 # Add number of subarrays # with length K # to total count count = count + ( (K)*(K + 1))//2 return count # Driver codeN = 3A =[1, 2, 3]B =[2, 3, 1]print(commonSubarrays(A, B, N)) N = 5A =[1, 2, 3, 4, 5]B =[2, 3, 1, 4, 5]print(commonSubarrays(A, B, N))", "e": 32494, "s": 31531, "text": null }, { "code": "// C# implementation of the above approachusing System;class GFG{ static int commonSubarrays(int []A, int []B, int N){ // Initialising Map for // Index Mapping int []Map = new int[N + 1]; // Mapping elements of A for(int i = 0; i < N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(int i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays int count = 0; // Traversing array B int a = 0, K; while (a < N) { K = 1; a += 1; // While consecutive elements // are found, we increment K while (a < N && B[a] == B[a - 1] + 1) { a += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver codepublic static void Main(){ int N = 3; int []A = {1, 2, 3}; int []B = {2, 3, 1}; Console.Write(commonSubarrays(A, B, N)); Console.Write(\"\\n\"); N = 5; int []C = {1, 2, 3, 4, 5}; int []D = {2, 3, 1, 4, 5}; Console.Write(commonSubarrays(C, D, N));}} // This code is contributed by Code_Mech", "e": 33824, "s": 32494, "text": null }, { "code": "<script>// Javascript implementation of the above approach function commonSubarrays(A, B, N){ // Initialising Map for // Index Mapping let Map = Array.from({length: N+1}, (_, i) => 0); // Mapping elements of A for(let i = 0; i< N; i++) Map[A[i]] = i; // Modify elements of B // according to Map for(let i = 0; i < N; i++) { // Changing B[i] as // the index of B[i] in A B[i] = Map[B[i]]; } // Count of common subarrays let count = 0; // Traversing array B let i = 0, K; while (i < N) { K = 1; i+= 1; // While consecutive elements // are found, we increment K while (i < N && B[i] == B[i - 1] + 1) { i += 1; K += 1; } // Add number of subarrays //with length K // to total count count = count + ((K) * (K + 1)) / 2; } return count;} // Driver Code let N = 3; let A = [1, 2, 3]; let B = [2, 3, 1]; document.write(commonSubarrays(A, B, N)); document.write(\"<br/>\"); N = 5; let C = [1, 2, 3, 4, 5]; let D = [2, 3, 1, 4, 5]; document.write(commonSubarrays(C, D, N)); // This code is contributed by target_2.</script>", "e": 35107, "s": 33824, "text": null }, { "code": null, "e": 35111, "s": 35107, "text": "4\n7" }, { "code": null, "e": 35158, "s": 35113, "text": "Time complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 35164, "s": 35158, "text": "ukasp" }, { "code": null, "e": 35178, "s": 35164, "text": "GauravRajput1" }, { "code": null, "e": 35188, "s": 35178, "text": "Code_Mech" }, { "code": null, "e": 35197, "s": 35188, "text": "target_2" }, { "code": null, "e": 35212, "s": 35197, "text": "sagar0719kumar" }, { "code": null, "e": 35228, "s": 35212, "text": "pankajsharmagfg" }, { "code": null, "e": 35240, "s": 35228, "text": "permutation" }, { "code": null, "e": 35249, "s": 35240, "text": "subarray" }, { "code": null, "e": 35260, "s": 35249, "text": "Algorithms" }, { "code": null, "e": 35267, "s": 35260, "text": "Arrays" }, { "code": null, "e": 35281, "s": 35267, "text": "Combinatorial" }, { "code": null, "e": 35297, "s": 35281, "text": "Data Structures" }, { "code": null, "e": 35310, "s": 35297, "text": "Mathematical" }, { "code": null, "e": 35326, "s": 35310, "text": "Data Structures" }, { "code": null, "e": 35333, "s": 35326, "text": "Arrays" }, { "code": null, "e": 35346, "s": 35333, "text": "Mathematical" }, { "code": null, "e": 35358, "s": 35346, "text": "permutation" }, { "code": null, "e": 35372, "s": 35358, "text": "Combinatorial" }, { "code": null, "e": 35383, "s": 35372, "text": "Algorithms" }, { "code": null, "e": 35481, "s": 35383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35530, "s": 35481, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 35555, "s": 35530, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35582, "s": 35555, "text": "How to Start Learning DSA?" }, { "code": null, "e": 35633, "s": 35582, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 35661, "s": 35633, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 35676, "s": 35661, "text": "Arrays in Java" }, { "code": null, "e": 35692, "s": 35676, "text": "Arrays in C/C++" }, { "code": null, "e": 35760, "s": 35692, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35806, "s": 35760, "text": "Write a program to reverse an array or string" } ]
Data Visualization with Python | Towards Data Science
“A picture is worth a thousand words” -Fred R. Barnard Data visualization is a visual (or graphic) representation of data to find useful insights (i.e. trends and patterns) in the data and making the process of data analysis easier and simpler. Aim of the data visualization is to make a quick and clear understanding of data in the first glance and make it visually presentable to comprehend the information. In Python, several comprehensive libraries are available for creating high quality, attractive, interactive, and informative statistical graphics (2D and 3D). Matplotlib is one such popular visualization library available which allows us to create high-quality graphics with a range of graphs such as scatter plots, line charts, bar charts, histograms, and pie charts. Seaborn is another of Python’s data visualization library built on top of Matplotlib, which have a high-level interface with attractive designs. Moreover, it reduces the lines of code required to produce the same result as in Matplotlib. Pandas is another great library available in Python for data analysis (data manipulation, time-series analysis, integrating indexing of data, etc.). Pandas Visualization (built on top of Matplotlib) is a tool of Pandas library that allows us to create a visual representation of data frames (data aligned in tabular form of columns and rows) and series (one-dimensional labeled array capable of holding data of any type) much quicker and easier way. Plotly library is used for creating interactive and multidimensional plots making the process of data analysis easier by providing a better visualization for the data. With this article, we will be able to visualize the data in different forms by learning how to plot data in different Python libraries and understand where to use which one appropriately. Note: We can use Google Colaboratory to avoid the process of installation of libraries. All the libraries can be used by simply importing them in the notebook. Figure: The entire area where everything is being drawn. It can contain multiple plots with axes, legends, a range of axes, grid, plot-title, etc. Axes: The area under the figure where the plot is being constructed (or the area your plot appears in) is known as axes. There can be multiple axes in a single figure. Axis: This is the number line present in the graph which represents the range of values for the plot (X-axis and Y-axis as mentioned in the above figure). There can be more than two axis in the graph in the case of a multi-dimensional graph. Plot title: The title is positioned in the center above the axes, giving an overview of the plot. In this article, at various points, we will be using the Iris data set (as an example), which is free and is commonly used (since it is one of the best-known databases to be found in the pattern recognition literature). We can import this data set in two ways: Without downloading the .csv file we can directly import the data set in the workspace using sci-kit learn library available in python. Using the above (by importing Pandas library) code, and downloading the .csv format of the dataset we can import the data in our workspace. These, are the first five elements in the iris dataset: Both of the above-mentioned methods can be used to import the dataset and to create graphs, but we will be using the latter because of the better readability of the data (as you can see the difference in the output results of both the methods). We begin by importing the library in our notebook by using the following code: There are various styles available in this library for drawing the plot. Line plot or line chart represents the data in a series (in continuation) showing the frequency of data along with the number line. It can be used to compare numerical sets of values. This is one of the most simple graphs that we can make using python. Here, using thenumpy linspace() function we will generate data-points and store them in variable x and calculate the square of values of x and store them in another variable y . We will use plt.plot() function to plot the graph and plt.show() to display the graph. We can add some more functions to our plot to make it much easier to interpret. To add a label:x-axis label and y-axis label we will use plt.xlabel() and plt.ylabel() functions respectively. We can also give a title to our plot using the plt.title() function. A grid in the plot can simply be applied by calling plt.grid(True) function (makes data easier to interpret). With the addition of these functions, the graph becomes much more readable and easier to analyze. We can add more than one line to our plot and make them distinguishable by using different colors and some other features: In the above code, we have added another variable z=x**3 (z=x3) and changed the style and color of the line. To change the color of a line in the line plot we have to add color='' parameter in plt.plot() function. To change the style of a line in the line plot we have to add linestyle=’’ parameter in plt.plot() function (or simply we can add ‘*’ or ‘- -’, etcetera). This makes the extraction of information and comparison of data variables easier. Similarly, we can create plots for mathematical functions as well: Here, we have created a plot for sin(x) and cos(x) . We can adjust the limit of axes by using the functions plt.xlim(lower_limit,upper_limit) for x-axis and plt.lim(lower_limit,upper_limit) for y-axis. For further labeling of the plot, we can add legend with plt.legend() function, it will help to identify which line stands for which function. For creating separate (multiple) plots in the same figure we can use theplt.subplots(num_rows,num_cols) function. Here the details of each subplot can be different. plt.sublots() function creates a figure and grid of subplots, in which we can define the number of columns and rows by passing an int value as the parameter. Moreover, we can also change the spacing between the sublopts by using the gridspec_kw={'hspace': , 'wspace': } argument. After that, by simply using the index number for the subplot we can easily plot the graphs. This kind of plot uses ‘dots’ to represent the numerical data for different variables. Scatter plots can be used to analyze how one variable affects the other variables. (We can use any number of variables we want to plot on the graph.) We will use dataset_name.plot() function to create the graph and in parameters, we will apply the kind = 'scatter’ with a label for x-axis and y-axis . Check out the example mentioned below (iris dataset). Here, we are comparing the petal length and petal width of different species of flowers present in the dataset. But, here it would be very difficult for us to analyze and extract information from this plot because we cannot differentiate between classes present. So now, we will try another approach which will solve our problem. In this method, we will use plt.scatter() to create a scatter plot. To change the color of dots based on the species of flower, we can create a dictionary with storing the colors corresponding to the names of the species. By using thefor loop we create a single scatter plot of three different species (each represented by a different color). This plot created is way better than the previous one. The data of species became easier to distinguish and gives an overall clarity for an easier analysis of information. Bar graphs can be used to compare categorical data. We have to provide the frequency and the categories, we want to represent on the plot. Here we are using the iris dataset, to compare the count of different species of flowers (however, they are equal to fifty). To find the count of each unique category in the dataset we are using thevalue_counts() function. The variable species and count in the following code store the name of each unique category ( .index function) and the frequency of each category ( .values function) This is the most basic kind of bar graph, you can try some variations of this plot like multiple bar plots in the same figure, change the width of bars (using width=parameter) or create a stacked bar plot (using bottomparameter). Box plots help plot and compare the values by plotting the distribution of data based on the sample minimum, the lower quartile, the median, the upper quartile, and the sample maximum (known as the five-number summary). This can help us analyze the data to find the outliers and the variation in the data. We have excluded the species column here since we are only comparing the petal length, petal width, sepal length, sepal width of all the flowers in the iris dataset. We create the box plot using the .boxplot() function. Histograms are used for the representation of frequency distribution (or we can say probability distribution) of the data. We have to use theplt.hist() function to create the histogram plot and we can also define the bins for the plot (i.e. breaking down the entire range of values into a series of intervals and calculating the count of values falling in each interval). Histograms are a special kind of bar graph. Error bar is an excellent tool to find out the statistical difference between the group of data by giving a visual representation of the variation in data. It helps to point the error and precision in the process of data analysis (and determine the quality of the model). To plot the error bars, we have to use errorbar() function where x and y are data point locations, yerr and xerr define the size of the error bars (in this code we are only using yerr ). We can also change the style and color of the error bars by using fmt parameter (like we set the style to dots ’o’in this particular example), ecolor for changing the color of dots and color parameter for changing the color of vertical lines. By adding loc = '' parameter in theplt.legend() function we can determine the position of the legend in the plot. Heat maps are used to represent categorical data in the form of ‘color-coded image plot’ (values in the data are represented as colors) to find the correlation of the features in data (cluster analysis). With the help of heat maps, we can have a quick and deep analysis of the data visually. In this example, we are using the iris dataset to create a heat map. .corr() is a panda’s data frame function used to find the correlation in the dataset. The Heat map is created by using the .imshow()function where we pass the correlation of dataset, cmap (for setting the style and color of the plot) as arguments. To add the colobar we use the .figure.colorbar() function. And finally to add annotations (the values you can see mentioned over the color blocks) we have used two for loops. Pie charts are used to find the correlation (it can be percentage or proportion of data) between the composition of categories in the data where each slice represents a different category, giving the summary of whole data. To plot the pie chart we have to use the plt.pie() function. To give a 3D effect to the plot we have used shadow = True parameter,explode parameter to show a category separately from the rest of the plot, and for displaying the percentage of each category we have to use autopct parameter. To make the circle proportionate we can use the plt.axis('equal') function. With the seaborn’s high-level interface and attractive designs, we can create amazing plots with better visualizations. Moreover, the lines of code required are reduced to a very great extent (as compared to matplotlib). Code for importing the library in the workplace: We can simply create the line plot in the seaborn library by using the sns.lineplot() function. Here we can vary the color of grid/background using .set_style() function available in the library. And using sns.lineplot() function we can plot the line chart. With the seaborn library, we can create the scatter plot in just a single line of code! Here, we have used FacetGrid() function (with which we can quickly explore our dataset) to create the plot in which we can define hue (i.e. colors for scatter dots) and .map function to define the graph type. (Alternative method for creating a scatter plot is using sns.scatterplot() ) We can create a bar plot in the seaborn library by using sns.barplot() function. We can create a histogram in the seaborn library by using sns.distplot() function. We can also calculate probability distribution frequency (PDF), cumulative distribution frequency (CDF), and kernel density estimate (KDE) using this library for data analysis. Seaborn gives some more features for data visualization than matplotlib. Seaborn is very efficient in creating heat maps by significantly reducing the lines of code to create the figure. Multiple lines of code in matplotlib is reduced to just two lines! This is a unique kind of plot available in the seaborn library. This plots a pairwise relationship in datasets (in a single figure). This is an amazing tool for the purpose of data analysis. By using sns.pairplot() function we can create pair plots ( heightis used to adjust the height of the plots). This library provides an easy way to plot graphs using pandas data frames and data structures. This library is also built on top of matplotlib thus requires fewer lines of code. It is very simple to create a histogram with this library, we simply have to use .plot.hist() function. We can also create subplots in the same figure by using subplots=True argument. We can create line plots using this library by using .plot.line() function. Legends are also automatically added in this library. With this library, we can create multidimensional interactive plots! This is easy to use library with a high-level interface. We can import this library by using the following code: You try running this code on your own to check and interact with the plot. I hope with this article you will be able to visualize the data using different libraries in python and start analyzing it. For a better understanding of these concepts, I will recommend you try writing these codes on your once. Keep exploring, and I am sure you will discover new features along the way. I am sharing my notebook repository at the end of the document for your reference. If you have any questions or comments, please post them in the comment section. github.com If you want to improve the way you write your code, check out our another article: medium.com Originally published at: www.patataeater.blogspot.com
[ { "code": null, "e": 209, "s": 171, "text": "“A picture is worth a thousand words”" }, { "code": null, "e": 226, "s": 209, "text": "-Fred R. Barnard" }, { "code": null, "e": 416, "s": 226, "text": "Data visualization is a visual (or graphic) representation of data to find useful insights (i.e. trends and patterns) in the data and making the process of data analysis easier and simpler." }, { "code": null, "e": 581, "s": 416, "text": "Aim of the data visualization is to make a quick and clear understanding of data in the first glance and make it visually presentable to comprehend the information." }, { "code": null, "e": 740, "s": 581, "text": "In Python, several comprehensive libraries are available for creating high quality, attractive, interactive, and informative statistical graphics (2D and 3D)." }, { "code": null, "e": 950, "s": 740, "text": "Matplotlib is one such popular visualization library available which allows us to create high-quality graphics with a range of graphs such as scatter plots, line charts, bar charts, histograms, and pie charts." }, { "code": null, "e": 1188, "s": 950, "text": "Seaborn is another of Python’s data visualization library built on top of Matplotlib, which have a high-level interface with attractive designs. Moreover, it reduces the lines of code required to produce the same result as in Matplotlib." }, { "code": null, "e": 1638, "s": 1188, "text": "Pandas is another great library available in Python for data analysis (data manipulation, time-series analysis, integrating indexing of data, etc.). Pandas Visualization (built on top of Matplotlib) is a tool of Pandas library that allows us to create a visual representation of data frames (data aligned in tabular form of columns and rows) and series (one-dimensional labeled array capable of holding data of any type) much quicker and easier way." }, { "code": null, "e": 1806, "s": 1638, "text": "Plotly library is used for creating interactive and multidimensional plots making the process of data analysis easier by providing a better visualization for the data." }, { "code": null, "e": 1994, "s": 1806, "text": "With this article, we will be able to visualize the data in different forms by learning how to plot data in different Python libraries and understand where to use which one appropriately." }, { "code": null, "e": 2154, "s": 1994, "text": "Note: We can use Google Colaboratory to avoid the process of installation of libraries. All the libraries can be used by simply importing them in the notebook." }, { "code": null, "e": 2301, "s": 2154, "text": "Figure: The entire area where everything is being drawn. It can contain multiple plots with axes, legends, a range of axes, grid, plot-title, etc." }, { "code": null, "e": 2469, "s": 2301, "text": "Axes: The area under the figure where the plot is being constructed (or the area your plot appears in) is known as axes. There can be multiple axes in a single figure." }, { "code": null, "e": 2711, "s": 2469, "text": "Axis: This is the number line present in the graph which represents the range of values for the plot (X-axis and Y-axis as mentioned in the above figure). There can be more than two axis in the graph in the case of a multi-dimensional graph." }, { "code": null, "e": 2809, "s": 2711, "text": "Plot title: The title is positioned in the center above the axes, giving an overview of the plot." }, { "code": null, "e": 3029, "s": 2809, "text": "In this article, at various points, we will be using the Iris data set (as an example), which is free and is commonly used (since it is one of the best-known databases to be found in the pattern recognition literature)." }, { "code": null, "e": 3070, "s": 3029, "text": "We can import this data set in two ways:" }, { "code": null, "e": 3206, "s": 3070, "text": "Without downloading the .csv file we can directly import the data set in the workspace using sci-kit learn library available in python." }, { "code": null, "e": 3402, "s": 3206, "text": "Using the above (by importing Pandas library) code, and downloading the .csv format of the dataset we can import the data in our workspace. These, are the first five elements in the iris dataset:" }, { "code": null, "e": 3647, "s": 3402, "text": "Both of the above-mentioned methods can be used to import the dataset and to create graphs, but we will be using the latter because of the better readability of the data (as you can see the difference in the output results of both the methods)." }, { "code": null, "e": 3726, "s": 3647, "text": "We begin by importing the library in our notebook by using the following code:" }, { "code": null, "e": 3799, "s": 3726, "text": "There are various styles available in this library for drawing the plot." }, { "code": null, "e": 4052, "s": 3799, "text": "Line plot or line chart represents the data in a series (in continuation) showing the frequency of data along with the number line. It can be used to compare numerical sets of values. This is one of the most simple graphs that we can make using python." }, { "code": null, "e": 4230, "s": 4052, "text": "Here, using thenumpy linspace() function we will generate data-points and store them in variable x and calculate the square of values of x and store them in another variable y ." }, { "code": null, "e": 4317, "s": 4230, "text": "We will use plt.plot() function to plot the graph and plt.show() to display the graph." }, { "code": null, "e": 4397, "s": 4317, "text": "We can add some more functions to our plot to make it much easier to interpret." }, { "code": null, "e": 4508, "s": 4397, "text": "To add a label:x-axis label and y-axis label we will use plt.xlabel() and plt.ylabel() functions respectively." }, { "code": null, "e": 4577, "s": 4508, "text": "We can also give a title to our plot using the plt.title() function." }, { "code": null, "e": 4687, "s": 4577, "text": "A grid in the plot can simply be applied by calling plt.grid(True) function (makes data easier to interpret)." }, { "code": null, "e": 4785, "s": 4687, "text": "With the addition of these functions, the graph becomes much more readable and easier to analyze." }, { "code": null, "e": 4908, "s": 4785, "text": "We can add more than one line to our plot and make them distinguishable by using different colors and some other features:" }, { "code": null, "e": 5017, "s": 4908, "text": "In the above code, we have added another variable z=x**3 (z=x3) and changed the style and color of the line." }, { "code": null, "e": 5122, "s": 5017, "text": "To change the color of a line in the line plot we have to add color='' parameter in plt.plot() function." }, { "code": null, "e": 5277, "s": 5122, "text": "To change the style of a line in the line plot we have to add linestyle=’’ parameter in plt.plot() function (or simply we can add ‘*’ or ‘- -’, etcetera)." }, { "code": null, "e": 5359, "s": 5277, "text": "This makes the extraction of information and comparison of data variables easier." }, { "code": null, "e": 5426, "s": 5359, "text": "Similarly, we can create plots for mathematical functions as well:" }, { "code": null, "e": 5479, "s": 5426, "text": "Here, we have created a plot for sin(x) and cos(x) ." }, { "code": null, "e": 5628, "s": 5479, "text": "We can adjust the limit of axes by using the functions plt.xlim(lower_limit,upper_limit) for x-axis and plt.lim(lower_limit,upper_limit) for y-axis." }, { "code": null, "e": 5771, "s": 5628, "text": "For further labeling of the plot, we can add legend with plt.legend() function, it will help to identify which line stands for which function." }, { "code": null, "e": 5936, "s": 5771, "text": "For creating separate (multiple) plots in the same figure we can use theplt.subplots(num_rows,num_cols) function. Here the details of each subplot can be different." }, { "code": null, "e": 6308, "s": 5936, "text": "plt.sublots() function creates a figure and grid of subplots, in which we can define the number of columns and rows by passing an int value as the parameter. Moreover, we can also change the spacing between the sublopts by using the gridspec_kw={'hspace': , 'wspace': } argument. After that, by simply using the index number for the subplot we can easily plot the graphs." }, { "code": null, "e": 6395, "s": 6308, "text": "This kind of plot uses ‘dots’ to represent the numerical data for different variables." }, { "code": null, "e": 6545, "s": 6395, "text": "Scatter plots can be used to analyze how one variable affects the other variables. (We can use any number of variables we want to plot on the graph.)" }, { "code": null, "e": 6751, "s": 6545, "text": "We will use dataset_name.plot() function to create the graph and in parameters, we will apply the kind = 'scatter’ with a label for x-axis and y-axis . Check out the example mentioned below (iris dataset)." }, { "code": null, "e": 6863, "s": 6751, "text": "Here, we are comparing the petal length and petal width of different species of flowers present in the dataset." }, { "code": null, "e": 7014, "s": 6863, "text": "But, here it would be very difficult for us to analyze and extract information from this plot because we cannot differentiate between classes present." }, { "code": null, "e": 7149, "s": 7014, "text": "So now, we will try another approach which will solve our problem. In this method, we will use plt.scatter() to create a scatter plot." }, { "code": null, "e": 7424, "s": 7149, "text": "To change the color of dots based on the species of flower, we can create a dictionary with storing the colors corresponding to the names of the species. By using thefor loop we create a single scatter plot of three different species (each represented by a different color)." }, { "code": null, "e": 7596, "s": 7424, "text": "This plot created is way better than the previous one. The data of species became easier to distinguish and gives an overall clarity for an easier analysis of information." }, { "code": null, "e": 7735, "s": 7596, "text": "Bar graphs can be used to compare categorical data. We have to provide the frequency and the categories, we want to represent on the plot." }, { "code": null, "e": 8124, "s": 7735, "text": "Here we are using the iris dataset, to compare the count of different species of flowers (however, they are equal to fifty). To find the count of each unique category in the dataset we are using thevalue_counts() function. The variable species and count in the following code store the name of each unique category ( .index function) and the frequency of each category ( .values function)" }, { "code": null, "e": 8354, "s": 8124, "text": "This is the most basic kind of bar graph, you can try some variations of this plot like multiple bar plots in the same figure, change the width of bars (using width=parameter) or create a stacked bar plot (using bottomparameter)." }, { "code": null, "e": 8660, "s": 8354, "text": "Box plots help plot and compare the values by plotting the distribution of data based on the sample minimum, the lower quartile, the median, the upper quartile, and the sample maximum (known as the five-number summary). This can help us analyze the data to find the outliers and the variation in the data." }, { "code": null, "e": 8880, "s": 8660, "text": "We have excluded the species column here since we are only comparing the petal length, petal width, sepal length, sepal width of all the flowers in the iris dataset. We create the box plot using the .boxplot() function." }, { "code": null, "e": 9252, "s": 8880, "text": "Histograms are used for the representation of frequency distribution (or we can say probability distribution) of the data. We have to use theplt.hist() function to create the histogram plot and we can also define the bins for the plot (i.e. breaking down the entire range of values into a series of intervals and calculating the count of values falling in each interval)." }, { "code": null, "e": 9296, "s": 9252, "text": "Histograms are a special kind of bar graph." }, { "code": null, "e": 9568, "s": 9296, "text": "Error bar is an excellent tool to find out the statistical difference between the group of data by giving a visual representation of the variation in data. It helps to point the error and precision in the process of data analysis (and determine the quality of the model)." }, { "code": null, "e": 9755, "s": 9568, "text": "To plot the error bars, we have to use errorbar() function where x and y are data point locations, yerr and xerr define the size of the error bars (in this code we are only using yerr )." }, { "code": null, "e": 9998, "s": 9755, "text": "We can also change the style and color of the error bars by using fmt parameter (like we set the style to dots ’o’in this particular example), ecolor for changing the color of dots and color parameter for changing the color of vertical lines." }, { "code": null, "e": 10112, "s": 9998, "text": "By adding loc = '' parameter in theplt.legend() function we can determine the position of the legend in the plot." }, { "code": null, "e": 10404, "s": 10112, "text": "Heat maps are used to represent categorical data in the form of ‘color-coded image plot’ (values in the data are represented as colors) to find the correlation of the features in data (cluster analysis). With the help of heat maps, we can have a quick and deep analysis of the data visually." }, { "code": null, "e": 10896, "s": 10404, "text": "In this example, we are using the iris dataset to create a heat map. .corr() is a panda’s data frame function used to find the correlation in the dataset. The Heat map is created by using the .imshow()function where we pass the correlation of dataset, cmap (for setting the style and color of the plot) as arguments. To add the colobar we use the .figure.colorbar() function. And finally to add annotations (the values you can see mentioned over the color blocks) we have used two for loops." }, { "code": null, "e": 11119, "s": 10896, "text": "Pie charts are used to find the correlation (it can be percentage or proportion of data) between the composition of categories in the data where each slice represents a different category, giving the summary of whole data." }, { "code": null, "e": 11485, "s": 11119, "text": "To plot the pie chart we have to use the plt.pie() function. To give a 3D effect to the plot we have used shadow = True parameter,explode parameter to show a category separately from the rest of the plot, and for displaying the percentage of each category we have to use autopct parameter. To make the circle proportionate we can use the plt.axis('equal') function." }, { "code": null, "e": 11706, "s": 11485, "text": "With the seaborn’s high-level interface and attractive designs, we can create amazing plots with better visualizations. Moreover, the lines of code required are reduced to a very great extent (as compared to matplotlib)." }, { "code": null, "e": 11755, "s": 11706, "text": "Code for importing the library in the workplace:" }, { "code": null, "e": 11851, "s": 11755, "text": "We can simply create the line plot in the seaborn library by using the sns.lineplot() function." }, { "code": null, "e": 12013, "s": 11851, "text": "Here we can vary the color of grid/background using .set_style() function available in the library. And using sns.lineplot() function we can plot the line chart." }, { "code": null, "e": 12101, "s": 12013, "text": "With the seaborn library, we can create the scatter plot in just a single line of code!" }, { "code": null, "e": 12387, "s": 12101, "text": "Here, we have used FacetGrid() function (with which we can quickly explore our dataset) to create the plot in which we can define hue (i.e. colors for scatter dots) and .map function to define the graph type. (Alternative method for creating a scatter plot is using sns.scatterplot() )" }, { "code": null, "e": 12468, "s": 12387, "text": "We can create a bar plot in the seaborn library by using sns.barplot() function." }, { "code": null, "e": 12728, "s": 12468, "text": "We can create a histogram in the seaborn library by using sns.distplot() function. We can also calculate probability distribution frequency (PDF), cumulative distribution frequency (CDF), and kernel density estimate (KDE) using this library for data analysis." }, { "code": null, "e": 12801, "s": 12728, "text": "Seaborn gives some more features for data visualization than matplotlib." }, { "code": null, "e": 12915, "s": 12801, "text": "Seaborn is very efficient in creating heat maps by significantly reducing the lines of code to create the figure." }, { "code": null, "e": 12982, "s": 12915, "text": "Multiple lines of code in matplotlib is reduced to just two lines!" }, { "code": null, "e": 13173, "s": 12982, "text": "This is a unique kind of plot available in the seaborn library. This plots a pairwise relationship in datasets (in a single figure). This is an amazing tool for the purpose of data analysis." }, { "code": null, "e": 13283, "s": 13173, "text": "By using sns.pairplot() function we can create pair plots ( heightis used to adjust the height of the plots)." }, { "code": null, "e": 13461, "s": 13283, "text": "This library provides an easy way to plot graphs using pandas data frames and data structures. This library is also built on top of matplotlib thus requires fewer lines of code." }, { "code": null, "e": 13645, "s": 13461, "text": "It is very simple to create a histogram with this library, we simply have to use .plot.hist() function. We can also create subplots in the same figure by using subplots=True argument." }, { "code": null, "e": 13775, "s": 13645, "text": "We can create line plots using this library by using .plot.line() function. Legends are also automatically added in this library." }, { "code": null, "e": 13957, "s": 13775, "text": "With this library, we can create multidimensional interactive plots! This is easy to use library with a high-level interface. We can import this library by using the following code:" }, { "code": null, "e": 14032, "s": 13957, "text": "You try running this code on your own to check and interact with the plot." }, { "code": null, "e": 14156, "s": 14032, "text": "I hope with this article you will be able to visualize the data using different libraries in python and start analyzing it." }, { "code": null, "e": 14420, "s": 14156, "text": "For a better understanding of these concepts, I will recommend you try writing these codes on your once. Keep exploring, and I am sure you will discover new features along the way. I am sharing my notebook repository at the end of the document for your reference." }, { "code": null, "e": 14500, "s": 14420, "text": "If you have any questions or comments, please post them in the comment section." }, { "code": null, "e": 14511, "s": 14500, "text": "github.com" }, { "code": null, "e": 14594, "s": 14511, "text": "If you want to improve the way you write your code, check out our another article:" }, { "code": null, "e": 14605, "s": 14594, "text": "medium.com" } ]
LCA for general or n-ary trees (Sparse Matrix DP approach )
06 Jul, 2022 In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA) for a binary tree and a binary search tree (this, this and this). Now let’s look at a method that can calculate LCA for any tree (not only for binary tree). We use Dynamic Programming with Sparse Matrix Approach in our method. This method is very handy and fast when you need to answer multiple queries of LCA for a tree. Pre-requisites: DFS Basic DP knowledge (This and this) Range Minimum Query (Square Root Decomposition and Sparse Table) DFS Basic DP knowledge (This and this) Range Minimum Query (Square Root Decomposition and Sparse Table) Naive Approach:- O(n) The naive approach for this general tree LCA calculation will be the same as the naive approach for the LCA calculation of Binary Tree (this naive approach is already well described here. The implementation for the naive approach is given below:- C++ Java Python3 C# Javascript /* Program to find LCA of n1 and n2 using one DFS on the Tree */#include<bits/stdc++.h>using namespace std; // Maximum number of nodes is 100000 and nodes are// numbered from 1 to 100000#define MAXN 100001 vector < int > tree[MAXN];int path[3][MAXN]; // storing root to node path // storing the path from root to nodevoid dfs(int cur, int prev, int pathNumber, int ptr, int node, bool &flag){ for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev and !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber][ptr+1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr+1, node, flag); } }} // This Function compares the path from root to 'a' & root// to 'b' and returns LCA of a and b. Time Complexity : O(n)int LCA(int a, int b){ // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a bool flag = false; dfs(1, 0, 1, 1, a, flag); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b, flag); // runs till path 1 & path 2 matches int i = 0; while (path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i-1];} void addEdge(int a,int b){ tree[a].push_back(b); tree[b].push_back(a);} // Driver codeint main(){ int n = 8; // Number of nodes addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); cout << "LCA(4, 7) = " << LCA(4,7) << endl; cout << "LCA(4, 6) = " << LCA(4,6) << endl; return 0;} /* Program to find LCA of n1 and n2 using one DFS onthe Tree */ import java.util.*; class GFG{ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000 static final int MAXN = 100001; static Vector<Integer>[] tree = new Vector[MAXN]; static int[][] path = new int[3][MAXN]; // storing root to node path static boolean flag; // storing the path from root to node static void dfs(int cur, int prev, int pathNumber, int ptr, int node) { for (int i = 0; i < tree[cur].size(); i++) { if (tree[cur].get(i) != prev && !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur].get(i); if (tree[cur].get(i) == node) { // node found flag = true; // terminating the path path[pathNumber][ptr + 1] = -1; return; } dfs(tree[cur].get(i), cur, pathNumber, ptr + 1, node); } } } // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n) static int LCA(int a, int b) { // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches int i = 0; while (i < MAXN && path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i - 1]; } static void addEdge(int a, int b) { tree[a].add(b); tree[b].add(a); } // Driver code public static void main(String[] args) { for (int i = 0; i < MAXN; i++) tree[i] = new Vector<Integer>(); // Number of nodes addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); System.out.print("LCA(4, 7) = " + LCA(4, 7) + "\n"); System.out.print("LCA(4, 6) = " + LCA(4, 6) + "\n"); }} // This code is contributed by 29AjayKumar # Python3 program to find LCA of n1 and# n2 using one DFS on the Tree # Maximum number of nodes is 100000 and# nodes are numbered from 1 to 100000MAXN = 100001 tree = [0] * MAXNfor i in range(MAXN): tree[i] = [] # Storing root to node pathpath = [0] * 3for i in range(3): path[i] = [0] * MAXN flag = False # Storing the path from root to nodedef dfs(cur: int, prev: int, pathNumber: int, ptr: int, node: int) -> None: global tree, path, flag for i in range(len(tree[cur])): if (tree[cur][i] != prev and not flag): # Pushing current node into the path path[pathNumber][ptr] = tree[cur][i] if (tree[cur][i] == node): # Node found flag = True # Terminating the path path[pathNumber][ptr + 1] = -1 return dfs(tree[cur][i], cur, pathNumber, ptr + 1, node) # This Function compares the path from root# to 'a' & root to 'b' and returns LCA of# a and b. Time Complexity : O(n)def LCA(a: int, b: int) -> int: global flag # Trivial case if (a == b): return a # Setting root to be first element # in path path[1][0] = path[2][0] = 1 # Calculating path from root to a flag = False dfs(1, 0, 1, 1, a) # Calculating path from root to b flag = False dfs(1, 0, 2, 1, b) # Runs till path 1 & path 2 matches i = 0 while (path[1][i] == path[2][i]): i += 1 # Returns the last matching # node in the paths return path[1][i - 1] def addEdge(a: int, b: int) -> None: tree[a].append(b) tree[b].append(a) # Driver codeif __name__ == "__main__": n = 8 # Number of nodes addEdge(1, 2) addEdge(1, 3) addEdge(2, 4) addEdge(2, 5) addEdge(2, 6) addEdge(3, 7) addEdge(3, 8) print("LCA(4, 7) = {}".format(LCA(4, 7))) print("LCA(4, 6) = {}".format(LCA(4, 6))) # This code is contributed by sanjeev2552 /* C# Program to find LCA of n1 and n2 using one DFS onthe Tree */using System;using System.Collections.Generic; class GFG{ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000 static readonly int MAXN = 100001; static List<int>[] tree = new List<int>[MAXN]; static int[,] path = new int[3, MAXN]; // storing root to node path static bool flag; // storing the path from root to node static void dfs(int cur, int prev, int pathNumber, int ptr, int node) { for (int i = 0; i < tree[cur].Count; i++) { if (tree[cur][i] != prev && !flag) { // pushing current node into the path path[pathNumber,ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber, ptr + 1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr + 1, node); } } } // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n) static int LCA(int a, int b) { // trivial case if (a == b) return a; // setting root to be first element in path path[1, 0] = path[2, 0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches int i = 0; while (i < MAXN && path[1, i] == path[2, i]) i++; // returns the last matching node in the paths return path[1, i - 1]; } static void addEdge(int a, int b) { tree[a].Add(b); tree[b].Add(a); } // Driver code public static void Main(String[] args) { for (int i = 0; i < MAXN; i++) tree[i] = new List<int>(); // Number of nodes addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); Console.Write("LCA(4, 7) = " + LCA(4, 7) + "\n"); Console.Write("LCA(4, 6) = " + LCA(4, 6) + "\n"); }} // This code is contributed by Rajput-Ji <script>/* Program to find LCA of n1 and n2 using one DFS onthe Tree */ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000let MAXN = 100001; let tree = new Array(MAXN); let path = new Array(3); for(let i = 0; i < 3; i++){ path[i] = new Array(MAXN); for(let j = 0; j < MAXN; j++) { path[i][j] = 0; }} let flag; /// storing the path from root to nodefunction dfs(cur,prev,pathNumber,ptr,node){ for (let i = 0; i < tree[cur].length; i++) { if (tree[cur][i] != prev && !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber][ptr + 1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr + 1, node); } }} // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n)function LCA(a,b){ // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches let i = 0; while (i < MAXN && path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i - 1];} function addEdge(a,b){ tree[a].push(b); tree[b].push(a);} // Driver codefor (let i = 0; i < MAXN; i++) tree[i] = []; // Number of nodesaddEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8); document.write("LCA(4, 7) = " + LCA(4, 7) + "<br>");document.write("LCA(4, 6) = " + LCA(4, 6) + "<br>"); // This code is contributed by rag2127</script> LCA(4, 7) = 1 LCA(4, 6) = 2 Sparse Matrix Approach (O(nlogn) pre-processing, O(log n) – query) Pre-computation: Here we store the 2^i th parent for every node, where 0 <= i < LEVEL, here “LEVEL” is a constant integer that tells the maximum number of 2^i th ancestor possible. Therefore, we assume the worst case to see what is the value of the constant LEVEL. In our worst case every node in our tree will have at max 1 parent and 1 child or we can say it simply reduces to a linked list. So, in this case LEVEL = ceil ( log(number of nodes) ). We also pre-compute the height for each node using one dfs in O(n) time. int n // number of nodes int parent[MAXN][LEVEL] // all initialized to -1 parent[node][0] : contains the 2^0th(first) parent of all the nodes pre-computed using DFS // Sparse matrix Approach for node -> 1 to n : for i-> 1 to LEVEL : if ( parent[node][i-1] != -1 ) : parent[node][i] = parent[ parent[node][i-1] ][i-1] Now , as we see the above dynamic programming code runs two nested loop that runs over their complete range respectively. Hence, it can be easily be inferred that its asymptotic Time Complexity is O(number of nodes * LEVEL) ~ O(n*LEVEL) ~ O(nlogn). Return LCA(u,v): First Step is to bring both the nodes at the same height. As we have already pre-computed the heights for each node. We first calculate the difference in the heights of u and v (let’s say v >=u). Now we need the node ‘v’ to jump h nodes above. This can be easily done in O(log h) time ( where h is the difference in the heights of u and v) as we have already stored the 2^i parent for each node. This process is exactly same as calculating x^y in O(log y) time. (See the code for better understanding).Now both u and v nodes are at same height. Therefore now once again we will use 2^i jumping strategy to reach the first Common Parent of u and v. First Step is to bring both the nodes at the same height. As we have already pre-computed the heights for each node. We first calculate the difference in the heights of u and v (let’s say v >=u). Now we need the node ‘v’ to jump h nodes above. This can be easily done in O(log h) time ( where h is the difference in the heights of u and v) as we have already stored the 2^i parent for each node. This process is exactly same as calculating x^y in O(log y) time. (See the code for better understanding). Now both u and v nodes are at same height. Therefore now once again we will use 2^i jumping strategy to reach the first Common Parent of u and v. Pseudo-code: For i-> LEVEL to 0 : If parent[u][i] != parent[v][i] : u = parent[u][i] v = parent[v][i] Implementation of the above algorithm is given below: C++ Java C# Javascript // Sparse Matrix DP approach to find LCA of two nodes#include <bits/stdc++.h>using namespace std;#define MAXN 100000#define level 18 vector <int> tree[MAXN];int depth[MAXN];int parent[MAXN][level]; // pre-compute the depth for each node and their// first parent(2^0th parent)// time complexity : O(n)void dfs(int cur, int prev){ depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); }} // Dynamic Programming Sparse Matrix Approach// populating 2^i parent for each node// Time complexity : O(nlogn)void precomputeSparseMatrix(int n){ for (int i=1; i<level; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i-1] != -1) parent[node][i] = parent[parent[node][i-1]][i-1]; } }} // Returning the LCA of u and v// Time complexity : O(log n)int lca(int u, int v){ if (depth[v] < depth[u]) swap(u, v); int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i=0; i<level; i++) if ((diff>>i)&1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i=level-1; i>=0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0];} void addEdge(int u,int v){ tree[u].push_back(v); tree[v].push_back(u);} // driver functionint main(){ memset(parent,-1,sizeof(parent)); int n = 8; addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1,0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function cout << "LCA(4, 7) = " << lca(4,7) << endl; cout << "LCA(4, 6) = " << lca(4,6) << endl; return 0;} // Sparse Matrix DP approach to find LCA of two nodesimport java.util.*; class GFG{ static final int MAXN = 100000; static final int level = 18; @SuppressWarnings("unchecked") static Vector<Integer>[] tree = new Vector[MAXN]; static int[] depth = new int[MAXN]; static int[][] parent = new int[MAXN][level]; // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) static void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i = 0; i < tree[cur].size(); i++) { if (tree[cur].get(i) != prev) dfs(tree[cur].get(i), cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) static void precomputeSparseMatrix(int n) { for (int i = 1; i < level; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i - 1] != -1) parent[node][i] = parent[parent[node][i - 1]][i - 1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) static int lca(int u, int v) { if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i = level - 1; i >= 0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0]; } static void addEdge(int u, int v) { tree[u].add(v); tree[v].add(u); } static void memset(int value) { for (int i = 0; i < MAXN; i++) { for (int j = 0; j < level; j++) { parent[i][j] = -1; } } } // driver function public static void main(String[] args) { memset(-1); for (int i = 0; i < MAXN; i++) tree[i] = new Vector<Integer>(); int n = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1, 0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function System.out.print("LCA(4, 7) = " + lca(4, 7) + "\n"); System.out.print("LCA(4, 6) = " + lca(4, 6) + "\n"); }} // This code is contributed by 29AjayKumar // Sparse Matrix DP approach to find LCA of two nodesusing System;using System.Collections.Generic; class GFG{ static readonly int MAXN = 100000; static readonly int level = 18; static List<int>[] tree = new List<int>[MAXN]; static int[] depth = new int[MAXN]; static int[,] parent = new int[MAXN, level]; // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) static void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur,0] = prev; for (int i = 0; i < tree[cur].Count; i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) static void precomputeSparseMatrix(int n) { for (int i = 1; i < level; i++) { for (int node = 1; node <= n; node++) { if (parent[node, i - 1] != -1) parent[node, i] = parent[parent[node, i - 1], i - 1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) static int lca(int u, int v) { if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v, i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i = level - 1; i >= 0; i--) if (parent[u, i] != parent[v, i]) { u = parent[u, i]; v = parent[v, i]; } return parent[u, 0]; } static void addEdge(int u, int v) { tree[u].Add(v); tree[v].Add(u); } static void memset(int value) { for (int i = 0; i < MAXN; i++) { for (int j = 0; j < level; j++) { parent[i, j] = -1; } } } // Driver function public static void Main(String[] args) { memset(-1); for (int i = 0; i < MAXN; i++) tree[i] = new List<int>(); int n = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1, 0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function Console.Write("LCA(4, 7) = " + lca(4, 7) + "\n"); Console.Write("LCA(4, 6) = " + lca(4, 6) + "\n"); }} // This code is contributed by PrinciRaj1992 <script> // Sparse Matrix DP approach to find LCA of two nodesvar MAXN = 100000;var level = 18;var tree = Array.from(Array(MAXN), ()=>Array());var depth = Array(MAXN).fill(0);var parent = Array.from(Array(MAXN), ()=>Array(level).fill(-1));// pre-compute the depth for each node and their// first parent(2^0th parent)// time complexity : O(n)function dfs(cur, prev){ depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (var i = 0; i < tree[cur].length; i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); }}// Dynamic Programming Sparse Matrix Approach// populating 2^i parent for each node// Time complexity : O(nlogn)function precomputeSparseMatrix(n){ for (var i = 1; i < level; i++) { for(var node = 1; node <= n; node++) { if (parent[node][i - 1] != -1) parent[node][i] = parent[parent[node][i - 1]][i - 1]; } }}// Returning the LCA of u and v// Time complexity : O(log n)function lca(u, v){ if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } var diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (var i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (var i = level - 1; i >= 0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0];}function addEdge(u, v){ tree[u].push(v); tree[v].push(u);}function memset(value){ for (var i = 0; i < MAXN; i++) { for (var j = 0; j < level; j++) { parent[i][j] = -1; } }}// Driver functionmemset(-1);var n = 8;addEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8);depth[0] = 0;// running dfs and precalculating depth// of each node.dfs(1, 0);// Precomputing the 2^i th ancestor for every nodeprecomputeSparseMatrix(n);// calling the LCA functiondocument.write("LCA(4, 7) = " + lca(4, 7) + "<br>");document.write("LCA(4, 6) = " + lca(4, 6) + "<br>"); </script> LCA(4, 7) = 1 LCA(4, 6) = 2 Time Complexity: The time complexity for answering a single LCA query will be O(logn) but the overall time complexity is dominated by precalculation of the 2^i th ( 0<=i<=level ) ancestors for each node. Hence, the overall asymptotic Time Complexity will be O(n*logn) and Space Complexity will be O(nlogn), for storing the data about the ancestors of each node. This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 29AjayKumar Rajput-Ji princiraj1992 sanjeev2552 rag2127 itsok sumitgumber28 avtarkumar719 hardikkoriintern array-range-queries LCA n-ary-tree Advanced Data Structure Competitive Programming Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 462, "s": 52, "text": "In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA) for a binary tree and a binary search tree (this, this and this). Now let’s look at a method that can calculate LCA for any tree (not only for binary tree). We use Dynamic Programming with Sparse Matrix Approach in our method. This method is very handy and fast when you need to answer multiple queries of LCA for a tree. " }, { "code": null, "e": 478, "s": 462, "text": "Pre-requisites:" }, { "code": null, "e": 582, "s": 478, "text": "DFS Basic DP knowledge (This and this) Range Minimum Query (Square Root Decomposition and Sparse Table)" }, { "code": null, "e": 587, "s": 582, "text": "DFS " }, { "code": null, "e": 623, "s": 587, "text": "Basic DP knowledge (This and this) " }, { "code": null, "e": 688, "s": 623, "text": "Range Minimum Query (Square Root Decomposition and Sparse Table)" }, { "code": null, "e": 898, "s": 688, "text": "Naive Approach:- O(n) The naive approach for this general tree LCA calculation will be the same as the naive approach for the LCA calculation of Binary Tree (this naive approach is already well described here." }, { "code": null, "e": 958, "s": 898, "text": "The implementation for the naive approach is given below:- " }, { "code": null, "e": 962, "s": 958, "text": "C++" }, { "code": null, "e": 967, "s": 962, "text": "Java" }, { "code": null, "e": 975, "s": 967, "text": "Python3" }, { "code": null, "e": 978, "s": 975, "text": "C#" }, { "code": null, "e": 989, "s": 978, "text": "Javascript" }, { "code": "/* Program to find LCA of n1 and n2 using one DFS on the Tree */#include<bits/stdc++.h>using namespace std; // Maximum number of nodes is 100000 and nodes are// numbered from 1 to 100000#define MAXN 100001 vector < int > tree[MAXN];int path[3][MAXN]; // storing root to node path // storing the path from root to nodevoid dfs(int cur, int prev, int pathNumber, int ptr, int node, bool &flag){ for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev and !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber][ptr+1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr+1, node, flag); } }} // This Function compares the path from root to 'a' & root// to 'b' and returns LCA of a and b. Time Complexity : O(n)int LCA(int a, int b){ // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a bool flag = false; dfs(1, 0, 1, 1, a, flag); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b, flag); // runs till path 1 & path 2 matches int i = 0; while (path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i-1];} void addEdge(int a,int b){ tree[a].push_back(b); tree[b].push_back(a);} // Driver codeint main(){ int n = 8; // Number of nodes addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); cout << \"LCA(4, 7) = \" << LCA(4,7) << endl; cout << \"LCA(4, 6) = \" << LCA(4,6) << endl; return 0;}", "e": 2948, "s": 989, "text": null }, { "code": "/* Program to find LCA of n1 and n2 using one DFS onthe Tree */ import java.util.*; class GFG{ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000 static final int MAXN = 100001; static Vector<Integer>[] tree = new Vector[MAXN]; static int[][] path = new int[3][MAXN]; // storing root to node path static boolean flag; // storing the path from root to node static void dfs(int cur, int prev, int pathNumber, int ptr, int node) { for (int i = 0; i < tree[cur].size(); i++) { if (tree[cur].get(i) != prev && !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur].get(i); if (tree[cur].get(i) == node) { // node found flag = true; // terminating the path path[pathNumber][ptr + 1] = -1; return; } dfs(tree[cur].get(i), cur, pathNumber, ptr + 1, node); } } } // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n) static int LCA(int a, int b) { // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches int i = 0; while (i < MAXN && path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i - 1]; } static void addEdge(int a, int b) { tree[a].add(b); tree[b].add(a); } // Driver code public static void main(String[] args) { for (int i = 0; i < MAXN; i++) tree[i] = new Vector<Integer>(); // Number of nodes addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); System.out.print(\"LCA(4, 7) = \" + LCA(4, 7) + \"\\n\"); System.out.print(\"LCA(4, 6) = \" + LCA(4, 6) + \"\\n\"); }} // This code is contributed by 29AjayKumar", "e": 5341, "s": 2948, "text": null }, { "code": "# Python3 program to find LCA of n1 and# n2 using one DFS on the Tree # Maximum number of nodes is 100000 and# nodes are numbered from 1 to 100000MAXN = 100001 tree = [0] * MAXNfor i in range(MAXN): tree[i] = [] # Storing root to node pathpath = [0] * 3for i in range(3): path[i] = [0] * MAXN flag = False # Storing the path from root to nodedef dfs(cur: int, prev: int, pathNumber: int, ptr: int, node: int) -> None: global tree, path, flag for i in range(len(tree[cur])): if (tree[cur][i] != prev and not flag): # Pushing current node into the path path[pathNumber][ptr] = tree[cur][i] if (tree[cur][i] == node): # Node found flag = True # Terminating the path path[pathNumber][ptr + 1] = -1 return dfs(tree[cur][i], cur, pathNumber, ptr + 1, node) # This Function compares the path from root# to 'a' & root to 'b' and returns LCA of# a and b. Time Complexity : O(n)def LCA(a: int, b: int) -> int: global flag # Trivial case if (a == b): return a # Setting root to be first element # in path path[1][0] = path[2][0] = 1 # Calculating path from root to a flag = False dfs(1, 0, 1, 1, a) # Calculating path from root to b flag = False dfs(1, 0, 2, 1, b) # Runs till path 1 & path 2 matches i = 0 while (path[1][i] == path[2][i]): i += 1 # Returns the last matching # node in the paths return path[1][i - 1] def addEdge(a: int, b: int) -> None: tree[a].append(b) tree[b].append(a) # Driver codeif __name__ == \"__main__\": n = 8 # Number of nodes addEdge(1, 2) addEdge(1, 3) addEdge(2, 4) addEdge(2, 5) addEdge(2, 6) addEdge(3, 7) addEdge(3, 8) print(\"LCA(4, 7) = {}\".format(LCA(4, 7))) print(\"LCA(4, 6) = {}\".format(LCA(4, 6))) # This code is contributed by sanjeev2552", "e": 7330, "s": 5341, "text": null }, { "code": "/* C# Program to find LCA of n1 and n2 using one DFS onthe Tree */using System;using System.Collections.Generic; class GFG{ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000 static readonly int MAXN = 100001; static List<int>[] tree = new List<int>[MAXN]; static int[,] path = new int[3, MAXN]; // storing root to node path static bool flag; // storing the path from root to node static void dfs(int cur, int prev, int pathNumber, int ptr, int node) { for (int i = 0; i < tree[cur].Count; i++) { if (tree[cur][i] != prev && !flag) { // pushing current node into the path path[pathNumber,ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber, ptr + 1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr + 1, node); } } } // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n) static int LCA(int a, int b) { // trivial case if (a == b) return a; // setting root to be first element in path path[1, 0] = path[2, 0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches int i = 0; while (i < MAXN && path[1, i] == path[2, i]) i++; // returns the last matching node in the paths return path[1, i - 1]; } static void addEdge(int a, int b) { tree[a].Add(b); tree[b].Add(a); } // Driver code public static void Main(String[] args) { for (int i = 0; i < MAXN; i++) tree[i] = new List<int>(); // Number of nodes addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); Console.Write(\"LCA(4, 7) = \" + LCA(4, 7) + \"\\n\"); Console.Write(\"LCA(4, 6) = \" + LCA(4, 6) + \"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 9716, "s": 7330, "text": null }, { "code": "<script>/* Program to find LCA of n1 and n2 using one DFS onthe Tree */ // Maximum number of nodes is 100000 and nodes are // numbered from 1 to 100000let MAXN = 100001; let tree = new Array(MAXN); let path = new Array(3); for(let i = 0; i < 3; i++){ path[i] = new Array(MAXN); for(let j = 0; j < MAXN; j++) { path[i][j] = 0; }} let flag; /// storing the path from root to nodefunction dfs(cur,prev,pathNumber,ptr,node){ for (let i = 0; i < tree[cur].length; i++) { if (tree[cur][i] != prev && !flag) { // pushing current node into the path path[pathNumber][ptr] = tree[cur][i]; if (tree[cur][i] == node) { // node found flag = true; // terminating the path path[pathNumber][ptr + 1] = -1; return; } dfs(tree[cur][i], cur, pathNumber, ptr + 1, node); } }} // This Function compares the path from root to 'a' & root // to 'b' and returns LCA of a and b. Time Complexity : O(n)function LCA(a,b){ // trivial case if (a == b) return a; // setting root to be first element in path path[1][0] = path[2][0] = 1; // calculating path from root to a flag = false; dfs(1, 0, 1, 1, a); // calculating path from root to b flag = false; dfs(1, 0, 2, 1, b); // runs till path 1 & path 2 matches let i = 0; while (i < MAXN && path[1][i] == path[2][i]) i++; // returns the last matching node in the paths return path[1][i - 1];} function addEdge(a,b){ tree[a].push(b); tree[b].push(a);} // Driver codefor (let i = 0; i < MAXN; i++) tree[i] = []; // Number of nodesaddEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8); document.write(\"LCA(4, 7) = \" + LCA(4, 7) + \"<br>\");document.write(\"LCA(4, 6) = \" + LCA(4, 6) + \"<br>\"); // This code is contributed by rag2127</script>", "e": 11819, "s": 9716, "text": null }, { "code": null, "e": 11848, "s": 11819, "text": "LCA(4, 7) = 1\nLCA(4, 6) = 2\n" }, { "code": null, "e": 11916, "s": 11848, "text": "Sparse Matrix Approach (O(nlogn) pre-processing, O(log n) – query) " }, { "code": null, "e": 11933, "s": 11916, "text": "Pre-computation:" }, { "code": null, "e": 12098, "s": 11933, "text": "Here we store the 2^i th parent for every node, where 0 <= i < LEVEL, here “LEVEL” is a constant integer that tells the maximum number of 2^i th ancestor possible. " }, { "code": null, "e": 12312, "s": 12098, "text": "Therefore, we assume the worst case to see what is the value of the constant LEVEL. In our worst case every node in our tree will have at max 1 parent and 1 child or we can say it simply reduces to a linked list. " }, { "code": null, "e": 12369, "s": 12312, "text": "So, in this case LEVEL = ceil ( log(number of nodes) ). " }, { "code": null, "e": 12443, "s": 12369, "text": "We also pre-compute the height for each node using one dfs in O(n) time. " }, { "code": null, "e": 12808, "s": 12443, "text": "int n // number of nodes\nint parent[MAXN][LEVEL] // all initialized to -1 \n\nparent[node][0] : contains the 2^0th(first) \nparent of all the nodes pre-computed using DFS\n\n// Sparse matrix Approach\nfor node -> 1 to n : \n for i-> 1 to LEVEL :\n if ( parent[node][i-1] != -1 ) :\n parent[node][i] = \n parent[ parent[node][i-1] ][i-1]" }, { "code": null, "e": 13057, "s": 12808, "text": "Now , as we see the above dynamic programming code runs two nested loop that runs over their complete range respectively. Hence, it can be easily be inferred that its asymptotic Time Complexity is O(number of nodes * LEVEL) ~ O(n*LEVEL) ~ O(nlogn)." }, { "code": null, "e": 13075, "s": 13057, "text": "Return LCA(u,v): " }, { "code": null, "e": 13724, "s": 13075, "text": "First Step is to bring both the nodes at the same height. As we have already pre-computed the heights for each node. We first calculate the difference in the heights of u and v (let’s say v >=u). Now we need the node ‘v’ to jump h nodes above. This can be easily done in O(log h) time ( where h is the difference in the heights of u and v) as we have already stored the 2^i parent for each node. This process is exactly same as calculating x^y in O(log y) time. (See the code for better understanding).Now both u and v nodes are at same height. Therefore now once again we will use 2^i jumping strategy to reach the first Common Parent of u and v. " }, { "code": null, "e": 14227, "s": 13724, "text": "First Step is to bring both the nodes at the same height. As we have already pre-computed the heights for each node. We first calculate the difference in the heights of u and v (let’s say v >=u). Now we need the node ‘v’ to jump h nodes above. This can be easily done in O(log h) time ( where h is the difference in the heights of u and v) as we have already stored the 2^i parent for each node. This process is exactly same as calculating x^y in O(log y) time. (See the code for better understanding)." }, { "code": null, "e": 14374, "s": 14227, "text": "Now both u and v nodes are at same height. Therefore now once again we will use 2^i jumping strategy to reach the first Common Parent of u and v. " }, { "code": null, "e": 14505, "s": 14374, "text": "Pseudo-code:\nFor i-> LEVEL to 0 :\n If parent[u][i] != parent[v][i] :\n u = parent[u][i]\n v = parent[v][i]" }, { "code": null, "e": 14560, "s": 14505, "text": "Implementation of the above algorithm is given below: " }, { "code": null, "e": 14564, "s": 14560, "text": "C++" }, { "code": null, "e": 14569, "s": 14564, "text": "Java" }, { "code": null, "e": 14572, "s": 14569, "text": "C#" }, { "code": null, "e": 14583, "s": 14572, "text": "Javascript" }, { "code": "// Sparse Matrix DP approach to find LCA of two nodes#include <bits/stdc++.h>using namespace std;#define MAXN 100000#define level 18 vector <int> tree[MAXN];int depth[MAXN];int parent[MAXN][level]; // pre-compute the depth for each node and their// first parent(2^0th parent)// time complexity : O(n)void dfs(int cur, int prev){ depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i=0; i<tree[cur].size(); i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); }} // Dynamic Programming Sparse Matrix Approach// populating 2^i parent for each node// Time complexity : O(nlogn)void precomputeSparseMatrix(int n){ for (int i=1; i<level; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i-1] != -1) parent[node][i] = parent[parent[node][i-1]][i-1]; } }} // Returning the LCA of u and v// Time complexity : O(log n)int lca(int u, int v){ if (depth[v] < depth[u]) swap(u, v); int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i=0; i<level; i++) if ((diff>>i)&1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i=level-1; i>=0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0];} void addEdge(int u,int v){ tree[u].push_back(v); tree[v].push_back(u);} // driver functionint main(){ memset(parent,-1,sizeof(parent)); int n = 8; addEdge(1,2); addEdge(1,3); addEdge(2,4); addEdge(2,5); addEdge(2,6); addEdge(3,7); addEdge(3,8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1,0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function cout << \"LCA(4, 7) = \" << lca(4,7) << endl; cout << \"LCA(4, 6) = \" << lca(4,6) << endl; return 0;}", "e": 16621, "s": 14583, "text": null }, { "code": "// Sparse Matrix DP approach to find LCA of two nodesimport java.util.*; class GFG{ static final int MAXN = 100000; static final int level = 18; @SuppressWarnings(\"unchecked\") static Vector<Integer>[] tree = new Vector[MAXN]; static int[] depth = new int[MAXN]; static int[][] parent = new int[MAXN][level]; // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) static void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (int i = 0; i < tree[cur].size(); i++) { if (tree[cur].get(i) != prev) dfs(tree[cur].get(i), cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) static void precomputeSparseMatrix(int n) { for (int i = 1; i < level; i++) { for (int node = 1; node <= n; node++) { if (parent[node][i - 1] != -1) parent[node][i] = parent[parent[node][i - 1]][i - 1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) static int lca(int u, int v) { if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i = level - 1; i >= 0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0]; } static void addEdge(int u, int v) { tree[u].add(v); tree[v].add(u); } static void memset(int value) { for (int i = 0; i < MAXN; i++) { for (int j = 0; j < level; j++) { parent[i][j] = -1; } } } // driver function public static void main(String[] args) { memset(-1); for (int i = 0; i < MAXN; i++) tree[i] = new Vector<Integer>(); int n = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1, 0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function System.out.print(\"LCA(4, 7) = \" + lca(4, 7) + \"\\n\"); System.out.print(\"LCA(4, 6) = \" + lca(4, 6) + \"\\n\"); }} // This code is contributed by 29AjayKumar", "e": 19550, "s": 16621, "text": null }, { "code": "// Sparse Matrix DP approach to find LCA of two nodesusing System;using System.Collections.Generic; class GFG{ static readonly int MAXN = 100000; static readonly int level = 18; static List<int>[] tree = new List<int>[MAXN]; static int[] depth = new int[MAXN]; static int[,] parent = new int[MAXN, level]; // pre-compute the depth for each node and their // first parent(2^0th parent) // time complexity : O(n) static void dfs(int cur, int prev) { depth[cur] = depth[prev] + 1; parent[cur,0] = prev; for (int i = 0; i < tree[cur].Count; i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); } } // Dynamic Programming Sparse Matrix Approach // populating 2^i parent for each node // Time complexity : O(nlogn) static void precomputeSparseMatrix(int n) { for (int i = 1; i < level; i++) { for (int node = 1; node <= n; node++) { if (parent[node, i - 1] != -1) parent[node, i] = parent[parent[node, i - 1], i - 1]; } } } // Returning the LCA of u and v // Time complexity : O(log n) static int lca(int u, int v) { if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } int diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (int i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v, i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (int i = level - 1; i >= 0; i--) if (parent[u, i] != parent[v, i]) { u = parent[u, i]; v = parent[v, i]; } return parent[u, 0]; } static void addEdge(int u, int v) { tree[u].Add(v); tree[v].Add(u); } static void memset(int value) { for (int i = 0; i < MAXN; i++) { for (int j = 0; j < level; j++) { parent[i, j] = -1; } } } // Driver function public static void Main(String[] args) { memset(-1); for (int i = 0; i < MAXN; i++) tree[i] = new List<int>(); int n = 8; addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); depth[0] = 0; // running dfs and precalculating depth // of each node. dfs(1, 0); // Precomputing the 2^i th ancestor for every node precomputeSparseMatrix(n); // calling the LCA function Console.Write(\"LCA(4, 7) = \" + lca(4, 7) + \"\\n\"); Console.Write(\"LCA(4, 6) = \" + lca(4, 6) + \"\\n\"); }} // This code is contributed by PrinciRaj1992", "e": 22450, "s": 19550, "text": null }, { "code": "<script> // Sparse Matrix DP approach to find LCA of two nodesvar MAXN = 100000;var level = 18;var tree = Array.from(Array(MAXN), ()=>Array());var depth = Array(MAXN).fill(0);var parent = Array.from(Array(MAXN), ()=>Array(level).fill(-1));// pre-compute the depth for each node and their// first parent(2^0th parent)// time complexity : O(n)function dfs(cur, prev){ depth[cur] = depth[prev] + 1; parent[cur][0] = prev; for (var i = 0; i < tree[cur].length; i++) { if (tree[cur][i] != prev) dfs(tree[cur][i], cur); }}// Dynamic Programming Sparse Matrix Approach// populating 2^i parent for each node// Time complexity : O(nlogn)function precomputeSparseMatrix(n){ for (var i = 1; i < level; i++) { for(var node = 1; node <= n; node++) { if (parent[node][i - 1] != -1) parent[node][i] = parent[parent[node][i - 1]][i - 1]; } }}// Returning the LCA of u and v// Time complexity : O(log n)function lca(u, v){ if (depth[v] < depth[u]) { u = u + v; v = u - v; u = u - v; } var diff = depth[v] - depth[u]; // Step 1 of the pseudocode for (var i = 0; i < level; i++) if (((diff >> i) & 1) == 1) v = parent[v][i]; // now depth[u] == depth[v] if (u == v) return u; // Step 2 of the pseudocode for (var i = level - 1; i >= 0; i--) if (parent[u][i] != parent[v][i]) { u = parent[u][i]; v = parent[v][i]; } return parent[u][0];}function addEdge(u, v){ tree[u].push(v); tree[v].push(u);}function memset(value){ for (var i = 0; i < MAXN; i++) { for (var j = 0; j < level; j++) { parent[i][j] = -1; } }}// Driver functionmemset(-1);var n = 8;addEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8);depth[0] = 0;// running dfs and precalculating depth// of each node.dfs(1, 0);// Precomputing the 2^i th ancestor for every nodeprecomputeSparseMatrix(n);// calling the LCA functiondocument.write(\"LCA(4, 7) = \" + lca(4, 7) + \"<br>\");document.write(\"LCA(4, 6) = \" + lca(4, 6) + \"<br>\"); </script>", "e": 24630, "s": 22450, "text": null }, { "code": null, "e": 24659, "s": 24630, "text": "LCA(4, 7) = 1\nLCA(4, 6) = 2\n" }, { "code": null, "e": 24677, "s": 24659, "text": "Time Complexity: " }, { "code": null, "e": 25022, "s": 24677, "text": "The time complexity for answering a single LCA query will be O(logn) but the overall time complexity is dominated by precalculation of the 2^i th ( 0<=i<=level ) ancestors for each node. Hence, the overall asymptotic Time Complexity will be O(n*logn) and Space Complexity will be O(nlogn), for storing the data about the ancestors of each node." }, { "code": null, "e": 25319, "s": 25022, "text": "This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 25331, "s": 25319, "text": "29AjayKumar" }, { "code": null, "e": 25341, "s": 25331, "text": "Rajput-Ji" }, { "code": null, "e": 25355, "s": 25341, "text": "princiraj1992" }, { "code": null, "e": 25367, "s": 25355, "text": "sanjeev2552" }, { "code": null, "e": 25375, "s": 25367, "text": "rag2127" }, { "code": null, "e": 25381, "s": 25375, "text": "itsok" }, { "code": null, "e": 25395, "s": 25381, "text": "sumitgumber28" }, { "code": null, "e": 25409, "s": 25395, "text": "avtarkumar719" }, { "code": null, "e": 25426, "s": 25409, "text": "hardikkoriintern" }, { "code": null, "e": 25446, "s": 25426, "text": "array-range-queries" }, { "code": null, "e": 25450, "s": 25446, "text": "LCA" }, { "code": null, "e": 25461, "s": 25450, "text": "n-ary-tree" }, { "code": null, "e": 25485, "s": 25461, "text": "Advanced Data Structure" }, { "code": null, "e": 25509, "s": 25485, "text": "Competitive Programming" }, { "code": null, "e": 25514, "s": 25509, "text": "Tree" }, { "code": null, "e": 25519, "s": 25514, "text": "Tree" } ]
Maximum length of Strictly Increasing Sub-array after removing at most one element
01 Apr, 2022 Given an array arr[], the task is to remove at most one element and calculate the maximum length of strictly increasing subarray. Examples: Input: arr[] = {1, 2, 5, 3, 4} Output: 4 After deleting 5, the resulting array will be {1, 2, 3, 4} and the maximum length of its strictly increasing subarray is 4. Input: arr[] = {1, 2} Output: 2 The complete array is already strictly increasing. Approach: Create two arrays pre[] and pos[] of size N. Iterate over the input array arr[] from (0, N) to find out the contribution of the current element arr[i] in the array till now [0, i) and update the pre[] array if it contributes in the strictly increasing subarray. Iterate over the input array arr[] from [N – 2, 0] to find out the contribution of the current element arr[j] in the array till now (N, j) and update the pos[] array if arr[j] contributes in the longest increasing subarray. Calculate the maximum length of the strictly increasing subarray without removing any element. Iterate over the array pre[] and pos[] to find out the contribution of the current element by excluding that element. Maintain a variable ans to find the maximum found till now. 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 maximum length of// strictly increasing subarray after// removing atmost one elementint maxIncSubarr(int a[], int n){ // Create two arrays pre and pos int pre[n] = { 0 }; int pos[n] = { 0 }; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = max(pre[i - 1] + pos[i + 1], ans); } return ans;} // Driver codeint main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(int); cout << maxIncSubarr(arr, n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the maximum length of // strictly increasing subarray after // removing atmost one element static int maxIncSubarr(int a[], int n) { // Create two arrays pre and pos int pre[] = new int[n] ; int pos[] = new int[n] ; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.max(pre[i - 1] + pos[i + 1], ans); } return ans; } // Driver code public static void main (String[] args) { int arr[] = {1, 2}; int n = arr.length; System.out.println(maxIncSubarr(arr, n)); }} // This code is contributed by AnkitRai01 # Python implementation of the approach # Function to return the maximum length of# strictly increasing subarray after# removing atmost one elementdef maxIncSubarr(a, n): # Create two arrays pre and pos pre = [0] * n; pos = [0] * n; pre[0] = 1; pos[n - 1] = 1; l = 0; # Find out the contribution of the current # element in array[0, i] and update pre[i] for i in range(1, n): if (a[i] > a[i - 1]): pre[i] = pre[i - 1] + 1; else: pre[i] = 1; # Find out the contribution of the current # element in array[N - 1, i] and update pos[i] l = 1; for i in range(n - 2, -1, -1): if (a[i] < a[i + 1]): pos[i] = pos[i + 1] + 1; else: pos[i] = 1; # Calculate the maximum length of the # strictly increasing subarray without # removing any element ans = 0; l = 1; for i in range(1, n): if (a[i] > a[i - 1]): l += 1; else: l = 1; ans = max(ans, l); # Calculate the maximum length of the # strictly increasing subarray after # removing the current element for i in range(1, n - 1): if (a[i - 1] < a[i + 1]): ans = max(pre[i - 1] + pos[i + 1], ans); return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 2 ]; n = len(arr); print(maxIncSubarr(arr, n)); # This code is contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum length of // strictly increasing subarray after // removing atmost one element static int maxIncSubarr(int []a, int n) { // Create two arrays pre and pos int []pre = new int[n] ; int []pos = new int[n] ; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.Max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.Max(pre[i - 1] + pos[i + 1], ans); } return ans; } // Driver code public static void Main() { int []arr = {1, 2}; int n = arr.Length; Console.WriteLine(maxIncSubarr(arr, n)); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation of the approach // Function to return the maximum length of// strictly increasing subarray after// removing atmost one elementfunction maxIncSubarr(a, n){ // Create two arrays pre and pos let pre = new Array(n); let pos = new Array(n); pre.fill(0); pos.fill(0); pre[0] = 1; pos[n - 1] = 1; let l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for(let i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for(let i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element let ans = 0; l = 1; for(let i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for(let i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.max(pre[i - 1] + pos[i + 1], ans); } return ans;} // Driver codelet arr = [ 1, 2 ];let n = arr.length; document.write(maxIncSubarr(arr, n)); // This code is contributed by rameshtravel07 </script> 2 Time Complexity: O(N) Space Complexity: O(N) ankthon princiraj1992 sriashi0397 YashSharmaEmbark OmkarKhodwe1 rameshtravel07 simranarora5sos subarray Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Apr, 2022" }, { "code": null, "e": 184, "s": 54, "text": "Given an array arr[], the task is to remove at most one element and calculate the maximum length of strictly increasing subarray." }, { "code": null, "e": 195, "s": 184, "text": "Examples: " }, { "code": null, "e": 360, "s": 195, "text": "Input: arr[] = {1, 2, 5, 3, 4} Output: 4 After deleting 5, the resulting array will be {1, 2, 3, 4} and the maximum length of its strictly increasing subarray is 4." }, { "code": null, "e": 444, "s": 360, "text": "Input: arr[] = {1, 2} Output: 2 The complete array is already strictly increasing. " }, { "code": null, "e": 456, "s": 444, "text": "Approach: " }, { "code": null, "e": 501, "s": 456, "text": "Create two arrays pre[] and pos[] of size N." }, { "code": null, "e": 718, "s": 501, "text": "Iterate over the input array arr[] from (0, N) to find out the contribution of the current element arr[i] in the array till now [0, i) and update the pre[] array if it contributes in the strictly increasing subarray." }, { "code": null, "e": 942, "s": 718, "text": "Iterate over the input array arr[] from [N – 2, 0] to find out the contribution of the current element arr[j] in the array till now (N, j) and update the pos[] array if arr[j] contributes in the longest increasing subarray." }, { "code": null, "e": 1037, "s": 942, "text": "Calculate the maximum length of the strictly increasing subarray without removing any element." }, { "code": null, "e": 1155, "s": 1037, "text": "Iterate over the array pre[] and pos[] to find out the contribution of the current element by excluding that element." }, { "code": null, "e": 1215, "s": 1155, "text": "Maintain a variable ans to find the maximum found till now." }, { "code": null, "e": 1268, "s": 1215, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1272, "s": 1268, "text": "C++" }, { "code": null, "e": 1277, "s": 1272, "text": "Java" }, { "code": null, "e": 1285, "s": 1277, "text": "Python3" }, { "code": null, "e": 1288, "s": 1285, "text": "C#" }, { "code": null, "e": 1299, "s": 1288, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum length of// strictly increasing subarray after// removing atmost one elementint maxIncSubarr(int a[], int n){ // Create two arrays pre and pos int pre[n] = { 0 }; int pos[n] = { 0 }; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = max(pre[i - 1] + pos[i + 1], ans); } return ans;} // Driver codeint main(){ int arr[] = { 1, 2 }; int n = sizeof(arr) / sizeof(int); cout << maxIncSubarr(arr, n); return 0;}", "e": 2816, "s": 1299, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum length of // strictly increasing subarray after // removing atmost one element static int maxIncSubarr(int a[], int n) { // Create two arrays pre and pos int pre[] = new int[n] ; int pos[] = new int[n] ; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.max(pre[i - 1] + pos[i + 1], ans); } return ans; } // Driver code public static void main (String[] args) { int arr[] = {1, 2}; int n = arr.length; System.out.println(maxIncSubarr(arr, n)); }} // This code is contributed by AnkitRai01", "e": 4690, "s": 2816, "text": null }, { "code": "# Python implementation of the approach # Function to return the maximum length of# strictly increasing subarray after# removing atmost one elementdef maxIncSubarr(a, n): # Create two arrays pre and pos pre = [0] * n; pos = [0] * n; pre[0] = 1; pos[n - 1] = 1; l = 0; # Find out the contribution of the current # element in array[0, i] and update pre[i] for i in range(1, n): if (a[i] > a[i - 1]): pre[i] = pre[i - 1] + 1; else: pre[i] = 1; # Find out the contribution of the current # element in array[N - 1, i] and update pos[i] l = 1; for i in range(n - 2, -1, -1): if (a[i] < a[i + 1]): pos[i] = pos[i + 1] + 1; else: pos[i] = 1; # Calculate the maximum length of the # strictly increasing subarray without # removing any element ans = 0; l = 1; for i in range(1, n): if (a[i] > a[i - 1]): l += 1; else: l = 1; ans = max(ans, l); # Calculate the maximum length of the # strictly increasing subarray after # removing the current element for i in range(1, n - 1): if (a[i - 1] < a[i + 1]): ans = max(pre[i - 1] + pos[i + 1], ans); return ans; # Driver codeif __name__ == '__main__': arr = [ 1, 2 ]; n = len(arr); print(maxIncSubarr(arr, n)); # This code is contributed by PrinciRaj1992", "e": 6123, "s": 4690, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum length of // strictly increasing subarray after // removing atmost one element static int maxIncSubarr(int []a, int n) { // Create two arrays pre and pos int []pre = new int[n] ; int []pos = new int[n] ; pre[0] = 1; pos[n - 1] = 1; int l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for (int i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element int ans = 0; l = 1; for (int i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.Max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for (int i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.Max(pre[i - 1] + pos[i + 1], ans); } return ans; } // Driver code public static void Main() { int []arr = {1, 2}; int n = arr.Length; Console.WriteLine(maxIncSubarr(arr, n)); }} // This code is contributed by AnkitRai01", "e": 7994, "s": 6123, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum length of// strictly increasing subarray after// removing atmost one elementfunction maxIncSubarr(a, n){ // Create two arrays pre and pos let pre = new Array(n); let pos = new Array(n); pre.fill(0); pos.fill(0); pre[0] = 1; pos[n - 1] = 1; let l = 0; // Find out the contribution of the current // element in array[0, i] and update pre[i] for(let i = 1; i < n; i++) { if (a[i] > a[i - 1]) pre[i] = pre[i - 1] + 1; else pre[i] = 1; } // Find out the contribution of the current // element in array[N - 1, i] and update pos[i] l = 1; for(let i = n - 2; i >= 0; i--) { if (a[i] < a[i + 1]) pos[i] = pos[i + 1] + 1; else pos[i] = 1; } // Calculate the maximum length of the // strictly increasing subarray without // removing any element let ans = 0; l = 1; for(let i = 1; i < n; i++) { if (a[i] > a[i - 1]) l++; else l = 1; ans = Math.max(ans, l); } // Calculate the maximum length of the // strictly increasing subarray after // removing the current element for(let i = 1; i <= n - 2; i++) { if (a[i - 1] < a[i + 1]) ans = Math.max(pre[i - 1] + pos[i + 1], ans); } return ans;} // Driver codelet arr = [ 1, 2 ];let n = arr.length; document.write(maxIncSubarr(arr, n)); // This code is contributed by rameshtravel07 </script>", "e": 9575, "s": 7994, "text": null }, { "code": null, "e": 9577, "s": 9575, "text": "2" }, { "code": null, "e": 9601, "s": 9579, "text": "Time Complexity: O(N)" }, { "code": null, "e": 9624, "s": 9601, "text": "Space Complexity: O(N)" }, { "code": null, "e": 9632, "s": 9624, "text": "ankthon" }, { "code": null, "e": 9646, "s": 9632, "text": "princiraj1992" }, { "code": null, "e": 9658, "s": 9646, "text": "sriashi0397" }, { "code": null, "e": 9675, "s": 9658, "text": "YashSharmaEmbark" }, { "code": null, "e": 9688, "s": 9675, "text": "OmkarKhodwe1" }, { "code": null, "e": 9703, "s": 9688, "text": "rameshtravel07" }, { "code": null, "e": 9719, "s": 9703, "text": "simranarora5sos" }, { "code": null, "e": 9728, "s": 9719, "text": "subarray" }, { "code": null, "e": 9735, "s": 9728, "text": "Arrays" }, { "code": null, "e": 9755, "s": 9735, "text": "Dynamic Programming" }, { "code": null, "e": 9762, "s": 9755, "text": "Arrays" }, { "code": null, "e": 9782, "s": 9762, "text": "Dynamic Programming" } ]
How to make rounded corner using CSS ?
14 Sep, 2021 To create a rounded corner, we use the CSS border-radius property. This property is used to set the border-radius of element. Syntax: /* It sets the radius value to all 4 corners */ border-radius: value; Example 1: This example describes the border-radius to make the rounded corners. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; /* This set radius to all 4 corners */ border-radius: 10px; } </style></head> <body> <h2 style="color:green">GeeksforGeeks</h2> <div class="container"> <p text-align="center"> Rounded corner</p> </div></body> </html> Output: rounded corner Example 2: This example describes the use of border-bottom-left-radius property to make a rounded corner at the bottom left. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-bottom-left-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class="container"> <p text-align="center"> This is Rounded corner at <b>bottom left</b> </p> </div></body> </html> Output: Example 3: This example describes the use of border-top-right-radius property to make a rounded corner at the top-right corner. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-top-right-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class="container"> <p text-align="center"> This is Rounded corner at <b>top right</b> </p> </div></body> </html> Output: Example 4: This example describes the use of border-bottom-right-radius property to make the rounded corner at the bottom right. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-bottom-right-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class="container"> <p text-align="center"> This is Rounded corner at <b>bottom right</b> </p> </div></body> </html> Output: Example 5:This example describes the use of border-top-left-radius property to make the corner at the top-left. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-top-left-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class="container"> <p text-align="center"> This is Rounded corner at <b>top left</b> </p> </div></body> </html> Output: top left Shorthands: Apply Radius value to all four corners: border-radius: value; Apply value1 to top-left and bottom-right corners and value2 to top-right and bottom-left corners. border-radius: value1 value2; Apply value1 to top-left corner, value2 to top-right and bottom-left corners and value3 to bottom-right corner. border-radius: value1 value2 value3; Apply value1 to top-left corner, value2 to top-right corner , value3 to bottom-right corner and value4 to bottom-left corner. border-radius: value1 value2 value3 value4; Blogathon-2021 CSS-Properties CSS-Questions Picked Blogathon CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 154, "s": 28, "text": "To create a rounded corner, we use the CSS border-radius property. This property is used to set the border-radius of element." }, { "code": null, "e": 162, "s": 154, "text": "Syntax:" }, { "code": null, "e": 232, "s": 162, "text": "/* It sets the radius value to all 4 corners */\nborder-radius: value;" }, { "code": null, "e": 313, "s": 232, "text": "Example 1: This example describes the border-radius to make the rounded corners." }, { "code": null, "e": 318, "s": 313, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; /* This set radius to all 4 corners */ border-radius: 10px; } </style></head> <body> <h2 style=\"color:green\">GeeksforGeeks</h2> <div class=\"container\"> <p text-align=\"center\"> Rounded corner</p> </div></body> </html>", "e": 960, "s": 318, "text": null }, { "code": null, "e": 968, "s": 960, "text": "Output:" }, { "code": null, "e": 983, "s": 968, "text": "rounded corner" }, { "code": null, "e": 1110, "s": 985, "text": "Example 2: This example describes the use of border-bottom-left-radius property to make a rounded corner at the bottom left." }, { "code": null, "e": 1115, "s": 1110, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-bottom-left-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class=\"container\"> <p text-align=\"center\"> This is Rounded corner at <b>bottom left</b> </p> </div></body> </html>", "e": 1770, "s": 1115, "text": null }, { "code": null, "e": 1778, "s": 1770, "text": "Output:" }, { "code": null, "e": 1906, "s": 1778, "text": "Example 3: This example describes the use of border-top-right-radius property to make a rounded corner at the top-right corner." }, { "code": null, "e": 1911, "s": 1906, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-top-right-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class=\"container\"> <p text-align=\"center\"> This is Rounded corner at <b>top right</b> </p> </div></body> </html>", "e": 2561, "s": 1911, "text": null }, { "code": null, "e": 2569, "s": 2561, "text": "Output:" }, { "code": null, "e": 2698, "s": 2569, "text": "Example 4: This example describes the use of border-bottom-right-radius property to make the rounded corner at the bottom right." }, { "code": null, "e": 2703, "s": 2698, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-bottom-right-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class=\"container\"> <p text-align=\"center\"> This is Rounded corner at <b>bottom right</b> </p> </div></body> </html>", "e": 3360, "s": 2703, "text": null }, { "code": null, "e": 3370, "s": 3362, "text": "Output:" }, { "code": null, "e": 3482, "s": 3370, "text": "Example 5:This example describes the use of border-top-left-radius property to make the corner at the top-left." }, { "code": null, "e": 3487, "s": 3482, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> .container { border: 1px solid black; width: 300px; height: 200px; background-color: aqua; border-top-left-radius: 30px; } </style></head> <body> <h2>GeeksforGeeks</h2> <div class=\"container\"> <p text-align=\"center\"> This is Rounded corner at <b>top left</b> </p> </div></body> </html>", "e": 4136, "s": 3487, "text": null }, { "code": null, "e": 4144, "s": 4136, "text": "Output:" }, { "code": null, "e": 4154, "s": 4144, "text": "top left " }, { "code": null, "e": 4166, "s": 4154, "text": "Shorthands:" }, { "code": null, "e": 4206, "s": 4166, "text": "Apply Radius value to all four corners:" }, { "code": null, "e": 4229, "s": 4206, "text": "border-radius: value; " }, { "code": null, "e": 4328, "s": 4229, "text": "Apply value1 to top-left and bottom-right corners and value2 to top-right and bottom-left corners." }, { "code": null, "e": 4359, "s": 4328, "text": "border-radius: value1 value2; " }, { "code": null, "e": 4471, "s": 4359, "text": "Apply value1 to top-left corner, value2 to top-right and bottom-left corners and value3 to bottom-right corner." }, { "code": null, "e": 4509, "s": 4471, "text": "border-radius: value1 value2 value3; " }, { "code": null, "e": 4635, "s": 4509, "text": "Apply value1 to top-left corner, value2 to top-right corner , value3 to bottom-right corner and value4 to bottom-left corner." }, { "code": null, "e": 4680, "s": 4635, "text": "border-radius: value1 value2 value3 value4; " }, { "code": null, "e": 4695, "s": 4680, "text": "Blogathon-2021" }, { "code": null, "e": 4710, "s": 4695, "text": "CSS-Properties" }, { "code": null, "e": 4724, "s": 4710, "text": "CSS-Questions" }, { "code": null, "e": 4731, "s": 4724, "text": "Picked" }, { "code": null, "e": 4741, "s": 4731, "text": "Blogathon" }, { "code": null, "e": 4745, "s": 4741, "text": "CSS" }, { "code": null, "e": 4762, "s": 4745, "text": "Web Technologies" } ]
Sklearn.StratifiedShuffleSplit() function in Python
28 Dec, 2021 In this article, we’ll learn about the StratifiedShuffleSplit cross validator from sklearn library which gives train-test indices to split the data into train-test sets. StratifiedShuffleSplit is a combination of both ShuffleSplit and StratifiedKFold. Using StratifiedShuffleSplit the proportion of distribution of class labels is almost even between train and test dataset. The major difference between StratifiedShuffleSplit and StratifiedKFold (shuffle=True) is that in StratifiedKFold, the dataset is shuffled only once in the beginning and then split into the specified number of folds. This discards any chances of overlapping of the train-test sets. However, in StratifiedShuffleSplit the data is shuffled each time before the split is done and this is why there’s a greater chance that overlapping might be possible between train-test sets. Syntax: sklearn.model_selection.StratifiedShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) Parameters: n_splits: int, default=10 Number of re-shuffling & splitting iterations. test_size: float or int, default=None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. train_size: float or int, default=None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. random_state: int Controls the randomness of the training and testing indices produced. Below is the Implementation. Step 1) Import required modules. Python3 # import the librariesimport pandas as pdfrom sklearn.ensemble import RandomForestClassifierfrom sklearn import preprocessingfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import StratifiedShuffleSplit Step 2) Load the dataset and identify the dependent and independent variables. The dataset can be downloaded from here. Python3 # convert data set into dataframechurn_df = pd.read_csv(r"ChurnData.csv") # assign dependent and independent variablesX = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless']] y = churn_df['churn'].astype('int') Step 3) Pre-process data. Python3 # data pre-processingX = preprocessing.StandardScaler().fit(X).transform(X) Step 4) Create object of StratifiedShuffleSplit Class. Python3 # use StratifiedShuffleSplit()sss = StratifiedShuffleSplit(n_splits=4, test_size=0.5, random_state=0)sss.get_n_splits(X, y) Output: Step 5) Call the instance and split the data frame into training sample and testing sample. The split() function returns indices for the train-test samples. Use a regression algorithm and compare accuracy fo each predicted value. Python3 scores = [] # using regression to get predicted datarf = RandomForestClassifier(n_estimators=40, max_depth=7)for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] rf.fit(X_train, y_train) pred = rf.predict(X_test) scores.append(accuracy_score(y_test, pred)) # get accuracy of each predictionprint(scores) Output: simmytarika5 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Dec, 2021" }, { "code": null, "e": 199, "s": 28, "text": "In this article, we’ll learn about the StratifiedShuffleSplit cross validator from sklearn library which gives train-test indices to split the data into train-test sets. " }, { "code": null, "e": 879, "s": 199, "text": "StratifiedShuffleSplit is a combination of both ShuffleSplit and StratifiedKFold. Using StratifiedShuffleSplit the proportion of distribution of class labels is almost even between train and test dataset. The major difference between StratifiedShuffleSplit and StratifiedKFold (shuffle=True) is that in StratifiedKFold, the dataset is shuffled only once in the beginning and then split into the specified number of folds. This discards any chances of overlapping of the train-test sets. However, in StratifiedShuffleSplit the data is shuffled each time before the split is done and this is why there’s a greater chance that overlapping might be possible between train-test sets. " }, { "code": null, "e": 1004, "s": 879, "text": "Syntax: sklearn.model_selection.StratifiedShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None) " }, { "code": null, "e": 1016, "s": 1004, "text": "Parameters:" }, { "code": null, "e": 1042, "s": 1016, "text": "n_splits: int, default=10" }, { "code": null, "e": 1089, "s": 1042, "text": "Number of re-shuffling & splitting iterations." }, { "code": null, "e": 1127, "s": 1089, "text": "test_size: float or int, default=None" }, { "code": null, "e": 1242, "s": 1127, "text": "If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. " }, { "code": null, "e": 1281, "s": 1242, "text": "train_size: float or int, default=None" }, { "code": null, "e": 1397, "s": 1281, "text": "If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. " }, { "code": null, "e": 1415, "s": 1397, "text": "random_state: int" }, { "code": null, "e": 1486, "s": 1415, "text": "Controls the randomness of the training and testing indices produced. " }, { "code": null, "e": 1515, "s": 1486, "text": "Below is the Implementation." }, { "code": null, "e": 1548, "s": 1515, "text": "Step 1) Import required modules." }, { "code": null, "e": 1556, "s": 1548, "text": "Python3" }, { "code": "# import the librariesimport pandas as pdfrom sklearn.ensemble import RandomForestClassifierfrom sklearn import preprocessingfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import StratifiedShuffleSplit", "e": 1782, "s": 1556, "text": null }, { "code": null, "e": 1862, "s": 1782, "text": "Step 2) Load the dataset and identify the dependent and independent variables. " }, { "code": null, "e": 1903, "s": 1862, "text": "The dataset can be downloaded from here." }, { "code": null, "e": 1911, "s": 1903, "text": "Python3" }, { "code": "# convert data set into dataframechurn_df = pd.read_csv(r\"ChurnData.csv\") # assign dependent and independent variablesX = churn_df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless']] y = churn_df['churn'].astype('int')", "e": 2182, "s": 1911, "text": null }, { "code": null, "e": 2208, "s": 2182, "text": "Step 3) Pre-process data." }, { "code": null, "e": 2216, "s": 2208, "text": "Python3" }, { "code": "# data pre-processingX = preprocessing.StandardScaler().fit(X).transform(X)", "e": 2292, "s": 2216, "text": null }, { "code": null, "e": 2347, "s": 2292, "text": "Step 4) Create object of StratifiedShuffleSplit Class." }, { "code": null, "e": 2355, "s": 2347, "text": "Python3" }, { "code": "# use StratifiedShuffleSplit()sss = StratifiedShuffleSplit(n_splits=4, test_size=0.5, random_state=0)sss.get_n_splits(X, y)", "e": 2507, "s": 2355, "text": null }, { "code": null, "e": 2515, "s": 2507, "text": "Output:" }, { "code": null, "e": 2745, "s": 2515, "text": "Step 5) Call the instance and split the data frame into training sample and testing sample. The split() function returns indices for the train-test samples. Use a regression algorithm and compare accuracy fo each predicted value." }, { "code": null, "e": 2753, "s": 2745, "text": "Python3" }, { "code": "scores = [] # using regression to get predicted datarf = RandomForestClassifier(n_estimators=40, max_depth=7)for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] rf.fit(X_train, y_train) pred = rf.predict(X_test) scores.append(accuracy_score(y_test, pred)) # get accuracy of each predictionprint(scores)", "e": 3163, "s": 2753, "text": null }, { "code": null, "e": 3171, "s": 3163, "text": "Output:" }, { "code": null, "e": 3184, "s": 3171, "text": "simmytarika5" }, { "code": null, "e": 3201, "s": 3184, "text": "Machine Learning" }, { "code": null, "e": 3208, "s": 3201, "text": "Python" }, { "code": null, "e": 3225, "s": 3208, "text": "Machine Learning" } ]
Meta Strings (Check if two strings can become same after a swap in one string)
11 Jul, 2022 Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input : str1 = "geeks" str2 = "keegs" Output : Yes By just swapping 'k' and 'g' in any of string, both will become same. Input : str1 = "rsting" str2 = "string Output : No Input : str1 = "Converse" str2 = "Conserve" Asked in : Google Below are steps used in the algorithm. Check if both strings are of equal length or not, if not return false.Otherwise, start comparing both strings and count number of unmatched characters and also store the index of unmatched characters.If unmatched characters are more than 2 then return false.Otherwise check if on swapping any of these two characters in any string would make the string equal or not.If yes then return true. Otherwise return false. Check if both strings are of equal length or not, if not return false. Otherwise, start comparing both strings and count number of unmatched characters and also store the index of unmatched characters. If unmatched characters are more than 2 then return false. Otherwise check if on swapping any of these two characters in any string would make the string equal or not. If yes then return true. Otherwise return false. Implementation: C++ C# PHP Python3 Javascript // C++ program to check if two strings are meta strings#include <bits/stdc++.h>using namespace std; // Returns true if str1 and str2 are meta stringsbool areMetaStrings(string str1, string str2){ int len1 = str1.length(); int len2 = str2.length(); // Return false if both are not of equal length if (len1 != len2) return false; //If strings are equal if(str1 == str2){ set<char>se(str1.begin(), str1.end()); //If there is a character,which occur more than //once, we can swap, so that resultant string //remains same if(se.size() < str1.length()){ return true; } return false; } // To store indexes of previously mismatched // characters int prev = -1, curr = -1; int count = 0; for (int i=0; i<len1; i++) { // If current character doesn't match if (str1[i] != str2[i]) { // Count number of unmatched character count++; // If unmatched are greater than 2, // then return false if (count > 2) return false; // Store both unmatched characters of // both strings prev = curr; curr = i; } } // Check if previous unmatched of string1 // is equal to curr unmatched of string2 // and also check for curr unmatched character, // if both are same, then return true return (count == 2 && str1[prev] == str2[curr] && str1[curr] == str2[prev]);} // Driver codeint main(){ string str1 = "converse"; string str2 = "converse"; areMetaStrings(str1,str2) ? cout << "Yes" : cout << "No"; return 0;} // C# program to check if two strings// are meta stringsusing System;using System.Collections.Generic; class GFG { // Returns true if str1 and str2 // are meta strings static bool areMetaStrings(String str1, String str2) { int len1 = str1.Length; int len2 = str2.Length; // Return false if both are not of // equal length if (len1 != len2) return false; if(str1==str2){ var c = (new HashSet<char>(str1)).Count; if (c<len1){ return true; } return false; } // To store indexes of previously // mismatched characters int prev = -1, curr = -1; int count = 0; for (int i = 0; i < len1; i++) { // If current character // doesn't match if (str1[i] != str2[i]) { // Count number of unmatched // character count++; // If unmatched are greater // than 2, then return false if (count > 2) return false; // Store both unmatched // characters of both strings prev = curr; curr = i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return (count == 2 && str1[prev] == str2[curr] && str1[curr] == str2[prev]); } // Driver method public static void Main() { String str1 = "converse"; String str2 = "conserve"; Console.WriteLine( areMetaStrings(str1,str2) ? "Yes" :"No"); }} // This code is contributed by Sam007. <?php// php program to check if two strings// are meta strings // Returns true if str1 and str2 are// meta stringsfunction areMetaStrings($str1, $str2){ $len1 = strlen($str1); $len2 = strlen($str1); // Return false if both are not // of equal length if ($len1 != $len2) return false; if($str1 == $str2){ $result = (count_chars($str1, len1)); if(strlen($result) < $len1){ return true; } return false; } // To store indexes of previously // mismatched characters $prev = -1; $curr = -1; $count = 0; for ($i = 0; $i < $len1; $i++) { // If current character // doesn't match if ($str1[$i] != $str2[$i]) { // Count number of unmatched // character $count++; // If unmatched are greater // than 2, then return false if ($count > 2) return false; // Store both unmatched // characters of both // strings $prev = $curr; $curr = $i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return ($count == 2 && $str1[$prev] == $str2[$curr] && $str1[$curr] == $str2[$prev]);} // Driver code $str1 = "converse"; $str2 = "conserve"; if(areMetaStrings($str1, $str2)) echo "Yes"; else echo "No"; // This code is contributed by nitin mittal.?> # Python program to check if two strings# are meta strings # Returns true if str1 and str2 are meta stringsdef areMetaStrings( str1, str2) : len1 = len(str1) len2 = len(str2) # Return false if both are not of equal length if (len1 != len2) : return False if str1 == str2: char_seen = [] for char in str1: if char not in char_seen: char_seen.append(char) if len(char_seen) < len(str1): return True return False # To store indexes of previously mismatched # characters prev = -1 curr = -1 count = 0 i = 0 while i < len1 : # If current character doesn't match if (str1[i] != str2[i] ) : # Count number of unmatched character count = count + 1 # If unmatched are greater than 2, # then return false if (count > 2) : return False # Store both unmatched characters of # both strings prev = curr curr = i i = i + 1 # Check if previous unmatched of string1 # is equal to curr unmatched of string2 # and also check for curr unmatched character, # if both are same, then return true return (count == 2 and str1[prev] == str2[curr] and str1[curr] == str2[prev]) # Driver methodstr1 = "converse"str2 = "converse"if ( areMetaStrings(str1,str2) ) : print("Yes")else: print("No") # This code is contributed by Koulick Sadhu. <script> // JavaScript program to check if two strings // are meta strings // Returns true if str1 and str2 // are meta strings function areMetaStrings(str1, str2) { var len1 = str1.length; var len2 = str2.length; // Return false if both are not of // equal length if (len1 !== len2) return false; if (str1 === str2) { var c = new Set(str1.split("")); if (c < len1) { return true; } return false; } // To store indexes of previously // mismatched characters var prev = -1, curr = -1; var count = 0; for (var i = 0; i < len1; i++) { // If current character // doesn't match if (str1[i] !== str2[i]) { // Count number of unmatched // character count++; // If unmatched are greater // than 2, then return false if (count > 2) return false; // Store both unmatched // characters of both strings prev = curr; curr = i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return ( count === 2 && str1[prev] === str2[curr] && str1[curr] === str2[prev] ); } // Driver method var str1 = "converse"; var str2 = "conserve"; document.write(areMetaStrings(str1, str2) ? "Yes" : "No"); </script> Yes Time Complexity: O(N*log N) where N is the length of the string.Auxiliary Space: O(N) This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Sam007 nitin mittal koulick_sadhu rdtank pushpeshrajdx01 hardikkoriintern Google Strings Google Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 289, "s": 52, "text": "Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings." }, { "code": null, "e": 300, "s": 289, "text": "Examples: " }, { "code": null, "e": 546, "s": 300, "text": "Input : str1 = \"geeks\" \n str2 = \"keegs\"\nOutput : Yes\nBy just swapping 'k' and 'g' in any of string, \nboth will become same.\n\nInput : str1 = \"rsting\"\n str2 = \"string\nOutput : No\n\nInput : str1 = \"Converse\"\n str2 = \"Conserve\"" }, { "code": null, "e": 565, "s": 546, "text": "Asked in : Google " }, { "code": null, "e": 605, "s": 565, "text": "Below are steps used in the algorithm. " }, { "code": null, "e": 1020, "s": 605, "text": "Check if both strings are of equal length or not, if not return false.Otherwise, start comparing both strings and count number of unmatched characters and also store the index of unmatched characters.If unmatched characters are more than 2 then return false.Otherwise check if on swapping any of these two characters in any string would make the string equal or not.If yes then return true. Otherwise return false." }, { "code": null, "e": 1091, "s": 1020, "text": "Check if both strings are of equal length or not, if not return false." }, { "code": null, "e": 1222, "s": 1091, "text": "Otherwise, start comparing both strings and count number of unmatched characters and also store the index of unmatched characters." }, { "code": null, "e": 1281, "s": 1222, "text": "If unmatched characters are more than 2 then return false." }, { "code": null, "e": 1390, "s": 1281, "text": "Otherwise check if on swapping any of these two characters in any string would make the string equal or not." }, { "code": null, "e": 1439, "s": 1390, "text": "If yes then return true. Otherwise return false." }, { "code": null, "e": 1455, "s": 1439, "text": "Implementation:" }, { "code": null, "e": 1459, "s": 1455, "text": "C++" }, { "code": null, "e": 1462, "s": 1459, "text": "C#" }, { "code": null, "e": 1466, "s": 1462, "text": "PHP" }, { "code": null, "e": 1474, "s": 1466, "text": "Python3" }, { "code": null, "e": 1485, "s": 1474, "text": "Javascript" }, { "code": "// C++ program to check if two strings are meta strings#include <bits/stdc++.h>using namespace std; // Returns true if str1 and str2 are meta stringsbool areMetaStrings(string str1, string str2){ int len1 = str1.length(); int len2 = str2.length(); // Return false if both are not of equal length if (len1 != len2) return false; //If strings are equal if(str1 == str2){ set<char>se(str1.begin(), str1.end()); //If there is a character,which occur more than //once, we can swap, so that resultant string //remains same if(se.size() < str1.length()){ return true; } return false; } // To store indexes of previously mismatched // characters int prev = -1, curr = -1; int count = 0; for (int i=0; i<len1; i++) { // If current character doesn't match if (str1[i] != str2[i]) { // Count number of unmatched character count++; // If unmatched are greater than 2, // then return false if (count > 2) return false; // Store both unmatched characters of // both strings prev = curr; curr = i; } } // Check if previous unmatched of string1 // is equal to curr unmatched of string2 // and also check for curr unmatched character, // if both are same, then return true return (count == 2 && str1[prev] == str2[curr] && str1[curr] == str2[prev]);} // Driver codeint main(){ string str1 = \"converse\"; string str2 = \"converse\"; areMetaStrings(str1,str2) ? cout << \"Yes\" : cout << \"No\"; return 0;}", "e": 3212, "s": 1485, "text": null }, { "code": "// C# program to check if two strings// are meta stringsusing System;using System.Collections.Generic; class GFG { // Returns true if str1 and str2 // are meta strings static bool areMetaStrings(String str1, String str2) { int len1 = str1.Length; int len2 = str2.Length; // Return false if both are not of // equal length if (len1 != len2) return false; if(str1==str2){ var c = (new HashSet<char>(str1)).Count; if (c<len1){ return true; } return false; } // To store indexes of previously // mismatched characters int prev = -1, curr = -1; int count = 0; for (int i = 0; i < len1; i++) { // If current character // doesn't match if (str1[i] != str2[i]) { // Count number of unmatched // character count++; // If unmatched are greater // than 2, then return false if (count > 2) return false; // Store both unmatched // characters of both strings prev = curr; curr = i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return (count == 2 && str1[prev] == str2[curr] && str1[curr] == str2[prev]); } // Driver method public static void Main() { String str1 = \"converse\"; String str2 = \"conserve\"; Console.WriteLine( areMetaStrings(str1,str2) ? \"Yes\" :\"No\"); }} // This code is contributed by Sam007.", "e": 5217, "s": 3212, "text": null }, { "code": "<?php// php program to check if two strings// are meta strings // Returns true if str1 and str2 are// meta stringsfunction areMetaStrings($str1, $str2){ $len1 = strlen($str1); $len2 = strlen($str1); // Return false if both are not // of equal length if ($len1 != $len2) return false; if($str1 == $str2){ $result = (count_chars($str1, len1)); if(strlen($result) < $len1){ return true; } return false; } // To store indexes of previously // mismatched characters $prev = -1; $curr = -1; $count = 0; for ($i = 0; $i < $len1; $i++) { // If current character // doesn't match if ($str1[$i] != $str2[$i]) { // Count number of unmatched // character $count++; // If unmatched are greater // than 2, then return false if ($count > 2) return false; // Store both unmatched // characters of both // strings $prev = $curr; $curr = $i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return ($count == 2 && $str1[$prev] == $str2[$curr] && $str1[$curr] == $str2[$prev]);} // Driver code $str1 = \"converse\"; $str2 = \"conserve\"; if(areMetaStrings($str1, $str2)) echo \"Yes\"; else echo \"No\"; // This code is contributed by nitin mittal.?>", "e": 6831, "s": 5217, "text": null }, { "code": "# Python program to check if two strings# are meta strings # Returns true if str1 and str2 are meta stringsdef areMetaStrings( str1, str2) : len1 = len(str1) len2 = len(str2) # Return false if both are not of equal length if (len1 != len2) : return False if str1 == str2: char_seen = [] for char in str1: if char not in char_seen: char_seen.append(char) if len(char_seen) < len(str1): return True return False # To store indexes of previously mismatched # characters prev = -1 curr = -1 count = 0 i = 0 while i < len1 : # If current character doesn't match if (str1[i] != str2[i] ) : # Count number of unmatched character count = count + 1 # If unmatched are greater than 2, # then return false if (count > 2) : return False # Store both unmatched characters of # both strings prev = curr curr = i i = i + 1 # Check if previous unmatched of string1 # is equal to curr unmatched of string2 # and also check for curr unmatched character, # if both are same, then return true return (count == 2 and str1[prev] == str2[curr] and str1[curr] == str2[prev]) # Driver methodstr1 = \"converse\"str2 = \"converse\"if ( areMetaStrings(str1,str2) ) : print(\"Yes\")else: print(\"No\") # This code is contributed by Koulick Sadhu.", "e": 8413, "s": 6831, "text": null }, { "code": "<script> // JavaScript program to check if two strings // are meta strings // Returns true if str1 and str2 // are meta strings function areMetaStrings(str1, str2) { var len1 = str1.length; var len2 = str2.length; // Return false if both are not of // equal length if (len1 !== len2) return false; if (str1 === str2) { var c = new Set(str1.split(\"\")); if (c < len1) { return true; } return false; } // To store indexes of previously // mismatched characters var prev = -1, curr = -1; var count = 0; for (var i = 0; i < len1; i++) { // If current character // doesn't match if (str1[i] !== str2[i]) { // Count number of unmatched // character count++; // If unmatched are greater // than 2, then return false if (count > 2) return false; // Store both unmatched // characters of both strings prev = curr; curr = i; } } // Check if previous unmatched of // string1 is equal to curr unmatched // of string2 and also check for curr // unmatched character, if both are // same, then return true return ( count === 2 && str1[prev] === str2[curr] && str1[curr] === str2[prev] ); } // Driver method var str1 = \"converse\"; var str2 = \"conserve\"; document.write(areMetaStrings(str1, str2) ? \"Yes\" : \"No\"); </script>", "e": 10045, "s": 8413, "text": null }, { "code": null, "e": 10049, "s": 10045, "text": "Yes" }, { "code": null, "e": 10135, "s": 10049, "text": "Time Complexity: O(N*log N) where N is the length of the string.Auxiliary Space: O(N)" }, { "code": null, "e": 10440, "s": 10135, "text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 10447, "s": 10440, "text": "Sam007" }, { "code": null, "e": 10460, "s": 10447, "text": "nitin mittal" }, { "code": null, "e": 10474, "s": 10460, "text": "koulick_sadhu" }, { "code": null, "e": 10481, "s": 10474, "text": "rdtank" }, { "code": null, "e": 10497, "s": 10481, "text": "pushpeshrajdx01" }, { "code": null, "e": 10514, "s": 10497, "text": "hardikkoriintern" }, { "code": null, "e": 10521, "s": 10514, "text": "Google" }, { "code": null, "e": 10529, "s": 10521, "text": "Strings" }, { "code": null, "e": 10536, "s": 10529, "text": "Google" }, { "code": null, "e": 10544, "s": 10536, "text": "Strings" } ]
Rotating 3D Image Previewer Cube using CSS
25 Feb, 2021 The 3D Rotating Image Previewer cube is an effect in which a set of images appear on the faces of a revolving 3D cube. This effect can be created using HTML and CSS. Approach: The best way to animate HTML objects is by using CSS @keyframes and by setting transition state at different animation states. HTML Code: Create an HTML File (index.html). Link the CSS file in HTML that provides all the animation’s effect to our HTML. It is placed inside <head> tag. Create 6 <div> tags for each face of the cube and place your images on each face. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"></head> <body> <div class="cube"> <!-- Creating 6 divs for each face of the cube --> <div class="box box1"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223233400/gfg4.jpg" alt="image 1"> </div> <div class="box box2"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223232947/gfg2.jpg" alt="image 2"> </div> <div class="box box3"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223233400/gfg4.jpg" alt="image 3"> </div> <div class="box box4"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223232947/gfg2.jpg" alt="image 4"> </div> <div class="box box5"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223233046/gfg3.png" alt="image 5"> </div> <div class="box box6"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210223232853/gfg1.png" alt="image 6"> </div> </div></body> </html> CSS Code: The following is the content for the ‘style.css’ file used in the above HTML code. CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. Create a body class to give general styling to the whole page. Create ids and classes for each face of the cube to provide styling. Use @keyframes to animate the HTML elements. CSS /* CSS for general styling */body { display: flex; height: 100vh; justify-content: center; align-items: center; background: #1e6f0a;} .cube { width: 200px; height: 200px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite;} img { width: 100%; height: 100%; object-fit: cover;} .box { width: 100%; height: 100%; position: absolute; top: 0; left: 0; opacity: 0.9;} /* Applying styles to each face */.box1 { transform: translateZ(100px);} .box2 { transform: rotateY(90deg) translateX(100px); transform-origin: right;} .box3 { transform: rotateY(180deg) translateZ(100px);} .box4 { transform: rotateY(-90deg) translateX(-100px); transform-origin: left;} .box5 { transform: rotateX(-90deg) translateY(-100px); transform-origin: top;} .box6 { transform: rotateX(90deg) translateY(100px); transform-origin: bottom;} /* Animating the elements */@keyframes rotate { 0%, 100% { transform: rotate(0deg); } 20% { transform: rotateY(90deg) rotateZ(90deg); } 40% { transform: rotateY(180deg) rotateZ(-90deg); } 60% { transform: rotateY(270deg) rotateZ(90deg); } 80% { transform: rotateY(360deg) rotateZ(-90deg); }} Output: CSS-Questions HTML-Questions Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Feb, 2021" }, { "code": null, "e": 220, "s": 54, "text": "The 3D Rotating Image Previewer cube is an effect in which a set of images appear on the faces of a revolving 3D cube. This effect can be created using HTML and CSS." }, { "code": null, "e": 357, "s": 220, "text": "Approach: The best way to animate HTML objects is by using CSS @keyframes and by setting transition state at different animation states." }, { "code": null, "e": 368, "s": 357, "text": "HTML Code:" }, { "code": null, "e": 402, "s": 368, "text": "Create an HTML File (index.html)." }, { "code": null, "e": 514, "s": 402, "text": "Link the CSS file in HTML that provides all the animation’s effect to our HTML. It is placed inside <head> tag." }, { "code": null, "e": 596, "s": 514, "text": "Create 6 <div> tags for each face of the cube and place your images on each face." }, { "code": null, "e": 601, "s": 596, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"cube\"> <!-- Creating 6 divs for each face of the cube --> <div class=\"box box1\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223233400/gfg4.jpg\" alt=\"image 1\"> </div> <div class=\"box box2\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223232947/gfg2.jpg\" alt=\"image 2\"> </div> <div class=\"box box3\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223233400/gfg4.jpg\" alt=\"image 3\"> </div> <div class=\"box box4\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223232947/gfg2.jpg\" alt=\"image 4\"> </div> <div class=\"box box5\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223233046/gfg3.png\" alt=\"image 5\"> </div> <div class=\"box box6\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210223232853/gfg1.png\" alt=\"image 6\"> </div> </div></body> </html>", "e": 2015, "s": 601, "text": null }, { "code": null, "e": 2231, "s": 2015, "text": "CSS Code: The following is the content for the ‘style.css’ file used in the above HTML code. CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to all users. " }, { "code": null, "e": 2294, "s": 2231, "text": "Create a body class to give general styling to the whole page." }, { "code": null, "e": 2363, "s": 2294, "text": "Create ids and classes for each face of the cube to provide styling." }, { "code": null, "e": 2408, "s": 2363, "text": "Use @keyframes to animate the HTML elements." }, { "code": null, "e": 2416, "s": 2412, "text": "CSS" }, { "code": "/* CSS for general styling */body { display: flex; height: 100vh; justify-content: center; align-items: center; background: #1e6f0a;} .cube { width: 200px; height: 200px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite;} img { width: 100%; height: 100%; object-fit: cover;} .box { width: 100%; height: 100%; position: absolute; top: 0; left: 0; opacity: 0.9;} /* Applying styles to each face */.box1 { transform: translateZ(100px);} .box2 { transform: rotateY(90deg) translateX(100px); transform-origin: right;} .box3 { transform: rotateY(180deg) translateZ(100px);} .box4 { transform: rotateY(-90deg) translateX(-100px); transform-origin: left;} .box5 { transform: rotateX(-90deg) translateY(-100px); transform-origin: top;} .box6 { transform: rotateX(90deg) translateY(100px); transform-origin: bottom;} /* Animating the elements */@keyframes rotate { 0%, 100% { transform: rotate(0deg); } 20% { transform: rotateY(90deg) rotateZ(90deg); } 40% { transform: rotateY(180deg) rotateZ(-90deg); } 60% { transform: rotateY(270deg) rotateZ(90deg); } 80% { transform: rotateY(360deg) rotateZ(-90deg); }}", "e": 3719, "s": 2416, "text": null }, { "code": null, "e": 3727, "s": 3719, "text": "Output:" }, { "code": null, "e": 3741, "s": 3727, "text": "CSS-Questions" }, { "code": null, "e": 3756, "s": 3741, "text": "HTML-Questions" }, { "code": null, "e": 3780, "s": 3756, "text": "Technical Scripter 2020" }, { "code": null, "e": 3784, "s": 3780, "text": "CSS" }, { "code": null, "e": 3789, "s": 3784, "text": "HTML" }, { "code": null, "e": 3808, "s": 3789, "text": "Technical Scripter" }, { "code": null, "e": 3825, "s": 3808, "text": "Web Technologies" }, { "code": null, "e": 3830, "s": 3825, "text": "HTML" }, { "code": null, "e": 3928, "s": 3830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3967, "s": 3928, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4006, "s": 3967, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4045, "s": 4006, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4074, "s": 4045, "text": "Form validation using jQuery" }, { "code": null, "e": 4111, "s": 4074, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4135, "s": 4111, "text": "REST API (Introduction)" }, { "code": null, "e": 4188, "s": 4135, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4248, "s": 4188, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4309, "s": 4248, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Facebook Login using Python
16 Jul, 2020 Python scripting is one of the most intriguing and fascinating things to do meanwhile learning Python. Automation and controlling the browser is one of them. In this particular article, we will see how to log in to the Facebook account using Python and the power of selenium. Selenium automates and controls browsers and it’s activity. We can code in our way to control browser tasks with the help of selenium. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can be automated as well. As you learn more it’s so much fun to see things happening automatically and saving time in doing useless tasks again and again. We use selenium here to open the site of our requirement (in this case Facebook) and there we inspect elements across email box, password box, and login button to find the id of them. Using find_element_by_id() function provided by selenium module, we can find the required element (username box, password box, login button) Using send_keys() function, provided by selenium module, we will send the data into the box. Installing third party modules requiredSelenium getpass Additional Requirement : geckodriver for firefox and chromedriver for chrome Importing necessary modulesSelenium : to automate browserTime : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fastTaking username and password as input from userUsing input() function and passing prompt message as argument.Opening browser and required websitewebdriver.Chrome() will open new window of chrome. We will save it’s object in variable named driver.Now using get function we will open up the Facebook website.Finding element for sending data and Sending inputUse inspect element tool on the element of browser of which you want to find id. In this case we will inspect username box, password box, login button to find their id. And then use this id combining with selenium function find_element_by_id() to find it across web page and save it in variables for later use. Then by using send_keys() we will send data across the elements found previously.Closing the browserAfter all of the above steps we have to quit the session and will be achieved by using driver.quit().Note: Here driver is the name of variable you chose for webdriver.Chrome(). Installing third party modules requiredSelenium getpass Additional Requirement : geckodriver for firefox and chromedriver for chrome Selenium getpass Additional Requirement : geckodriver for firefox and chromedriver for chrome Importing necessary modulesSelenium : to automate browserTime : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fast Selenium : to automate browser Time : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fast Taking username and password as input from userUsing input() function and passing prompt message as argument. Opening browser and required websitewebdriver.Chrome() will open new window of chrome. We will save it’s object in variable named driver.Now using get function we will open up the Facebook website. Finding element for sending data and Sending inputUse inspect element tool on the element of browser of which you want to find id. In this case we will inspect username box, password box, login button to find their id. And then use this id combining with selenium function find_element_by_id() to find it across web page and save it in variables for later use. Then by using send_keys() we will send data across the elements found previously. Closing the browserAfter all of the above steps we have to quit the session and will be achieved by using driver.quit().Note: Here driver is the name of variable you chose for webdriver.Chrome(). Complete Code: from selenium import webdriverfrom time import sleepfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.chrome.options import Options usr=input('Enter Email Id:') pwd=input('Enter Password:') driver = webdriver.Chrome(ChromeDriverManager().install())driver.get('https://www.facebook.com/')print ("Opened facebook")sleep(1) username_box = driver.find_element_by_id('email')username_box.send_keys(usr)print ("Email Id entered")sleep(1) password_box = driver.find_element_by_id('pass')password_box.send_keys(pwd)print ("Password entered") login_box = driver.find_element_by_id('loginbutton')login_box.click() print ("Done")input('Press anything to quit')driver.quit()print("Finished") See how such a concise piece of code can automate things for you. Bonus:We can also enter the password without displaying it on screen, for security purpose. For that we have to include one more module called getpass. Now with just one change in input statement of the password we can input password without displaying it on screen. from getpass import getpasspwd = getpass('Enter Password:') Getpass prompts the user for a password without echoing. Basically it lets you enter the password without showing it on the screen. Similarly you can also automate many other things like twitter login, tweeting, Facebook logout, and much more. In case of any queries, post them below in the comments section. If you liked this article and want to see any more of the similar stuff, let me know in the comments section below. This article is contributed by Umang Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prernasrivastava1 Python-projects python-utility selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jul, 2020" }, { "code": null, "e": 210, "s": 52, "text": "Python scripting is one of the most intriguing and fascinating things to do meanwhile learning Python. Automation and controlling the browser is one of them." }, { "code": null, "e": 328, "s": 210, "text": "In this particular article, we will see how to log in to the Facebook account using Python and the power of selenium." }, { "code": null, "e": 770, "s": 328, "text": "Selenium automates and controls browsers and it’s activity. We can code in our way to control browser tasks with the help of selenium. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can be automated as well. As you learn more it’s so much fun to see things happening automatically and saving time in doing useless tasks again and again." }, { "code": null, "e": 954, "s": 770, "text": "We use selenium here to open the site of our requirement (in this case Facebook) and there we inspect elements across email box, password box, and login button to find the id of them." }, { "code": null, "e": 1095, "s": 954, "text": "Using find_element_by_id() function provided by selenium module, we can find the required element (username box, password box, login button)" }, { "code": null, "e": 1188, "s": 1095, "text": "Using send_keys() function, provided by selenium module, we will send the data into the box." }, { "code": null, "e": 2463, "s": 1188, "text": "Installing third party modules requiredSelenium \ngetpass\nAdditional Requirement : geckodriver for firefox and \n chromedriver for chrome\nImporting necessary modulesSelenium : to automate browserTime : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fastTaking username and password as input from userUsing input() function and passing prompt message as argument.Opening browser and required websitewebdriver.Chrome() will open new window of chrome. We will save it’s object in variable named driver.Now using get function we will open up the Facebook website.Finding element for sending data and Sending inputUse inspect element tool on the element of browser of which you want to find id. In this case we will inspect username box, password box, login button to find their id. And then use this id combining with selenium function find_element_by_id() to find it across web page and save it in variables for later use. Then by using send_keys() we will send data across the elements found previously.Closing the browserAfter all of the above steps we have to quit the session and will be achieved by using driver.quit().Note: Here driver is the name of variable you chose for webdriver.Chrome()." }, { "code": null, "e": 2624, "s": 2463, "text": "Installing third party modules requiredSelenium \ngetpass\nAdditional Requirement : geckodriver for firefox and \n chromedriver for chrome\n" }, { "code": null, "e": 2746, "s": 2624, "text": "Selenium \ngetpass\nAdditional Requirement : geckodriver for firefox and \n chromedriver for chrome\n" }, { "code": null, "e": 2918, "s": 2746, "text": "Importing necessary modulesSelenium : to automate browserTime : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fast" }, { "code": null, "e": 2949, "s": 2918, "text": "Selenium : to automate browser" }, { "code": null, "e": 3064, "s": 2949, "text": "Time : to pause running of script for some seconds as browsers try to detect automation stuff if we input too fast" }, { "code": null, "e": 3174, "s": 3064, "text": "Taking username and password as input from userUsing input() function and passing prompt message as argument." }, { "code": null, "e": 3372, "s": 3174, "text": "Opening browser and required websitewebdriver.Chrome() will open new window of chrome. We will save it’s object in variable named driver.Now using get function we will open up the Facebook website." }, { "code": null, "e": 3815, "s": 3372, "text": "Finding element for sending data and Sending inputUse inspect element tool on the element of browser of which you want to find id. In this case we will inspect username box, password box, login button to find their id. And then use this id combining with selenium function find_element_by_id() to find it across web page and save it in variables for later use. Then by using send_keys() we will send data across the elements found previously." }, { "code": null, "e": 4011, "s": 3815, "text": "Closing the browserAfter all of the above steps we have to quit the session and will be achieved by using driver.quit().Note: Here driver is the name of variable you chose for webdriver.Chrome()." }, { "code": null, "e": 4026, "s": 4011, "text": "Complete Code:" }, { "code": "from selenium import webdriverfrom time import sleepfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.chrome.options import Options usr=input('Enter Email Id:') pwd=input('Enter Password:') driver = webdriver.Chrome(ChromeDriverManager().install())driver.get('https://www.facebook.com/')print (\"Opened facebook\")sleep(1) username_box = driver.find_element_by_id('email')username_box.send_keys(usr)print (\"Email Id entered\")sleep(1) password_box = driver.find_element_by_id('pass')password_box.send_keys(pwd)print (\"Password entered\") login_box = driver.find_element_by_id('loginbutton')login_box.click() print (\"Done\")input('Press anything to quit')driver.quit()print(\"Finished\")", "e": 4744, "s": 4026, "text": null }, { "code": null, "e": 4810, "s": 4744, "text": "See how such a concise piece of code can automate things for you." }, { "code": null, "e": 5077, "s": 4810, "text": "Bonus:We can also enter the password without displaying it on screen, for security purpose. For that we have to include one more module called getpass. Now with just one change in input statement of the password we can input password without displaying it on screen." }, { "code": "from getpass import getpasspwd = getpass('Enter Password:') ", "e": 5138, "s": 5077, "text": null }, { "code": null, "e": 5270, "s": 5138, "text": "Getpass prompts the user for a password without echoing. Basically it lets you enter the password without showing it on the screen." }, { "code": null, "e": 5382, "s": 5270, "text": "Similarly you can also automate many other things like twitter login, tweeting, Facebook logout, and much more." }, { "code": null, "e": 5563, "s": 5382, "text": "In case of any queries, post them below in the comments section. If you liked this article and want to see any more of the similar stuff, let me know in the comments section below." }, { "code": null, "e": 5862, "s": 5563, "text": "This article is contributed by Umang Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5987, "s": 5862, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6005, "s": 5987, "text": "prernasrivastava1" }, { "code": null, "e": 6021, "s": 6005, "text": "Python-projects" }, { "code": null, "e": 6036, "s": 6021, "text": "python-utility" }, { "code": null, "e": 6045, "s": 6036, "text": "selenium" }, { "code": null, "e": 6052, "s": 6045, "text": "Python" } ]
seq command in Linux with Examples
06 Jul, 2021 seq command in Linux is used to generate numbers from FIRST to LAST in steps of INCREMENT. It is a very useful command where we had to generate list of numbers in while, for, until loop. Syntax: seq [OPTION]... LAST or seq [OPTION]... FIRST LAST or seq [OPTION]... FIRST INCREMENT LAST Options: seq LAST: When only one argument is given then it produces numbers from 1 to LAST in step increment of 1. If the LAST is less than 1, then is produces no output. seq FIRST LAST: When two arguments are given then it produces numbers from FIRST till LAST is step increment of 1. If LAST is less than FIRST, then it produces no output. seq FIRST INCREMENT LAST: When three arguments are given then it produces numbers from FIRST till LAST in step of INCREMENT. If LAST is less than FIRST, then it produces no output. seq -f “FORMAT” FIRST INCREMENT LAST: This command is used to generate sequence in a formatted manner. FIRST and INCREMENT are optional. seq -s “STRING” FIRST INCREMENT LAST: This command is uses to STRING to separate numbers. By default this value is equal to “\n”. FIRST and INCREMENT are optional. seq -w FIRST INCREMENT LAST: This command is used to equalize width by padding with leading zeroes. FIRST and INCREMENT are optional. seq –help: It displays help information. seq –version: It displays version information. sagar0719kumar sumitgumber28 linux-command Linux-misc-commands Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2021" }, { "code": null, "e": 240, "s": 52, "text": "seq command in Linux is used to generate numbers from FIRST to LAST in steps of INCREMENT. It is a very useful command where we had to generate list of numbers in while, for, until loop. " }, { "code": null, "e": 250, "s": 240, "text": "Syntax: " }, { "code": null, "e": 345, "s": 250, "text": "seq [OPTION]... LAST\n or\nseq [OPTION]... FIRST LAST\n or\nseq [OPTION]... FIRST INCREMENT LAST" }, { "code": null, "e": 356, "s": 345, "text": "Options: " }, { "code": null, "e": 519, "s": 356, "text": "seq LAST: When only one argument is given then it produces numbers from 1 to LAST in step increment of 1. If the LAST is less than 1, then is produces no output. " }, { "code": null, "e": 692, "s": 519, "text": "seq FIRST LAST: When two arguments are given then it produces numbers from FIRST till LAST is step increment of 1. If LAST is less than FIRST, then it produces no output. " }, { "code": null, "e": 875, "s": 692, "text": "seq FIRST INCREMENT LAST: When three arguments are given then it produces numbers from FIRST till LAST in step of INCREMENT. If LAST is less than FIRST, then it produces no output. " }, { "code": null, "e": 1013, "s": 875, "text": "seq -f “FORMAT” FIRST INCREMENT LAST: This command is used to generate sequence in a formatted manner. FIRST and INCREMENT are optional. " }, { "code": null, "e": 1178, "s": 1013, "text": "seq -s “STRING” FIRST INCREMENT LAST: This command is uses to STRING to separate numbers. By default this value is equal to “\\n”. FIRST and INCREMENT are optional. " }, { "code": null, "e": 1313, "s": 1178, "text": "seq -w FIRST INCREMENT LAST: This command is used to equalize width by padding with leading zeroes. FIRST and INCREMENT are optional. " }, { "code": null, "e": 1355, "s": 1313, "text": "seq –help: It displays help information. " }, { "code": null, "e": 1403, "s": 1355, "text": "seq –version: It displays version information. " }, { "code": null, "e": 1422, "s": 1407, "text": "sagar0719kumar" }, { "code": null, "e": 1436, "s": 1422, "text": "sumitgumber28" }, { "code": null, "e": 1450, "s": 1436, "text": "linux-command" }, { "code": null, "e": 1470, "s": 1450, "text": "Linux-misc-commands" }, { "code": null, "e": 1481, "s": 1470, "text": "Linux-Unix" }, { "code": null, "e": 1500, "s": 1481, "text": "Technical Scripter" } ]
How to underline a text content using HTML ?
09 Feb, 2021 In this article, we will create an underline text by using the <u> tag in the document. It stands for underline and it is used to underline the text enclosed within the <u> tag. This tag is generally used to underline misspelled words. This tag requires a starting as well as ending tag. Syntax: <u> Contents... </u> Example 1: This example uses <u> tag to create an underline text. html <!DOCTYPE html><html> <head> <title> How to underline a text content using HTML? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } p { font-size: 20px; } </style></head> <body> <div class="gfg"> GeeksforGeeks </div> <div class="geeks"> HTML5: How to underline a text in an HTML document <p> GeeksforGeeks: A <u>computer science</u> portal for geeks </p> </body> </html> Output: Example 2: This example is an alternate way of <u> tag to underline the text. In this example, we will use CSS text-decoration property to underline the text content. html <!DOCTYPE html><html> <head> <title> How to underline a text content using HTML? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } p { font-size: 20px; } span { text-decoration: underline; } </style></head> <body> <div class="gfg"> GeeksforGeeks </div> <div class="geeks"> HTML5: How to underline a text in an HTML document <p> GeeksforGeeks: A <span> computer science</span> portal for geeks </p> </body> </html> Output: Supported browsers: Google Chrome Internet Explorer Firefox Opera Safari AshokJaiswal CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2021" }, { "code": null, "e": 326, "s": 28, "text": "In this article, we will create an underline text by using the <u> tag in the document. It stands for underline and it is used to underline the text enclosed within the <u> tag. This tag is generally used to underline misspelled words. This tag requires a starting as well as ending tag. Syntax: " }, { "code": null, "e": 347, "s": 326, "text": "<u> Contents... </u>" }, { "code": null, "e": 413, "s": 347, "text": "Example 1: This example uses <u> tag to create an underline text." }, { "code": null, "e": 418, "s": 413, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to underline a text content using HTML? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } p { font-size: 20px; } </style></head> <body> <div class=\"gfg\"> GeeksforGeeks </div> <div class=\"geeks\"> HTML5: How to underline a text in an HTML document <p> GeeksforGeeks: A <u>computer science</u> portal for geeks </p> </body> </html>", "e": 1122, "s": 418, "text": null }, { "code": null, "e": 1130, "s": 1122, "text": "Output:" }, { "code": null, "e": 1297, "s": 1130, "text": "Example 2: This example is an alternate way of <u> tag to underline the text. In this example, we will use CSS text-decoration property to underline the text content." }, { "code": null, "e": 1302, "s": 1297, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to underline a text content using HTML? </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } .geeks { font-size: 25px; font-weight: bold; } p { font-size: 20px; } span { text-decoration: underline; } </style></head> <body> <div class=\"gfg\"> GeeksforGeeks </div> <div class=\"geeks\"> HTML5: How to underline a text in an HTML document <p> GeeksforGeeks: A <span> computer science</span> portal for geeks </p> </body> </html>", "e": 2087, "s": 1302, "text": null }, { "code": null, "e": 2095, "s": 2087, "text": "Output:" }, { "code": null, "e": 2115, "s": 2095, "text": "Supported browsers:" }, { "code": null, "e": 2129, "s": 2115, "text": "Google Chrome" }, { "code": null, "e": 2147, "s": 2129, "text": "Internet Explorer" }, { "code": null, "e": 2155, "s": 2147, "text": "Firefox" }, { "code": null, "e": 2161, "s": 2155, "text": "Opera" }, { "code": null, "e": 2168, "s": 2161, "text": "Safari" }, { "code": null, "e": 2181, "s": 2168, "text": "AshokJaiswal" }, { "code": null, "e": 2190, "s": 2181, "text": "CSS-Misc" }, { "code": null, "e": 2200, "s": 2190, "text": "HTML-Misc" }, { "code": null, "e": 2204, "s": 2200, "text": "CSS" }, { "code": null, "e": 2209, "s": 2204, "text": "HTML" }, { "code": null, "e": 2226, "s": 2209, "text": "Web Technologies" }, { "code": null, "e": 2253, "s": 2226, "text": "Web technologies Questions" }, { "code": null, "e": 2258, "s": 2253, "text": "HTML" } ]
Introduction to Node.js - GeeksforGeeks
10 Nov, 2021 Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart, and so on. Features of NodeJS: There are other programming languages also which we can use to build back-end services so what makes Node.js different I am going to explain. It’s easy to get started and can be used for prototyping and agile developmentIt provides fast and highly scalable servicesIt uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build back-end services using Node.jsSource code cleaner and consistent.Large ecosystem for open source library.It has Asynchronous or Non-blocking nature. It’s easy to get started and can be used for prototyping and agile development It provides fast and highly scalable services It uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build back-end services using Node.js Source code cleaner and consistent. Large ecosystem for open source library. It has Asynchronous or Non-blocking nature. Advantages of NodeJS: Here are the benefits of using Node.js Easy Scalability: Developers prefer to use Node.js because it is easily scaling the application in both horizontal and vertical directions. We can also add extra resources during the scalability of the application.Real-time web apps: If you are building a web app you can also use PHP, and it will take the same amount of time when you use Node.js, But if I am talking about building chat apps or gaming apps Node.js is much more preferable because of faster synchronization. Also, the event loop avoids HTTP overloaded for Node.js development.Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in NodeJs handles all asynchronous operation so NodeJs acts like a fast suite and all the operations can be done quickly like reading or writing in the database, network connection, or file systemEasy to learn and code: NodeJs is easy to learn and code because it uses JavaScript. If you are a front-end developer and have a good grasp of JavaScript you can easily learn and build the application on NodeJSAdvantage of Caching: It provides the caching of a single module. Whenever there is any request for the first module, it gets cached in the application memory, so you don’t need to re-execute the code.Data Streaming: In NodeJs HTTP request and response are considered as two separate events. They are data stream so when you process a file at the time of loading it will reduce the overall time and will make it faster when the data is presented in the form of transmissions. It also allows you to stream audio and video files at lightning speed.Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms for NodeJS application deployment which is easy to use without facing any issue.Corporate Support: Most of the well-known companies like Walmart, Paypal, Microsoft, Yahoo are using NodeJS for building the applications. NodeJS uses JavaScript, so most of the companies are combining front-end and backend Teams together into a single unit. Easy Scalability: Developers prefer to use Node.js because it is easily scaling the application in both horizontal and vertical directions. We can also add extra resources during the scalability of the application. Real-time web apps: If you are building a web app you can also use PHP, and it will take the same amount of time when you use Node.js, But if I am talking about building chat apps or gaming apps Node.js is much more preferable because of faster synchronization. Also, the event loop avoids HTTP overloaded for Node.js development. Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in NodeJs handles all asynchronous operation so NodeJs acts like a fast suite and all the operations can be done quickly like reading or writing in the database, network connection, or file system Easy to learn and code: NodeJs is easy to learn and code because it uses JavaScript. If you are a front-end developer and have a good grasp of JavaScript you can easily learn and build the application on NodeJS Advantage of Caching: It provides the caching of a single module. Whenever there is any request for the first module, it gets cached in the application memory, so you don’t need to re-execute the code. Data Streaming: In NodeJs HTTP request and response are considered as two separate events. They are data stream so when you process a file at the time of loading it will reduce the overall time and will make it faster when the data is presented in the form of transmissions. It also allows you to stream audio and video files at lightning speed. Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms for NodeJS application deployment which is easy to use without facing any issue. Corporate Support: Most of the well-known companies like Walmart, Paypal, Microsoft, Yahoo are using NodeJS for building the applications. NodeJS uses JavaScript, so most of the companies are combining front-end and backend Teams together into a single unit. Application of NodeJS: NodeJS should be preferred to build: Real-Time Chats, Complex Single-Page applications, Real-time collaboration tools, Streaming apps JSON APIs based application Installing Node and using It: Using Website: 1. You can visit the link Download Node and download LTS version. 2. After installing the node you can check your node version in command prompt using command.. ~ $node --version 3. After that, you can just create a folder and add a file here for example app.js. To run this file you need to execute command... first app $node app.js 4. Node Modules: There are some built-in modules that you can use to create your applications. Some popular modules are- OS, fs, events, HTTP, URL and then you can include these modules in your file using these lines. var fs = require('fs'); 5. Here is an example of how to include an HTTP module to build the server... javascript var http = require('http'); // Create a server object:http.createServer(function (req, res) { // Write a response to the client res.write('GeeksForGeeks'); // End the response res.end(); // The server object listens on port 8080}).listen(8080); This will listen to the server on port 8080. Once you will run your file in command prompt it will execute your file and listen to the server on this port. You can also create your own module and include it in your file. Using NPM: NPM is a Node Package Manager that provides packages to download and use. It contains all the files and modules that you require in your application. To install any package you need to execute a command... npm install This is an example of using the Events module. javascript var events = require('events');var eventEmitter = new events.EventEmitter(); // Create an event handler:var myEventHandler = function () { console.log('Welcome to GeeksforGeeks');} // Assign the event handler to an event:eventEmitter.on('geeks', myEventHandler); // Fire the 'geeks' event:eventEmitter.emit('geeks'); So this is how you can start with node and build your own applications. There are some frameworks of the node which you can use to build your applications. Some popular frameworks of node are...Express.js, Socket.io, Koa.js, Meteor.js, Sail.js. realabbas ghoshsuman0129 Node.js Articles JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Time Complexity and Space Complexity Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js
[ { "code": null, "e": 36627, "s": 36599, "text": "\n10 Nov, 2021" }, { "code": null, "e": 37112, "s": 36627, "text": "Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart, and so on." }, { "code": null, "e": 37274, "s": 37112, "text": "Features of NodeJS: There are other programming languages also which we can use to build back-end services so what makes Node.js different I am going to explain." }, { "code": null, "e": 37628, "s": 37274, "text": "It’s easy to get started and can be used for prototyping and agile developmentIt provides fast and highly scalable servicesIt uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build back-end services using Node.jsSource code cleaner and consistent.Large ecosystem for open source library.It has Asynchronous or Non-blocking nature." }, { "code": null, "e": 37707, "s": 37628, "text": "It’s easy to get started and can be used for prototyping and agile development" }, { "code": null, "e": 37753, "s": 37707, "text": "It provides fast and highly scalable services" }, { "code": null, "e": 37866, "s": 37753, "text": "It uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build back-end services using Node.js" }, { "code": null, "e": 37902, "s": 37866, "text": "Source code cleaner and consistent." }, { "code": null, "e": 37943, "s": 37902, "text": "Large ecosystem for open source library." }, { "code": null, "e": 37987, "s": 37943, "text": "It has Asynchronous or Non-blocking nature." }, { "code": null, "e": 38050, "s": 37987, "text": "Advantages of NodeJS: Here are the benefits of using Node.js " }, { "code": null, "e": 40033, "s": 38050, "text": "Easy Scalability: Developers prefer to use Node.js because it is easily scaling the application in both horizontal and vertical directions. We can also add extra resources during the scalability of the application.Real-time web apps: If you are building a web app you can also use PHP, and it will take the same amount of time when you use Node.js, But if I am talking about building chat apps or gaming apps Node.js is much more preferable because of faster synchronization. Also, the event loop avoids HTTP overloaded for Node.js development.Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in NodeJs handles all asynchronous operation so NodeJs acts like a fast suite and all the operations can be done quickly like reading or writing in the database, network connection, or file systemEasy to learn and code: NodeJs is easy to learn and code because it uses JavaScript. If you are a front-end developer and have a good grasp of JavaScript you can easily learn and build the application on NodeJSAdvantage of Caching: It provides the caching of a single module. Whenever there is any request for the first module, it gets cached in the application memory, so you don’t need to re-execute the code.Data Streaming: In NodeJs HTTP request and response are considered as two separate events. They are data stream so when you process a file at the time of loading it will reduce the overall time and will make it faster when the data is presented in the form of transmissions. It also allows you to stream audio and video files at lightning speed.Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms for NodeJS application deployment which is easy to use without facing any issue.Corporate Support: Most of the well-known companies like Walmart, Paypal, Microsoft, Yahoo are using NodeJS for building the applications. NodeJS uses JavaScript, so most of the companies are combining front-end and backend Teams together into a single unit." }, { "code": null, "e": 40248, "s": 40033, "text": "Easy Scalability: Developers prefer to use Node.js because it is easily scaling the application in both horizontal and vertical directions. We can also add extra resources during the scalability of the application." }, { "code": null, "e": 40579, "s": 40248, "text": "Real-time web apps: If you are building a web app you can also use PHP, and it will take the same amount of time when you use Node.js, But if I am talking about building chat apps or gaming apps Node.js is much more preferable because of faster synchronization. Also, the event loop avoids HTTP overloaded for Node.js development." }, { "code": null, "e": 40849, "s": 40579, "text": "Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in NodeJs handles all asynchronous operation so NodeJs acts like a fast suite and all the operations can be done quickly like reading or writing in the database, network connection, or file system" }, { "code": null, "e": 41060, "s": 40849, "text": "Easy to learn and code: NodeJs is easy to learn and code because it uses JavaScript. If you are a front-end developer and have a good grasp of JavaScript you can easily learn and build the application on NodeJS" }, { "code": null, "e": 41262, "s": 41060, "text": "Advantage of Caching: It provides the caching of a single module. Whenever there is any request for the first module, it gets cached in the application memory, so you don’t need to re-execute the code." }, { "code": null, "e": 41608, "s": 41262, "text": "Data Streaming: In NodeJs HTTP request and response are considered as two separate events. They are data stream so when you process a file at the time of loading it will reduce the overall time and will make it faster when the data is presented in the form of transmissions. It also allows you to stream audio and video files at lightning speed." }, { "code": null, "e": 41764, "s": 41608, "text": "Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms for NodeJS application deployment which is easy to use without facing any issue." }, { "code": null, "e": 42023, "s": 41764, "text": "Corporate Support: Most of the well-known companies like Walmart, Paypal, Microsoft, Yahoo are using NodeJS for building the applications. NodeJS uses JavaScript, so most of the companies are combining front-end and backend Teams together into a single unit." }, { "code": null, "e": 42083, "s": 42023, "text": "Application of NodeJS: NodeJS should be preferred to build:" }, { "code": null, "e": 42100, "s": 42083, "text": "Real-Time Chats," }, { "code": null, "e": 42134, "s": 42100, "text": "Complex Single-Page applications," }, { "code": null, "e": 42165, "s": 42134, "text": "Real-time collaboration tools," }, { "code": null, "e": 42180, "s": 42165, "text": "Streaming apps" }, { "code": null, "e": 42208, "s": 42180, "text": "JSON APIs based application" }, { "code": null, "e": 42238, "s": 42208, "text": "Installing Node and using It:" }, { "code": null, "e": 42255, "s": 42238, "text": "Using Website: " }, { "code": null, "e": 42321, "s": 42255, "text": "1. You can visit the link Download Node and download LTS version." }, { "code": null, "e": 42416, "s": 42321, "text": "2. After installing the node you can check your node version in command prompt using command.." }, { "code": null, "e": 42434, "s": 42416, "text": "~ $node --version" }, { "code": null, "e": 42566, "s": 42434, "text": "3. After that, you can just create a folder and add a file here for example app.js. To run this file you need to execute command..." }, { "code": null, "e": 42589, "s": 42566, "text": "first app $node app.js" }, { "code": null, "e": 42807, "s": 42589, "text": "4. Node Modules: There are some built-in modules that you can use to create your applications. Some popular modules are- OS, fs, events, HTTP, URL and then you can include these modules in your file using these lines." }, { "code": null, "e": 42831, "s": 42807, "text": "var fs = require('fs');" }, { "code": null, "e": 42910, "s": 42831, "text": "5. Here is an example of how to include an HTTP module to build the server... " }, { "code": null, "e": 42921, "s": 42910, "text": "javascript" }, { "code": "var http = require('http'); // Create a server object:http.createServer(function (req, res) { // Write a response to the client res.write('GeeksForGeeks'); // End the response res.end(); // The server object listens on port 8080}).listen(8080); ", "e": 43189, "s": 42921, "text": null }, { "code": null, "e": 43412, "s": 43189, "text": "This will listen to the server on port 8080. Once you will run your file in command prompt it will execute your file and listen to the server on this port. You can also create your own module and include it in your file. " }, { "code": null, "e": 43631, "s": 43412, "text": "Using NPM: NPM is a Node Package Manager that provides packages to download and use. It contains all the files and modules that you require in your application. To install any package you need to execute a command... " }, { "code": null, "e": 43644, "s": 43631, "text": "npm install " }, { "code": null, "e": 43692, "s": 43644, "text": "This is an example of using the Events module. " }, { "code": null, "e": 43703, "s": 43692, "text": "javascript" }, { "code": "var events = require('events');var eventEmitter = new events.EventEmitter(); // Create an event handler:var myEventHandler = function () { console.log('Welcome to GeeksforGeeks');} // Assign the event handler to an event:eventEmitter.on('geeks', myEventHandler); // Fire the 'geeks' event:eventEmitter.emit('geeks');", "e": 44030, "s": 43703, "text": null }, { "code": null, "e": 44276, "s": 44030, "text": "So this is how you can start with node and build your own applications. There are some frameworks of the node which you can use to build your applications. Some popular frameworks of node are...Express.js, Socket.io, Koa.js, Meteor.js, Sail.js. " }, { "code": null, "e": 44286, "s": 44276, "text": "realabbas" }, { "code": null, "e": 44301, "s": 44286, "text": "ghoshsuman0129" }, { "code": null, "e": 44309, "s": 44301, "text": "Node.js" }, { "code": null, "e": 44318, "s": 44309, "text": "Articles" }, { "code": null, "e": 44329, "s": 44318, "text": "JavaScript" }, { "code": null, "e": 44427, "s": 44329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44436, "s": 44427, "text": "Comments" }, { "code": null, "e": 44449, "s": 44436, "text": "Old Comments" }, { "code": null, "e": 44499, "s": 44449, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 44546, "s": 44499, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 44582, "s": 44546, "text": "find command in Linux with examples" }, { "code": null, "e": 44635, "s": 44582, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 44672, "s": 44635, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 44733, "s": 44672, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 44778, "s": 44733, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 44850, "s": 44778, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 44919, "s": 44850, "text": "How to calculate the number of days between two dates in javascript?" } ]
SWING - JMenu Class
The Menu class represents the pull-down menu component which is deployed from a menu bar. Following is the declaration for javax.swing.JMenu class − public class JMenu extends JMenuItem implements Accessible, MenuElement Following is the field for java.awt.Component class − protected JMenu.WinListener popupListener − The window-closing listener for the popup. protected JMenu.WinListener popupListener − The window-closing listener for the popup. JMenu() Constructs a new JMenu with no text. JMenu(Action a) Constructs a menu whose properties are taken from the Action supplied. JMenu(String s) Constructs a new JMenu with the supplied string as its text. JMenu(String s, boolean b) Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not. JMenuItem add(Action a) Creates a new menu item attached to the specified Action object and appends it to the end of this menu. Component add(Component c) Appends a component to the end of this menu. Component add(Component c, int index) Adds the specified component to this container at the given position. JMenuItem add(JMenuItem menuItem) Appends a menu item to the end of this menu. JMenuItem add(String s) Creates a new menu item with the specified text and appends it to the end of this menu. void addMenuListener(MenuListener l) Adds a listener for menu events. void addSeparator() Appends a new separator to the end of the menu. void applyComponentOrientation(ComponentOrientation o) Sets the ComponentOrientation property of this menu and all components contained within it. protected PropertyChangeListener createActionChangeListener(JMenuItem b) Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur. protected JMenuItem createActionComponent(Action a) Factory method which creates the JMenuItem for Actions added to the JMenu. protected JMenu.WinListener createWinListener(JPopupMenu p) Creates a window-closing listener for the popup. void doClick(int pressTime) Programmatically performs a "click". protected void fireMenuCanceled() Notifies all listeners that have registered interest for notification on this event type. protected void fireMenuDeselected() Notifies all listeners that have registered interest for notification on this event type. protected void fireMenuSelected() Notifies all listeners that have registered interest for notification on this event type. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JMenu. Component getComponent() Returns the java.awt.Component used to paint this MenuElement. int getDelay() Returns the suggested delay, in milliseconds, before submenus are popped up or down. JMenuItem getItem(int pos) Returns the JMenuItem at the specified position. int getItemCount() Returns the number of items on the menu, including separators. Component getMenuComponent(int n) Returns the component at position n. int getMenuComponentCount() Returns the number of components on the menu. Component[] getMenuComponents() Returns an array of Components of the menu's subcomponents. MenuListener[]getMenuListeners() Returns an array of all the MenuListeners added to this JMenu with addMenuListener(). JPopupMenu getPopupMenu() Returns the popupmenu associated with this menu. protected Point getPopupMenuOrigin() Computes the origin for the JMenu's popup menu. MenuElement[] getSubElements() Returns an array of MenuElements containing the submenu for this menu component. String getUIClassID() Returns the name of the L&F class that renders this component. JMenuItem insert(Action a, int pos) Inserts a new menu item attached to the specified Action object at a given position. JMenuItem insert(JMenuItem mi, int pos) Inserts the specified JMenuitem at a given position. void insert(String s, int pos) Inserts a new menu item with the specified text at a given position. void insertSeparator(int index) Inserts a separator at the specified position. boolean isMenuComponent(Component c) Returns true, if the specified component exists in the submenu hierarchy. boolean isPopupMenuVisible() Returns true, if the menu's popup window is visible. boolean isSelected() Returns true, if the menu is currently selected (highlighted). boolean isTearOff() Returns true, if the menu can be torn off. boolean isTopLevelMenu() Returns true, if the menu is a 'top-level menu', that is, if it is the direct child of a menubar. void menuSelectionChanged(boolean isIncluded) Messaged when the menubar selection changes to activate or deactivate this menu. protected String paramString() Returns a string representation of this JMenu. protected void processKeyEvent(KeyEvent evt) Processes key stroke events such as mnemonics and accelerators. void remove(Component c) Removes the component c from this menu. void remove(int pos) Removes the menu item at the specified index from this menu. void remove(JMenuItem item) Removes the specified menu item from this menu. void removeAll() Removes all menu items from this menu. void removeMenuListener(MenuListener l) Removes a listener for menu events. void setAccelerator(KeyStroke keyStroke) setAccelerator is not defined for JMenu. void setComponentOrientation(ComponentOrientation o) Sets the language-sensitive orientation that is used to order the elements or text within this component. void setDelay(int d) Sets the suggested delay before the menu's PopupMenu is popped up or down. void setMenuLocation(int x, int y) Sets the location of the popup component. void setModel(ButtonModel newModel) Sets the data model for the "menu button" the label that the user clicks to open or close the menu. void setPopupMenuVisible(boolean b) Sets the visibility of the menu's popup. void setSelected(boolean b) Sets the selection status of the menu. void updateUI() Resets the UI property with a value from the current look and feel. This class inherits methods from the following classes − javax.swing.JAbstractButton javax.swing.JComponent java.awt.Container java.awt.Component java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingMenuDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class SwingMenuDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingMenuDemo(){ prepareGUI(); } public static void main(String[] args){ SwingMenuDemo swingMenuDemo = new SwingMenuDemo(); swingMenuDemo.showMenuDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showMenuDemo(){ //create a menu bar final JMenuBar menuBar = new JMenuBar(); //create menus JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); final JMenu aboutMenu = new JMenu("About"); final JMenu linkMenu = new JMenu("Links"); //create menu items JMenuItem newMenuItem = new JMenuItem("New"); newMenuItem.setMnemonic(KeyEvent.VK_N); newMenuItem.setActionCommand("New"); JMenuItem openMenuItem = new JMenuItem("Open"); openMenuItem.setActionCommand("Open"); JMenuItem saveMenuItem = new JMenuItem("Save"); saveMenuItem.setActionCommand("Save"); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.setActionCommand("Exit"); JMenuItem cutMenuItem = new JMenuItem("Cut"); cutMenuItem.setActionCommand("Cut"); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.setActionCommand("Copy"); JMenuItem pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.setActionCommand("Paste"); MenuItemListener menuItemListener = new MenuItemListener(); newMenuItem.addActionListener(menuItemListener); openMenuItem.addActionListener(menuItemListener); saveMenuItem.addActionListener(menuItemListener); exitMenuItem.addActionListener(menuItemListener); cutMenuItem.addActionListener(menuItemListener); copyMenuItem.addActionListener(menuItemListener); pasteMenuItem.addActionListener(menuItemListener); final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem( "Show About", true); showWindowMenu.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(showWindowMenu.getState()){ menuBar.add(aboutMenu); } else { menuBar.remove(aboutMenu); } } }); final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem( "Show Links", true); showLinksMenu.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(menuBar.getMenu(3)!= null){ menuBar.remove(linkMenu); mainFrame.repaint(); } else { menuBar.add(linkMenu); mainFrame.repaint(); } } }); //add menu items to menus fileMenu.add(newMenuItem); fileMenu.add(openMenuItem); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); fileMenu.add(showWindowMenu); fileMenu.addSeparator(); fileMenu.add(showLinksMenu); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); editMenu.add(cutMenuItem); editMenu.add(copyMenuItem); editMenu.add(pasteMenuItem); //add menu to menubar menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(aboutMenu); menuBar.add(linkMenu); //add menubar to the frame mainFrame.setJMenuBar(menuBar); mainFrame.setVisible(true); } class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { statusLabel.setText(e.getActionCommand() + " JMenuItem clicked."); } } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo Verify the following output. (Click on File Menu.) 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1853, "s": 1763, "text": "The Menu class represents the pull-down menu component which is deployed from a menu bar." }, { "code": null, "e": 1912, "s": 1853, "text": "Following is the declaration for javax.swing.JMenu class −" }, { "code": null, "e": 1994, "s": 1912, "text": "public class JMenu\n extends JMenuItem\n implements Accessible, MenuElement\n" }, { "code": null, "e": 2048, "s": 1994, "text": "Following is the field for java.awt.Component class −" }, { "code": null, "e": 2135, "s": 2048, "text": "protected JMenu.WinListener popupListener − The window-closing listener for the popup." }, { "code": null, "e": 2222, "s": 2135, "text": "protected JMenu.WinListener popupListener − The window-closing listener for the popup." }, { "code": null, "e": 2230, "s": 2222, "text": "JMenu()" }, { "code": null, "e": 2267, "s": 2230, "text": "Constructs a new JMenu with no text." }, { "code": null, "e": 2283, "s": 2267, "text": "JMenu(Action a)" }, { "code": null, "e": 2354, "s": 2283, "text": "Constructs a menu whose properties are taken from the Action supplied." }, { "code": null, "e": 2370, "s": 2354, "text": "JMenu(String s)" }, { "code": null, "e": 2431, "s": 2370, "text": "Constructs a new JMenu with the supplied string as its text." }, { "code": null, "e": 2458, "s": 2431, "text": "JMenu(String s, boolean b)" }, { "code": null, "e": 2559, "s": 2458, "text": "Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not." }, { "code": null, "e": 2583, "s": 2559, "text": "JMenuItem add(Action a)" }, { "code": null, "e": 2687, "s": 2583, "text": "Creates a new menu item attached to the specified Action object and appends it to the end of this menu." }, { "code": null, "e": 2714, "s": 2687, "text": "Component add(Component c)" }, { "code": null, "e": 2759, "s": 2714, "text": "Appends a component to the end of this menu." }, { "code": null, "e": 2797, "s": 2759, "text": "Component add(Component c, int index)" }, { "code": null, "e": 2867, "s": 2797, "text": "Adds the specified component to this container at the given position." }, { "code": null, "e": 2901, "s": 2867, "text": "JMenuItem add(JMenuItem menuItem)" }, { "code": null, "e": 2946, "s": 2901, "text": "Appends a menu item to the end of this menu." }, { "code": null, "e": 2970, "s": 2946, "text": "JMenuItem add(String s)" }, { "code": null, "e": 3058, "s": 2970, "text": "Creates a new menu item with the specified text and appends it to the end of this menu." }, { "code": null, "e": 3095, "s": 3058, "text": "void addMenuListener(MenuListener l)" }, { "code": null, "e": 3128, "s": 3095, "text": "Adds a listener for menu events." }, { "code": null, "e": 3148, "s": 3128, "text": "void addSeparator()" }, { "code": null, "e": 3196, "s": 3148, "text": "Appends a new separator to the end of the menu." }, { "code": null, "e": 3251, "s": 3196, "text": "void applyComponentOrientation(ComponentOrientation o)" }, { "code": null, "e": 3343, "s": 3251, "text": "Sets the ComponentOrientation property of this menu and all components contained within it." }, { "code": null, "e": 3416, "s": 3343, "text": "protected PropertyChangeListener createActionChangeListener(JMenuItem b)" }, { "code": null, "e": 3527, "s": 3416, "text": "Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur." }, { "code": null, "e": 3579, "s": 3527, "text": "protected JMenuItem createActionComponent(Action a)" }, { "code": null, "e": 3654, "s": 3579, "text": "Factory method which creates the JMenuItem for Actions added to the JMenu." }, { "code": null, "e": 3714, "s": 3654, "text": "protected JMenu.WinListener createWinListener(JPopupMenu p)" }, { "code": null, "e": 3763, "s": 3714, "text": "Creates a window-closing listener for the popup." }, { "code": null, "e": 3791, "s": 3763, "text": "void doClick(int pressTime)" }, { "code": null, "e": 3828, "s": 3791, "text": "Programmatically performs a \"click\"." }, { "code": null, "e": 3862, "s": 3828, "text": "protected void fireMenuCanceled()" }, { "code": null, "e": 3952, "s": 3862, "text": "Notifies all listeners that have registered interest for notification on this event type." }, { "code": null, "e": 3988, "s": 3952, "text": "protected void fireMenuDeselected()" }, { "code": null, "e": 4078, "s": 3988, "text": "Notifies all listeners that have registered interest for notification on this event type." }, { "code": null, "e": 4112, "s": 4078, "text": "protected void fireMenuSelected()" }, { "code": null, "e": 4202, "s": 4112, "text": "Notifies all listeners that have registered interest for notification on this event type." }, { "code": null, "e": 4243, "s": 4202, "text": "AccessibleContext getAccessibleContext()" }, { "code": null, "e": 4298, "s": 4243, "text": "Gets the AccessibleContext associated with this JMenu." }, { "code": null, "e": 4323, "s": 4298, "text": "Component getComponent()" }, { "code": null, "e": 4386, "s": 4323, "text": "Returns the java.awt.Component used to paint this MenuElement." }, { "code": null, "e": 4401, "s": 4386, "text": "int getDelay()" }, { "code": null, "e": 4486, "s": 4401, "text": "Returns the suggested delay, in milliseconds, before submenus are popped up or down." }, { "code": null, "e": 4513, "s": 4486, "text": "JMenuItem getItem(int pos)" }, { "code": null, "e": 4562, "s": 4513, "text": "Returns the JMenuItem at the specified position." }, { "code": null, "e": 4581, "s": 4562, "text": "int getItemCount()" }, { "code": null, "e": 4644, "s": 4581, "text": "Returns the number of items on the menu, including separators." }, { "code": null, "e": 4678, "s": 4644, "text": "Component getMenuComponent(int n)" }, { "code": null, "e": 4715, "s": 4678, "text": "Returns the component at position n." }, { "code": null, "e": 4743, "s": 4715, "text": "int getMenuComponentCount()" }, { "code": null, "e": 4789, "s": 4743, "text": "Returns the number of components on the menu." }, { "code": null, "e": 4821, "s": 4789, "text": "Component[] getMenuComponents()" }, { "code": null, "e": 4881, "s": 4821, "text": "Returns an array of Components of the menu's subcomponents." }, { "code": null, "e": 4914, "s": 4881, "text": "MenuListener[]getMenuListeners()" }, { "code": null, "e": 5000, "s": 4914, "text": "Returns an array of all the MenuListeners added to this JMenu with addMenuListener()." }, { "code": null, "e": 5026, "s": 5000, "text": "JPopupMenu getPopupMenu()" }, { "code": null, "e": 5075, "s": 5026, "text": "Returns the popupmenu associated with this menu." }, { "code": null, "e": 5112, "s": 5075, "text": "protected Point getPopupMenuOrigin()" }, { "code": null, "e": 5160, "s": 5112, "text": "Computes the origin for the JMenu's popup menu." }, { "code": null, "e": 5191, "s": 5160, "text": "MenuElement[] getSubElements()" }, { "code": null, "e": 5272, "s": 5191, "text": "Returns an array of MenuElements containing the submenu for this menu component." }, { "code": null, "e": 5294, "s": 5272, "text": "String getUIClassID()" }, { "code": null, "e": 5357, "s": 5294, "text": "Returns the name of the L&F class that renders this component." }, { "code": null, "e": 5393, "s": 5357, "text": "JMenuItem insert(Action a, int pos)" }, { "code": null, "e": 5478, "s": 5393, "text": "Inserts a new menu item attached to the specified Action object at a given position." }, { "code": null, "e": 5518, "s": 5478, "text": "JMenuItem insert(JMenuItem mi, int pos)" }, { "code": null, "e": 5571, "s": 5518, "text": "Inserts the specified JMenuitem at a given position." }, { "code": null, "e": 5602, "s": 5571, "text": "void insert(String s, int pos)" }, { "code": null, "e": 5671, "s": 5602, "text": "Inserts a new menu item with the specified text at a given position." }, { "code": null, "e": 5703, "s": 5671, "text": "void insertSeparator(int index)" }, { "code": null, "e": 5750, "s": 5703, "text": "Inserts a separator at the specified position." }, { "code": null, "e": 5787, "s": 5750, "text": "boolean isMenuComponent(Component c)" }, { "code": null, "e": 5861, "s": 5787, "text": "Returns true, if the specified component exists in the submenu hierarchy." }, { "code": null, "e": 5890, "s": 5861, "text": "boolean isPopupMenuVisible()" }, { "code": null, "e": 5943, "s": 5890, "text": "Returns true, if the menu's popup window is visible." }, { "code": null, "e": 5964, "s": 5943, "text": "boolean isSelected()" }, { "code": null, "e": 6027, "s": 5964, "text": "Returns true, if the menu is currently selected (highlighted)." }, { "code": null, "e": 6047, "s": 6027, "text": "boolean isTearOff()" }, { "code": null, "e": 6090, "s": 6047, "text": "Returns true, if the menu can be torn off." }, { "code": null, "e": 6115, "s": 6090, "text": "boolean isTopLevelMenu()" }, { "code": null, "e": 6213, "s": 6115, "text": "Returns true, if the menu is a 'top-level menu', that is, if it is the direct child of a menubar." }, { "code": null, "e": 6259, "s": 6213, "text": "void menuSelectionChanged(boolean isIncluded)" }, { "code": null, "e": 6340, "s": 6259, "text": "Messaged when the menubar selection changes to activate or deactivate this menu." }, { "code": null, "e": 6371, "s": 6340, "text": "protected String\tparamString()" }, { "code": null, "e": 6418, "s": 6371, "text": "Returns a string representation of this JMenu." }, { "code": null, "e": 6463, "s": 6418, "text": "protected void processKeyEvent(KeyEvent evt)" }, { "code": null, "e": 6527, "s": 6463, "text": "Processes key stroke events such as mnemonics and accelerators." }, { "code": null, "e": 6552, "s": 6527, "text": "void remove(Component c)" }, { "code": null, "e": 6592, "s": 6552, "text": "Removes the component c from this menu." }, { "code": null, "e": 6613, "s": 6592, "text": "void remove(int pos)" }, { "code": null, "e": 6674, "s": 6613, "text": "Removes the menu item at the specified index from this menu." }, { "code": null, "e": 6702, "s": 6674, "text": "void remove(JMenuItem item)" }, { "code": null, "e": 6750, "s": 6702, "text": "Removes the specified menu item from this menu." }, { "code": null, "e": 6767, "s": 6750, "text": "void removeAll()" }, { "code": null, "e": 6806, "s": 6767, "text": "Removes all menu items from this menu." }, { "code": null, "e": 6846, "s": 6806, "text": "void removeMenuListener(MenuListener l)" }, { "code": null, "e": 6882, "s": 6846, "text": "Removes a listener for menu events." }, { "code": null, "e": 6923, "s": 6882, "text": "void setAccelerator(KeyStroke keyStroke)" }, { "code": null, "e": 6964, "s": 6923, "text": "setAccelerator is not defined for JMenu." }, { "code": null, "e": 7017, "s": 6964, "text": "void setComponentOrientation(ComponentOrientation o)" }, { "code": null, "e": 7123, "s": 7017, "text": "Sets the language-sensitive orientation that is used to order the elements or text within this component." }, { "code": null, "e": 7144, "s": 7123, "text": "void setDelay(int d)" }, { "code": null, "e": 7219, "s": 7144, "text": "Sets the suggested delay before the menu's PopupMenu is popped up or down." }, { "code": null, "e": 7254, "s": 7219, "text": "void setMenuLocation(int x, int y)" }, { "code": null, "e": 7296, "s": 7254, "text": "Sets the location of the popup component." }, { "code": null, "e": 7332, "s": 7296, "text": "void setModel(ButtonModel newModel)" }, { "code": null, "e": 7432, "s": 7332, "text": "Sets the data model for the \"menu button\" the label that the user clicks to open or close the menu." }, { "code": null, "e": 7468, "s": 7432, "text": "void setPopupMenuVisible(boolean b)" }, { "code": null, "e": 7509, "s": 7468, "text": "Sets the visibility of the menu's popup." }, { "code": null, "e": 7537, "s": 7509, "text": "void setSelected(boolean b)" }, { "code": null, "e": 7576, "s": 7537, "text": "Sets the selection status of the menu." }, { "code": null, "e": 7592, "s": 7576, "text": "void updateUI()" }, { "code": null, "e": 7660, "s": 7592, "text": "Resets the UI property with a value from the current look and feel." }, { "code": null, "e": 7717, "s": 7660, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 7745, "s": 7717, "text": "javax.swing.JAbstractButton" }, { "code": null, "e": 7768, "s": 7745, "text": "javax.swing.JComponent" }, { "code": null, "e": 7787, "s": 7768, "text": "java.awt.Container" }, { "code": null, "e": 7806, "s": 7787, "text": "java.awt.Component" }, { "code": null, "e": 7823, "s": 7806, "text": "java.lang.Object" }, { "code": null, "e": 7939, "s": 7823, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 7958, "s": 7939, "text": "SwingMenuDemo.java" }, { "code": null, "e": 12502, "s": 7958, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class SwingMenuDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel; \n\n public SwingMenuDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingMenuDemo swingMenuDemo = new SwingMenuDemo(); \n swingMenuDemo.showMenuDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showMenuDemo(){\n //create a menu bar\n final JMenuBar menuBar = new JMenuBar();\n\n //create menus\n JMenu fileMenu = new JMenu(\"File\");\n JMenu editMenu = new JMenu(\"Edit\"); \n final JMenu aboutMenu = new JMenu(\"About\");\n final JMenu linkMenu = new JMenu(\"Links\");\n \n //create menu items\n JMenuItem newMenuItem = new JMenuItem(\"New\");\n newMenuItem.setMnemonic(KeyEvent.VK_N);\n newMenuItem.setActionCommand(\"New\");\n\n JMenuItem openMenuItem = new JMenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n JMenuItem saveMenuItem = new JMenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n JMenuItem exitMenuItem = new JMenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n JMenuItem cutMenuItem = new JMenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n JMenuItem copyMenuItem = new JMenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n JMenuItem pasteMenuItem = new JMenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n\n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final JCheckBoxMenuItem showWindowMenu = new JCheckBoxMenuItem(\n \"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n \n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n } else {\n menuBar.remove(aboutMenu);\n }\n }\n });\n final JRadioButtonMenuItem showLinksMenu = new JRadioButtonMenuItem(\n \"Show Links\", true);\n \n showLinksMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n \n if(menuBar.getMenu(3)!= null){\n menuBar.remove(linkMenu);\n mainFrame.repaint();\n } else { \n menuBar.add(linkMenu);\n mainFrame.repaint();\n }\n }\n });\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(showLinksMenu); \n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem); \n \n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu); \n menuBar.add(linkMenu);\n\n //add menubar to the frame\n mainFrame.setJMenuBar(menuBar);\n mainFrame.setVisible(true); \n }\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() + \" JMenuItem clicked.\");\n } \n }\n}" }, { "code": null, "e": 12598, "s": 12502, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 12656, "s": 12598, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingMenuDemo.java\n" }, { "code": null, "e": 12761, "s": 12656, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 12813, "s": 12761, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingMenuDemo\n" }, { "code": null, "e": 12864, "s": 12813, "text": "Verify the following output. (Click on File Menu.)" }, { "code": null, "e": 12899, "s": 12864, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12919, "s": 12899, "text": " Pranjal Srivastava" }, { "code": null, "e": 12952, "s": 12919, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 12972, "s": 12952, "text": " Pranjal Srivastava" }, { "code": null, "e": 13007, "s": 12972, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13043, "s": 13007, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 13078, "s": 13043, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13091, "s": 13078, "text": " Travis Rose" }, { "code": null, "e": 13124, "s": 13091, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 13137, "s": 13124, "text": " Travis Rose" }, { "code": null, "e": 13144, "s": 13137, "text": " Print" }, { "code": null, "e": 13155, "s": 13144, "text": " Add Notes" } ]
Downloading Tableau crosstabs like a boss using Python and Pandas | by Elliott Stam | Towards Data Science
In another article we covered how you can query your Tableau view data like a boss, and I received some feedback from one person that they wanted to tumble deeper down the rabbit hole. That brings us to this article, where we will demonstrate how you can download view data for a table (crosstab) in Tableau, and reconstruct the shape of that data as it appeared in Tableau. This tutorial walks through using the Python tableau-api-lib package and is part of a series on how to tap Tableau Server like a keg, giving you control over Tableau Server’s REST API. These tutorials assume you have Python 3 installed already. If you do not have Python 3 yet, this will get you started: guide to install Python. Let’s say you have a crosstab in Tableau and you need to download it for whatever reason. If you go about doing this with the Tableau REST API, you’ll get the data you want... it just won’t necessarily be in the format you need. The main issue is that when you download the view data, you are not going to get data in the form of a ‘pivot table’ or a crosstab. You’ll have a raw table in database format, where all your dimensions appear as columns. Let’s see how we can download the data and shape it back into the table or crosstab you had in mind. Here’s a quick look at the Tableau view whose data we’ll download: Even if you’re a pro at these tutorials, do yourself a favor and pull the latest version of the library. pip install --upgrade tableau-api-lib New to this Python stuff? Don’t sweat it, you’ll catch on quick. Follow this getting started tutorial. That tutorial walks you through getting connected to Tableau Server using tableau-api-lib. Use the code below as a template for getting connected to your server. In future steps, we will build upon this boilerplate with one-off lines of code. At the end of the article, you’ll find a consolidated block of code you can copy/paste for your convenience. from tableau_api_lib import TableauServerConnectionfrom tableau_api_lib.utils import queryingtableau_server_config = { 'my_env': { 'server': 'https://YourTableauServer.com', 'api_version': '<YOUR_API_VERSION>', 'username': '<YOUR_USERNAME>', 'password': '<YOUR_PASSWORD>', 'site_name': '<YOUR_SITE_NAME>', 'site_url': '<YOUR_SITE_CONTENT_URL>' }}conn = TableauServerConnection(tableau_server_config, env='my_env')conn.sign_in() Fun fact: you can also use personal access tokens, assuming you are on Tableau Server 2019.4 or newer. If you’re all about the access tokens, check out my article for details on how to use them. We want to query a view, so first we’ll need to fetch the ID value for the desired view. site_views_df = querying.get_views_dataframe(conn) Here’s what my resulting DataFrame looks like: If we wanted to, we could search through manually and copy/paste the relevant ‘id’ value. However, if you are working in a large Tableau environment then you might have many views with the same name. For that reason, let’s do this the right way and unpack the details in our ‘workbook’ column so we can filter on the workbook name to make sure we are really getting the droid we’re looking for. Using a handy tableau-api-lib function, we can easily unpack the workbook details. You can see how this function is imported by referencing the complete code provided at the end of the article. site_views_detailed_df = flatten_dict_column(site_views_df, keys=['name', 'id'], col_name='workbook') And now we can quickly verify that the resulting DataFrame has the workbook details unpacked: Now we can easily filter on the workbook name we care about. In my case, the workbook is named ‘query_view_as_crosstab’ and the view I’m wanting to download is named ‘Visual C’. To reiterate a point made earlier, we want to filter on the workbook because it’s very likely that view names are not unique across our entire Tableau site but they are always unique within workbooks. relevant_views_df = site_views_detailed_df[site_views_detailed_df['workbook_name'] == 'query_view_as_crosstab'] Now that we’ve isolated our views to the workbook we are interested in, let’s get the view ID for the target view. visual_c_id = relevant_views_df[relevant_views_df['name'] == 'Visual C']['id'].to_list()[0] Equipped with the view ID, we can now query the view data: view_data_raw = querying.get_view_data_dataframe(conn, view_id=visual_c_id) The tableau-api-lib querying function ‘get_view_data_dataframe()’ returns a Pandas DataFrame, and mine looks like this: It’s a good start, but we need to pivot this data such that ‘Sub-Category’ defines our rows, ‘Year of Order Date’ defines our columns, and ‘Sales’ fills in the values of the pivoted table. Before we do the final step of pivoting the table, let’s quickly apply an optional improvement to the data: renaming the weirdly-named ‘Year of Order Date’ column to ‘Year’. view_data_raw.rename(columns={'Year of Order Date': 'Year'}, inplace=True) Ah, that’s better. Now let’s wrap this thing up! view_data_raw.pivot_table(values=['Sales'], index=['Sub-Category'], columns=['Year']) Before we call it a day, let’s quickly dissect this last bit of code. The Pandas DataFrame ‘pivot_table()’ function has provided us an easy way to redefine the structure of our data. The ‘values’ parameter defines what will fill in the values of the table, while the ‘index’ value defines the rows and ‘columns’ defines... the columns! Here’s how we look now: That’s a wrap! Use this GitHub gist as a starting point for modifying the steps we have covered in this tutorial for your own use.
[ { "code": null, "e": 357, "s": 172, "text": "In another article we covered how you can query your Tableau view data like a boss, and I received some feedback from one person that they wanted to tumble deeper down the rabbit hole." }, { "code": null, "e": 547, "s": 357, "text": "That brings us to this article, where we will demonstrate how you can download view data for a table (crosstab) in Tableau, and reconstruct the shape of that data as it appeared in Tableau." }, { "code": null, "e": 732, "s": 547, "text": "This tutorial walks through using the Python tableau-api-lib package and is part of a series on how to tap Tableau Server like a keg, giving you control over Tableau Server’s REST API." }, { "code": null, "e": 877, "s": 732, "text": "These tutorials assume you have Python 3 installed already. If you do not have Python 3 yet, this will get you started: guide to install Python." }, { "code": null, "e": 1106, "s": 877, "text": "Let’s say you have a crosstab in Tableau and you need to download it for whatever reason. If you go about doing this with the Tableau REST API, you’ll get the data you want... it just won’t necessarily be in the format you need." }, { "code": null, "e": 1327, "s": 1106, "text": "The main issue is that when you download the view data, you are not going to get data in the form of a ‘pivot table’ or a crosstab. You’ll have a raw table in database format, where all your dimensions appear as columns." }, { "code": null, "e": 1428, "s": 1327, "text": "Let’s see how we can download the data and shape it back into the table or crosstab you had in mind." }, { "code": null, "e": 1495, "s": 1428, "text": "Here’s a quick look at the Tableau view whose data we’ll download:" }, { "code": null, "e": 1600, "s": 1495, "text": "Even if you’re a pro at these tutorials, do yourself a favor and pull the latest version of the library." }, { "code": null, "e": 1638, "s": 1600, "text": "pip install --upgrade tableau-api-lib" }, { "code": null, "e": 1832, "s": 1638, "text": "New to this Python stuff? Don’t sweat it, you’ll catch on quick. Follow this getting started tutorial. That tutorial walks you through getting connected to Tableau Server using tableau-api-lib." }, { "code": null, "e": 2093, "s": 1832, "text": "Use the code below as a template for getting connected to your server. In future steps, we will build upon this boilerplate with one-off lines of code. At the end of the article, you’ll find a consolidated block of code you can copy/paste for your convenience." }, { "code": null, "e": 2625, "s": 2093, "text": "from tableau_api_lib import TableauServerConnectionfrom tableau_api_lib.utils import queryingtableau_server_config = { 'my_env': { 'server': 'https://YourTableauServer.com', 'api_version': '<YOUR_API_VERSION>', 'username': '<YOUR_USERNAME>', 'password': '<YOUR_PASSWORD>', 'site_name': '<YOUR_SITE_NAME>', 'site_url': '<YOUR_SITE_CONTENT_URL>' }}conn = TableauServerConnection(tableau_server_config, env='my_env')conn.sign_in()" }, { "code": null, "e": 2820, "s": 2625, "text": "Fun fact: you can also use personal access tokens, assuming you are on Tableau Server 2019.4 or newer. If you’re all about the access tokens, check out my article for details on how to use them." }, { "code": null, "e": 2909, "s": 2820, "text": "We want to query a view, so first we’ll need to fetch the ID value for the desired view." }, { "code": null, "e": 2960, "s": 2909, "text": "site_views_df = querying.get_views_dataframe(conn)" }, { "code": null, "e": 3007, "s": 2960, "text": "Here’s what my resulting DataFrame looks like:" }, { "code": null, "e": 3207, "s": 3007, "text": "If we wanted to, we could search through manually and copy/paste the relevant ‘id’ value. However, if you are working in a large Tableau environment then you might have many views with the same name." }, { "code": null, "e": 3402, "s": 3207, "text": "For that reason, let’s do this the right way and unpack the details in our ‘workbook’ column so we can filter on the workbook name to make sure we are really getting the droid we’re looking for." }, { "code": null, "e": 3596, "s": 3402, "text": "Using a handy tableau-api-lib function, we can easily unpack the workbook details. You can see how this function is imported by referencing the complete code provided at the end of the article." }, { "code": null, "e": 3698, "s": 3596, "text": "site_views_detailed_df = flatten_dict_column(site_views_df, keys=['name', 'id'], col_name='workbook')" }, { "code": null, "e": 3792, "s": 3698, "text": "And now we can quickly verify that the resulting DataFrame has the workbook details unpacked:" }, { "code": null, "e": 4171, "s": 3792, "text": "Now we can easily filter on the workbook name we care about. In my case, the workbook is named ‘query_view_as_crosstab’ and the view I’m wanting to download is named ‘Visual C’. To reiterate a point made earlier, we want to filter on the workbook because it’s very likely that view names are not unique across our entire Tableau site but they are always unique within workbooks." }, { "code": null, "e": 4283, "s": 4171, "text": "relevant_views_df = site_views_detailed_df[site_views_detailed_df['workbook_name'] == 'query_view_as_crosstab']" }, { "code": null, "e": 4398, "s": 4283, "text": "Now that we’ve isolated our views to the workbook we are interested in, let’s get the view ID for the target view." }, { "code": null, "e": 4490, "s": 4398, "text": "visual_c_id = relevant_views_df[relevant_views_df['name'] == 'Visual C']['id'].to_list()[0]" }, { "code": null, "e": 4549, "s": 4490, "text": "Equipped with the view ID, we can now query the view data:" }, { "code": null, "e": 4625, "s": 4549, "text": "view_data_raw = querying.get_view_data_dataframe(conn, view_id=visual_c_id)" }, { "code": null, "e": 4745, "s": 4625, "text": "The tableau-api-lib querying function ‘get_view_data_dataframe()’ returns a Pandas DataFrame, and mine looks like this:" }, { "code": null, "e": 4934, "s": 4745, "text": "It’s a good start, but we need to pivot this data such that ‘Sub-Category’ defines our rows, ‘Year of Order Date’ defines our columns, and ‘Sales’ fills in the values of the pivoted table." }, { "code": null, "e": 5108, "s": 4934, "text": "Before we do the final step of pivoting the table, let’s quickly apply an optional improvement to the data: renaming the weirdly-named ‘Year of Order Date’ column to ‘Year’." }, { "code": null, "e": 5183, "s": 5108, "text": "view_data_raw.rename(columns={'Year of Order Date': 'Year'}, inplace=True)" }, { "code": null, "e": 5232, "s": 5183, "text": "Ah, that’s better. Now let’s wrap this thing up!" }, { "code": null, "e": 5318, "s": 5232, "text": "view_data_raw.pivot_table(values=['Sales'], index=['Sub-Category'], columns=['Year'])" }, { "code": null, "e": 5501, "s": 5318, "text": "Before we call it a day, let’s quickly dissect this last bit of code. The Pandas DataFrame ‘pivot_table()’ function has provided us an easy way to redefine the structure of our data." }, { "code": null, "e": 5654, "s": 5501, "text": "The ‘values’ parameter defines what will fill in the values of the table, while the ‘index’ value defines the rows and ‘columns’ defines... the columns!" }, { "code": null, "e": 5678, "s": 5654, "text": "Here’s how we look now:" }, { "code": null, "e": 5693, "s": 5678, "text": "That’s a wrap!" } ]
Implementation of Ridge Regression from Scratch using Python - GeeksforGeeks
18 Sep, 2020 Prerequisites: Linear RegressionGradient Descent Linear Regression Gradient Descent Introduction:Ridge Regression ( or L2 Regularization ) is a variation of Linear Regression. In Linear Regression, it minimizes the Residual Sum of Squares ( or RSS or cost function ) to fit the training examples perfectly as possible. The cost function is also represented by J. Cost Function for Linear Regression: Here, h(x(i)) represents the hypothetical function for prediction. y(i) represents the value of target variable for ith example.m is the total number of training examples in the given dataset. Linear regression treats all the features equally and finds unbiased weights to minimizes the cost function. This could arise the problem of overfitting ( or a model fails to perform well on new data ). Linear Regression also can’t deal with the collinear data ( collinearity refers to the event when the features are highly correlated ). In short, Linear Regression is a model with high variance. So, Ridge Regression comes for the rescue. In Ridge Regression, there is an addition of l2 penalty ( square of the magnitude of weights ) in the cost function of Linear Regression. This is done so that the model does not overfit the data. The Modified cost function for Ridge Regression is given below: Here, wj represents the weight for jth feature.n is the number of features in the dataset. Mathematical Intuition:During gradient descent optimization of its cost function, added l2 penalty term leads to reduces the weights of the model to zero or close to zero. Due to the penalization of weights, our hypothesis gets simpler, more generalized, and less prone to overfitting. All weights are reduced by the same factor lambda. We can control the strength of regularization by hyperparameter lambda. Different cases for tuning values of lambda. If lambda is set to be 0, Ridge Regression equals Linear RegressionIf lambda is set to be infinity, all weights are shrunk to zero. If lambda is set to be 0, Ridge Regression equals Linear Regression If lambda is set to be infinity, all weights are shrunk to zero. So, we should set lambda somewhere in between 0 and infinity. Implementation From Scratch:Dataset used in this implementation can be downloaded from linkIt has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will train a Ridge Regression model to learn the correlation between the number of years of experience of each employee and their respective salary. Once the model is trained, we will be able to predict the salary of an employee on the basis of his years of experience. Code: # Importing libraries import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt # Ridge Regression class RidgeRegression() : def __init__( self, learning_rate, iterations, l2_penality ) : self.learning_rate = learning_rate self.iterations = iterations self.l2_penality = l2_penality # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : Y_pred = self.predict( self.X ) # calculate gradients dW = ( - ( 2 * ( self.X.T ).dot( self.Y - Y_pred ) ) + ( 2 * self.l2_penality * self.W ) ) / self.m db = - 2 * np.sum( self.Y - Y_pred ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : return X.dot( self.W ) + self.b # Driver code def main() : # Importing dataset df = pd.read_csv( "salary_data.csv" ) X = df.iloc[:, :-1].values Y = df.iloc[:, 1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1 / 3, random_state = 0 ) # Model training model = RidgeRegression( iterations = 1000, learning_rate = 0.01, l2_penality = 1 ) model.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) print( "Predicted values ", np.round( Y_pred[:3], 2 ) ) print( "Real values ", Y_test[:3] ) print( "Trained W ", round( model.W[0], 2 ) ) print( "Trained b ", round( model.b, 2 ) ) # Visualization on test set plt.scatter( X_test, Y_test, color = 'blue' ) plt.plot( X_test, Y_pred, color = 'orange' ) plt.title( 'Salary vs Experience' ) plt.xlabel( 'Years of Experience' ) plt.ylabel( 'Salary' ) plt.show() if __name__ == "__main__" : main() Output: Predicted values [ 40831.44 122898.14 65078.42] Real values [ 37731 122391 57081] Trained W 9325.76 Trained b 26842.8 Visualization ML-Regression Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Python | Decision tree implementation Search Algorithms in AI Difference between Informed and Uninformed Search in AI Decision Tree Introduction with example Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24361, "s": 24333, "text": "\n18 Sep, 2020" }, { "code": null, "e": 24376, "s": 24361, "text": "Prerequisites:" }, { "code": null, "e": 24410, "s": 24376, "text": "Linear RegressionGradient Descent" }, { "code": null, "e": 24428, "s": 24410, "text": "Linear Regression" }, { "code": null, "e": 24445, "s": 24428, "text": "Gradient Descent" }, { "code": null, "e": 24724, "s": 24445, "text": "Introduction:Ridge Regression ( or L2 Regularization ) is a variation of Linear Regression. In Linear Regression, it minimizes the Residual Sum of Squares ( or RSS or cost function ) to fit the training examples perfectly as possible. The cost function is also represented by J." }, { "code": null, "e": 24761, "s": 24724, "text": "Cost Function for Linear Regression:" }, { "code": null, "e": 24954, "s": 24761, "text": "Here, h(x(i)) represents the hypothetical function for prediction. y(i) represents the value of target variable for ith example.m is the total number of training examples in the given dataset." }, { "code": null, "e": 25655, "s": 24954, "text": "Linear regression treats all the features equally and finds unbiased weights to minimizes the cost function. This could arise the problem of overfitting ( or a model fails to perform well on new data ). Linear Regression also can’t deal with the collinear data ( collinearity refers to the event when the features are highly correlated ). In short, Linear Regression is a model with high variance. So, Ridge Regression comes for the rescue. In Ridge Regression, there is an addition of l2 penalty ( square of the magnitude of weights ) in the cost function of Linear Regression. This is done so that the model does not overfit the data. The Modified cost function for Ridge Regression is given below:" }, { "code": null, "e": 25746, "s": 25655, "text": "Here, wj represents the weight for jth feature.n is the number of features in the dataset." }, { "code": null, "e": 26155, "s": 25746, "text": "Mathematical Intuition:During gradient descent optimization of its cost function, added l2 penalty term leads to reduces the weights of the model to zero or close to zero. Due to the penalization of weights, our hypothesis gets simpler, more generalized, and less prone to overfitting. All weights are reduced by the same factor lambda. We can control the strength of regularization by hyperparameter lambda." }, { "code": null, "e": 26200, "s": 26155, "text": "Different cases for tuning values of lambda." }, { "code": null, "e": 26332, "s": 26200, "text": "If lambda is set to be 0, Ridge Regression equals Linear RegressionIf lambda is set to be infinity, all weights are shrunk to zero." }, { "code": null, "e": 26400, "s": 26332, "text": "If lambda is set to be 0, Ridge Regression equals Linear Regression" }, { "code": null, "e": 26465, "s": 26400, "text": "If lambda is set to be infinity, all weights are shrunk to zero." }, { "code": null, "e": 26527, "s": 26465, "text": "So, we should set lambda somewhere in between 0 and infinity." }, { "code": null, "e": 26984, "s": 26527, "text": "Implementation From Scratch:Dataset used in this implementation can be downloaded from linkIt has 2 columns — “YearsExperience” and “Salary” for 30 employees in a company. So in this, we will train a Ridge Regression model to learn the correlation between the number of years of experience of each employee and their respective salary. Once the model is trained, we will be able to predict the salary of an employee on the basis of his years of experience." }, { "code": null, "e": 26990, "s": 26984, "text": "Code:" }, { "code": "# Importing libraries import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt # Ridge Regression class RidgeRegression() : def __init__( self, learning_rate, iterations, l2_penality ) : self.learning_rate = learning_rate self.iterations = iterations self.l2_penality = l2_penality # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : Y_pred = self.predict( self.X ) # calculate gradients dW = ( - ( 2 * ( self.X.T ).dot( self.Y - Y_pred ) ) + ( 2 * self.l2_penality * self.W ) ) / self.m db = - 2 * np.sum( self.Y - Y_pred ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : return X.dot( self.W ) + self.b # Driver code def main() : # Importing dataset df = pd.read_csv( \"salary_data.csv\" ) X = df.iloc[:, :-1].values Y = df.iloc[:, 1].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1 / 3, random_state = 0 ) # Model training model = RidgeRegression( iterations = 1000, learning_rate = 0.01, l2_penality = 1 ) model.fit( X_train, Y_train ) # Prediction on test set Y_pred = model.predict( X_test ) print( \"Predicted values \", np.round( Y_pred[:3], 2 ) ) print( \"Real values \", Y_test[:3] ) print( \"Trained W \", round( model.W[0], 2 ) ) print( \"Trained b \", round( model.b, 2 ) ) # Visualization on test set plt.scatter( X_test, Y_test, color = 'blue' ) plt.plot( X_test, Y_pred, color = 'orange' ) plt.title( 'Salary vs Experience' ) plt.xlabel( 'Years of Experience' ) plt.ylabel( 'Salary' ) plt.show() if __name__ == \"__main__\" : main()", "e": 29825, "s": 26990, "text": null }, { "code": null, "e": 29833, "s": 29825, "text": "Output:" }, { "code": null, "e": 29977, "s": 29833, "text": "Predicted values [ 40831.44 122898.14 65078.42]\nReal values [ 37731 122391 57081]\nTrained W 9325.76\nTrained b 26842.8\n" }, { "code": null, "e": 29991, "s": 29977, "text": "Visualization" }, { "code": null, "e": 30005, "s": 29991, "text": "ML-Regression" }, { "code": null, "e": 30022, "s": 30005, "text": "Machine Learning" }, { "code": null, "e": 30029, "s": 30022, "text": "Python" }, { "code": null, "e": 30046, "s": 30029, "text": "Machine Learning" }, { "code": null, "e": 30144, "s": 30046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30153, "s": 30144, "text": "Comments" }, { "code": null, "e": 30166, "s": 30153, "text": "Old Comments" }, { "code": null, "e": 30180, "s": 30166, "text": "Decision Tree" }, { "code": null, "e": 30218, "s": 30180, "text": "Python | Decision tree implementation" }, { "code": null, "e": 30242, "s": 30218, "text": "Search Algorithms in AI" }, { "code": null, "e": 30298, "s": 30242, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 30338, "s": 30298, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 30366, "s": 30338, "text": "Read JSON file using Python" }, { "code": null, "e": 30416, "s": 30366, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30438, "s": 30416, "text": "Python map() function" } ]
CSS | grid-auto-flow Property - GeeksforGeeks
08 Aug, 2019 The grid-auto-flow property Specifying exactly how auto-placed items get flowed into the grid. Syntax: grid-auto-flow: row|column|row dense|column dense; Row: auto-placement algorithm places items, by filling each row in turn, adding new rows as necessary.Syntax:grid-auto-flow: row; Example-1:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output:Column: auto-placement algorithm places items, by filling each column in turn, adding new columns as necessary.Syntax: grid-auto-flow: column; Example-2:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output:Column Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for column.Syntax: grid-auto-flow: column dense; Example-3:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output:Row Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for rows.Syntax: grid-auto-flow: row dense; Example-4:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Row: auto-placement algorithm places items, by filling each row in turn, adding new rows as necessary.Syntax:grid-auto-flow: row; Example-1:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Syntax: grid-auto-flow: row; Example-1: <!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Column: auto-placement algorithm places items, by filling each column in turn, adding new columns as necessary.Syntax: grid-auto-flow: column; Example-2:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Syntax: grid-auto-flow: column; Example-2: <!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Column Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for column.Syntax: grid-auto-flow: column dense; Example-3:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Syntax: grid-auto-flow: column dense; Example-3: <!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Row Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for rows.Syntax: grid-auto-flow: row dense; Example-4:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: grid-auto-flow: row dense; Example-4: <!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = "main"> <div class = "Geeks1"></div> <div class = "Geeks2"></div> <div class = "Geeks3"></div> <div class = "Geeks4"></div> </div> </body> </html> Output: Supported Browsers: The browser supported by CSS | grid-auto-flow Property are listde below: Google Chrome 57 Mozilla Firefox 52 Edge 16 Safari 10 Opera 44 CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23325, "s": 23297, "text": "\n08 Aug, 2019" }, { "code": null, "e": 23420, "s": 23325, "text": "The grid-auto-flow property Specifying exactly how auto-placed items get flowed into the grid." }, { "code": null, "e": 23428, "s": 23420, "text": "Syntax:" }, { "code": null, "e": 23480, "s": 23428, "text": "grid-auto-flow: row|column|row dense|column dense;\n" }, { "code": null, "e": 28065, "s": 23480, "text": "Row: auto-placement algorithm places items, by filling each row in turn, adding new rows as necessary.Syntax:grid-auto-flow: row; \nExample-1:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:Column: auto-placement algorithm places items, by filling each column in turn, adding new columns as necessary.Syntax: grid-auto-flow: column; \nExample-2:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:Column Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for column.Syntax: grid-auto-flow: column dense; \nExample-3:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:Row Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for rows.Syntax: grid-auto-flow: row dense; \nExample-4:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:" }, { "code": null, "e": 29190, "s": 28065, "text": "Row: auto-placement algorithm places items, by filling each row in turn, adding new rows as necessary.Syntax:grid-auto-flow: row; \nExample-1:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:" }, { "code": null, "e": 29198, "s": 29190, "text": "Syntax:" }, { "code": null, "e": 29221, "s": 29198, "text": "grid-auto-flow: row; \n" }, { "code": null, "e": 29232, "s": 29221, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> ", "e": 30209, "s": 29232, "text": null }, { "code": null, "e": 30217, "s": 30209, "text": "Output:" }, { "code": null, "e": 31369, "s": 30217, "text": "Column: auto-placement algorithm places items, by filling each column in turn, adding new columns as necessary.Syntax: grid-auto-flow: column; \nExample-2:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:" }, { "code": null, "e": 31377, "s": 31369, "text": "Syntax:" }, { "code": null, "e": 31407, "s": 31377, "text": " grid-auto-flow: column; \n" }, { "code": null, "e": 31418, "s": 31407, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> ", "e": 32406, "s": 31418, "text": null }, { "code": null, "e": 32414, "s": 32406, "text": "Output:" }, { "code": null, "e": 33569, "s": 32414, "text": "Column Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for column.Syntax: grid-auto-flow: column dense; \nExample-3:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:" }, { "code": null, "e": 33577, "s": 33569, "text": "Syntax:" }, { "code": null, "e": 33612, "s": 33577, "text": " grid-auto-flow: column dense; \n" }, { "code": null, "e": 33623, "s": 33612, "text": "Example-3:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: column dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> ", "e": 34617, "s": 33623, "text": null }, { "code": null, "e": 34625, "s": 34617, "text": "Output:" }, { "code": null, "e": 35781, "s": 34625, "text": "Row Dense: specifying that the auto-placement algorithm uses a “dense” packing algorithm for rows.Syntax: grid-auto-flow: row dense; \nExample-4:<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> Output:" }, { "code": null, "e": 35813, "s": 35781, "text": " grid-auto-flow: row dense; \n" }, { "code": null, "e": 35824, "s": 35813, "text": "Example-4:" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-auto-flow Property </title> <style> .main { height: 200px; width: 200px; display: grid; grid-gap: 10px; grid-template: repeat(4, 1fr) / repeat(2, 1fr); /* grid-auto-flow property used here */ grid-auto-flow: row dense; } .Geeks1 { background-color: red; grid-row-start: 3; } .Geeks2 { background-color: blue; } .Geeks3 { background-color: black; } .Geeks4 { grid-column-start: 2; background-color: orange; } </style></head> <body> <div class = \"main\"> <div class = \"Geeks1\"></div> <div class = \"Geeks2\"></div> <div class = \"Geeks3\"></div> <div class = \"Geeks4\"></div> </div> </body> </html> ", "e": 36827, "s": 35824, "text": null }, { "code": null, "e": 36835, "s": 36827, "text": "Output:" }, { "code": null, "e": 36928, "s": 36835, "text": "Supported Browsers: The browser supported by CSS | grid-auto-flow Property are listde below:" }, { "code": null, "e": 36945, "s": 36928, "text": "Google Chrome 57" }, { "code": null, "e": 36964, "s": 36945, "text": "Mozilla Firefox 52" }, { "code": null, "e": 36972, "s": 36964, "text": "Edge 16" }, { "code": null, "e": 36982, "s": 36972, "text": "Safari 10" }, { "code": null, "e": 36991, "s": 36982, "text": "Opera 44" }, { "code": null, "e": 37006, "s": 36991, "text": "CSS-Properties" }, { "code": null, "e": 37013, "s": 37006, "text": "Picked" }, { "code": null, "e": 37017, "s": 37013, "text": "CSS" }, { "code": null, "e": 37034, "s": 37017, "text": "Web Technologies" }, { "code": null, "e": 37132, "s": 37034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37141, "s": 37132, "text": "Comments" }, { "code": null, "e": 37154, "s": 37141, "text": "Old Comments" }, { "code": null, "e": 37216, "s": 37154, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37266, "s": 37216, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 37324, "s": 37266, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 37372, "s": 37324, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 37409, "s": 37372, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 37465, "s": 37409, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 37498, "s": 37465, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37560, "s": 37498, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37603, "s": 37560, "text": "How to fetch data from an API in ReactJS ?" } ]
Similarities between Java and C++
01 Jul, 2022 Both are very successful and popular programming languages. Though there are many differences between the both, there are considerable similarities which are given as follows: Both C++ and Java supports Object Oriented Programming: OOPs is a modular approach, which allows the data to be applied within stipulated program area, It also provides the re-usability feature to develop productive logic, which means to give more emphasis on data. It supports classes and objects. OOPs features include:Inheritance: process by which objects of one class can link and share some common properties of objects from another class. Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. Abstraction: It is the act of representing essential features without including the background details. Encapsulation.: Wrapping up of data and functions into a single unit. They have similar syntax: C++ Syntax: Both C++ and Java supports Object Oriented Programming: OOPs is a modular approach, which allows the data to be applied within stipulated program area, It also provides the re-usability feature to develop productive logic, which means to give more emphasis on data. It supports classes and objects. OOPs features include:Inheritance: process by which objects of one class can link and share some common properties of objects from another class. Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. Abstraction: It is the act of representing essential features without including the background details. Encapsulation.: Wrapping up of data and functions into a single unit. Inheritance: process by which objects of one class can link and share some common properties of objects from another class. Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. Abstraction: It is the act of representing essential features without including the background details. Encapsulation.: Wrapping up of data and functions into a single unit. They have similar syntax: C++ Syntax: CPP #include& lt; iostream & gt;using namespace std; int main(){ cout& lt; < " Hello World" ; return 0;} Java Syntax: Java public class first { public static void main(String[] args) { // prints Hello World System.out.println(" Hello World "); }} 3. Comments Syntax are identical: Both the single and multiple line comments are written as //.... and /* .... */ respectively. C++: CPP #include <iostream>using namespace std; int main(){ // main() is where program execution begins int a = 5, b = 10, sum; sum = a + b; /* This will add the values of a and band will display the output stored in sum */ cout << sum; return 0;} Java: Java public class GFG { public static void main(String[] args) { // main() is where program execution begins int a = 5, b = 10, sum; sum = a + b; /* This will add the values of a and band will display the output stored in sum */ System.out.println(sum); }} 4. The loops (like while, for etc.) and conditional statements (like if-else, switch etc.) are similar: C++: CPP #include <iostream>using namespace std; int main(){ int a = 5, b = 10; if (a > b) cout << a; else cout << b; return 0;} Output: 10 Java: Java public class firstjava { public static void main(String[] args) { // to display the greater number int a = 5, b = 10; if (a > b) System.out.println(a); else System.out.println(b); }} Output: 10 5. Both have same arithmetic and relational operators. Arithmetic operators such as +, -, *, / Relational operators such as >, <, =, != (not equal to) 6. Execution of both the C++ and Java programs starts from the main function: It is the entry point of the execution of the program. However, the function declaration is different, but the name is same. C++: CPP #include& lt; iostream & gt;using namespace std; int main(){ // main() is where program execution begins cout& lt; < " Hello World" ; return 0;} Java: Java public class GFG { public static void main(String[] args) { // main() is where program execution begins System.out.println(" Hello World "); }} 7. Statement in both the C++ and Java programs ends with semi-colon(;) : C++: C++ //C++ program statements ends with Semicolons (;) #include <iostream>using namespace std; int main(){ cout <<"GEEKSFORGEEKS"; return 0;} //This code is contributed by Susobhan AKhuli GEEKSFORGEEKS Java: Java //Java program statements ends with Semicolons (;) import java.io.*; class GFG { public static void main (String[] args) { System.out.println("GEEKSFORGEEKS"); }} //This code is contributed by Susobhan AKhuli GEEKSFORGEEKS 8. They have same primitive data types: These include datatypes like int, float, char, double etc. with some differences like the Boolean data type is called boolean in Java but it is called bool in C++. 9. Many of their keywords are same: Example: break, continue, char, double, new, public, private, return, static etc. 10. Both have multi threading support: Both allow executing multiple threads(sub-processes) simultaneously to achieve multitasking. 11. Areas of Application: C++ is best suitable for developing large software like Library management system, Employee management system, Passenger reservation systems etc. Java can be used to develop all these software but in addition to this Java is best suitable for developing Communication/Internet application software. eg: Network protocols, Internet programs, Web page, Web browser etc. Learn Java Learn C++ anonymous007 vaibhavsinghtanwar susobhanakhuli surinderdawra388 CPP-Basics java-basics Picked C++ Java Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jul, 2022" }, { "code": null, "e": 204, "s": 28, "text": "Both are very successful and popular programming languages. Though there are many differences between the both, there are considerable similarities which are given as follows:" }, { "code": null, "e": 997, "s": 204, "text": "Both C++ and Java supports Object Oriented Programming: OOPs is a modular approach, which allows the data to be applied within stipulated program area, It also provides the re-usability feature to develop productive logic, which means to give more emphasis on data. It supports classes and objects. OOPs features include:Inheritance: process by which objects of one class can link and share some common properties of objects from another class. Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. Abstraction: It is the act of representing essential features without including the background details. Encapsulation.: Wrapping up of data and functions into a single unit. They have similar syntax: C++ Syntax: " }, { "code": null, "e": 1752, "s": 997, "text": "Both C++ and Java supports Object Oriented Programming: OOPs is a modular approach, which allows the data to be applied within stipulated program area, It also provides the re-usability feature to develop productive logic, which means to give more emphasis on data. It supports classes and objects. OOPs features include:Inheritance: process by which objects of one class can link and share some common properties of objects from another class. Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. Abstraction: It is the act of representing essential features without including the background details. Encapsulation.: Wrapping up of data and functions into a single unit. " }, { "code": null, "e": 1877, "s": 1752, "text": "Inheritance: process by which objects of one class can link and share some common properties of objects from another class. " }, { "code": null, "e": 2013, "s": 1877, "text": "Polymorphism: Allows us to perform a single action in different ways. It is the process of using a function for more than one purpose. " }, { "code": null, "e": 2118, "s": 2013, "text": "Abstraction: It is the act of representing essential features without including the background details. " }, { "code": null, "e": 2189, "s": 2118, "text": "Encapsulation.: Wrapping up of data and functions into a single unit. " }, { "code": null, "e": 2228, "s": 2189, "text": "They have similar syntax: C++ Syntax: " }, { "code": null, "e": 2232, "s": 2228, "text": "CPP" }, { "code": "#include& lt; iostream & gt;using namespace std; int main(){ cout& lt; < \" Hello World\" ; return 0;}", "e": 2351, "s": 2232, "text": null }, { "code": null, "e": 2376, "s": 2351, "text": " Java Syntax: " }, { "code": null, "e": 2381, "s": 2376, "text": "Java" }, { "code": "public class first { public static void main(String[] args) { // prints Hello World System.out.println(\" Hello World \"); }}", "e": 2528, "s": 2381, "text": null }, { "code": null, "e": 2679, "s": 2528, "text": " 3. Comments Syntax are identical: Both the single and multiple line comments are written as //.... and /* .... */ respectively. C++: " }, { "code": null, "e": 2683, "s": 2679, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ // main() is where program execution begins int a = 5, b = 10, sum; sum = a + b; /* This will add the values of a and band will display the output stored in sum */ cout << sum; return 0;}", "e": 2940, "s": 2683, "text": null }, { "code": null, "e": 2958, "s": 2940, "text": " Java: " }, { "code": null, "e": 2963, "s": 2958, "text": "Java" }, { "code": "public class GFG { public static void main(String[] args) { // main() is where program execution begins int a = 5, b = 10, sum; sum = a + b; /* This will add the values of a and band will display the output stored in sum */ System.out.println(sum); }}", "e": 3256, "s": 2963, "text": null }, { "code": null, "e": 3384, "s": 3256, "text": " 4. The loops (like while, for etc.) and conditional statements (like if-else, switch etc.) are similar: C++: " }, { "code": null, "e": 3388, "s": 3384, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ int a = 5, b = 10; if (a > b) cout << a; else cout << b; return 0;}", "e": 3535, "s": 3388, "text": null }, { "code": null, "e": 3546, "s": 3535, "text": "Output: 10" }, { "code": null, "e": 3564, "s": 3546, "text": " Java: " }, { "code": null, "e": 3569, "s": 3564, "text": "Java" }, { "code": "public class firstjava { public static void main(String[] args) { // to display the greater number int a = 5, b = 10; if (a > b) System.out.println(a); else System.out.println(b); }}", "e": 3814, "s": 3569, "text": null }, { "code": null, "e": 3825, "s": 3814, "text": "Output: 10" }, { "code": null, "e": 3887, "s": 3825, "text": " 5. Both have same arithmetic and relational operators." }, { "code": null, "e": 3983, "s": 3887, "text": "Arithmetic operators such as +, -, *, /\nRelational operators such as >, <, =, != (not equal to)" }, { "code": null, "e": 4220, "s": 3983, "text": " 6. Execution of both the C++ and Java programs starts from the main function: It is the entry point of the execution of the program. However, the function declaration is different, but the name is same. C++: " }, { "code": null, "e": 4224, "s": 4220, "text": "CPP" }, { "code": "#include& lt; iostream & gt;using namespace std; int main(){ // main() is where program execution begins cout& lt; < \" Hello World\" ; return 0;}", "e": 4387, "s": 4224, "text": null }, { "code": null, "e": 4405, "s": 4387, "text": " Java: " }, { "code": null, "e": 4410, "s": 4405, "text": "Java" }, { "code": "public class GFG { public static void main(String[] args) { // main() is where program execution begins System.out.println(\" Hello World \"); }}", "e": 4577, "s": 4410, "text": null }, { "code": null, "e": 4672, "s": 4577, "text": " 7. Statement in both the C++ and Java programs ends with semi-colon(;) : C++:" }, { "code": null, "e": 4676, "s": 4672, "text": "C++" }, { "code": "//C++ program statements ends with Semicolons (;) #include <iostream>using namespace std; int main(){ cout <<\"GEEKSFORGEEKS\"; return 0;} //This code is contributed by Susobhan AKhuli", "e": 4865, "s": 4676, "text": null }, { "code": null, "e": 4879, "s": 4865, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 4896, "s": 4879, "text": " Java:" }, { "code": null, "e": 4901, "s": 4896, "text": "Java" }, { "code": "//Java program statements ends with Semicolons (;) import java.io.*; class GFG { public static void main (String[] args) { System.out.println(\"GEEKSFORGEEKS\"); }} //This code is contributed by Susobhan AKhuli", "e": 5123, "s": 4901, "text": null }, { "code": null, "e": 5137, "s": 5123, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 5361, "s": 5137, "text": " 8. They have same primitive data types: These include datatypes like int, float, char, double etc. with some differences like the Boolean data type is called boolean in Java but it is called bool in C++. " }, { "code": null, "e": 5413, "s": 5361, "text": " 9. Many of their keywords are same: Example:" }, { "code": null, "e": 5493, "s": 5413, "text": " break, continue, char, double, new, public, private, return, static etc. " }, { "code": null, "e": 5633, "s": 5493, "text": " 10. Both have multi threading support: Both allow executing multiple threads(sub-processes) simultaneously to achieve multitasking. " }, { "code": null, "e": 6047, "s": 5633, "text": " 11. Areas of Application: C++ is best suitable for developing large software like Library management system, Employee management system, Passenger reservation systems etc. Java can be used to develop all these software but in addition to this Java is best suitable for developing Communication/Internet application software. eg: Network protocols, Internet programs, Web page, Web browser etc." }, { "code": null, "e": 6068, "s": 6047, "text": "Learn Java Learn C++" }, { "code": null, "e": 6081, "s": 6068, "text": "anonymous007" }, { "code": null, "e": 6100, "s": 6081, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 6115, "s": 6100, "text": "susobhanakhuli" }, { "code": null, "e": 6132, "s": 6115, "text": "surinderdawra388" }, { "code": null, "e": 6143, "s": 6132, "text": "CPP-Basics" }, { "code": null, "e": 6155, "s": 6143, "text": "java-basics" }, { "code": null, "e": 6162, "s": 6155, "text": "Picked" }, { "code": null, "e": 6166, "s": 6162, "text": "C++" }, { "code": null, "e": 6171, "s": 6166, "text": "Java" }, { "code": null, "e": 6176, "s": 6171, "text": "Java" }, { "code": null, "e": 6180, "s": 6176, "text": "CPP" }, { "code": null, "e": 6278, "s": 6180, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6332, "s": 6278, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6375, "s": 6332, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6409, "s": 6375, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 6434, "s": 6409, "text": "unordered_map in C++ STL" }, { "code": null, "e": 6451, "s": 6434, "text": "Substring in C++" }, { "code": null, "e": 6466, "s": 6451, "text": "Arrays in Java" }, { "code": null, "e": 6502, "s": 6466, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6546, "s": 6502, "text": "Split() String method in Java with examples" }, { "code": null, "e": 6571, "s": 6546, "text": "Reverse a string in Java" } ]
Program to print the series 1, 3, 4, 8, 15, 27, 50... till N terms
19 Mar, 2021 Given a number N, the task is to print the first N terms of the following series: 1, 3, 4, 8, 15, 27, 50... Examples: Input: N = 7 Output: 1, 3, 4, 8, 15, 27, 50Input: N = 3 Output: 1, 3, 4 Approach: From the given series we can find the formula for Nth term: 1st term = 1, 2nd term = 3, 3rd term = 4 4th term = 1st term + 2nd term + 3rd term 5th term = 2nd term + 3rd term + 4th term 6th term = 3rd term + 4th term + 5th term . . so on Therefore, the idea is to keep track of the last three terms of the series and find the consecutive terms of the series. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to print the// N terms of the series whose three// terms are given #include "bits/stdc++.h"using namespace std; // Function to print the seriesvoid printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { cout << a << " "; return; } if (n == 2) { cout << a << " " << b << " "; return; } cout << a << " " << b << " " << c << " "; for (int i = 4; i <= n; i++) { d = a + b + c; cout << d << " "; a = b; b = c; c = d; }} // Driver Codeint main(){ int N = 7, a = 1, b = 3; int c = 4; // Function Call printSeries(N, a, b, c); return 0;} // Java implementation to print the// N terms of the series whose three// terms are given //include "bits/stdJava.h"import java.util.*;class GFG{ // Function to print the seriesstatic void printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { System.out.print(a + " "); return; } if (n == 2) { System.out.print(a + " " + b + " "); return; } System.out.print(a + " " + b + " " + c + " "); for (int i = 4; i <= n; i++) { d = a + b + c; System.out.print(d + " "); a = b; b = c; c = d; }} // Driver Codepublic static void main(String[] args){ int N = 7, a = 1, b = 3; int c = 4; // Function Call printSeries(N, a, b, c);}} // This code is contributed by sapnasingh4991 # Python3 implementation to print the# N terms of the series whose three# terms are given # Function to print the seriesdef printSeries(n, a, b, c): # Generate the ith term and # print it if (n == 1): print(a, end = " "); return; if (n == 2): print(a, b, end = " "); return; print(a, b, c, end = " "); for i in range (4, n + 1): d = a + b + c; print(d, end = " "); a = b; b = c; c = d; # Driver CodeN = 7; a = 1; b = 3;c = 4; # Function CallprintSeries(N, a, b, c); # This code is contributed by Code_Mech // C# implementation to print the// N terms of the series whose three// terms are givenusing System;class GFG{ // Function to print the seriesstatic void printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { Console.Write(a + " "); return; } if (n == 2) { Console.Write(a + " " + b + " "); return; } Console.Write(a + " " + b + " " + c + " "); for(int i = 4; i <= n; i++) { d = a + b + c; Console.Write(d + " "); a = b; b = c; c = d; }} // Driver Codepublic static void Main(){ int N = 7, a = 1, b = 3; int c = 4; // Function call printSeries(N, a, b, c);}} // This code is contributed by rock cool <script>// javascript implementation to print the// N terms of the series whose three// terms are given // Function to print the seriesfunction printSeries( n, a, b, c){ let d; // Generate the ith term and // print it if (n == 1) { document.write( a + " "); return; } if (n == 2) { document.write( a + " " + b + " "); return; } document.write( a + " " + b + " " + c + " "); for (let i = 4; i <= n; i++) { d = a + b + c; document.write( d + " "); a = b; b = c; c = d; }} // Driver Code let N = 7, a = 1, b = 3; let c = 4; // Function Call printSeries(N, a, b, c); // This code is contributed by gauravrajput1 </script> 1 3 4 8 15 27 50 sapnasingh4991 rock_cool Code_Mech GauravRajput1 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Mar, 2021" }, { "code": null, "e": 110, "s": 28, "text": "Given a number N, the task is to print the first N terms of the following series:" }, { "code": null, "e": 136, "s": 110, "text": "1, 3, 4, 8, 15, 27, 50..." }, { "code": null, "e": 146, "s": 136, "text": "Examples:" }, { "code": null, "e": 220, "s": 146, "text": "Input: N = 7 Output: 1, 3, 4, 8, 15, 27, 50Input: N = 3 Output: 1, 3, 4 " }, { "code": null, "e": 290, "s": 220, "text": "Approach: From the given series we can find the formula for Nth term:" }, { "code": null, "e": 469, "s": 290, "text": "1st term = 1, 2nd term = 3, 3rd term = 4 4th term = 1st term + 2nd term + 3rd term 5th term = 2nd term + 3rd term + 4th term 6th term = 3rd term + 4th term + 5th term . . so on " }, { "code": null, "e": 590, "s": 469, "text": "Therefore, the idea is to keep track of the last three terms of the series and find the consecutive terms of the series." }, { "code": null, "e": 637, "s": 590, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 641, "s": 637, "text": "C++" }, { "code": null, "e": 646, "s": 641, "text": "Java" }, { "code": null, "e": 654, "s": 646, "text": "Python3" }, { "code": null, "e": 657, "s": 654, "text": "C#" }, { "code": null, "e": 668, "s": 657, "text": "Javascript" }, { "code": "// C++ implementation to print the// N terms of the series whose three// terms are given #include \"bits/stdc++.h\"using namespace std; // Function to print the seriesvoid printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { cout << a << \" \"; return; } if (n == 2) { cout << a << \" \" << b << \" \"; return; } cout << a << \" \" << b << \" \" << c << \" \"; for (int i = 4; i <= n; i++) { d = a + b + c; cout << d << \" \"; a = b; b = c; c = d; }} // Driver Codeint main(){ int N = 7, a = 1, b = 3; int c = 4; // Function Call printSeries(N, a, b, c); return 0;}", "e": 1405, "s": 668, "text": null }, { "code": "// Java implementation to print the// N terms of the series whose three// terms are given //include \"bits/stdJava.h\"import java.util.*;class GFG{ // Function to print the seriesstatic void printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { System.out.print(a + \" \"); return; } if (n == 2) { System.out.print(a + \" \" + b + \" \"); return; } System.out.print(a + \" \" + b + \" \" + c + \" \"); for (int i = 4; i <= n; i++) { d = a + b + c; System.out.print(d + \" \"); a = b; b = c; c = d; }} // Driver Codepublic static void main(String[] args){ int N = 7, a = 1, b = 3; int c = 4; // Function Call printSeries(N, a, b, c);}} // This code is contributed by sapnasingh4991", "e": 2310, "s": 1405, "text": null }, { "code": "# Python3 implementation to print the# N terms of the series whose three# terms are given # Function to print the seriesdef printSeries(n, a, b, c): # Generate the ith term and # print it if (n == 1): print(a, end = \" \"); return; if (n == 2): print(a, b, end = \" \"); return; print(a, b, c, end = \" \"); for i in range (4, n + 1): d = a + b + c; print(d, end = \" \"); a = b; b = c; c = d; # Driver CodeN = 7; a = 1; b = 3;c = 4; # Function CallprintSeries(N, a, b, c); # This code is contributed by Code_Mech", "e": 2913, "s": 2310, "text": null }, { "code": "// C# implementation to print the// N terms of the series whose three// terms are givenusing System;class GFG{ // Function to print the seriesstatic void printSeries(int n, int a, int b, int c){ int d; // Generate the ith term and // print it if (n == 1) { Console.Write(a + \" \"); return; } if (n == 2) { Console.Write(a + \" \" + b + \" \"); return; } Console.Write(a + \" \" + b + \" \" + c + \" \"); for(int i = 4; i <= n; i++) { d = a + b + c; Console.Write(d + \" \"); a = b; b = c; c = d; }} // Driver Codepublic static void Main(){ int N = 7, a = 1, b = 3; int c = 4; // Function call printSeries(N, a, b, c);}} // This code is contributed by rock cool", "e": 3753, "s": 2913, "text": null }, { "code": "<script>// javascript implementation to print the// N terms of the series whose three// terms are given // Function to print the seriesfunction printSeries( n, a, b, c){ let d; // Generate the ith term and // print it if (n == 1) { document.write( a + \" \"); return; } if (n == 2) { document.write( a + \" \" + b + \" \"); return; } document.write( a + \" \" + b + \" \" + c + \" \"); for (let i = 4; i <= n; i++) { d = a + b + c; document.write( d + \" \"); a = b; b = c; c = d; }} // Driver Code let N = 7, a = 1, b = 3; let c = 4; // Function Call printSeries(N, a, b, c); // This code is contributed by gauravrajput1 </script>", "e": 4513, "s": 3753, "text": null }, { "code": null, "e": 4530, "s": 4513, "text": "1 3 4 8 15 27 50" }, { "code": null, "e": 4547, "s": 4532, "text": "sapnasingh4991" }, { "code": null, "e": 4557, "s": 4547, "text": "rock_cool" }, { "code": null, "e": 4567, "s": 4557, "text": "Code_Mech" }, { "code": null, "e": 4581, "s": 4567, "text": "GauravRajput1" }, { "code": null, "e": 4588, "s": 4581, "text": "series" }, { "code": null, "e": 4601, "s": 4588, "text": "Mathematical" }, { "code": null, "e": 4614, "s": 4601, "text": "Mathematical" }, { "code": null, "e": 4621, "s": 4614, "text": "series" }, { "code": null, "e": 4719, "s": 4621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4743, "s": 4719, "text": "Merge two sorted arrays" }, { "code": null, "e": 4764, "s": 4743, "text": "Operators in C / C++" }, { "code": null, "e": 4778, "s": 4764, "text": "Prime Numbers" }, { "code": null, "e": 4820, "s": 4778, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 4873, "s": 4820, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 4905, "s": 4873, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4942, "s": 4905, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 4969, "s": 4942, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 5012, "s": 4969, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Powershell - For Loop
The following scripts demonstrates the for loop. > $array = @("item1", "item2", "item3") > for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
[ { "code": null, "e": 2217, "s": 2168, "text": "The following scripts demonstrates the for loop." } ]
How to remove unused dependencies from composer?
27 Jan, 2021 Removing unused Dependencies from Composer is very easy. Following are the two approaches: 1. Using Composer Remove:This is the simplest command to remove unused Dependencies from Composer. Syntax: composer remove dependency_name Firstly decide which dependency you want to remove from the composer. Here we will be removing stripe/stripe-php dependency as shown below in the composer and the stripe folder is also present in the directory. Dependencies in the composer. Stripe folder is present before deleting. Now just go to the directory in which your composer.json file is there and then type the below command: composer remove stripe/stripe-php composer remove stripe/stripe-php Command Output: This command removed the stripe/stripe-php dependency from the composer as shown below: Stripe folder removed after the command. Thus, the composer remove is a very easy command and will remove the unused dependencies from the composer. 2. Using Composer Update:It’s another way of removing unused Dependencies from Composer. Syntax: composer update Running composer update Command. The above command will update the complete directory and will add all the dependencies and folders shown below: All the Folders Added and Updated. Now just open the composer.json file and delete the dependency which you want to remove. composer.json File Contents Now just delete the phpunit/phpunit:4.6.1 dependency and the updated composer.json is shown below: composer.json File after Deletion Now we just need to run the composer update command once more and it will remove all the phpunit dependencies which we don’t want as shown below: Running composer update once again. Dependencies Removed “composer update” will do the task, but it will also update the other packages. Now if you just want to remove a specific package without updating others then just specify that package name. composer update packageauthor/package_name It will remove the “package_name” package. Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jan, 2021" }, { "code": null, "e": 143, "s": 52, "text": "Removing unused Dependencies from Composer is very easy. Following are the two approaches:" }, { "code": null, "e": 243, "s": 143, "text": "1. Using Composer Remove:This is the simplest command to remove unused Dependencies from Composer. " }, { "code": null, "e": 251, "s": 243, "text": "Syntax:" }, { "code": null, "e": 283, "s": 251, "text": "composer remove dependency_name" }, { "code": null, "e": 494, "s": 283, "text": "Firstly decide which dependency you want to remove from the composer. Here we will be removing stripe/stripe-php dependency as shown below in the composer and the stripe folder is also present in the directory." }, { "code": null, "e": 524, "s": 494, "text": "Dependencies in the composer." }, { "code": null, "e": 566, "s": 524, "text": "Stripe folder is present before deleting." }, { "code": null, "e": 670, "s": 566, "text": "Now just go to the directory in which your composer.json file is there and then type the below command:" }, { "code": null, "e": 704, "s": 670, "text": "composer remove stripe/stripe-php" }, { "code": null, "e": 746, "s": 704, "text": "composer remove stripe/stripe-php Command" }, { "code": null, "e": 842, "s": 746, "text": "Output: This command removed the stripe/stripe-php dependency from the composer as shown below:" }, { "code": null, "e": 883, "s": 842, "text": "Stripe folder removed after the command." }, { "code": null, "e": 991, "s": 883, "text": "Thus, the composer remove is a very easy command and will remove the unused dependencies from the composer." }, { "code": null, "e": 1081, "s": 991, "text": "2. Using Composer Update:It’s another way of removing unused Dependencies from Composer. " }, { "code": null, "e": 1089, "s": 1081, "text": "Syntax:" }, { "code": null, "e": 1106, "s": 1089, "text": "composer update " }, { "code": null, "e": 1140, "s": 1106, "text": "Running composer update Command. " }, { "code": null, "e": 1252, "s": 1140, "text": "The above command will update the complete directory and will add all the dependencies and folders shown below:" }, { "code": null, "e": 1287, "s": 1252, "text": "All the Folders Added and Updated." }, { "code": null, "e": 1376, "s": 1287, "text": "Now just open the composer.json file and delete the dependency which you want to remove." }, { "code": null, "e": 1404, "s": 1376, "text": "composer.json File Contents" }, { "code": null, "e": 1503, "s": 1404, "text": "Now just delete the phpunit/phpunit:4.6.1 dependency and the updated composer.json is shown below:" }, { "code": null, "e": 1537, "s": 1503, "text": "composer.json File after Deletion" }, { "code": null, "e": 1683, "s": 1537, "text": "Now we just need to run the composer update command once more and it will remove all the phpunit dependencies which we don’t want as shown below:" }, { "code": null, "e": 1719, "s": 1683, "text": "Running composer update once again." }, { "code": null, "e": 1741, "s": 1719, "text": "Dependencies Removed " }, { "code": null, "e": 1821, "s": 1741, "text": "“composer update” will do the task, but it will also update the other packages." }, { "code": null, "e": 1932, "s": 1821, "text": "Now if you just want to remove a specific package without updating others then just specify that package name." }, { "code": null, "e": 1975, "s": 1932, "text": "composer update packageauthor/package_name" }, { "code": null, "e": 2018, "s": 1975, "text": "It will remove the “package_name” package." }, { "code": null, "e": 2025, "s": 2018, "text": "Picked" }, { "code": null, "e": 2029, "s": 2025, "text": "PHP" }, { "code": null, "e": 2046, "s": 2029, "text": "Web Technologies" }, { "code": null, "e": 2050, "s": 2046, "text": "PHP" } ]
How to set column in center using Bootstrap 5?
05 Nov, 2021 The goal here is to center a column in bootstrap. Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. There are two approaches to centering a column <div> in Bootstrap. Approach 1 (offsets): The first approach uses bootstrap offset class. The key is to set an offset equal to half of the remaining size of the row. So for example, a column of size 2 would be centered by adding an offset of 5, that’s (12-2)/2. The below example implements this. html <!DOCTYPE html><html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <body> <div class="container"> <div class="row"> <div style="height: 200px;" class="col-md-6 offset-md-3 text-center bg-success">. col-md-6 .offset-md-3</div> </div> </div> </body></html> Output Approach 2(Margin auto): Setting left and right margins to auto will center the div with respect to its parent element. The left and right margin can be set with .ml-auto and .mr-auto class respectively. The below example implements this. html <!DOCTYPE html><html> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <body> <div class="container"> <div class="row"> <div style="height: 200px;" class="mr-auto ml-auto text-center bg-success"> .ml-auto .mr-auto</div> </div> </div> </body></html> Output ysachin2314 chhabradhanvi Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set Bootstrap Timepicker using datetimepicker library ? How to Add Image into Dropdown List for each items ? How to change the background color of the active nav-item? 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": "\n05 Nov, 2021" }, { "code": null, "e": 259, "s": 28, "text": "The goal here is to center a column in bootstrap. Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. There are two approaches to centering a column <div> in Bootstrap." }, { "code": null, "e": 283, "s": 259, "text": "Approach 1 (offsets): " }, { "code": null, "e": 538, "s": 283, "text": "The first approach uses bootstrap offset class. The key is to set an offset equal to half of the remaining size of the row. So for example, a column of size 2 would be centered by adding an offset of 5, that’s (12-2)/2. The below example implements this." }, { "code": null, "e": 545, "s": 540, "text": "html" }, { "code": "<!DOCTYPE html><html> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <body> <div class=\"container\"> <div class=\"row\"> <div style=\"height: 200px;\" class=\"col-md-6 offset-md-3 text-center bg-success\">. col-md-6 .offset-md-3</div> </div> </div> </body></html>", "e": 1120, "s": 545, "text": null }, { "code": null, "e": 1127, "s": 1120, "text": "Output" }, { "code": null, "e": 1154, "s": 1127, "text": "Approach 2(Margin auto): " }, { "code": null, "e": 1368, "s": 1154, "text": "Setting left and right margins to auto will center the div with respect to its parent element. The left and right margin can be set with .ml-auto and .mr-auto class respectively. The below example implements this." }, { "code": null, "e": 1375, "s": 1370, "text": "html" }, { "code": "<!DOCTYPE html><html> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\" /> <body> <div class=\"container\"> <div class=\"row\"> <div style=\"height: 200px;\" class=\"mr-auto ml-auto text-center bg-success\"> .ml-auto .mr-auto</div> </div> </div> </body></html>", "e": 1941, "s": 1375, "text": null }, { "code": null, "e": 1948, "s": 1941, "text": "Output" }, { "code": null, "e": 1960, "s": 1948, "text": "ysachin2314" }, { "code": null, "e": 1974, "s": 1960, "text": "chhabradhanvi" }, { "code": null, "e": 1989, "s": 1974, "text": "Bootstrap-Misc" }, { "code": null, "e": 1999, "s": 1989, "text": "Bootstrap" }, { "code": null, "e": 2016, "s": 1999, "text": "Web Technologies" }, { "code": null, "e": 2114, "s": 2016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2155, "s": 2114, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 2188, "s": 2155, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 2251, "s": 2188, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 2304, "s": 2251, "text": "How to Add Image into Dropdown List for each items ?" }, { "code": null, "e": 2363, "s": 2304, "text": "How to change the background color of the active nav-item?" }, { "code": null, "e": 2425, "s": 2363, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2458, "s": 2425, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2519, "s": 2458, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2569, "s": 2519, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Node in Apache Cassandra
15 Jul, 2020 In this article, we are going to discuss what is a node in Cassandra, information of node, how we can access the information about the node, and by using Nodetool utility we will also discuss some nodetool commands. let’s discuss one by one. Node : A node in Cassandra contains the actual data and it’s information such that location, data center information, etc. A node contains the data such that keyspaces, tables, the schema of data, etc. you can perform operations such that read, write, delete data, etc. on a node. A node plays an important role in Cassandra clusters. In Cassandra ring where every node is connected peer to peer and every node is similar to every other node in the cluster. Let’s consider an example where you have three replicas of data and each replica on different nodes. now, if you want to read data then anyone node can respond that’s why the concept of distributed data across the cluster is so effective and high availability mechanism in Cassandra. Nodetool : It is the node management utility tool by which you can get the node health information, node information, cluster information, etc. with the help of nodetool commands, you can access all the required information of the nodes. Nodetool commands such that help, info, the status will give you the general information about the node. It’s by default located in the bin/ folder where Cassandra is installed. Some basics Nodetool commands : Example – nodetool status let’s consider an example if a user wants to know the status of the node, then nodetool status commands need to be executed. In given below output is showing node is in the UN (Up and Normal) state and the address of a default node is 127.0.0.1 and also about load and rack information, etc. C:\Program Files\apache-cassandra-3.11.4\bin>nodetool status Datacenter: datacenter1 ======================== Status=Up/Down |/ State=Normal/Leaving/Joining/Moving -- Address Load Tokens Owns Host ID Rack UN 127.0.0.1 322.11 KiB 256 ? 83ae1bed-37b7-46c0-a166-2a774e147205 rack1 Apache NoSQL DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS What is Temporary Table in SQL? MySQL | Regular expressions (Regexp) Difference between OLAP and OLTP in DBMS Difference between Where and Having Clause in SQL SQL | DDL, DML, TCL and DCL Introduction of Relational Algebra in DBMS Relational Model in DBMS Difference between Star Schema and Snowflake Schema KDD Process in Data Mining
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2020" }, { "code": null, "e": 270, "s": 28, "text": "In this article, we are going to discuss what is a node in Cassandra, information of node, how we can access the information about the node, and by using Nodetool utility we will also discuss some nodetool commands. let’s discuss one by one." }, { "code": null, "e": 277, "s": 270, "text": "Node :" }, { "code": null, "e": 393, "s": 277, "text": "A node in Cassandra contains the actual data and it’s information such that location, data center information, etc." }, { "code": null, "e": 472, "s": 393, "text": "A node contains the data such that keyspaces, tables, the schema of data, etc." }, { "code": null, "e": 551, "s": 472, "text": "you can perform operations such that read, write, delete data, etc. on a node." }, { "code": null, "e": 605, "s": 551, "text": "A node plays an important role in Cassandra clusters." }, { "code": null, "e": 728, "s": 605, "text": "In Cassandra ring where every node is connected peer to peer and every node is similar to every other node in the cluster." }, { "code": null, "e": 1012, "s": 728, "text": "Let’s consider an example where you have three replicas of data and each replica on different nodes. now, if you want to read data then anyone node can respond that’s why the concept of distributed data across the cluster is so effective and high availability mechanism in Cassandra." }, { "code": null, "e": 1023, "s": 1012, "text": "Nodetool :" }, { "code": null, "e": 1156, "s": 1023, "text": "It is the node management utility tool by which you can get the node health information, node information, cluster information, etc." }, { "code": null, "e": 1250, "s": 1156, "text": "with the help of nodetool commands, you can access all the required information of the nodes." }, { "code": null, "e": 1355, "s": 1250, "text": "Nodetool commands such that help, info, the status will give you the general information about the node." }, { "code": null, "e": 1428, "s": 1355, "text": "It’s by default located in the bin/ folder where Cassandra is installed." }, { "code": null, "e": 1460, "s": 1428, "text": "Some basics Nodetool commands :" }, { "code": null, "e": 1470, "s": 1460, "text": "Example –" }, { "code": null, "e": 1487, "s": 1470, "text": "nodetool status\n" }, { "code": null, "e": 1779, "s": 1487, "text": "let’s consider an example if a user wants to know the status of the node, then nodetool status commands need to be executed. In given below output is showing node is in the UN (Up and Normal) state and the address of a default node is 127.0.0.1 and also about load and rack information, etc." }, { "code": null, "e": 2127, "s": 1779, "text": " C:\\Program Files\\apache-cassandra-3.11.4\\bin>nodetool status\nDatacenter: datacenter1\n========================\nStatus=Up/Down\n|/ State=Normal/Leaving/Joining/Moving\n-- Address Load Tokens Owns Host ID Rack\nUN 127.0.0.1 322.11 KiB 256 ? 83ae1bed-37b7-46c0-a166-2a774e147205 rack1 " }, { "code": null, "e": 2134, "s": 2127, "text": "Apache" }, { "code": null, "e": 2140, "s": 2134, "text": "NoSQL" }, { "code": null, "e": 2145, "s": 2140, "text": "DBMS" }, { "code": null, "e": 2150, "s": 2145, "text": "DBMS" }, { "code": null, "e": 2248, "s": 2150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2289, "s": 2248, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 2321, "s": 2289, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2358, "s": 2321, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 2399, "s": 2358, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 2449, "s": 2399, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 2477, "s": 2449, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 2520, "s": 2477, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 2545, "s": 2520, "text": "Relational Model in DBMS" }, { "code": null, "e": 2597, "s": 2545, "text": "Difference between Star Schema and Snowflake Schema" } ]
How to Calculate Euclidean Distance in R?
28 Nov, 2021 Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefore occasionally being called the Pythagorean distance. The Euclidean distance between the two vectors is given by √Σ(vect1i - vect2i)2 where, vect1 is the first vector vect2 is the second vector For example, we are given two vectors, vect1 as (1, 4, 3, 5) and vect2 as (2, 3, 2, 4). Their Euclidean distance is given by, √(1 – 2)2 + (4 – 3)2 + (3 – 2)2 + (5 – 4)2 which is equal to 2. Below is the implementation using two vectors of equal length: Example 1: R # Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(2, 4, 4, 7)vect2 <- c(1, 2, 2, 10) print("Euclidean distance between vect1 and vect2 is: ") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2) Output: Example 2: R # Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(2, 3, 4, 7)vect2 <- c(1, 2, 3, 8) print("Euclidean distance between vect1 and vect2 is: ") # Calling CalculateEuclideanDistance functionCalculateEuclideanDistance(vect1, vect2) Output: If the two vectors have unequal length then the compiler gives a warning message. Below is the implementation using two vectors having unequal length. Example 3: R # Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(4, 3, 4, 8)vect2 <- c(3, 2, 3, 1, 2) print("Euclidean distance between vect1 and vect2 is: ") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2) Output: As you can see in the output, the compiler gives us a warning since the length of vect1 is shorter than vect2. Example 4: R # Function to calculate Euclidean distance# Sum function calculates the sum of the# squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(1, 7, 1, 3, 10, 15 )vect2 <- c(3, 2, 10, 11 ) print("Euclidean distance between vect1 and vect2 is: ") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2) Output: As you can see in the output, the compiler gives us a warning since the length of vect2 is shorter than vect1. Picked R-Mathematics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to filter R DataFrame by values in a column? Group by function in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R Remove Objects from Memory in R Programming - rm() Function How to Change Axis Scales in R Plots? Multiple linear regression using ggplot2 in R How to create a plot using ggplot2 with Multiple Lines in R ? For loop in R
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 361, "s": 28, "text": "Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefore occasionally being called the Pythagorean distance. The Euclidean distance between the two vectors is given by " }, { "code": null, "e": 382, "s": 361, "text": "√Σ(vect1i - vect2i)2" }, { "code": null, "e": 389, "s": 382, "text": "where," }, { "code": null, "e": 415, "s": 389, "text": "vect1 is the first vector" }, { "code": null, "e": 442, "s": 415, "text": "vect2 is the second vector" }, { "code": null, "e": 697, "s": 442, "text": "For example, we are given two vectors, vect1 as (1, 4, 3, 5) and vect2 as (2, 3, 2, 4). Their Euclidean distance is given by, √(1 – 2)2 + (4 – 3)2 + (3 – 2)2 + (5 – 4)2 which is equal to 2. Below is the implementation using two vectors of equal length:" }, { "code": null, "e": 708, "s": 697, "text": "Example 1:" }, { "code": null, "e": 710, "s": 708, "text": "R" }, { "code": "# Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(2, 4, 4, 7)vect2 <- c(1, 2, 2, 10) print(\"Euclidean distance between vect1 and vect2 is: \") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2)", "e": 1198, "s": 710, "text": null }, { "code": null, "e": 1206, "s": 1198, "text": "Output:" }, { "code": null, "e": 1217, "s": 1206, "text": "Example 2:" }, { "code": null, "e": 1219, "s": 1217, "text": "R" }, { "code": "# Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(2, 3, 4, 7)vect2 <- c(1, 2, 3, 8) print(\"Euclidean distance between vect1 and vect2 is: \") # Calling CalculateEuclideanDistance functionCalculateEuclideanDistance(vect1, vect2)", "e": 1704, "s": 1219, "text": null }, { "code": null, "e": 1712, "s": 1704, "text": "Output:" }, { "code": null, "e": 1863, "s": 1712, "text": "If the two vectors have unequal length then the compiler gives a warning message. Below is the implementation using two vectors having unequal length." }, { "code": null, "e": 1874, "s": 1863, "text": "Example 3:" }, { "code": null, "e": 1876, "s": 1874, "text": "R" }, { "code": "# Function to calculate Euclidean distance# Sum function calculates the sum of the # squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(4, 3, 4, 8)vect2 <- c(3, 2, 3, 1, 2) print(\"Euclidean distance between vect1 and vect2 is: \") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2)", "e": 2365, "s": 1876, "text": null }, { "code": null, "e": 2373, "s": 2365, "text": "Output:" }, { "code": null, "e": 2484, "s": 2373, "text": "As you can see in the output, the compiler gives us a warning since the length of vect1 is shorter than vect2." }, { "code": null, "e": 2495, "s": 2484, "text": "Example 4:" }, { "code": null, "e": 2497, "s": 2495, "text": "R" }, { "code": "# Function to calculate Euclidean distance# Sum function calculates the sum of the# squares of absolute difference between# corresponding elements of vect1 and vect2CalculateEuclideanDistance <- function(vect1, vect2) sqrt(sum((vect1 - vect2)^2)) # Initializing two vectors having equal lengthvect1 <- c(1, 7, 1, 3, 10, 15 )vect2 <- c(3, 2, 10, 11 ) print(\"Euclidean distance between vect1 and vect2 is: \") # Calling CalculateEuclideanDistance function CalculateEuclideanDistance(vect1, vect2)", "e": 2994, "s": 2497, "text": null }, { "code": null, "e": 3002, "s": 2994, "text": "Output:" }, { "code": null, "e": 3113, "s": 3002, "text": "As you can see in the output, the compiler gives us a warning since the length of vect2 is shorter than vect1." }, { "code": null, "e": 3120, "s": 3113, "text": "Picked" }, { "code": null, "e": 3134, "s": 3120, "text": "R-Mathematics" }, { "code": null, "e": 3145, "s": 3134, "text": "R Language" }, { "code": null, "e": 3243, "s": 3145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3292, "s": 3243, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3327, "s": 3292, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3379, "s": 3327, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3437, "s": 3379, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3480, "s": 3437, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3540, "s": 3480, "text": "Remove Objects from Memory in R Programming - rm() Function" }, { "code": null, "e": 3578, "s": 3540, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3624, "s": 3578, "text": "Multiple linear regression using ggplot2 in R" }, { "code": null, "e": 3686, "s": 3624, "text": "How to create a plot using ggplot2 with Multiple Lines in R ?" } ]
Jump Statements in Java
19 Oct, 2021 Jumping statements are control statements that transfer execution control from one point to another point in the program. There are two Jump statements that are provided in the Java programming language: Break statement.Continue statement. Break statement. Continue statement. 1. Using Break Statement to exit a loop: In java, the break statement is used to terminate the execution of the nearest looping statement or switch statement. The break statement is widely used with the switch statement, for loop, while loop, do-while loop. break; When a break statement is found inside a loop, the loop is terminated, and the control reaches the statement that follows the loop. here is an example: Java // Java program to illustrate the // break keyword in Javaimport java.io.*; class GFG { public static void main(String[] args) { int n = 10; for (int i = 0; i < n; i++) { if (i == 6) break; System.out.println(i); } }} 0 1 2 3 4 5 As you see, the code is meant to print 1 to 10 numbers using for loop, but it prints only 1 to 5 . as soon as i is equal to 6, the control terminates the loop. In a switch statement, if the break statement is missing, every case label is executed till the end of the switch. 2. Use Break as a form of goto Java does not have a goto statement because it produces an unstructured way to alter the flow of program execution. Java illustrates an extended form of the break statement. This form of break works with the label. The label is the name of a label that identifies a statement or a block of code. break label; When this form of break executes, control jumps out of the labeled statement or block. Here is an example: Java // Java program to illustrate the // break keyword as a Goto statement in Javaimport java.io.*; class GFG { public static void main(String[] args) { for (int i = 0; i < 3; i++) { one : { // label one two : { // label two three : { // label three System.out.println("i=" + i); if (i == 0) break one; // break to label one if (i == 1) break two; // break to label two if (i == 2) break three; // break to label three } System.out.println("after label three"); } System.out.println("after label two"); } System.out.println("after label one"); } }} i=0 after label one i=1 after label two after label one i=2 after label three after label two after label one In the above program, when i=0, the first if statement succeeds, and cause a break to label one and then prints the statement. When i=1, the second if statement succeeds, and cause a break to label two and then prints the statements. When i=2, the third if statement succeeds, and cause a break to the to label three and then prints all the three statements. The continue statement pushes the next repetition of the loop to take place, hopping any code between itself and the conditional expression that controls the loop. Here is an example: Java // Java program to illustrate the // continue keyword in Javaimport java.io.*; class GFG { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 6){ System.out.println(); // using continue keyword // to skip the current iteration continue; } System.out.println(i); } }} 0 1 2 3 4 5 7 8 9 In the program, when the value of i is 6, the compiler encounters the continue statement, then 6 is skipped. Java-Control-Flow Picked TrueGeek-2021 Java TrueGeek Java-Control-Flow Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Oct, 2021" }, { "code": null, "e": 257, "s": 53, "text": "Jumping statements are control statements that transfer execution control from one point to another point in the program. There are two Jump statements that are provided in the Java programming language:" }, { "code": null, "e": 293, "s": 257, "text": "Break statement.Continue statement." }, { "code": null, "e": 310, "s": 293, "text": "Break statement." }, { "code": null, "e": 330, "s": 310, "text": "Continue statement." }, { "code": null, "e": 371, "s": 330, "text": "1. Using Break Statement to exit a loop:" }, { "code": null, "e": 589, "s": 371, "text": "In java, the break statement is used to terminate the execution of the nearest looping statement or switch statement. The break statement is widely used with the switch statement, for loop, while loop, do-while loop. " }, { "code": null, "e": 596, "s": 589, "text": "break;" }, { "code": null, "e": 748, "s": 596, "text": "When a break statement is found inside a loop, the loop is terminated, and the control reaches the statement that follows the loop. here is an example:" }, { "code": null, "e": 753, "s": 748, "text": "Java" }, { "code": "// Java program to illustrate the // break keyword in Javaimport java.io.*; class GFG { public static void main(String[] args) { int n = 10; for (int i = 0; i < n; i++) { if (i == 6) break; System.out.println(i); } }}", "e": 1039, "s": 753, "text": null }, { "code": null, "e": 1051, "s": 1039, "text": "0\n1\n2\n3\n4\n5" }, { "code": null, "e": 1212, "s": 1051, "text": "As you see, the code is meant to print 1 to 10 numbers using for loop, but it prints only 1 to 5 . as soon as i is equal to 6, the control terminates the loop. " }, { "code": null, "e": 1327, "s": 1212, "text": "In a switch statement, if the break statement is missing, every case label is executed till the end of the switch." }, { "code": null, "e": 1358, "s": 1327, "text": "2. Use Break as a form of goto" }, { "code": null, "e": 1654, "s": 1358, "text": "Java does not have a goto statement because it produces an unstructured way to alter the flow of program execution. Java illustrates an extended form of the break statement. This form of break works with the label. The label is the name of a label that identifies a statement or a block of code." }, { "code": null, "e": 1667, "s": 1654, "text": "break label;" }, { "code": null, "e": 1754, "s": 1667, "text": "When this form of break executes, control jumps out of the labeled statement or block." }, { "code": null, "e": 1774, "s": 1754, "text": "Here is an example:" }, { "code": null, "e": 1779, "s": 1774, "text": "Java" }, { "code": "// Java program to illustrate the // break keyword as a Goto statement in Javaimport java.io.*; class GFG { public static void main(String[] args) { for (int i = 0; i < 3; i++) { one : { // label one two : { // label two three : { // label three System.out.println(\"i=\" + i); if (i == 0) break one; // break to label one if (i == 1) break two; // break to label two if (i == 2) break three; // break to label three } System.out.println(\"after label three\"); } System.out.println(\"after label two\"); } System.out.println(\"after label one\"); } }}", "e": 2512, "s": 1779, "text": null }, { "code": null, "e": 2622, "s": 2512, "text": "i=0\nafter label one\ni=1\nafter label two\nafter label one\ni=2\nafter label three\nafter label two\nafter label one" }, { "code": null, "e": 2981, "s": 2622, "text": "In the above program, when i=0, the first if statement succeeds, and cause a break to label one and then prints the statement. When i=1, the second if statement succeeds, and cause a break to label two and then prints the statements. When i=2, the third if statement succeeds, and cause a break to the to label three and then prints all the three statements." }, { "code": null, "e": 3145, "s": 2981, "text": "The continue statement pushes the next repetition of the loop to take place, hopping any code between itself and the conditional expression that controls the loop." }, { "code": null, "e": 3165, "s": 3145, "text": "Here is an example:" }, { "code": null, "e": 3170, "s": 3165, "text": "Java" }, { "code": "// Java program to illustrate the // continue keyword in Javaimport java.io.*; class GFG { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 6){ System.out.println(); // using continue keyword // to skip the current iteration continue; } System.out.println(i); } }}", "e": 3591, "s": 3170, "text": null }, { "code": null, "e": 3610, "s": 3591, "text": "0\n1\n2\n3\n4\n5\n\n7\n8\n9" }, { "code": null, "e": 3719, "s": 3610, "text": "In the program, when the value of i is 6, the compiler encounters the continue statement, then 6 is skipped." }, { "code": null, "e": 3737, "s": 3719, "text": "Java-Control-Flow" }, { "code": null, "e": 3744, "s": 3737, "text": "Picked" }, { "code": null, "e": 3758, "s": 3744, "text": "TrueGeek-2021" }, { "code": null, "e": 3763, "s": 3758, "text": "Java" }, { "code": null, "e": 3772, "s": 3763, "text": "TrueGeek" }, { "code": null, "e": 3790, "s": 3772, "text": "Java-Control-Flow" }, { "code": null, "e": 3795, "s": 3790, "text": "Java" } ]
GATE | GATE-CS-2014-(Set-3) | Question 65
28 Jun, 2021 Consider the transactions T1, T2, and T3 and the schedules S1 and S2 given below. T1: r1(X); r1(Z); w1(X); w1(Z) T2: r2(Y); r2(Z); w2(Z) T3: r3(Y); r3(X); w3(Y) S1: r1(X); r3(Y); r3(X); r2(Y); r2(Z); w3(Y); w2(Z); r1(Z); w1(X); w1(Z) S2: r1(X); r3(Y); r2(Y); r3(X); r1(Z); r2(Z); w3(Y); w1(X); w2(Z); w1(Z) Which one of the following statements about the schedules is TRUE?(A) Only S1 is conflict-serializable.(B) Only S2 is conflict-serializable.(C) Both S1 and S2 are conflict-serializable.(D) Neither S1 nor S2 is conflict-serializable.Answer: (A)Explanation: For conflict serializability of a schedule( which gives same effect as a serial schedule ) we should check for conflict operations, which are Read-Write, Write-Read and Write-Write between each pair of transactions, and based on those conflicts we make a precedence graph, if the graph contains a cycle, it’s not a conflict serializable schedule. To make a precedence graph: if Read(X) in Ti followed by Write(X) in Tj ( hence a conflict ), then we draw an edge from Ti to Tj ( Ti -> Tj) If we make a precedence graph for S1 and S2 , we would get directed edges for S1 as T2->T1, T2->T3, T3->T1, and for S2 as T2->T1, T2->T3, T3->T1, T1->T2. In S1 there is no cycle, but S2 has a cycle. Hence only S1 is conflict serializable. Note : The serial order for S1 is T2 -> T3 -> T1.Quiz of this Question GATE-CS-2014-(Set-3) GATE-GATE-CS-2014-(Set-3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2015 (Set 2) | Question 55 GATE | GATE CS 2008 | Question 40
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 136, "s": 54, "text": "Consider the transactions T1, T2, and T3 and the schedules S1 and S2 given below." }, { "code": null, "e": 370, "s": 136, "text": "T1: r1(X); r1(Z); w1(X); w1(Z)\nT2: r2(Y); r2(Z); w2(Z)\nT3: r3(Y); r3(X); w3(Y)\nS1: r1(X); r3(Y); r3(X); r2(Y); r2(Z);\n w3(Y); w2(Z); r1(Z); w1(X); w1(Z)\nS2: r1(X); r3(Y); r2(Y); r3(X); r1(Z);\n r2(Z); w3(Y); w1(X); w2(Z); w1(Z) " }, { "code": null, "e": 973, "s": 370, "text": "Which one of the following statements about the schedules is TRUE?(A) Only S1 is conflict-serializable.(B) Only S2 is conflict-serializable.(C) Both S1 and S2 are conflict-serializable.(D) Neither S1 nor S2 is conflict-serializable.Answer: (A)Explanation: For conflict serializability of a schedule( which gives same effect as a serial schedule ) we should check for conflict operations, which are Read-Write, Write-Read and Write-Write between each pair of transactions, and based on those conflicts we make a precedence graph, if the graph contains a cycle, it’s not a conflict serializable schedule." }, { "code": null, "e": 1114, "s": 973, "text": "To make a precedence graph: if Read(X) in Ti followed by Write(X) in Tj ( hence a conflict ), then we draw an edge from Ti to Tj ( Ti -> Tj)" }, { "code": null, "e": 1353, "s": 1114, "text": "If we make a precedence graph for S1 and S2 , we would get directed edges for S1 as T2->T1, T2->T3, T3->T1, and for S2 as T2->T1, T2->T3, T3->T1, T1->T2. In S1 there is no cycle, but S2 has a cycle. Hence only S1 is conflict serializable." }, { "code": null, "e": 1424, "s": 1353, "text": "Note : The serial order for S1 is T2 -> T3 -> T1.Quiz of this Question" }, { "code": null, "e": 1445, "s": 1424, "text": "GATE-CS-2014-(Set-3)" }, { "code": null, "e": 1471, "s": 1445, "text": "GATE-GATE-CS-2014-(Set-3)" }, { "code": null, "e": 1476, "s": 1471, "text": "GATE" }, { "code": null, "e": 1574, "s": 1476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1616, "s": 1574, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1678, "s": 1616, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1720, "s": 1678, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1754, "s": 1720, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1796, "s": 1754, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1838, "s": 1796, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 1880, "s": 1838, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1914, "s": 1880, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1956, "s": 1914, "text": "GATE | GATE-CS-2015 (Set 2) | Question 55" } ]
The Slowest Sorting Algorithms
30 Jun, 2022 A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the element in the respective data structure. But Below is some of the slowest sorting algorithms: Stooge Sort: A Stooge sort is a recursive sorting algorithm. It recursively divides and sorts the array in parts. Below are the steps of the Stooge Sort: If the value at index 0 is greater than the value at the last index, swap them. If the number of elements in the array is greater than two:Recursively call stoogesort function for the initial 2/3rd elements of the array.Recursively call stoogesort function for the last 2/3rd elements of the array.Recursively call stoogesort function for the initial 2/3rd elements again to confirm the resultant array is sorted or not. Recursively call stoogesort function for the initial 2/3rd elements of the array. Recursively call stoogesort function for the last 2/3rd elements of the array. Recursively call stoogesort function for the initial 2/3rd elements again to confirm the resultant array is sorted or not. Print the sorted array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the stooge sort#include <iostream>using namespace std; // Function to implement stooge sortvoid stoogesort(int arr[], int l, int h){ // Base Case if (l >= h) return; // If first element is smaller than // last element, swap them if (arr[l] > arr[h]) swap(arr[l], arr[h]); // If there are more than 2 elements // in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the first // 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 3, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { cout << arr[i] << " "; } return 0;} // Java program for the// stooge sortclass GFG{ // Function to implement// stooge sortstatic void stoogesort(int arr[], int l, int h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { int temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 4, 5, 3, 1}; int N = arr.length; // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { System.out.print(arr[i] + " "); }}} // This code is contributed by Chitranayal # Python3 program for the stooge sort # Function to implement stooge sortdef stoogesort(arr, l, h): # Base Case if (l >= h): return # If first element is smaller than # last element, swap them if (arr[l] > arr[h]): temp = arr[l] arr[l] = arr[h] arr[h] = temp # If there are more than 2 elements # in the array if (h - l + 1 > 2): t = (h - l + 1) // 3 # Recursively sort the first # 2/3 elements stoogesort(arr, l, h - t) # Recursively sort the last # 2/3 elements stoogesort(arr, l + t, h) # Recursively sort the first # 2/3 elements again stoogesort(arr, l, h - t) # Driver Codearr = [ 2, 4, 5, 3, 1 ]N = len(arr) # Function Callstoogesort(arr, 0, N - 1) # Display the sorted arrayfor i in range(N): print(arr[i], end = " ") # This code is contributed by code_hunt // C# program for the// stooge sortusing System;class GFG{ // Function to implement// stooge sortstatic void stoogesort(int []arr, int l, int h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { int temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codepublic static void Main(String[] args){ int []arr = {2, 4, 5, 3, 1}; int N = arr.Length; // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { Console.Write(arr[i] + " "); }}} // This code is contributed by Princi Singh <script> // Javascript program for the// stooge sort // Function to implement// stooge sortfunction stoogesort(arr, l, h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { let temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { let t = Math.floor((h - l + 1) / 3); // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codelet arr = [ 2, 4, 5, 3, 1 ];let N = arr.length; // Function Callstoogesort(arr, 0, N - 1); // Display the sorted arrayfor (let i = 0; i < N; i++){ document.write(arr[i] + " ");} // This code is contributed by avanitrachhadiya2155 </script> 1 2 3 4 5 Time Complexity: O(N2.709). Therefore, it is slower than even the Bubble Sort that has a time complexity of O(N2). Slow Sort: The slow sort is an example of Multiply And Surrender a tongue-in-cheek joke of divide and conquer. Slow sort stores the maximum element of the array at the last position by recursively divides the array by half and compares each of them. Then it recursively calls the array without the previous maximum element and stores the new maximum element at the new last position. Below are the steps of Slow sort: Find the maximum of the array and place it at the end of the array byRecursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum.Print the sorted array. Find the maximum of the array and place it at the end of the array byRecursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum. Recursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum. Recursively call slowsort function for the maximum of the first N/2 elements. Recursively call slowsort function for the maximum of the remaining N/2 elements. Find the largest of that two maximum and store it at the end. Recursively call slowsort function for the entire array except for the maximum. Print the sorted array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement Slow sort#include <bits/stdc++.h>using namespace std; // Function for swap two numbers using// pointersvoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Function that implements Slow Sortvoid slowSort(int A[], int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { swap(&A[j], &A[m]); } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arrayvoid printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} // Driver Codeint main(){ int arr[] = { 6, 8, 9, 4, 12, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N); return 0;} // Java program to implement Slow sortimport java.util.*; class GFG{ // Function that implements Slow Sortstatic void slowSort(int A[], int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { int temp = A[j]; A[j] = A[m]; A[m] = temp; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arraystatic void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) System.out.print(arr[i]+ " "); System.out.println();} // Driver Codepublic static void main(String[] args){ int arr[] = { 6, 8, 9, 4, 12, 1 }; int N = arr.length; // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N);}} // This code is contributed by 29AjayKumar # Python program to implement Slow sort # Function that implements Slow Sortdef slowSort(A, i, j): # Base Case if (i >= j): return; # Middle value m = (i + j) // 2; # Recursively call with left half slowSort(A, i, m); # Recursively call with right half slowSort(A, m + 1, j); # Swap if first element # is lower than second if (A[j] < A[m]): temp = A[j]; A[j] = A[m]; A[m] = temp; # Recursively call with whole # array except maximum element slowSort(A, i, j - 1); # Function to print the arraydef printArray(arr, size): i = 0; for i in range(size): print(arr[i], end=" "); print(); # Driver Codeif __name__ == '__main__': arr = [6, 8, 9, 4, 12, 1]; N = len(arr); # Function call slowSort(arr, 0, N - 1); # Display the sorted array printArray(arr, N); # This code contributed by gauravrajput1 // C# program to implement Slow sortusing System;class GFG{ // Function that implements Slow Sortstatic void slowSort(int []A, int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { int temp = A[j]; A[j] = A[m]; A[m] = temp; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arraystatic void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) Console.Write(arr[i] + " "); Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ int []arr = { 6, 8, 9, 4, 12, 1 }; int N = arr.Length; // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N);}} // This code is contributed by 29AjayKumar <script> //Javascript program to implement Slow sort // Function that implements Slow Sortfunction slowSort(A, i,j){ // Base Case if (i >= j) return; // Middle value var m = parseInt((i + j) / 2); // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { //swapp(A[j], A[m]); var t = A[j]; A[j]=A[m]; A[m]=t; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1); } // Function to print the arrayfunction printArray(arr, size){ var i; for (i = 0; i < size; i++) document.write( arr[i] + " "); document.write("<br>");} var arr = [ 6, 8, 9, 4, 12, 1 ];var N = arr.length; // Function callslowSort(arr, 0, N - 1); // Display the sorted arrayprintArray(arr, N); //This code is contributed by SoumikMondal</script> 1 4 6 8 9 12 Time Complexity: Base Case: O(N((log N)/(2+e)) where, e > 0 Average Case: O(N(log(N)/2)) Even the best case is worse than Bubble sort. It is less efficient than Stooge sort. Sleep Sort: Below is the steps of Stooge sort: Create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of the corresponding array element.The thread having the least amount of sleeping time wakes up first and the number gets printed and then the second least element and so on.The largest element wakes up after a long time and then the element gets printed at the last. Thus, the output is a sorted one. Create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of the corresponding array element. The thread having the least amount of sleeping time wakes up first and the number gets printed and then the second least element and so on. The largest element wakes up after a long time and then the element gets printed at the last. Thus, the output is a sorted one. All this Multithreading process happens in the background and at the core of the OS Below is the implementation of the above approach: C++ // C++ program to implement Sleep sort#ifdef _WIN32 // sleep() function for windows machine#include <Windows.h>#else // sleep() function for linux machine#include <unistd.h>#endif#include <iostream>#include <thread>#include <vector> using namespace std; // Array for storing the sorted valuesvector<int> A; // Function for print the arrayvoid printArray(vector<int> arr, int size){ int i; for (i = 0; i < size; i++) { cout << arr[i] << " "; }} // The instruction set for a threadvoid add(int x){ // Temporarily suspend execution // of each thread for x amount // of seconds sleep(x); // Every thead will wake up after // a particular time and push the // value in sorted array A.push_back(x);} // Function for Sleep sortvoid sleepSort(int arr[], int N){ vector<thread> threads; for (int i = 0; i < N; i++) { // New threads were launched by // using function pointer as // callable threads.push_back( thread(add, arr[i])); } // Waiting for each thread // to finish execution for (auto& th : threads) { th.join(); } // Display the sorted array cout << "Array after sorting: "; printArray(A, A.size());} // Driver Codeint main(){ int arr[] = { 8, 9, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); // sleep_sort function call sleepSort(arr, N); return 0;} // To run compile using -pthread// { 1, 3, 4, 8, 9} Array after sorting 1 3 4 8 9 Time Complexity: O(max(input) + N) where, input = value of array element Other algorithm’s time complexity depends upon the number of data but for sleep sort, it depends on the amount of data. This algorithm won’t work for negative numbers as a thread cannot sleep for a negative amount of time. Bogo Sort: Two versions of this algorithm exist: one enumerates all permutations until it hits a sorted one, and a randomized version that randomly permutes its input. Example 1: C++ // C++ program to implement Bogo Sort// using permutation#include <bits/stdc++.h>using namespace std; // Function to sort array using bogosortvoid bogosort(int arr[], int N){ // Run the loop until // array is not sorted while (!is_sorted(arr, arr + N)) { // All possible permutations next_permutation(arr, arr + N); }}// Driver Codeint main(){ int arr[] = { 8, 9, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call bogosort(arr, N); // Display the sorted array cout << "Array after sorting "; for (int i = 0; i < N; ++i) { cout << arr[i] << " "; } cout << endl; return 0;} Array after sorting 1 3 4 8 9 Time Complexity: Base Case: O(N) Average Case: O(N!) Worst Case: O(N!) Example 2: C++ Python3 // C++ program to implement Bogo Sort// using random shuffle#include <bits/stdc++.h>using namespace std; // Function to check if array is// sorted or notbool isSorted(int a[], int N){ while (--N > 1) { // Break condition for // unsorted array if (a[N] < a[N - 1]) return false; } return true;} // Function to generate permutation// of the arrayvoid shuffle(int a[], int N){ for (int i = 0; i < N; i++) swap(a[i], a[rand() % N]);} // Function to sort array using// Bogo sortvoid bogosort(int a[], int N){ // If array is not sorted // then shuffle array again while (!isSorted(a, N)) { shuffle(a, N); }} // Function to print the arrayvoid printArray(int a[], int N){ for (int i = 0; i < N; i++) { printf("%d ", a[i]); } printf("\n");} // Driver Codeint main(){ int a[] = { 3, 2, 5, 1, 0, 4 }; int N = sizeof a / sizeof a[0]; // Function Call bogosort(a, N); printf("Array after sorting:"); printArray(a, N); return 0;} # Python program to implement Bogo Sort# using random shuffleimport random # Function to check if array is# sorted or notdef isSorted(a,N): while(N > 1): N = N - 1 # Break condition for # unsorted array if (a[N] < a[N - 1]): return False return True # To generate permutation# of the arraydef shuffle(a, N): for i in range (0, N): r = random.randint(0,N-1) a[i], a[r] = a[r], a[i] # Function to sort array using# Bogo sortdef bogosort(a, N): # If array is not sorted # then shuffle array again while (not isSorted(a, N)): shuffle(a, N) # Function to print the arraydef printArray(a, N): for i in range(N): print(a[i], end=" ") print() # Driver code to test abovea = [3, 2, 5, 1, 0, 4]N=len(a) # Function Callbogosort(a,N)print("Array after sorting:",end="")printArray(a, N) # This code is contributed by Pushpesh Raj. Array after sorting:0 1 2 3 4 5 Time Complexity: Base Case: O(N) Average Case: O(N*N!) Worst Case: O(∞) Clearly, in the worst situation, Bogo sort using random shuffle takes an infinite amount of time to sort an array, and we may say that this is the slowest sorting algorithm. But the thing about Bogo Sort is that it violates some rules in Complexity Analysis. One of the rules is that you actually have to progress towards a goal. You can’t just obviously waste time for example by putting delay loops. The Slow Sort or stooge sort algorithm actually never makes a wrong move. Once it swaps two nodes the nodes will be in the correct order relative to each other and their order will not be reversed. ukasp princi singh code_hunt 29AjayKumar GauravRajput1 avanitrachhadiya2155 SoumikMondal akshaysingh98088 ankita_saini pushpeshrajdx01 Algorithms-Sorting-Quiz Algorithms Analysis Arrays Articles Sorting Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples Find if there is a path between two vertices in an undirected graph Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Practice Questions on Time Complexity Analysis Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 334, "s": 52, "text": "A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the element in the respective data structure. But Below is some of the slowest sorting algorithms:" }, { "code": null, "e": 488, "s": 334, "text": "Stooge Sort: A Stooge sort is a recursive sorting algorithm. It recursively divides and sorts the array in parts. Below are the steps of the Stooge Sort:" }, { "code": null, "e": 568, "s": 488, "text": "If the value at index 0 is greater than the value at the last index, swap them." }, { "code": null, "e": 909, "s": 568, "text": "If the number of elements in the array is greater than two:Recursively call stoogesort function for the initial 2/3rd elements of the array.Recursively call stoogesort function for the last 2/3rd elements of the array.Recursively call stoogesort function for the initial 2/3rd elements again to confirm the resultant array is sorted or not." }, { "code": null, "e": 991, "s": 909, "text": "Recursively call stoogesort function for the initial 2/3rd elements of the array." }, { "code": null, "e": 1070, "s": 991, "text": "Recursively call stoogesort function for the last 2/3rd elements of the array." }, { "code": null, "e": 1193, "s": 1070, "text": "Recursively call stoogesort function for the initial 2/3rd elements again to confirm the resultant array is sorted or not." }, { "code": null, "e": 1217, "s": 1193, "text": "Print the sorted array." }, { "code": null, "e": 1268, "s": 1217, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1272, "s": 1268, "text": "C++" }, { "code": null, "e": 1277, "s": 1272, "text": "Java" }, { "code": null, "e": 1285, "s": 1277, "text": "Python3" }, { "code": null, "e": 1288, "s": 1285, "text": "C#" }, { "code": null, "e": 1299, "s": 1288, "text": "Javascript" }, { "code": "// C++ program for the stooge sort#include <iostream>using namespace std; // Function to implement stooge sortvoid stoogesort(int arr[], int l, int h){ // Base Case if (l >= h) return; // If first element is smaller than // last element, swap them if (arr[l] > arr[h]) swap(arr[l], arr[h]); // If there are more than 2 elements // in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the first // 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the last // 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the first // 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codeint main(){ int arr[] = { 2, 4, 5, 3, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { cout << arr[i] << \" \"; } return 0;}", "e": 2299, "s": 1299, "text": null }, { "code": "// Java program for the// stooge sortclass GFG{ // Function to implement// stooge sortstatic void stoogesort(int arr[], int l, int h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { int temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 4, 5, 3, 1}; int N = arr.length; // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); }}} // This code is contributed by Chitranayal", "e": 3314, "s": 2299, "text": null }, { "code": "# Python3 program for the stooge sort # Function to implement stooge sortdef stoogesort(arr, l, h): # Base Case if (l >= h): return # If first element is smaller than # last element, swap them if (arr[l] > arr[h]): temp = arr[l] arr[l] = arr[h] arr[h] = temp # If there are more than 2 elements # in the array if (h - l + 1 > 2): t = (h - l + 1) // 3 # Recursively sort the first # 2/3 elements stoogesort(arr, l, h - t) # Recursively sort the last # 2/3 elements stoogesort(arr, l + t, h) # Recursively sort the first # 2/3 elements again stoogesort(arr, l, h - t) # Driver Codearr = [ 2, 4, 5, 3, 1 ]N = len(arr) # Function Callstoogesort(arr, 0, N - 1) # Display the sorted arrayfor i in range(N): print(arr[i], end = \" \") # This code is contributed by code_hunt", "e": 4224, "s": 3314, "text": null }, { "code": "// C# program for the// stooge sortusing System;class GFG{ // Function to implement// stooge sortstatic void stoogesort(int []arr, int l, int h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { int temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { int t = (h - l + 1) / 3; // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codepublic static void Main(String[] args){ int []arr = {2, 4, 5, 3, 1}; int N = arr.Length; // Function Call stoogesort(arr, 0, N - 1); // Display the sorted array for (int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); }}} // This code is contributed by Princi Singh", "e": 5248, "s": 4224, "text": null }, { "code": "<script> // Javascript program for the// stooge sort // Function to implement// stooge sortfunction stoogesort(arr, l, h){ // Base Case if (l >= h) return; // If first element is smaller // than last element, swap them if (arr[l] > arr[h]) { let temp = arr[l]; arr[l] = arr[h]; arr[h] = temp; } // If there are more than // 2 elements in the array if (h - l + 1 > 2) { let t = Math.floor((h - l + 1) / 3); // Recursively sort the // first 2/3 elements stoogesort(arr, l, h - t); // Recursively sort the // last 2/3 elements stoogesort(arr, l + t, h); // Recursively sort the // first 2/3 elements again stoogesort(arr, l, h - t); }} // Driver Codelet arr = [ 2, 4, 5, 3, 1 ];let N = arr.length; // Function Callstoogesort(arr, 0, N - 1); // Display the sorted arrayfor (let i = 0; i < N; i++){ document.write(arr[i] + \" \");} // This code is contributed by avanitrachhadiya2155 </script>", "e": 6314, "s": 5248, "text": null }, { "code": null, "e": 6324, "s": 6314, "text": "1 2 3 4 5" }, { "code": null, "e": 6441, "s": 6326, "text": "Time Complexity: O(N2.709). Therefore, it is slower than even the Bubble Sort that has a time complexity of O(N2)." }, { "code": null, "e": 6859, "s": 6441, "text": "Slow Sort: The slow sort is an example of Multiply And Surrender a tongue-in-cheek joke of divide and conquer. Slow sort stores the maximum element of the array at the last position by recursively divides the array by half and compares each of them. Then it recursively calls the array without the previous maximum element and stores the new maximum element at the new last position. Below are the steps of Slow sort:" }, { "code": null, "e": 7250, "s": 6859, "text": "Find the maximum of the array and place it at the end of the array byRecursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum.Print the sorted array." }, { "code": null, "e": 7618, "s": 7250, "text": "Find the maximum of the array and place it at the end of the array byRecursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum." }, { "code": null, "e": 7917, "s": 7618, "text": "Recursively call slowsort function for the maximum of the first N/2 elements.Recursively call slowsort function for the maximum of the remaining N/2 elements.Find the largest of that two maximum and store it at the end.Recursively call slowsort function for the entire array except for the maximum." }, { "code": null, "e": 7995, "s": 7917, "text": "Recursively call slowsort function for the maximum of the first N/2 elements." }, { "code": null, "e": 8077, "s": 7995, "text": "Recursively call slowsort function for the maximum of the remaining N/2 elements." }, { "code": null, "e": 8139, "s": 8077, "text": "Find the largest of that two maximum and store it at the end." }, { "code": null, "e": 8219, "s": 8139, "text": "Recursively call slowsort function for the entire array except for the maximum." }, { "code": null, "e": 8243, "s": 8219, "text": "Print the sorted array." }, { "code": null, "e": 8294, "s": 8243, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8298, "s": 8294, "text": "C++" }, { "code": null, "e": 8303, "s": 8298, "text": "Java" }, { "code": null, "e": 8311, "s": 8303, "text": "Python3" }, { "code": null, "e": 8314, "s": 8311, "text": "C#" }, { "code": null, "e": 8325, "s": 8314, "text": "Javascript" }, { "code": "// C++ program to implement Slow sort#include <bits/stdc++.h>using namespace std; // Function for swap two numbers using// pointersvoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Function that implements Slow Sortvoid slowSort(int A[], int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { swap(&A[j], &A[m]); } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arrayvoid printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} // Driver Codeint main(){ int arr[] = { 6, 8, 9, 4, 12, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N); return 0;}", "e": 9413, "s": 8325, "text": null }, { "code": "// Java program to implement Slow sortimport java.util.*; class GFG{ // Function that implements Slow Sortstatic void slowSort(int A[], int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { int temp = A[j]; A[j] = A[m]; A[m] = temp; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arraystatic void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) System.out.print(arr[i]+ \" \"); System.out.println();} // Driver Codepublic static void main(String[] args){ int arr[] = { 6, 8, 9, 4, 12, 1 }; int N = arr.length; // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N);}} // This code is contributed by 29AjayKumar", "e": 10471, "s": 9413, "text": null }, { "code": "# Python program to implement Slow sort # Function that implements Slow Sortdef slowSort(A, i, j): # Base Case if (i >= j): return; # Middle value m = (i + j) // 2; # Recursively call with left half slowSort(A, i, m); # Recursively call with right half slowSort(A, m + 1, j); # Swap if first element # is lower than second if (A[j] < A[m]): temp = A[j]; A[j] = A[m]; A[m] = temp; # Recursively call with whole # array except maximum element slowSort(A, i, j - 1); # Function to print the arraydef printArray(arr, size): i = 0; for i in range(size): print(arr[i], end=\" \"); print(); # Driver Codeif __name__ == '__main__': arr = [6, 8, 9, 4, 12, 1]; N = len(arr); # Function call slowSort(arr, 0, N - 1); # Display the sorted array printArray(arr, N); # This code contributed by gauravrajput1", "e": 11377, "s": 10471, "text": null }, { "code": "// C# program to implement Slow sortusing System;class GFG{ // Function that implements Slow Sortstatic void slowSort(int []A, int i, int j){ // Base Case if (i >= j) return; // Middle value int m = (i + j) / 2; // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { int temp = A[j]; A[j] = A[m]; A[m] = temp; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1);} // Function to print the arraystatic void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) Console.Write(arr[i] + \" \"); Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ int []arr = { 6, 8, 9, 4, 12, 1 }; int N = arr.Length; // Function call slowSort(arr, 0, N - 1); // Display the sorted array printArray(arr, N);}} // This code is contributed by 29AjayKumar", "e": 12423, "s": 11377, "text": null }, { "code": "<script> //Javascript program to implement Slow sort // Function that implements Slow Sortfunction slowSort(A, i,j){ // Base Case if (i >= j) return; // Middle value var m = parseInt((i + j) / 2); // Recursively call with left half slowSort(A, i, m); // Recursively call with right half slowSort(A, m + 1, j); // Swap if first element // is lower than second if (A[j] < A[m]) { //swapp(A[j], A[m]); var t = A[j]; A[j]=A[m]; A[m]=t; } // Recursively call with whole // array except maximum element slowSort(A, i, j - 1); } // Function to print the arrayfunction printArray(arr, size){ var i; for (i = 0; i < size; i++) document.write( arr[i] + \" \"); document.write(\"<br>\");} var arr = [ 6, 8, 9, 4, 12, 1 ];var N = arr.length; // Function callslowSort(arr, 0, N - 1); // Display the sorted arrayprintArray(arr, N); //This code is contributed by SoumikMondal</script>", "e": 13394, "s": 12423, "text": null }, { "code": null, "e": 13407, "s": 13394, "text": "1 4 6 8 9 12" }, { "code": null, "e": 13426, "s": 13409, "text": "Time Complexity:" }, { "code": null, "e": 13469, "s": 13426, "text": "Base Case: O(N((log N)/(2+e)) where, e > 0" }, { "code": null, "e": 13498, "s": 13469, "text": "Average Case: O(N(log(N)/2))" }, { "code": null, "e": 13584, "s": 13498, "text": "Even the best case is worse than Bubble sort. It is less efficient than Stooge sort. " }, { "code": null, "e": 13631, "s": 13584, "text": "Sleep Sort: Below is the steps of Stooge sort:" }, { "code": null, "e": 14087, "s": 13631, "text": "Create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of the corresponding array element.The thread having the least amount of sleeping time wakes up first and the number gets printed and then the second least element and so on.The largest element wakes up after a long time and then the element gets printed at the last. Thus, the output is a sorted one." }, { "code": null, "e": 14277, "s": 14087, "text": "Create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of the corresponding array element." }, { "code": null, "e": 14417, "s": 14277, "text": "The thread having the least amount of sleeping time wakes up first and the number gets printed and then the second least element and so on." }, { "code": null, "e": 14545, "s": 14417, "text": "The largest element wakes up after a long time and then the element gets printed at the last. Thus, the output is a sorted one." }, { "code": null, "e": 14629, "s": 14545, "text": "All this Multithreading process happens in the background and at the core of the OS" }, { "code": null, "e": 14681, "s": 14629, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 14685, "s": 14681, "text": "C++" }, { "code": "// C++ program to implement Sleep sort#ifdef _WIN32 // sleep() function for windows machine#include <Windows.h>#else // sleep() function for linux machine#include <unistd.h>#endif#include <iostream>#include <thread>#include <vector> using namespace std; // Array for storing the sorted valuesvector<int> A; // Function for print the arrayvoid printArray(vector<int> arr, int size){ int i; for (i = 0; i < size; i++) { cout << arr[i] << \" \"; }} // The instruction set for a threadvoid add(int x){ // Temporarily suspend execution // of each thread for x amount // of seconds sleep(x); // Every thead will wake up after // a particular time and push the // value in sorted array A.push_back(x);} // Function for Sleep sortvoid sleepSort(int arr[], int N){ vector<thread> threads; for (int i = 0; i < N; i++) { // New threads were launched by // using function pointer as // callable threads.push_back( thread(add, arr[i])); } // Waiting for each thread // to finish execution for (auto& th : threads) { th.join(); } // Display the sorted array cout << \"Array after sorting: \"; printArray(A, A.size());} // Driver Codeint main(){ int arr[] = { 8, 9, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); // sleep_sort function call sleepSort(arr, N); return 0;} // To run compile using -pthread// { 1, 3, 4, 8, 9}", "e": 16130, "s": 14685, "text": null }, { "code": null, "e": 16160, "s": 16130, "text": "Array after sorting 1 3 4 8 9" }, { "code": null, "e": 16235, "s": 16162, "text": "Time Complexity: O(max(input) + N) where, input = value of array element" }, { "code": null, "e": 16458, "s": 16235, "text": "Other algorithm’s time complexity depends upon the number of data but for sleep sort, it depends on the amount of data. This algorithm won’t work for negative numbers as a thread cannot sleep for a negative amount of time." }, { "code": null, "e": 16626, "s": 16458, "text": "Bogo Sort: Two versions of this algorithm exist: one enumerates all permutations until it hits a sorted one, and a randomized version that randomly permutes its input." }, { "code": null, "e": 16637, "s": 16626, "text": "Example 1:" }, { "code": null, "e": 16641, "s": 16637, "text": "C++" }, { "code": "// C++ program to implement Bogo Sort// using permutation#include <bits/stdc++.h>using namespace std; // Function to sort array using bogosortvoid bogosort(int arr[], int N){ // Run the loop until // array is not sorted while (!is_sorted(arr, arr + N)) { // All possible permutations next_permutation(arr, arr + N); }}// Driver Codeint main(){ int arr[] = { 8, 9, 1, 4, 3 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call bogosort(arr, N); // Display the sorted array cout << \"Array after sorting \"; for (int i = 0; i < N; ++i) { cout << arr[i] << \" \"; } cout << endl; return 0;}", "e": 17298, "s": 16641, "text": null }, { "code": null, "e": 17328, "s": 17298, "text": "Array after sorting 1 3 4 8 9" }, { "code": null, "e": 17347, "s": 17330, "text": "Time Complexity:" }, { "code": null, "e": 17363, "s": 17347, "text": "Base Case: O(N)" }, { "code": null, "e": 17383, "s": 17363, "text": "Average Case: O(N!)" }, { "code": null, "e": 17401, "s": 17383, "text": "Worst Case: O(N!)" }, { "code": null, "e": 17412, "s": 17401, "text": "Example 2:" }, { "code": null, "e": 17416, "s": 17412, "text": "C++" }, { "code": null, "e": 17424, "s": 17416, "text": "Python3" }, { "code": "// C++ program to implement Bogo Sort// using random shuffle#include <bits/stdc++.h>using namespace std; // Function to check if array is// sorted or notbool isSorted(int a[], int N){ while (--N > 1) { // Break condition for // unsorted array if (a[N] < a[N - 1]) return false; } return true;} // Function to generate permutation// of the arrayvoid shuffle(int a[], int N){ for (int i = 0; i < N; i++) swap(a[i], a[rand() % N]);} // Function to sort array using// Bogo sortvoid bogosort(int a[], int N){ // If array is not sorted // then shuffle array again while (!isSorted(a, N)) { shuffle(a, N); }} // Function to print the arrayvoid printArray(int a[], int N){ for (int i = 0; i < N; i++) { printf(\"%d \", a[i]); } printf(\"\\n\");} // Driver Codeint main(){ int a[] = { 3, 2, 5, 1, 0, 4 }; int N = sizeof a / sizeof a[0]; // Function Call bogosort(a, N); printf(\"Array after sorting:\"); printArray(a, N); return 0;}", "e": 18452, "s": 17424, "text": null }, { "code": "# Python program to implement Bogo Sort# using random shuffleimport random # Function to check if array is# sorted or notdef isSorted(a,N): while(N > 1): N = N - 1 # Break condition for # unsorted array if (a[N] < a[N - 1]): return False return True # To generate permutation# of the arraydef shuffle(a, N): for i in range (0, N): r = random.randint(0,N-1) a[i], a[r] = a[r], a[i] # Function to sort array using# Bogo sortdef bogosort(a, N): # If array is not sorted # then shuffle array again while (not isSorted(a, N)): shuffle(a, N) # Function to print the arraydef printArray(a, N): for i in range(N): print(a[i], end=\" \") print() # Driver code to test abovea = [3, 2, 5, 1, 0, 4]N=len(a) # Function Callbogosort(a,N)print(\"Array after sorting:\",end=\"\")printArray(a, N) # This code is contributed by Pushpesh Raj.", "e": 19374, "s": 18452, "text": null }, { "code": null, "e": 19406, "s": 19374, "text": "Array after sorting:0 1 2 3 4 5" }, { "code": null, "e": 19425, "s": 19408, "text": "Time Complexity:" }, { "code": null, "e": 19441, "s": 19425, "text": "Base Case: O(N)" }, { "code": null, "e": 19463, "s": 19441, "text": "Average Case: O(N*N!)" }, { "code": null, "e": 19480, "s": 19463, "text": "Worst Case: O(∞)" }, { "code": null, "e": 20080, "s": 19480, "text": "Clearly, in the worst situation, Bogo sort using random shuffle takes an infinite amount of time to sort an array, and we may say that this is the slowest sorting algorithm. But the thing about Bogo Sort is that it violates some rules in Complexity Analysis. One of the rules is that you actually have to progress towards a goal. You can’t just obviously waste time for example by putting delay loops. The Slow Sort or stooge sort algorithm actually never makes a wrong move. Once it swaps two nodes the nodes will be in the correct order relative to each other and their order will not be reversed." }, { "code": null, "e": 20086, "s": 20080, "text": "ukasp" }, { "code": null, "e": 20099, "s": 20086, "text": "princi singh" }, { "code": null, "e": 20109, "s": 20099, "text": "code_hunt" }, { "code": null, "e": 20121, "s": 20109, "text": "29AjayKumar" }, { "code": null, "e": 20135, "s": 20121, "text": "GauravRajput1" }, { "code": null, "e": 20156, "s": 20135, "text": "avanitrachhadiya2155" }, { "code": null, "e": 20169, "s": 20156, "text": "SoumikMondal" }, { "code": null, "e": 20186, "s": 20169, "text": "akshaysingh98088" }, { "code": null, "e": 20199, "s": 20186, "text": "ankita_saini" }, { "code": null, "e": 20215, "s": 20199, "text": "pushpeshrajdx01" }, { "code": null, "e": 20239, "s": 20215, "text": "Algorithms-Sorting-Quiz" }, { "code": null, "e": 20250, "s": 20239, "text": "Algorithms" }, { "code": null, "e": 20259, "s": 20250, "text": "Analysis" }, { "code": null, "e": 20266, "s": 20259, "text": "Arrays" }, { "code": null, "e": 20275, "s": 20266, "text": "Articles" }, { "code": null, "e": 20283, "s": 20275, "text": "Sorting" }, { "code": null, "e": 20290, "s": 20283, "text": "Arrays" }, { "code": null, "e": 20298, "s": 20290, "text": "Sorting" }, { "code": null, "e": 20309, "s": 20298, "text": "Algorithms" }, { "code": null, "e": 20407, "s": 20309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20432, "s": 20407, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 20481, "s": 20432, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 20519, "s": 20481, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 20570, "s": 20519, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 20638, "s": 20570, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 20689, "s": 20638, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 20726, "s": 20689, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 20773, "s": 20726, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 20836, "s": 20773, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" } ]
Python math function | modf()
11 Jan, 2018 modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float. Syntax : modf(number) Parameter : There is only one mandatory parameter which is the number. Returns :This method returns the fractional and integer parts of number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float. Exception : TypeError: If anything other then a float number is passed, it returns a type error. Below is the Python3 implementation of modf() method : Code #1 # Python3 program to demonstrate the function modf() # This will import math moduleimport math # modf() function used with a positive numberprint("math.modf(100.12) : ", math.modf(100.12)) # modf() function used with a negative numberprint("math.modf(-100.72) : ", math.modf(-100.72)) print("math.modf(2) : ", math.modf(2)) Output : math.modf(100.12) : (0.12000000000000455, 100.0) math.modf(-100.72) : (-0.7199999999999989, -100.0) math.modf(2) : (0.0, 2.0) Code #2 : TypeError # Python3 program to demonstrate the # error in function modf() # This will import math moduleimport math # modf() function used with a positive numberprint("math.modf(100.12) : ", math.modf("100.12")) Output : Traceback (most recent call last): File "/home/fa6d7643de17bafe9a0e0693458e4bdb.py", line 9, in print("math.modf(100.12) : ", math.modf("100.12")) TypeError: a float is required Code #3 : # Python3 program to demonstrate the # error in function modf() # This will import math modulefrom math import modf lst = [3.12, -5.14, 13.25, -5.21]tpl = (33.12, -15.25, 3.15, -31.2) # modf() function on elements of listprint("modf() on First list element : ", modf(lst[0]))print("modf() on third list element : ", modf(lst[2])) # modf() function on elements of tupleprint("modf() on Second tuple element : ", modf(tpl[1]))print("modf() on Fourth tuple element : ", modf(tpl[3])) Output : modf() on First list element : (0.1200000000000001, 3.0) modf() on third list element : (0.25, 13.0) modf() on Second tuple element : (-0.25, -15.0) modf() on Fourth tuple element : (-0.1999999999999993, -31.0) Practical Application :Given two float numbers, multiply the fractional part and return the answer. Code #4 : # Python3 program to demonstrate the # application of function modf() # This will import math moduleimport math # modf() function to multiply fractional part a = math.modf(11.2) b = math.modf(12.3) # Multiply the fractional part as is stored # in 0th index of both the tupleprint(a[0]*b[0]) Output : 0.05999999999999993 Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jan, 2018" }, { "code": null, "e": 269, "s": 53, "text": "modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float." }, { "code": null, "e": 278, "s": 269, "text": "Syntax :" }, { "code": null, "e": 292, "s": 278, "text": "modf(number) " }, { "code": null, "e": 304, "s": 292, "text": "Parameter :" }, { "code": null, "e": 364, "s": 304, "text": "There is only one mandatory parameter which is the number. " }, { "code": null, "e": 543, "s": 364, "text": "Returns :This method returns the fractional and integer parts of number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float." }, { "code": null, "e": 555, "s": 543, "text": "Exception :" }, { "code": null, "e": 642, "s": 555, "text": "TypeError: If anything other then a float number is passed, it returns a type error. " }, { "code": null, "e": 697, "s": 642, "text": "Below is the Python3 implementation of modf() method :" }, { "code": null, "e": 705, "s": 697, "text": "Code #1" }, { "code": "# Python3 program to demonstrate the function modf() # This will import math moduleimport math # modf() function used with a positive numberprint(\"math.modf(100.12) : \", math.modf(100.12)) # modf() function used with a negative numberprint(\"math.modf(-100.72) : \", math.modf(-100.72)) print(\"math.modf(2) : \", math.modf(2)) ", "e": 1038, "s": 705, "text": null }, { "code": null, "e": 1047, "s": 1038, "text": "Output :" }, { "code": null, "e": 1177, "s": 1047, "text": "math.modf(100.12) : (0.12000000000000455, 100.0)\nmath.modf(-100.72) : (-0.7199999999999989, -100.0)\nmath.modf(2) : (0.0, 2.0)\n" }, { "code": null, "e": 1199, "s": 1179, "text": "Code #2 : TypeError" }, { "code": "# Python3 program to demonstrate the # error in function modf() # This will import math moduleimport math # modf() function used with a positive numberprint(\"math.modf(100.12) : \", math.modf(\"100.12\"))", "e": 1407, "s": 1199, "text": null }, { "code": null, "e": 1416, "s": 1407, "text": "Output :" }, { "code": null, "e": 1602, "s": 1416, "text": "Traceback (most recent call last):\n File \"/home/fa6d7643de17bafe9a0e0693458e4bdb.py\", line 9, in \n print(\"math.modf(100.12) : \", math.modf(\"100.12\"))\nTypeError: a float is required\n" }, { "code": null, "e": 1613, "s": 1602, "text": " Code #3 :" }, { "code": "# Python3 program to demonstrate the # error in function modf() # This will import math modulefrom math import modf lst = [3.12, -5.14, 13.25, -5.21]tpl = (33.12, -15.25, 3.15, -31.2) # modf() function on elements of listprint(\"modf() on First list element : \", modf(lst[0]))print(\"modf() on third list element : \", modf(lst[2])) # modf() function on elements of tupleprint(\"modf() on Second tuple element : \", modf(tpl[1]))print(\"modf() on Fourth tuple element : \", modf(tpl[3]))", "e": 2100, "s": 1613, "text": null }, { "code": null, "e": 2109, "s": 2100, "text": "Output :" }, { "code": null, "e": 2325, "s": 2109, "text": "modf() on First list element : (0.1200000000000001, 3.0)\nmodf() on third list element : (0.25, 13.0)\nmodf() on Second tuple element : (-0.25, -15.0)\nmodf() on Fourth tuple element : (-0.1999999999999993, -31.0)\n" }, { "code": null, "e": 2425, "s": 2325, "text": "Practical Application :Given two float numbers, multiply the fractional part and return the answer." }, { "code": null, "e": 2435, "s": 2425, "text": "Code #4 :" }, { "code": "# Python3 program to demonstrate the # application of function modf() # This will import math moduleimport math # modf() function to multiply fractional part a = math.modf(11.2) b = math.modf(12.3) # Multiply the fractional part as is stored # in 0th index of both the tupleprint(a[0]*b[0])", "e": 2733, "s": 2435, "text": null }, { "code": null, "e": 2742, "s": 2733, "text": "Output :" }, { "code": null, "e": 2763, "s": 2742, "text": "0.05999999999999993\n" }, { "code": null, "e": 2789, "s": 2763, "text": "Python-Built-in-functions" }, { "code": null, "e": 2796, "s": 2789, "text": "Python" }, { "code": null, "e": 2894, "s": 2796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2912, "s": 2894, "text": "Python Dictionary" }, { "code": null, "e": 2954, "s": 2912, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2976, "s": 2954, "text": "Enumerate() in Python" }, { "code": null, "e": 3011, "s": 2976, "text": "Read a file line by line in Python" }, { "code": null, "e": 3037, "s": 3011, "text": "Python String | replace()" }, { "code": null, "e": 3069, "s": 3037, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3098, "s": 3069, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3128, "s": 3098, "text": "Iterate over a list in Python" }, { "code": null, "e": 3155, "s": 3128, "text": "Python Classes and Objects" } ]
Total area of two overlapping rectangles
13 Jun, 2022 Given two overlapping rectangles on a plane. We are given bottom left and top right points of the two rectangles. We need to find the total area (Green and pink areas in the below diagram). Examples: Input : Point l1 = {2, 2}, r1 = {5, 7}; Point l2 = {3, 4}, r2 = {6, 9}; Output :Total Area = 24 Input : Point l1 = {2, 1}, r1 = {5, 5}; Point l2 = {3, 2}, r2 = {5, 7}; Output :Total Area = 16 Asked in Juniper We basically add areas of two rectangles. This includes the intersecting part twice, so we subtract the area of intersecting part. Total Area = (Area of 1st rectangle + Area of 2nd rectangle) - Area of Intersecting part Area of Rectangle = x_distance * y_distance Where, x_distance for 1st rectangle = abs(l1.x – r1.x) y_distance for 1st rectangle = abs(l1.y – r1.y) Similarly, we can compute area of 2nd rectangle. For area of intersecting part, x_distance for intersecting rectangle = min(r1.x, r2.x) – max(l1.x, l2.x) y_distance for 1st rectangle = min(r1.y, r2.y) – max(l1.y, l2.y) If the x_distance or y_distance is negative, then the two rectangles do not intersect. In that case, overlapping area is 0. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find total area of two// overlapping Rectangles#include <bits/stdc++.h>using namespace std; struct Point { int x, y;}; // Returns Total Area of two overlap// rectanglesint overlappingArea(Point l1, Point r1, Point l2, Point r2){ // Area of 1st Rectangle int area1 = abs(l1.x - r1.x) * abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = abs(l2.x - r2.x) * abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = min(r1.x, r2.x) - max(l1.x, l2.x); int y_dist = (min(r1.y, r2.y) - max(l1.y, l2.y)); int areaI = 0; if( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI);} // Driver Codeint main(){ Point l1 = { 2, 2 }, r1 = { 5, 7 }; Point l2 = { 3, 4 }, r2 = { 6, 9 }; // Function Call cout << overlappingArea(l1, r1, l2, r2); return 0;} // Java program to find total area of two// overlapping Rectanglesclass GFG { static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Returns Total Area of two overlap // rectangles static int overlappingArea(Point l1, Point r1, Point l2, Point r2) { // Area of 1st Rectangle int area1 = Math.abs(l1.x - r1.x) * Math.abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = Math.abs(l2.x - r2.x) * Math.abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = (Math.min(r1.x, r2.x) - Math.max(l1.x, l2.x); int y_dist = (Math.min(r1.y, r2.y) - Math.max(l1.y, l2.y); int areaI = 0; if( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI); } // Driver Code public static void main(String[] args) { Point l1 = new Point(2, 2), r1 = new Point(5, 7); Point l2 = new Point(3, 4), r2 = new Point(6, 9); // Function Call System.out.println(overlappingArea(l1, r1, l2, r2)); }} // This code is contributed by PrinciRaj1992 # Python program to find total area of two# overlapping Rectangles# Returns Total Area of two overlap# rectangles def overlappingArea(l1, r1, l2, r2): x = 0 y = 1 # Area of 1st Rectangle area1 = abs(l1[x] - r1[x]) * abs(l1[y] - r1[y]) # Area of 2nd Rectangle area2 = abs(l2[x] - r2[x]) * abs(l2[y] - r2[y]) ''' Length of intersecting part i.e start from max(l1[x], l2[x]) of x-coordinate and end at min(r1[x], r2[x]) x-coordinate by subtracting start from end we get required lengths ''' x_dist = (min(r1[x], r2[x]) - max(l1[x], l2[x])) y_dist = (min(r1[y], r2[y]) - max(l1[y], l2[y])) areaI = 0 if x_dist > 0 and y_dist > 0: areaI = x_dist * y_dist return (area1 + area2 - areaI) # Driver's Codel1 = [2, 2]r1 = [5, 7]l2 = [3, 4]r2 = [6, 9] # Function callprint(overlappingArea(l1, r1, l2, r2)) # This code is contributed by Manisha_Ediga // C# program to find total area of two// overlapping Rectanglesusing System; class GFG { public class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Returns Total Area of two overlap // rectangles static int overlappingArea(Point l1, Point r1, Point l2, Point r2) { // Area of 1st Rectangle int area1 = Math.Abs(l1.x - r1.x) * Math.Abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = Math.Abs(l2.x - r2.x) * Math.Abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = (Math.Min(r1.x, r2.x) - Math.Max(l1.x, l2.x)); int y_dist = (Math.Min(r1.y, r2.y) - Math.Max(l1.y, l2.y)); int areaI = 0; if (x_dist > 0 && y_dist > 0) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI); } // Driver Code public static void Main(String[] args) { Point l1 = new Point(2, 2), r1 = new Point(5, 7); Point l2 = new Point(3, 4), r2 = new Point(6, 9); // Function Call Console.WriteLine(overlappingArea(l1, r1, l2, r2)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find total area of two// overlapping Rectangles// Returns Total Area of two overlap// rectangles function overlappingArea(l1, r1, l2, r2){ let x = 0 let y = 1 // Area of 1st Rectangle let area1 = Math.abs(l1[x] - r1[x]) * Math.abs(l1[y] - r1[y]) // Area of 2nd Rectangle let area2 = Math.abs(l2[x] - r2[x]) * Math.abs(l2[y] - r2[y]) // Length of intersecting part i.e // start from max(l1[x], l2[x]) of // x-coordinate and end at min(r1[x], // r2[x]) x-coordinate by subtracting // start from end we get required // lengths let x_dist = (Math.min(r1[x], r2[x]) - Math.max(l1[x], l2[x])) let y_dist = (Math.min(r1[y], r2[y]) - Math.max(l1[y], l2[y])) let areaI = 0 if (x_dist > 0 && y_dist > 0) areaI = x_dist * y_dist return (area1 + area2 - areaI)} // Driver Code let l1 = [2, 2] let r1 = [5, 7] let l2 = [3, 4] let r2 = [6, 9] // Function call document.write(overlappingArea(l1, r1, l2, r2)) // This code is contributed by jana_sayantan. </script> 24 Time complexity: O(1) Auxiliary Space: O(1) princiraj1992 manishaediga23 kshtjpatil06 jana_sayantan hasani area-volume-programs Juniper Networks Geometric School Programming Juniper Networks Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation Find K Closest Points to the Origin Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 245, "s": 54, "text": "Given two overlapping rectangles on a plane. We are given bottom left and top right points of the two rectangles. We need to find the total area (Green and pink areas in the below diagram). " }, { "code": null, "e": 256, "s": 245, "text": "Examples: " }, { "code": null, "e": 466, "s": 256, "text": "Input : Point l1 = {2, 2}, r1 = {5, 7};\n Point l2 = {3, 4}, r2 = {6, 9};\nOutput :Total Area = 24 \n\nInput : Point l1 = {2, 1}, r1 = {5, 5};\n Point l2 = {3, 2}, r2 = {5, 7};\nOutput :Total Area = 16" }, { "code": null, "e": 483, "s": 466, "text": "Asked in Juniper" }, { "code": null, "e": 614, "s": 483, "text": "We basically add areas of two rectangles. This includes the intersecting part twice, so we subtract the area of intersecting part." }, { "code": null, "e": 733, "s": 614, "text": "Total Area = (Area of 1st rectangle + \n Area of 2nd rectangle) - \n Area of Intersecting part" }, { "code": null, "e": 778, "s": 733, "text": "Area of Rectangle = x_distance * y_distance " }, { "code": null, "e": 881, "s": 778, "text": "Where, x_distance for 1st rectangle = abs(l1.x – r1.x) y_distance for 1st rectangle = abs(l1.y – r1.y)" }, { "code": null, "e": 930, "s": 881, "text": "Similarly, we can compute area of 2nd rectangle." }, { "code": null, "e": 1100, "s": 930, "text": "For area of intersecting part, x_distance for intersecting rectangle = min(r1.x, r2.x) – max(l1.x, l2.x) y_distance for 1st rectangle = min(r1.y, r2.y) – max(l1.y, l2.y)" }, { "code": null, "e": 1224, "s": 1100, "text": "If the x_distance or y_distance is negative, then the two rectangles do not intersect. In that case, overlapping area is 0." }, { "code": null, "e": 1275, "s": 1224, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1279, "s": 1275, "text": "C++" }, { "code": null, "e": 1284, "s": 1279, "text": "Java" }, { "code": null, "e": 1292, "s": 1284, "text": "Python3" }, { "code": null, "e": 1295, "s": 1292, "text": "C#" }, { "code": null, "e": 1306, "s": 1295, "text": "Javascript" }, { "code": "// C++ program to find total area of two// overlapping Rectangles#include <bits/stdc++.h>using namespace std; struct Point { int x, y;}; // Returns Total Area of two overlap// rectanglesint overlappingArea(Point l1, Point r1, Point l2, Point r2){ // Area of 1st Rectangle int area1 = abs(l1.x - r1.x) * abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = abs(l2.x - r2.x) * abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = min(r1.x, r2.x) - max(l1.x, l2.x); int y_dist = (min(r1.y, r2.y) - max(l1.y, l2.y)); int areaI = 0; if( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI);} // Driver Codeint main(){ Point l1 = { 2, 2 }, r1 = { 5, 7 }; Point l2 = { 3, 4 }, r2 = { 6, 9 }; // Function Call cout << overlappingArea(l1, r1, l2, r2); return 0;}", "e": 2409, "s": 1306, "text": null }, { "code": "// Java program to find total area of two// overlapping Rectanglesclass GFG { static class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Returns Total Area of two overlap // rectangles static int overlappingArea(Point l1, Point r1, Point l2, Point r2) { // Area of 1st Rectangle int area1 = Math.abs(l1.x - r1.x) * Math.abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = Math.abs(l2.x - r2.x) * Math.abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = (Math.min(r1.x, r2.x) - Math.max(l1.x, l2.x); int y_dist = (Math.min(r1.y, r2.y) - Math.max(l1.y, l2.y); int areaI = 0; if( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI); } // Driver Code public static void main(String[] args) { Point l1 = new Point(2, 2), r1 = new Point(5, 7); Point l2 = new Point(3, 4), r2 = new Point(6, 9); // Function Call System.out.println(overlappingArea(l1, r1, l2, r2)); }} // This code is contributed by PrinciRaj1992", "e": 3917, "s": 2409, "text": null }, { "code": "# Python program to find total area of two# overlapping Rectangles# Returns Total Area of two overlap# rectangles def overlappingArea(l1, r1, l2, r2): x = 0 y = 1 # Area of 1st Rectangle area1 = abs(l1[x] - r1[x]) * abs(l1[y] - r1[y]) # Area of 2nd Rectangle area2 = abs(l2[x] - r2[x]) * abs(l2[y] - r2[y]) ''' Length of intersecting part i.e start from max(l1[x], l2[x]) of x-coordinate and end at min(r1[x], r2[x]) x-coordinate by subtracting start from end we get required lengths ''' x_dist = (min(r1[x], r2[x]) - max(l1[x], l2[x])) y_dist = (min(r1[y], r2[y]) - max(l1[y], l2[y])) areaI = 0 if x_dist > 0 and y_dist > 0: areaI = x_dist * y_dist return (area1 + area2 - areaI) # Driver's Codel1 = [2, 2]r1 = [5, 7]l2 = [3, 4]r2 = [6, 9] # Function callprint(overlappingArea(l1, r1, l2, r2)) # This code is contributed by Manisha_Ediga", "e": 4873, "s": 3917, "text": null }, { "code": "// C# program to find total area of two// overlapping Rectanglesusing System; class GFG { public class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } }; // Returns Total Area of two overlap // rectangles static int overlappingArea(Point l1, Point r1, Point l2, Point r2) { // Area of 1st Rectangle int area1 = Math.Abs(l1.x - r1.x) * Math.Abs(l1.y - r1.y); // Area of 2nd Rectangle int area2 = Math.Abs(l2.x - r2.x) * Math.Abs(l2.y - r2.y); // Length of intersecting part i.e // start from max(l1.x, l2.x) of // x-coordinate and end at min(r1.x, // r2.x) x-coordinate by subtracting // start from end we get required // lengths int x_dist = (Math.Min(r1.x, r2.x) - Math.Max(l1.x, l2.x)); int y_dist = (Math.Min(r1.y, r2.y) - Math.Max(l1.y, l2.y)); int areaI = 0; if (x_dist > 0 && y_dist > 0) { areaI = x_dist * y_dist; } return (area1 + area2 - areaI); } // Driver Code public static void Main(String[] args) { Point l1 = new Point(2, 2), r1 = new Point(5, 7); Point l2 = new Point(3, 4), r2 = new Point(6, 9); // Function Call Console.WriteLine(overlappingArea(l1, r1, l2, r2)); }} // This code is contributed by PrinciRaj1992", "e": 6350, "s": 4873, "text": null }, { "code": "<script> // Javascript program to find total area of two// overlapping Rectangles// Returns Total Area of two overlap// rectangles function overlappingArea(l1, r1, l2, r2){ let x = 0 let y = 1 // Area of 1st Rectangle let area1 = Math.abs(l1[x] - r1[x]) * Math.abs(l1[y] - r1[y]) // Area of 2nd Rectangle let area2 = Math.abs(l2[x] - r2[x]) * Math.abs(l2[y] - r2[y]) // Length of intersecting part i.e // start from max(l1[x], l2[x]) of // x-coordinate and end at min(r1[x], // r2[x]) x-coordinate by subtracting // start from end we get required // lengths let x_dist = (Math.min(r1[x], r2[x]) - Math.max(l1[x], l2[x])) let y_dist = (Math.min(r1[y], r2[y]) - Math.max(l1[y], l2[y])) let areaI = 0 if (x_dist > 0 && y_dist > 0) areaI = x_dist * y_dist return (area1 + area2 - areaI)} // Driver Code let l1 = [2, 2] let r1 = [5, 7] let l2 = [3, 4] let r2 = [6, 9] // Function call document.write(overlappingArea(l1, r1, l2, r2)) // This code is contributed by jana_sayantan. </script>", "e": 7470, "s": 6350, "text": null }, { "code": null, "e": 7473, "s": 7470, "text": "24" }, { "code": null, "e": 7495, "s": 7473, "text": "Time complexity: O(1)" }, { "code": null, "e": 7517, "s": 7495, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7531, "s": 7517, "text": "princiraj1992" }, { "code": null, "e": 7546, "s": 7531, "text": "manishaediga23" }, { "code": null, "e": 7559, "s": 7546, "text": "kshtjpatil06" }, { "code": null, "e": 7573, "s": 7559, "text": "jana_sayantan" }, { "code": null, "e": 7580, "s": 7573, "text": "hasani" }, { "code": null, "e": 7601, "s": 7580, "text": "area-volume-programs" }, { "code": null, "e": 7618, "s": 7601, "text": "Juniper Networks" }, { "code": null, "e": 7628, "s": 7618, "text": "Geometric" }, { "code": null, "e": 7647, "s": 7628, "text": "School Programming" }, { "code": null, "e": 7664, "s": 7647, "text": "Juniper Networks" }, { "code": null, "e": 7674, "s": 7664, "text": "Geometric" }, { "code": null, "e": 7772, "s": 7674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7825, "s": 7772, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 7883, "s": 7825, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 7930, "s": 7883, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 8005, "s": 7930, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 8041, "s": 8005, "text": "Find K Closest Points to the Origin" }, { "code": null, "e": 8059, "s": 8041, "text": "Python Dictionary" }, { "code": null, "e": 8084, "s": 8059, "text": "Reverse a string in Java" }, { "code": null, "e": 8100, "s": 8084, "text": "Arrays in C/C++" }, { "code": null, "e": 8123, "s": 8100, "text": "Introduction To PYTHON" } ]