title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Find max or min value in an array of primitives using Java - GeeksforGeeks
|
04 Nov, 2020
Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“. To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods. But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function.
Note: “The array you are are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter.
Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”
Java
// Java code to demonstrate how to// extract minimum and maximum number// in 1 line.import java.util.Arrays;import java.util.Collections; public class MinNMax { public static void main(String[] args) { // Initializing array of integers Integer[] num = { 2, 4, 7, 5, 9 }; // using Collections.min() to // find minimum element // using only 1 line. int min = Collections.min(Arrays.asList(num)); // using Collections.max() // to find maximum element // using only 1 line. int max = Collections.max(Arrays.asList(num)); // printing minimum and maximum numbers System.out.println("Minimum number of array is : " + min); System.out.println("Maximum number of array is : " + max); }}
Minimum number of array is : 2
Maximum number of array is : 9
This article is contributed by Astha Tyagi. 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.
Johnpk
mchac7
parascoding
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 24659,
"s": 24631,
"text": "\n04 Nov, 2020"
},
{
"code": null,
"e": 25295,
"s": 24659,
"text": "Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“. To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods. But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function."
},
{
"code": null,
"e": 25498,
"s": 25295,
"text": "Note: “The array you are are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter. "
},
{
"code": null,
"e": 25633,
"s": 25498,
"text": "Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”"
},
{
"code": null,
"e": 25638,
"s": 25633,
"text": "Java"
},
{
"code": "// Java code to demonstrate how to// extract minimum and maximum number// in 1 line.import java.util.Arrays;import java.util.Collections; public class MinNMax { public static void main(String[] args) { // Initializing array of integers Integer[] num = { 2, 4, 7, 5, 9 }; // using Collections.min() to // find minimum element // using only 1 line. int min = Collections.min(Arrays.asList(num)); // using Collections.max() // to find maximum element // using only 1 line. int max = Collections.max(Arrays.asList(num)); // printing minimum and maximum numbers System.out.println(\"Minimum number of array is : \" + min); System.out.println(\"Maximum number of array is : \" + max); }}",
"e": 26472,
"s": 25638,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26472,
"text": "Minimum number of array is : 2\nMaximum number of array is : 9\n"
},
{
"code": null,
"e": 26959,
"s": 26535,
"text": "This article is contributed by Astha Tyagi. 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. "
},
{
"code": null,
"e": 26966,
"s": 26959,
"text": "Johnpk"
},
{
"code": null,
"e": 26973,
"s": 26966,
"text": "mchac7"
},
{
"code": null,
"e": 26985,
"s": 26973,
"text": "parascoding"
},
{
"code": null,
"e": 27005,
"s": 26985,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 27017,
"s": 27005,
"text": "Java-Arrays"
},
{
"code": null,
"e": 27022,
"s": 27017,
"text": "Java"
},
{
"code": null,
"e": 27027,
"s": 27022,
"text": "Java"
},
{
"code": null,
"e": 27125,
"s": 27027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27176,
"s": 27125,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27191,
"s": 27176,
"text": "Stream In Java"
},
{
"code": null,
"e": 27221,
"s": 27191,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27240,
"s": 27221,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27271,
"s": 27240,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27289,
"s": 27271,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27321,
"s": 27289,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27341,
"s": 27321,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27365,
"s": 27341,
"text": "Singleton Class in Java"
}
] |
Check if one of the numbers is one's complement of the other - GeeksforGeeks
|
28 Apr, 2021
Given two non-negative integers a and b. The problem is to check if one of the two numbers is 1’s complement of the other. The ones’ complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa).
Examples:
Input : a = 10, b = 5
Output : Yes
(10)10 = (1010)2
1's complement of 10 is
= (0101)2 = (101)2 = (5)10
Input : a = 1, b = 14
Output : Yes
(14)10 = (1110)2
1's complement of 14 is
= (0001)2 = (1)2 = (1)10
Approach: Following are the steps:
Calculate n = a ^ b.Check whether all bits are set in the binary representation of n. Refer to this post.
Calculate n = a ^ b.
Check whether all bits are set in the binary representation of n. Refer to this post.
CPP
Java
Python3
C#
PHP
Javascript
// C++ implementation to check if one of the two// numbers is one's complement of the other#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set// or not in the binary representation of 'n'bool areAllBitsSet(unsigned int n){ // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false;} // function to check if one of the two numbers// is one's complement of the otherbool isOnesComplementOfOther(unsigned int a, unsigned int b){ return areAllBitsSet(a ^ b);} // Driver program to test aboveint main(){ unsigned int a = 10, b = 5; if (isOnesComplementOfOther(a,b)) cout << "Yes"; else cout << "No"; return 0; }
// Java implementation to// check if one of the two// numbers is one's complement// of the other import java.util.*;import java.lang.*; public class GfG{ // function to check // if all the bits are set // or not in the binary // representation of 'n' public static boolean areAllBitsSet(long n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other public static boolean isOnesComplementOfOther(long a, long b) { return areAllBitsSet(a ^ b); } // Driver function public static void main(String argc[]){ long a = 10, b = 5; if (isOnesComplementOfOther(a,b)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by Sagar Shukla
# Python3 implementation to# check if one of the two# numbers is one's complement# of the other # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return False; # if True, then all bits are set if (((n + 1) & n) == 0): return True; # else all bits are not set return False; # function to check if one# of the two numbers is# one's complement of the otherdef isOnesComplementOfOther(a, b): return areAllBitsSet(a ^ b) # Driver programa = 1b = 14if (isOnesComplementOfOther(a, b)): print ("Yes")else: print ("No") # This code is contributed by# Saloni Gupta 4
// C# implementation to check// if one of the two numbers is// one's complement of the otherusing System; class GFG { // function to check // if all the bits are set // or not in the binary // representation of 'n' public static bool areAllBitsSet(long n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other public static bool isOnesComplementOfOther(long a, long b) { return areAllBitsSet(a ^ b); } // Driver function public static void Main() { long a = 10, b = 5; if (isOnesComplementOfOther(a, b)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Sam007
<?php// PHP implementation to// check if one of the two// numbers is one's complement// of the other // function to check if// all the bits are set// or not in the binary// representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return false; // if true, then all // bits are set if ((($n + 1) & $n) == 0) return true; // else all bits // are not set return false;} // function to check if// one of the two numbers// is one's complement of// the otherfunction isOnesComplementOfOther($a, $b){ return areAllBitsSet($a ^ $b);} // Driver Code $a = 10; $b = 5; if (isOnesComplementOfOther($a, $b)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?>
<script> // Javascript implementation to// check if one of the two// numbers is one's complement// of the other // function to check // if all the bits are set // or not in the binary // representation of 'n' function areAllBitsSet(n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other function isOnesComplementOfOther(a, b) { return areAllBitsSet(a ^ b); } // Driver code let a = 10, b = 5; if (isOnesComplementOfOther(a,b)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
YouTubeGeeksforGeeks506K subscribersCheck if one of the numbers is one’s complement of the other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DHePoeaprNY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
sanjoy_62
Bitwise-XOR
complement
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
Find the element that appears once
1's and 2's complement of a Binary Number
|
[
{
"code": null,
"e": 26475,
"s": 26447,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26777,
"s": 26475,
"text": "Given two non-negative integers a and b. The problem is to check if one of the two numbers is 1’s complement of the other. The ones’ complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa)."
},
{
"code": null,
"e": 26788,
"s": 26777,
"text": "Examples: "
},
{
"code": null,
"e": 26993,
"s": 26788,
"text": "Input : a = 10, b = 5\nOutput : Yes\n(10)10 = (1010)2\n1's complement of 10 is\n= (0101)2 = (101)2 = (5)10\n\nInput : a = 1, b = 14\nOutput : Yes\n(14)10 = (1110)2\n1's complement of 14 is\n= (0001)2 = (1)2 = (1)10"
},
{
"code": null,
"e": 27029,
"s": 26993,
"text": "Approach: Following are the steps: "
},
{
"code": null,
"e": 27136,
"s": 27029,
"text": "Calculate n = a ^ b.Check whether all bits are set in the binary representation of n. Refer to this post. "
},
{
"code": null,
"e": 27157,
"s": 27136,
"text": "Calculate n = a ^ b."
},
{
"code": null,
"e": 27244,
"s": 27157,
"text": "Check whether all bits are set in the binary representation of n. Refer to this post. "
},
{
"code": null,
"e": 27248,
"s": 27244,
"text": "CPP"
},
{
"code": null,
"e": 27253,
"s": 27248,
"text": "Java"
},
{
"code": null,
"e": 27261,
"s": 27253,
"text": "Python3"
},
{
"code": null,
"e": 27264,
"s": 27261,
"text": "C#"
},
{
"code": null,
"e": 27268,
"s": 27264,
"text": "PHP"
},
{
"code": null,
"e": 27279,
"s": 27268,
"text": "Javascript"
},
{
"code": "// C++ implementation to check if one of the two// numbers is one's complement of the other#include <bits/stdc++.h>using namespace std; // function to check if all the bits are set// or not in the binary representation of 'n'bool areAllBitsSet(unsigned int n){ // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false;} // function to check if one of the two numbers// is one's complement of the otherbool isOnesComplementOfOther(unsigned int a, unsigned int b){ return areAllBitsSet(a ^ b);} // Driver program to test aboveint main(){ unsigned int a = 10, b = 5; if (isOnesComplementOfOther(a,b)) cout << \"Yes\"; else cout << \"No\"; return 0; }",
"e": 28142,
"s": 27279,
"text": null
},
{
"code": "// Java implementation to// check if one of the two// numbers is one's complement// of the other import java.util.*;import java.lang.*; public class GfG{ // function to check // if all the bits are set // or not in the binary // representation of 'n' public static boolean areAllBitsSet(long n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other public static boolean isOnesComplementOfOther(long a, long b) { return areAllBitsSet(a ^ b); } // Driver function public static void main(String argc[]){ long a = 10, b = 5; if (isOnesComplementOfOther(a,b)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } } // This code is contributed by Sagar Shukla",
"e": 29230,
"s": 28142,
"text": null
},
{
"code": "# Python3 implementation to# check if one of the two# numbers is one's complement# of the other # function to check if# all the bits are set# or not in the binary# representation of 'n'def areAllBitsSet(n): # all bits are not set if (n == 0): return False; # if True, then all bits are set if (((n + 1) & n) == 0): return True; # else all bits are not set return False; # function to check if one# of the two numbers is# one's complement of the otherdef isOnesComplementOfOther(a, b): return areAllBitsSet(a ^ b) # Driver programa = 1b = 14if (isOnesComplementOfOther(a, b)): print (\"Yes\")else: print (\"No\") # This code is contributed by# Saloni Gupta 4",
"e": 29944,
"s": 29230,
"text": null
},
{
"code": "// C# implementation to check// if one of the two numbers is// one's complement of the otherusing System; class GFG { // function to check // if all the bits are set // or not in the binary // representation of 'n' public static bool areAllBitsSet(long n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other public static bool isOnesComplementOfOther(long a, long b) { return areAllBitsSet(a ^ b); } // Driver function public static void Main() { long a = 10, b = 5; if (isOnesComplementOfOther(a, b)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Sam007",
"e": 30960,
"s": 29944,
"text": null
},
{
"code": "<?php// PHP implementation to// check if one of the two// numbers is one's complement// of the other // function to check if// all the bits are set// or not in the binary// representation of 'n'function areAllBitsSet($n){ // all bits are not set if ($n == 0) return false; // if true, then all // bits are set if ((($n + 1) & $n) == 0) return true; // else all bits // are not set return false;} // function to check if// one of the two numbers// is one's complement of// the otherfunction isOnesComplementOfOther($a, $b){ return areAllBitsSet($a ^ $b);} // Driver Code $a = 10; $b = 5; if (isOnesComplementOfOther($a, $b)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>",
"e": 31774,
"s": 30960,
"text": null
},
{
"code": "<script> // Javascript implementation to// check if one of the two// numbers is one's complement// of the other // function to check // if all the bits are set // or not in the binary // representation of 'n' function areAllBitsSet(n) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } // function to check if // one of the two numbers // is one's complement // of the other function isOnesComplementOfOther(a, b) { return areAllBitsSet(a ^ b); } // Driver code let a = 10, b = 5; if (isOnesComplementOfOther(a,b)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 32667,
"s": 31774,
"text": null
},
{
"code": null,
"e": 32676,
"s": 32667,
"text": "Output: "
},
{
"code": null,
"e": 32680,
"s": 32676,
"text": "Yes"
},
{
"code": null,
"e": 33539,
"s": 32680,
"text": "YouTubeGeeksforGeeks506K subscribersCheck if one of the numbers is one’s complement of the other | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DHePoeaprNY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 33965,
"s": 33539,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33970,
"s": 33965,
"text": "vt_m"
},
{
"code": null,
"e": 33980,
"s": 33970,
"text": "sanjoy_62"
},
{
"code": null,
"e": 33992,
"s": 33980,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 34003,
"s": 33992,
"text": "complement"
},
{
"code": null,
"e": 34013,
"s": 34003,
"text": "Bit Magic"
},
{
"code": null,
"e": 34023,
"s": 34013,
"text": "Bit Magic"
},
{
"code": null,
"e": 34121,
"s": 34023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34151,
"s": 34121,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 34197,
"s": 34151,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 34237,
"s": 34197,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 34290,
"s": 34237,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 34341,
"s": 34290,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 34392,
"s": 34341,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34435,
"s": 34392,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 34451,
"s": 34435,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 34486,
"s": 34451,
"text": "Find the element that appears once"
}
] |
Data Warehouse - Overview
|
A Data Warehouse consists of data from multiple heterogeneous data sources and is used for analytical reporting and decision making. Data Warehouse is a central place where data is stored from different data sources and applications.
The term Data Warehouse was first invented by Bill Inmom in 1990. A Data Warehouse is always kept separate from an Operational Database.
The data in a DW system is loaded from operational transaction systems like −
Sales
Marketing
HR
SCM, etc.
It may pass through operational data store or other transformations before it is loaded to the DW system for information processing.
A Data Warehouse is used for reporting and analyzing of information and stores both historical and current data. The data in DW system is used for Analytical reporting, which is later used by Business Analysts, Sales Managers or Knowledge workers for decision-making.
In the above image, you can see that the data is coming from multiple heterogeneous data sources to a Data Warehouse. Common data sources for a data warehouse includes −
Operational databases
SAP and non-SAP Applications
Flat Files (xls, csv, txt files)
Data in data warehouse is accessed by BI (Business Intelligence) users for Analytical Reporting, Data Mining and Analysis. This is used for decision making by Business Users, Sales Manager, Analysts to define future strategy.
It is a central data repository where data is stored from one or more heterogeneous data sources. A DW system stores both current and historical data. Normally a DW system stores 5-10 years of historical data. A DW system is always kept separate from an operational transaction system.
The data in a DW system is used for different types of analytical reporting range from Quarterly to Annual comparison.
The differences between a Data Warehouse and Operational Database are as follows −
An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data.
An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data.
An Operational System contains the current data of an organization and Data warehouse normally contains the historical data.
An Operational System contains the current data of an organization and Data warehouse normally contains the historical data.
An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database.
An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database.
An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement).
An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement).
Data Warehousing involves data cleaning, data integration, and data consolidations. A Data Warehouse has a 3-layer architecture −
It defines how the data comes to a Data Warehouse. It involves various data sources and operational transaction systems, flat files, applications, etc.
It consists of Operational Data Store and Staging area. Staging area is used to perform data cleansing, data transformation and loading data from different sources to a data warehouse. As multiple data sources are available for extraction at different time zones, staging area is used to store the data and later to apply transformations on data.
This is used to perform BI reporting by end users. The data in a DW system is accessed by BI users and used for reporting and analysis.
The following illustration shows the common architecture of a Data Warehouse System.
The following are the key characteristics of a Data Warehouse −
Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc.
Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc.
Integrated − Data from multiple data sources are integrated in a Data Warehouse.
Integrated − Data from multiple data sources are integrated in a Data Warehouse.
Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered.
Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered.
Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc.
Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc.
Firstly, OLTP stands for Online Transaction Processing, while OLAP stands for Online Analytical Processing
In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE.
Whereas, in an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP Data Warehouse System contains current and detailed data and is maintained in the schemas in the entity model (3NF).
For Example −
A Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides faster query processing. OLTP databases contain detailed and current data. The schema used to store OLTP database is the Entity model.
In an OLAP system, there are lesser number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations.
We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all the rows. This is called Aggregation.
There are various Aggregation functions that can be used in an OLAP system like Sum, Avg, Max, Min, etc.
For Example −
SELECT Avg(salary)
FROM employee
WHERE title = 'Programmer';
These are the major differences between an OLAP and an OLTP system.
Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization.
Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization.
Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized.
Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized.
Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used.
Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used.
Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system.
Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system.
Data mart focuses on a single functional area and represents the simplest form of a Data Warehouse. Consider a Data Warehouse that contains data for Sales, Marketing, HR, and Finance. A Data mart focuses on a single functional area like Sales or Marketing.
In the above image, you can see the difference between a Data Warehouse and a data mart.
A fact table represents the measures on which analysis is performed. It also contains foreign keys for the dimension keys.
For example − Every sale is a fact.
The Dimension table represents the characteristics of a dimension. A Customer dimension can have Customer_Name, Phone_No, Sex, etc.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2801,
"s": 2567,
"text": "A Data Warehouse consists of data from multiple heterogeneous data sources and is used for analytical reporting and decision making. Data Warehouse is a central place where data is stored from different data sources and applications."
},
{
"code": null,
"e": 2938,
"s": 2801,
"text": "The term Data Warehouse was first invented by Bill Inmom in 1990. A Data Warehouse is always kept separate from an Operational Database."
},
{
"code": null,
"e": 3016,
"s": 2938,
"text": "The data in a DW system is loaded from operational transaction systems like −"
},
{
"code": null,
"e": 3022,
"s": 3016,
"text": "Sales"
},
{
"code": null,
"e": 3032,
"s": 3022,
"text": "Marketing"
},
{
"code": null,
"e": 3035,
"s": 3032,
"text": "HR"
},
{
"code": null,
"e": 3045,
"s": 3035,
"text": "SCM, etc."
},
{
"code": null,
"e": 3178,
"s": 3045,
"text": "It may pass through operational data store or other transformations before it is loaded to the DW system for information processing."
},
{
"code": null,
"e": 3446,
"s": 3178,
"text": "A Data Warehouse is used for reporting and analyzing of information and stores both historical and current data. The data in DW system is used for Analytical reporting, which is later used by Business Analysts, Sales Managers or Knowledge workers for decision-making."
},
{
"code": null,
"e": 3616,
"s": 3446,
"text": "In the above image, you can see that the data is coming from multiple heterogeneous data sources to a Data Warehouse. Common data sources for a data warehouse includes −"
},
{
"code": null,
"e": 3638,
"s": 3616,
"text": "Operational databases"
},
{
"code": null,
"e": 3667,
"s": 3638,
"text": "SAP and non-SAP Applications"
},
{
"code": null,
"e": 3700,
"s": 3667,
"text": "Flat Files (xls, csv, txt files)"
},
{
"code": null,
"e": 3926,
"s": 3700,
"text": "Data in data warehouse is accessed by BI (Business Intelligence) users for Analytical Reporting, Data Mining and Analysis. This is used for decision making by Business Users, Sales Manager, Analysts to define future strategy."
},
{
"code": null,
"e": 4212,
"s": 3926,
"text": "It is a central data repository where data is stored from one or more heterogeneous data sources. A DW system stores both current and historical data. Normally a DW system stores 5-10 years of historical data. A DW system is always kept separate from an operational transaction system."
},
{
"code": null,
"e": 4331,
"s": 4212,
"text": "The data in a DW system is used for different types of analytical reporting range from Quarterly to Annual comparison."
},
{
"code": null,
"e": 4414,
"s": 4331,
"text": "The differences between a Data Warehouse and Operational Database are as follows −"
},
{
"code": null,
"e": 4629,
"s": 4414,
"text": "An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data."
},
{
"code": null,
"e": 4844,
"s": 4629,
"text": "An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data."
},
{
"code": null,
"e": 4969,
"s": 4844,
"text": "An Operational System contains the current data of an organization and Data warehouse normally contains the historical data."
},
{
"code": null,
"e": 5094,
"s": 4969,
"text": "An Operational System contains the current data of an organization and Data warehouse normally contains the historical data."
},
{
"code": null,
"e": 5271,
"s": 5094,
"text": "An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database."
},
{
"code": null,
"e": 5448,
"s": 5271,
"text": "An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database."
},
{
"code": null,
"e": 5626,
"s": 5448,
"text": "An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement)."
},
{
"code": null,
"e": 5804,
"s": 5626,
"text": "An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement)."
},
{
"code": null,
"e": 5934,
"s": 5804,
"text": "Data Warehousing involves data cleaning, data integration, and data consolidations. A Data Warehouse has a 3-layer architecture −"
},
{
"code": null,
"e": 6086,
"s": 5934,
"text": "It defines how the data comes to a Data Warehouse. It involves various data sources and operational transaction systems, flat files, applications, etc."
},
{
"code": null,
"e": 6433,
"s": 6086,
"text": "It consists of Operational Data Store and Staging area. Staging area is used to perform data cleansing, data transformation and loading data from different sources to a data warehouse. As multiple data sources are available for extraction at different time zones, staging area is used to store the data and later to apply transformations on data."
},
{
"code": null,
"e": 6569,
"s": 6433,
"text": "This is used to perform BI reporting by end users. The data in a DW system is accessed by BI users and used for reporting and analysis."
},
{
"code": null,
"e": 6654,
"s": 6569,
"text": "The following illustration shows the common architecture of a Data Warehouse System."
},
{
"code": null,
"e": 6718,
"s": 6654,
"text": "The following are the key characteristics of a Data Warehouse −"
},
{
"code": null,
"e": 6876,
"s": 6718,
"text": "Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc."
},
{
"code": null,
"e": 7034,
"s": 6876,
"text": "Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc."
},
{
"code": null,
"e": 7115,
"s": 7034,
"text": "Integrated − Data from multiple data sources are integrated in a Data Warehouse."
},
{
"code": null,
"e": 7196,
"s": 7115,
"text": "Integrated − Data from multiple data sources are integrated in a Data Warehouse."
},
{
"code": null,
"e": 7313,
"s": 7196,
"text": "Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered."
},
{
"code": null,
"e": 7430,
"s": 7313,
"text": "Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered."
},
{
"code": null,
"e": 7635,
"s": 7430,
"text": "Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc."
},
{
"code": null,
"e": 7840,
"s": 7635,
"text": "Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc."
},
{
"code": null,
"e": 7947,
"s": 7840,
"text": "Firstly, OLTP stands for Online Transaction Processing, while OLAP stands for Online Analytical Processing"
},
{
"code": null,
"e": 8056,
"s": 7947,
"text": "In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE."
},
{
"code": null,
"e": 8436,
"s": 8056,
"text": "Whereas, in an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP Data Warehouse System contains current and detailed data and is maintained in the schemas in the entity model (3NF)."
},
{
"code": null,
"e": 8450,
"s": 8436,
"text": "For Example −"
},
{
"code": null,
"e": 8727,
"s": 8450,
"text": "A Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides faster query processing. OLTP databases contain detailed and current data. The schema used to store OLTP database is the Entity model."
},
{
"code": null,
"e": 8900,
"s": 8727,
"text": "In an OLAP system, there are lesser number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations."
},
{
"code": null,
"e": 9175,
"s": 8900,
"text": "We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all the rows. This is called Aggregation."
},
{
"code": null,
"e": 9280,
"s": 9175,
"text": "There are various Aggregation functions that can be used in an OLAP system like Sum, Avg, Max, Min, etc."
},
{
"code": null,
"e": 9294,
"s": 9280,
"text": "For Example −"
},
{
"code": null,
"e": 9356,
"s": 9294,
"text": "SELECT Avg(salary)\nFROM employee\nWHERE title = 'Programmer';\n"
},
{
"code": null,
"e": 9424,
"s": 9356,
"text": "These are the major differences between an OLAP and an OLTP system."
},
{
"code": null,
"e": 9547,
"s": 9424,
"text": "Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization."
},
{
"code": null,
"e": 9670,
"s": 9547,
"text": "Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization."
},
{
"code": null,
"e": 9815,
"s": 9670,
"text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized."
},
{
"code": null,
"e": 9960,
"s": 9815,
"text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized."
},
{
"code": null,
"e": 10070,
"s": 9960,
"text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used."
},
{
"code": null,
"e": 10180,
"s": 10070,
"text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used."
},
{
"code": null,
"e": 10286,
"s": 10180,
"text": "Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system."
},
{
"code": null,
"e": 10392,
"s": 10286,
"text": "Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system."
},
{
"code": null,
"e": 10649,
"s": 10392,
"text": "Data mart focuses on a single functional area and represents the simplest form of a Data Warehouse. Consider a Data Warehouse that contains data for Sales, Marketing, HR, and Finance. A Data mart focuses on a single functional area like Sales or Marketing."
},
{
"code": null,
"e": 10738,
"s": 10649,
"text": "In the above image, you can see the difference between a Data Warehouse and a data mart."
},
{
"code": null,
"e": 10861,
"s": 10738,
"text": "A fact table represents the measures on which analysis is performed. It also contains foreign keys for the dimension keys."
},
{
"code": null,
"e": 10897,
"s": 10861,
"text": "For example − Every sale is a fact."
},
{
"code": null,
"e": 11029,
"s": 10897,
"text": "The Dimension table represents the characteristics of a dimension. A Customer dimension can have Customer_Name, Phone_No, Sex, etc."
},
{
"code": null,
"e": 11036,
"s": 11029,
"text": " Print"
},
{
"code": null,
"e": 11047,
"s": 11036,
"text": " Add Notes"
}
] |
Access Modifiers in C#
|
Access Modifiers specifies the scope of variable and functions in C#. The following are the access modifiers used provided by C#:
The public modifier sets no restriction on the access of members.
Access limited to the derived class or class definition.
The Internal access modifier access within the program that has its declaration.
It has both the access specifiers provided by protected and internal access modifiers.
Limited only inside the class in which it is declared. The members specified as private cannot be accessed outside the class.
Let us see an example of protected access modifier, accessing the protected members −
Live Demo
using System;
namespace MySpecifiers {
class Demo {
protected string name = "Website";
protected void Display(string str) {
Console.WriteLine("Tabs: " + str);
}
}
class Test : Demo {
static void Main(string[] args) {
Test t = new Test();
Console.WriteLine("Details: " + t.name);
t.Display("Product");
t.Display("Services");
t.Display("Tools");
t.Display("Plugins");
}
}
}
Details: Website
Tabs: Product
Tabs: Services
Tabs: Tools
Tabs: Plugins
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Access Modifiers specifies the scope of variable and functions in C#. The following are the access modifiers used provided by C#:"
},
{
"code": null,
"e": 1258,
"s": 1192,
"text": "The public modifier sets no restriction on the access of members."
},
{
"code": null,
"e": 1315,
"s": 1258,
"text": "Access limited to the derived class or class definition."
},
{
"code": null,
"e": 1396,
"s": 1315,
"text": "The Internal access modifier access within the program that has its declaration."
},
{
"code": null,
"e": 1483,
"s": 1396,
"text": "It has both the access specifiers provided by protected and internal access modifiers."
},
{
"code": null,
"e": 1609,
"s": 1483,
"text": "Limited only inside the class in which it is declared. The members specified as private cannot be accessed outside the class."
},
{
"code": null,
"e": 1695,
"s": 1609,
"text": "Let us see an example of protected access modifier, accessing the protected members −"
},
{
"code": null,
"e": 1705,
"s": 1695,
"text": "Live Demo"
},
{
"code": null,
"e": 2183,
"s": 1705,
"text": "using System;\nnamespace MySpecifiers {\n class Demo {\n protected string name = \"Website\";\n protected void Display(string str) {\n Console.WriteLine(\"Tabs: \" + str);\n }\n }\n\n class Test : Demo {\n static void Main(string[] args) {\n Test t = new Test();\n Console.WriteLine(\"Details: \" + t.name);\n t.Display(\"Product\");\n t.Display(\"Services\");\n t.Display(\"Tools\");\n t.Display(\"Plugins\");\n }\n }\n}"
},
{
"code": null,
"e": 2255,
"s": 2183,
"text": "Details: Website\nTabs: Product\nTabs: Services\nTabs: Tools\nTabs: Plugins"
}
] |
Minimum Swaps to Sort | Practice | GeeksforGeeks
|
Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order.
Example 1:
Input:
nums = {2, 8, 5, 4}
Output:
1
Explaination:
swap 8 with 4.
Example 2:
Input:
nums = {10, 19, 6, 3, 5}
Output:
2
Explaination:
swap 10 with 3 and swap 19 with 5.
Your Task:
You do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0.
Expected Time Complexity: O(nlogn)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 105
1 ≤ numsi ≤ 106
0
binnukaniki1234 days ago
class Pair{ int n,m; public Pair(int m,int n) { this.m=m; this.n=n; }}class Sortbyroll implements Comparator<Pair> { // Used for sorting in ascending order of // roll number public int compare(Pair a, Pair b) { return a.m - b.m; }}
class Solution{ //Function to find the minimum number of swaps required to sort the array. public int minSwaps(int nums[]) { // Code here Pair[]arr=new Pair[nums.length]; boolean[] vis=new boolean[nums.length]; for(int i=0;i<nums.length;i++) { arr[i]=new Pair(nums[i],i); } Arrays.sort(arr, new Sortbyroll()); int ans=0; for(int i=0;i<nums.length;i++) { int count=0; if(arr[i].m==nums[i]||vis[i]==true) continue; int j=i; while(vis[j]==false) { vis[j]=true; count++; j=arr[j].n; } ans+=(count-1); } return ans; } }
0
ashishaks02114 days ago
int minSwaps(vector<int>&nums)
{
map<int,int> mp;
for(int i = 0;i<nums.size();i++)
mp[nums[i]] = i;
sort(nums.begin(),nums.end());
int ans = 0;
for(int i = 0;i<nums.size();i++){
while(mp[nums[i]]!=i){
ans++;
int temp = nums[i];
nums[i] = nums[mp[temp]];
nums[mp[temp]] = temp;
}
}
return ans;
}
0
harshscode1 week ago
idea is first sort and compare to unsort if position is mismatch then swap and count...............
int minSwaps(vector<int>&nums){ vector<pair<int,int>> v(nums.size()); for(int i=0;i<nums.size();i++) v[i]={nums[i],i}; sort(v.begin(),v.end()); int cnt=0; for(int i=0;i<nums.size();i++) { if(i==v[i].second) continue; else { cnt++; swap(v[i],v[v[i].second]); i--; } } return cnt; }
0
shubham211019972 weeks ago
int minSwaps(vector<int>&nums)
{
vector<pair<int,int>> vec;
int n=nums.size();
for(int i=0;i<n;i++)
{
vec.push_back({nums[i],i});
}
sort(vec.begin(),vec.end());
vector<bool>vis(n,0);
int ans=0;
for(int i=0;i<n;i++)
{
int clen=0;
if(vis[i]==1||vec[i].second==i)
continue;
int j=i;
while(vis[j]==false)
{
vis[j]=true;
clen++;
j=vec[j].second;
}
ans+=clen-1;
}
return ans;
}
0
atharvapatil68482 weeks ago
int count = 0;
transfer all elements in new array a[] ,sort a,compare both the array if elements are changed count++,return count/2;
what is the problem in this solution?
0
user_udl52 weeks ago
def minSwaps(self, nums): temp = sorted(nums) mapp = {} swaps = 0 num_len = len(nums) for i in range(num_len): mapp[nums[i]] = i for i in range(num_len): if nums[i] == temp[i]: # element already in their place continue else: init = nums[i] #swapping the elements of input array to their correct pos nums[i], nums[mapp[temp[i]]] = nums[mapp[temp[i]]], nums[i] swaps += 1 # updating map values after swapping mapp[init] = mapp[temp[i]] mapp[temp[i]] = i return swaps # in the above approach im trying to sort the input array by the help # of sorted copy of input array(temp) and a dictionary which is storing the # input array elements as key and its index as values associated with key #
0
amanjugran12 weeks ago
Simple python Solution (All test cases passed)
def minSwaps(self, nums): arr = sorted(nums) dic={} for i in range(len(nums)): dic[nums[i]] = i c=0 for i in range(len(nums)): if arr[i] != nums[i]: c+=1 index = dic[arr[i]] index2 = dic[nums[i]] dic[arr[i]] = index2 dic[nums[i]] = index t = nums[index] nums[index]=nums[index2] nums[index2]=t return c
+1
mayank20213 weeks ago
TLE : 11/50 passed.. any suggestion in this code ? int minSwaps(vector<int>&nums){ int count=0, i=0, j=nums.size()-1, k , currentmin=INT_MAX , currentmax=INT_MIN ; int currentminindex=-1, currentmaxindex=-1,l; while (i<j) { for(l=i ; l<=j ; l++) { if(nums[l] < currentmin ) { currentmin=nums[l]; currentminindex=l; } if(nums[l] > currentmax) {currentmax =nums[l]; currentmaxindex=l; } } if(nums[i] != currentmin ) { if(nums[i]==currentmax) currentmaxindex=currentminindex; swap(nums[i], nums[currentminindex]); count++; } i++; if(nums[j] !=currentmax) { swap(nums[j], nums[currentmaxindex]); count++; } j--; currentmin=INT_MAX , currentmax=INT_MIN; } return count; }
0
for_the_luv_of_coding3 weeks ago
https://www.hackerrank.com/contests/aasf-bi-weekly-contest/challenges/big-head-is-worthy/problem
0
anupbagade20144 weeks ago
Python Solution
class Solution:
#Function to find the minimum number of swaps required to sort the array.
def minSwaps(self, nums):
nums_sorted = sorted(nums)
swaps_count = 0
# create dictionary
nums_dict = dict()
for i in range(len(nums)):
nums_dict[nums[i]] = i
for i in range(len(nums)):
if nums_sorted[i] != nums[i]:
idx = nums_dict[nums_sorted[i]]
nums[i] , nums[idx] = nums[idx], nums[i]
nums_dict[nums[i]] = i
nums_dict[nums[idx]] = idx
swaps_count += 1
#print(swaps_count)
return swaps_count
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 367,
"s": 238,
"text": "Given an array of n distinct elements. Find the minimum number of swaps required to sort the array in strictly increasing order."
},
{
"code": null,
"e": 379,
"s": 367,
"text": "\nExample 1:"
},
{
"code": null,
"e": 445,
"s": 379,
"text": "Input:\nnums = {2, 8, 5, 4}\nOutput:\n1\nExplaination:\nswap 8 with 4."
},
{
"code": null,
"e": 456,
"s": 445,
"text": "Example 2:"
},
{
"code": null,
"e": 547,
"s": 456,
"text": "Input:\nnums = {10, 19, 6, 3, 5}\nOutput:\n2\nExplaination:\nswap 10 with 3 and swap 19 with 5."
},
{
"code": null,
"e": 828,
"s": 547,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function minSwaps() which takes the nums as input parameter and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0. "
},
{
"code": null,
"e": 895,
"s": 828,
"text": "\nExpected Time Complexity: O(nlogn)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 937,
"s": 895,
"text": "\nConstraints:\n1 ≤ n ≤ 105\n1 ≤ numsi ≤ 106"
},
{
"code": null,
"e": 939,
"s": 937,
"text": "0"
},
{
"code": null,
"e": 964,
"s": 939,
"text": "binnukaniki1234 days ago"
},
{
"code": null,
"e": 1232,
"s": 964,
"text": "class Pair{ int n,m; public Pair(int m,int n) { this.m=m; this.n=n; }}class Sortbyroll implements Comparator<Pair> { // Used for sorting in ascending order of // roll number public int compare(Pair a, Pair b) { return a.m - b.m; }}"
},
{
"code": null,
"e": 1986,
"s": 1232,
"text": "class Solution{ //Function to find the minimum number of swaps required to sort the array. public int minSwaps(int nums[]) { // Code here Pair[]arr=new Pair[nums.length]; boolean[] vis=new boolean[nums.length]; for(int i=0;i<nums.length;i++) { arr[i]=new Pair(nums[i],i); } Arrays.sort(arr, new Sortbyroll()); int ans=0; for(int i=0;i<nums.length;i++) { int count=0; if(arr[i].m==nums[i]||vis[i]==true) continue; int j=i; while(vis[j]==false) { vis[j]=true; count++; j=arr[j].n; } ans+=(count-1); } return ans; } }"
},
{
"code": null,
"e": 1988,
"s": 1986,
"text": "0"
},
{
"code": null,
"e": 2012,
"s": 1988,
"text": "ashishaks02114 days ago"
},
{
"code": null,
"e": 2408,
"s": 2012,
"text": "int minSwaps(vector<int>&nums)\n\t{\n\t map<int,int> mp;\n\t for(int i = 0;i<nums.size();i++)\n\t mp[nums[i]] = i;\n\t sort(nums.begin(),nums.end());\n\t int ans = 0;\n\t for(int i = 0;i<nums.size();i++){\n\t while(mp[nums[i]]!=i){\n\t ans++;\n\t int temp = nums[i];\n\t nums[i] = nums[mp[temp]];\n\t nums[mp[temp]] = temp;\n\t }\n\t }\n\t return ans;\n\t}"
},
{
"code": null,
"e": 2410,
"s": 2408,
"text": "0"
},
{
"code": null,
"e": 2431,
"s": 2410,
"text": "harshscode1 week ago"
},
{
"code": null,
"e": 2531,
"s": 2431,
"text": "idea is first sort and compare to unsort if position is mismatch then swap and count..............."
},
{
"code": null,
"e": 2927,
"s": 2533,
"text": " int minSwaps(vector<int>&nums){ vector<pair<int,int>> v(nums.size()); for(int i=0;i<nums.size();i++) v[i]={nums[i],i}; sort(v.begin(),v.end()); int cnt=0; for(int i=0;i<nums.size();i++) { if(i==v[i].second) continue; else { cnt++; swap(v[i],v[v[i].second]); i--; } } return cnt; }"
},
{
"code": null,
"e": 2929,
"s": 2927,
"text": "0"
},
{
"code": null,
"e": 2956,
"s": 2929,
"text": "shubham211019972 weeks ago"
},
{
"code": null,
"e": 3477,
"s": 2956,
"text": " int minSwaps(vector<int>&nums)\n{\n vector<pair<int,int>> vec;\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n vec.push_back({nums[i],i});\n }\n sort(vec.begin(),vec.end());\n vector<bool>vis(n,0);\n int ans=0;\n for(int i=0;i<n;i++)\n { \n int clen=0;\n if(vis[i]==1||vec[i].second==i)\n continue;\n \n int j=i;\n while(vis[j]==false)\n {\n vis[j]=true;\n clen++;\n j=vec[j].second;\n }\n ans+=clen-1;\n }\n \n return ans;\n}"
},
{
"code": null,
"e": 3479,
"s": 3477,
"text": "0"
},
{
"code": null,
"e": 3507,
"s": 3479,
"text": "atharvapatil68482 weeks ago"
},
{
"code": null,
"e": 3522,
"s": 3507,
"text": "int count = 0;"
},
{
"code": null,
"e": 3640,
"s": 3522,
"text": "transfer all elements in new array a[] ,sort a,compare both the array if elements are changed count++,return count/2;"
},
{
"code": null,
"e": 3678,
"s": 3640,
"text": "what is the problem in this solution?"
},
{
"code": null,
"e": 3680,
"s": 3678,
"text": "0"
},
{
"code": null,
"e": 3701,
"s": 3680,
"text": "user_udl52 weeks ago"
},
{
"code": null,
"e": 4609,
"s": 3701,
"text": "def minSwaps(self, nums): temp = sorted(nums) mapp = {} swaps = 0 num_len = len(nums) for i in range(num_len): mapp[nums[i]] = i for i in range(num_len): if nums[i] == temp[i]: # element already in their place continue else: init = nums[i] #swapping the elements of input array to their correct pos nums[i], nums[mapp[temp[i]]] = nums[mapp[temp[i]]], nums[i] swaps += 1 # updating map values after swapping mapp[init] = mapp[temp[i]] mapp[temp[i]] = i return swaps # in the above approach im trying to sort the input array by the help # of sorted copy of input array(temp) and a dictionary which is storing the # input array elements as key and its index as values associated with key # "
},
{
"code": null,
"e": 4611,
"s": 4609,
"text": "0"
},
{
"code": null,
"e": 4634,
"s": 4611,
"text": "amanjugran12 weeks ago"
},
{
"code": null,
"e": 4681,
"s": 4634,
"text": "Simple python Solution (All test cases passed)"
},
{
"code": null,
"e": 5058,
"s": 4683,
"text": "def minSwaps(self, nums): arr = sorted(nums) dic={} for i in range(len(nums)): dic[nums[i]] = i c=0 for i in range(len(nums)): if arr[i] != nums[i]: c+=1 index = dic[arr[i]] index2 = dic[nums[i]] dic[arr[i]] = index2 dic[nums[i]] = index t = nums[index] nums[index]=nums[index2] nums[index2]=t return c"
},
{
"code": null,
"e": 5061,
"s": 5058,
"text": "+1"
},
{
"code": null,
"e": 5083,
"s": 5061,
"text": "mayank20213 weeks ago"
},
{
"code": null,
"e": 6101,
"s": 5083,
"text": "TLE : 11/50 passed.. any suggestion in this code ? int minSwaps(vector<int>&nums){ int count=0, i=0, j=nums.size()-1, k , currentmin=INT_MAX , currentmax=INT_MIN ; int currentminindex=-1, currentmaxindex=-1,l; while (i<j) { for(l=i ; l<=j ; l++) { if(nums[l] < currentmin ) { currentmin=nums[l]; currentminindex=l; } if(nums[l] > currentmax) {currentmax =nums[l]; currentmaxindex=l; } } if(nums[i] != currentmin ) { if(nums[i]==currentmax) currentmaxindex=currentminindex; swap(nums[i], nums[currentminindex]); count++; } i++; if(nums[j] !=currentmax) { swap(nums[j], nums[currentmaxindex]); count++; } j--; currentmin=INT_MAX , currentmax=INT_MIN; } return count; }"
},
{
"code": null,
"e": 6103,
"s": 6101,
"text": "0"
},
{
"code": null,
"e": 6136,
"s": 6103,
"text": "for_the_luv_of_coding3 weeks ago"
},
{
"code": null,
"e": 6233,
"s": 6136,
"text": "https://www.hackerrank.com/contests/aasf-bi-weekly-contest/challenges/big-head-is-worthy/problem"
},
{
"code": null,
"e": 6235,
"s": 6233,
"text": "0"
},
{
"code": null,
"e": 6261,
"s": 6235,
"text": "anupbagade20144 weeks ago"
},
{
"code": null,
"e": 6277,
"s": 6261,
"text": "Python Solution"
},
{
"code": null,
"e": 6927,
"s": 6277,
"text": "class Solution:\n \n #Function to find the minimum number of swaps required to sort the array.\n\tdef minSwaps(self, nums):\n\t\tnums_sorted = sorted(nums)\n\t\tswaps_count = 0\n\t\t\n # create dictionary\n nums_dict = dict()\n for i in range(len(nums)):\n nums_dict[nums[i]] = i\n\t\t\n\t\tfor i in range(len(nums)):\n\t\t \n\t\t if nums_sorted[i] != nums[i]:\n\t\t idx = nums_dict[nums_sorted[i]]\n\t\t nums[i] , nums[idx] = nums[idx], nums[i]\n\t\t nums_dict[nums[i]] = i\n\t\t nums_dict[nums[idx]] = idx\n\t\t swaps_count += 1\n\t\t \n #print(swaps_count)\n \n return swaps_count\n "
},
{
"code": null,
"e": 7073,
"s": 6927,
"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": 7109,
"s": 7073,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7119,
"s": 7109,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7129,
"s": 7119,
"text": "\nContest\n"
},
{
"code": null,
"e": 7192,
"s": 7129,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7340,
"s": 7192,
"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": 7548,
"s": 7340,
"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": 7654,
"s": 7548,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Build a Dash Web App for Binary Classification Model Selection | by Taylor Plumer | Towards Data Science
|
This post demonstrates a use case of a classifiers-dash web app tool I developed to automatically curate a compilation of machine learning visual diagnostics for binary classification problems. This web app offers established practitioners efficiency gains and enhanced interactivity in their modeling selection process. Further, budding data scientists and machine learning engineers can capture an extra benefit of honing their intuition of common classification assessment scoring metrics and benchmarking.
Inspiration for this post and web app is from an issue on the Yellowbrick project “to create an at-a-glance representation of multiple model scores so that I can easily compare and contrast different model instances.” Such a tool also helps the analyst gain an intuition for algorithm selection before moving on to the hyperparameter tuning stage.
Leveraging the interactivity of Dash by Plotly, I extended the concept to incorporate existing Yellowbrick classification visualizations, named visualizers. A snapshot of what we will be using for this use case can be found in the header image above.
The data used in this example is the ‘default of credit card clients Data Set’ from the UCI Machine Learning Repository. The dataset consists of customer default payments in Taiwan. We’ll be using it to score model performance on the binary result of classification — credible or not credible clients.
The dataset includes a binary variable, “default payment”, as the response variable. There are 23 predictor variables that consist of demographic information, history of past payments, amount of bill statement, etc.
The data has already been cleaned, so we can move on to the fun part — modeling!
Before diving into the tool, it’d be helpful to provide the context for where in the workflow this tool will be most useful. I’m a fan of the Model Selection Triple framing provided by Arun Kumar et al. [1]
The three stages are:
Our use case resides within the “Algorithm Selection” stage, as we’ll use the web app to narrow down the search space rather than performing an exhaustive search.
So why a dashboard to analyze model performance? Because visual diagnostics are critical to building intuition for more effective machine learning!
..And the interactivity of the dashboard can lend itself to a more seamless UX experience since you can avoid the seemingly infinite scroll when reviewing models’ performance output in notebooks. This scrolling intensive exercise is especially true if there are a lot of supporting data visualizations.
To start off, clone the Github repository
git clone https://github.com/taylorplumer/classifiers-dash
After creating a virtual environment (recommended), you can install the dependencies with the following command:
pip install -r requirements.txt
config.py will be the most hands-on file as this is where we’ll make the configurations necessary for the problem at hand.
In this use case, we’ll be exploring a variety of popular algorithms for binary classification that are available as sklearn estimators such as Gaussian Naive Bayes, Logistic Regression, Random Forest, and Gradient Boosting.
The Yellowbrick visualizers used are pulled from the suite of existing classification visualizers.
*Note that any sklearn estimators and/or yellowbrick visualizers inputted that are not provided by default in the cloned repo will need to be imported.
Run the following command in the project’s root directory to set up the data and images. The target variable should be the first column int the csv file followed by however many predictor variables.
python3 process_data.py credit.csv
The saved output will be the following:
A csv file of model scores for each model from sklearn.metrics.classification_reportThe Yellowbrick visualizations saved as png files.
A csv file of model scores for each model from sklearn.metrics.classification_report
The Yellowbrick visualizations saved as png files.
Before describing the components, let’s run the Dash Plotly web app.
python3 app.py
The app will run locally at http://127.0.0.1:8050/ (or whichever port you selected). We’re live!
A demo deployed to Heroku is available for viewing at the following address: https://classifier-dash-app.herokuapp.com/
The demo is not mobile friendly so please view on desktop/PC for full functionality.
The web app consists of three components:
A dropdown allowing the user to view models with training data either as-is or synthetically upsampled to address any class imbalance.
A dropdown allowing the user to view models with training data either as-is or synthetically upsampled to address any class imbalance.
The default is no upsampling
The upsample.py module within the utils directory can provide details on the upsampling method.
2. A heatmap containing precision, recall, and f1 scores for each sklearn model along with the following:
macro average: averaging the unweighted mean per label
weighted average: averaging the support weighted mean per label
3. When hovering over associated row in heatmap for sklearn model, model-specific images of matplotlib plots will appear that were populated from utilizing Yellowbrick classification visualizers.
ROCAUC: Graphs the receiver operating characteristics and area under the curve.
Precision-Recall Curves: Plots the precision and recall for different probability thresholds.
Classification Report: A visual classification report that displays precision, recall, and F1 per-class as a heatmap.
Confusion Matrix: A heatmap view of the confusion matrix of pairs of classes.
We can see clearly that the Gaussian naive Bayes model does not perform well (at least with the given set of parameters). The logistic regression model is biased due to the class imbalance and performs poorly on precision and recall for positive cases. We see that it performs better when the upsampling is applied to the training data, but it still doesn’t reach performance similar to either of the ensemble methods represented by the random forest and gradient boosting models.
The visualization is hinting at ensemble methods performing better but can we better distinguish between which family of ensemble methods is better — bagging or boosting? This could be done by editing the config.py file to incorporate extra-trees and AdaBoost classifiers.
The initial diagnostics also help inform us of how to allocate our time moving forward, i.e. looking into the decision trees for feature importance and then moving on to more exhaustive hyperparameter tuning within these algorithms.
Machine learning is an iterative exploratory process, so we’d likely be going back and forth between all three stages of the Model Selection Triple.
If you’re interested in what’s going on under the hood for the process_data.py and app.py files, then I encourage you to check out the github repo!
If you have any issues and/or ideas to make the tool more effective, then please open an issue. Happy coding!
[1] Kumar, Arun & McCann, Robert & Naughton, Jeffrey & Patel, Jignesh. Model Selection Management Systems: The Next Frontier of Advanced Analytics (2016), ACM SIGMOD Record. 44. 17–22. 10.1145/2935694.2935698.
|
[
{
"code": null,
"e": 682,
"s": 172,
"text": "This post demonstrates a use case of a classifiers-dash web app tool I developed to automatically curate a compilation of machine learning visual diagnostics for binary classification problems. This web app offers established practitioners efficiency gains and enhanced interactivity in their modeling selection process. Further, budding data scientists and machine learning engineers can capture an extra benefit of honing their intuition of common classification assessment scoring metrics and benchmarking."
},
{
"code": null,
"e": 1030,
"s": 682,
"text": "Inspiration for this post and web app is from an issue on the Yellowbrick project “to create an at-a-glance representation of multiple model scores so that I can easily compare and contrast different model instances.” Such a tool also helps the analyst gain an intuition for algorithm selection before moving on to the hyperparameter tuning stage."
},
{
"code": null,
"e": 1281,
"s": 1030,
"text": "Leveraging the interactivity of Dash by Plotly, I extended the concept to incorporate existing Yellowbrick classification visualizations, named visualizers. A snapshot of what we will be using for this use case can be found in the header image above."
},
{
"code": null,
"e": 1583,
"s": 1281,
"text": "The data used in this example is the ‘default of credit card clients Data Set’ from the UCI Machine Learning Repository. The dataset consists of customer default payments in Taiwan. We’ll be using it to score model performance on the binary result of classification — credible or not credible clients."
},
{
"code": null,
"e": 1799,
"s": 1583,
"text": "The dataset includes a binary variable, “default payment”, as the response variable. There are 23 predictor variables that consist of demographic information, history of past payments, amount of bill statement, etc."
},
{
"code": null,
"e": 1880,
"s": 1799,
"text": "The data has already been cleaned, so we can move on to the fun part — modeling!"
},
{
"code": null,
"e": 2087,
"s": 1880,
"text": "Before diving into the tool, it’d be helpful to provide the context for where in the workflow this tool will be most useful. I’m a fan of the Model Selection Triple framing provided by Arun Kumar et al. [1]"
},
{
"code": null,
"e": 2109,
"s": 2087,
"text": "The three stages are:"
},
{
"code": null,
"e": 2272,
"s": 2109,
"text": "Our use case resides within the “Algorithm Selection” stage, as we’ll use the web app to narrow down the search space rather than performing an exhaustive search."
},
{
"code": null,
"e": 2420,
"s": 2272,
"text": "So why a dashboard to analyze model performance? Because visual diagnostics are critical to building intuition for more effective machine learning!"
},
{
"code": null,
"e": 2723,
"s": 2420,
"text": "..And the interactivity of the dashboard can lend itself to a more seamless UX experience since you can avoid the seemingly infinite scroll when reviewing models’ performance output in notebooks. This scrolling intensive exercise is especially true if there are a lot of supporting data visualizations."
},
{
"code": null,
"e": 2765,
"s": 2723,
"text": "To start off, clone the Github repository"
},
{
"code": null,
"e": 2824,
"s": 2765,
"text": "git clone https://github.com/taylorplumer/classifiers-dash"
},
{
"code": null,
"e": 2937,
"s": 2824,
"text": "After creating a virtual environment (recommended), you can install the dependencies with the following command:"
},
{
"code": null,
"e": 2969,
"s": 2937,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 3092,
"s": 2969,
"text": "config.py will be the most hands-on file as this is where we’ll make the configurations necessary for the problem at hand."
},
{
"code": null,
"e": 3317,
"s": 3092,
"text": "In this use case, we’ll be exploring a variety of popular algorithms for binary classification that are available as sklearn estimators such as Gaussian Naive Bayes, Logistic Regression, Random Forest, and Gradient Boosting."
},
{
"code": null,
"e": 3416,
"s": 3317,
"text": "The Yellowbrick visualizers used are pulled from the suite of existing classification visualizers."
},
{
"code": null,
"e": 3568,
"s": 3416,
"text": "*Note that any sklearn estimators and/or yellowbrick visualizers inputted that are not provided by default in the cloned repo will need to be imported."
},
{
"code": null,
"e": 3767,
"s": 3568,
"text": "Run the following command in the project’s root directory to set up the data and images. The target variable should be the first column int the csv file followed by however many predictor variables."
},
{
"code": null,
"e": 3802,
"s": 3767,
"text": "python3 process_data.py credit.csv"
},
{
"code": null,
"e": 3842,
"s": 3802,
"text": "The saved output will be the following:"
},
{
"code": null,
"e": 3977,
"s": 3842,
"text": "A csv file of model scores for each model from sklearn.metrics.classification_reportThe Yellowbrick visualizations saved as png files."
},
{
"code": null,
"e": 4062,
"s": 3977,
"text": "A csv file of model scores for each model from sklearn.metrics.classification_report"
},
{
"code": null,
"e": 4113,
"s": 4062,
"text": "The Yellowbrick visualizations saved as png files."
},
{
"code": null,
"e": 4182,
"s": 4113,
"text": "Before describing the components, let’s run the Dash Plotly web app."
},
{
"code": null,
"e": 4197,
"s": 4182,
"text": "python3 app.py"
},
{
"code": null,
"e": 4294,
"s": 4197,
"text": "The app will run locally at http://127.0.0.1:8050/ (or whichever port you selected). We’re live!"
},
{
"code": null,
"e": 4414,
"s": 4294,
"text": "A demo deployed to Heroku is available for viewing at the following address: https://classifier-dash-app.herokuapp.com/"
},
{
"code": null,
"e": 4499,
"s": 4414,
"text": "The demo is not mobile friendly so please view on desktop/PC for full functionality."
},
{
"code": null,
"e": 4541,
"s": 4499,
"text": "The web app consists of three components:"
},
{
"code": null,
"e": 4676,
"s": 4541,
"text": "A dropdown allowing the user to view models with training data either as-is or synthetically upsampled to address any class imbalance."
},
{
"code": null,
"e": 4811,
"s": 4676,
"text": "A dropdown allowing the user to view models with training data either as-is or synthetically upsampled to address any class imbalance."
},
{
"code": null,
"e": 4840,
"s": 4811,
"text": "The default is no upsampling"
},
{
"code": null,
"e": 4936,
"s": 4840,
"text": "The upsample.py module within the utils directory can provide details on the upsampling method."
},
{
"code": null,
"e": 5042,
"s": 4936,
"text": "2. A heatmap containing precision, recall, and f1 scores for each sklearn model along with the following:"
},
{
"code": null,
"e": 5097,
"s": 5042,
"text": "macro average: averaging the unweighted mean per label"
},
{
"code": null,
"e": 5161,
"s": 5097,
"text": "weighted average: averaging the support weighted mean per label"
},
{
"code": null,
"e": 5357,
"s": 5161,
"text": "3. When hovering over associated row in heatmap for sklearn model, model-specific images of matplotlib plots will appear that were populated from utilizing Yellowbrick classification visualizers."
},
{
"code": null,
"e": 5437,
"s": 5357,
"text": "ROCAUC: Graphs the receiver operating characteristics and area under the curve."
},
{
"code": null,
"e": 5531,
"s": 5437,
"text": "Precision-Recall Curves: Plots the precision and recall for different probability thresholds."
},
{
"code": null,
"e": 5649,
"s": 5531,
"text": "Classification Report: A visual classification report that displays precision, recall, and F1 per-class as a heatmap."
},
{
"code": null,
"e": 5727,
"s": 5649,
"text": "Confusion Matrix: A heatmap view of the confusion matrix of pairs of classes."
},
{
"code": null,
"e": 6208,
"s": 5727,
"text": "We can see clearly that the Gaussian naive Bayes model does not perform well (at least with the given set of parameters). The logistic regression model is biased due to the class imbalance and performs poorly on precision and recall for positive cases. We see that it performs better when the upsampling is applied to the training data, but it still doesn’t reach performance similar to either of the ensemble methods represented by the random forest and gradient boosting models."
},
{
"code": null,
"e": 6481,
"s": 6208,
"text": "The visualization is hinting at ensemble methods performing better but can we better distinguish between which family of ensemble methods is better — bagging or boosting? This could be done by editing the config.py file to incorporate extra-trees and AdaBoost classifiers."
},
{
"code": null,
"e": 6714,
"s": 6481,
"text": "The initial diagnostics also help inform us of how to allocate our time moving forward, i.e. looking into the decision trees for feature importance and then moving on to more exhaustive hyperparameter tuning within these algorithms."
},
{
"code": null,
"e": 6863,
"s": 6714,
"text": "Machine learning is an iterative exploratory process, so we’d likely be going back and forth between all three stages of the Model Selection Triple."
},
{
"code": null,
"e": 7011,
"s": 6863,
"text": "If you’re interested in what’s going on under the hood for the process_data.py and app.py files, then I encourage you to check out the github repo!"
},
{
"code": null,
"e": 7121,
"s": 7011,
"text": "If you have any issues and/or ideas to make the tool more effective, then please open an issue. Happy coding!"
}
] |
Groovy - Template Engines
|
Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general.
If you take the simple example below, we are first defining a name variable to hold the string “Groovy”. In the println statement, we are using $ symbol to define a parameter or template where a value can be inserted.
def name = "Groovy"
println "This Tutorial is about ${name}"
If the above code is executed in groovy, the following output will be shown. The output clearly shows that the $name was replaced by the value which was assigned by the def statement.
Following is an example of the SimpleTemplateEngine that allows you to use JSP-like scriptlets and EL expressions in your template in order to generate parametrized text. The templating engine allows you to bind a list of parameters and their values so that they can be replaced in the string which has the defined placeholders.
def text ='This Tutorial focuses on $TutorialName. In this tutorial you will learn
about $Topic'
def binding = ["TutorialName":"Groovy", "Topic":"Templates"]
def engine = new groovy.text.SimpleTemplateEngine()
def template = engine.createTemplate(text).make(binding)
println template
If the above code is executed in groovy, the following output will be shown.
Let’s now use the templating feature for an XML file. As a first step let’s add the following code to a file called Student.template. In the following file you will notice that we have not added the actual values for the elements, but placeholders. So $name,$is and $subject are all put as placeholders which will need to replaced at runtime.
<Student>
<name>${name}</name>
<ID>${id}</ID>
<subject>${subject}</subject>
</Student>
Now let’s add our Groovy script code to add the functionality which can be used to replace the above template with actual values. The following things should be noted about the following code.
The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values.
The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values.
import groovy.text.*
import java.io.*
def file = new File("D:/Student.template")
def binding = ['name' : 'Joe', 'id' : 1, 'subject' : 'Physics']
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(file)
def writable = template.make(binding)
println writable
If the above code is executed in groovy, the following output will be shown. From the output it can be seen that the values are successfully replaced in the relevant placeholders.
<Student>
<name>Joe</name>
<ID>1</ID>
<subject>Physics</subject>
</Student>
The StreamingTemplateEngine engine is another templating engine available in Groovy. This is kind of equivalent to the SimpleTemplateEngine, but creates the template using writeable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k.
Following is an example of how StreamingTemplateEngine are used −
def text = '''This Tutorial is <% out.print TutorialName %> The Topic name
is ${TopicName}'''
def template = new groovy.text.StreamingTemplateEngine().createTemplate(text)
def binding = [TutorialName : "Groovy", TopicName : "Templates",]
String response = template.make(binding)
println(response)
If the above code is executed in groovy, the following output will be shown.
This Tutorial is Groovy The Topic name is Templates
The XmlTemplateEngine is used in templating scenarios where both the template source and the expected output are intended to be XML. Templates use the normal ${expression} and $variable notations to insert an arbitrary expression into the template.
Following is an example of how XMLTemplateEngine is used.
def binding = [StudentName: 'Joe', id: 1, subject: 'Physics']
def engine = new groovy.text.XmlTemplateEngine()
def text = '''\
<document xmlns:gsp='http://groovy.codehaus.org/2005/gsp'>
<Student>
<name>${StudentName}</name>
<ID>${id}</ID>
<subject>${subject}</subject>
</Student>
</document>
'''
def template = engine.createTemplate(text).make(binding)
println template.toString()
If the above code is executed in groovy, the following output will be shown
Joe
1
Physics
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2487,
"s": 2238,
"text": "Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general."
},
{
"code": null,
"e": 2705,
"s": 2487,
"text": "If you take the simple example below, we are first defining a name variable to hold the string “Groovy”. In the println statement, we are using $ symbol to define a parameter or template where a value can be inserted."
},
{
"code": null,
"e": 2767,
"s": 2705,
"text": "def name = \"Groovy\" \nprintln \"This Tutorial is about ${name}\""
},
{
"code": null,
"e": 2951,
"s": 2767,
"text": "If the above code is executed in groovy, the following output will be shown. The output clearly shows that the $name was replaced by the value which was assigned by the def statement."
},
{
"code": null,
"e": 3280,
"s": 2951,
"text": "Following is an example of the SimpleTemplateEngine that allows you to use JSP-like scriptlets and EL expressions in your template in order to generate parametrized text. The templating engine allows you to bind a list of parameters and their values so that they can be replaced in the string which has the defined placeholders."
},
{
"code": null,
"e": 3574,
"s": 3280,
"text": "def text ='This Tutorial focuses on $TutorialName. In this tutorial you will learn \n\nabout $Topic' \n\ndef binding = [\"TutorialName\":\"Groovy\", \"Topic\":\"Templates\"] \ndef engine = new groovy.text.SimpleTemplateEngine() \ndef template = engine.createTemplate(text).make(binding) \n\nprintln template"
},
{
"code": null,
"e": 3651,
"s": 3574,
"text": "If the above code is executed in groovy, the following output will be shown."
},
{
"code": null,
"e": 3995,
"s": 3651,
"text": "Let’s now use the templating feature for an XML file. As a first step let’s add the following code to a file called Student.template. In the following file you will notice that we have not added the actual values for the elements, but placeholders. So $name,$is and $subject are all put as placeholders which will need to replaced at runtime."
},
{
"code": null,
"e": 4095,
"s": 3995,
"text": "<Student> \n <name>${name}</name> \n <ID>${id}</ID> \n <subject>${subject}</subject> \n</Student>"
},
{
"code": null,
"e": 4288,
"s": 4095,
"text": "Now let’s add our Groovy script code to add the functionality which can be used to replace the above template with actual values. The following things should be noted about the following code."
},
{
"code": null,
"e": 4480,
"s": 4288,
"text": "The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values."
},
{
"code": null,
"e": 4672,
"s": 4480,
"text": "The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values."
},
{
"code": null,
"e": 4970,
"s": 4672,
"text": "import groovy.text.* \nimport java.io.* \n\ndef file = new File(\"D:/Student.template\") \ndef binding = ['name' : 'Joe', 'id' : 1, 'subject' : 'Physics']\n\t\t\t\t \ndef engine = new SimpleTemplateEngine() \ndef template = engine.createTemplate(file) \ndef writable = template.make(binding) \n\nprintln writable"
},
{
"code": null,
"e": 5150,
"s": 4970,
"text": "If the above code is executed in groovy, the following output will be shown. From the output it can be seen that the values are successfully replaced in the relevant placeholders."
},
{
"code": null,
"e": 5239,
"s": 5150,
"text": "<Student> \n <name>Joe</name> \n <ID>1</ID> \n <subject>Physics</subject> \n</Student>"
},
{
"code": null,
"e": 5545,
"s": 5239,
"text": "The StreamingTemplateEngine engine is another templating engine available in Groovy. This is kind of equivalent to the SimpleTemplateEngine, but creates the template using writeable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k."
},
{
"code": null,
"e": 5611,
"s": 5545,
"text": "Following is an example of how StreamingTemplateEngine are used −"
},
{
"code": null,
"e": 5916,
"s": 5611,
"text": "def text = '''This Tutorial is <% out.print TutorialName %> The Topic name \n\nis ${TopicName}''' \ndef template = new groovy.text.StreamingTemplateEngine().createTemplate(text)\n \ndef binding = [TutorialName : \"Groovy\", TopicName : \"Templates\",]\nString response = template.make(binding) \nprintln(response)"
},
{
"code": null,
"e": 5993,
"s": 5916,
"text": "If the above code is executed in groovy, the following output will be shown."
},
{
"code": null,
"e": 6046,
"s": 5993,
"text": "This Tutorial is Groovy The Topic name is Templates\n"
},
{
"code": null,
"e": 6295,
"s": 6046,
"text": "The XmlTemplateEngine is used in templating scenarios where both the template source and the expected output are intended to be XML. Templates use the normal ${expression} and $variable notations to insert an arbitrary expression into the template."
},
{
"code": null,
"e": 6353,
"s": 6295,
"text": "Following is an example of how XMLTemplateEngine is used."
},
{
"code": null,
"e": 6786,
"s": 6353,
"text": "def binding = [StudentName: 'Joe', id: 1, subject: 'Physics'] \ndef engine = new groovy.text.XmlTemplateEngine() \n\ndef text = '''\\\n <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp'>\n <Student>\n <name>${StudentName}</name>\n <ID>${id}</ID>\n <subject>${subject}</subject>\n </Student>\n </document> \n''' \n\ndef template = engine.createTemplate(text).make(binding) \nprintln template.toString()"
},
{
"code": null,
"e": 6862,
"s": 6786,
"text": "If the above code is executed in groovy, the following output will be shown"
},
{
"code": null,
"e": 6907,
"s": 6862,
"text": " Joe\n \n \n 1\n \n \n Physics \n"
},
{
"code": null,
"e": 6940,
"s": 6907,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6958,
"s": 6940,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 6993,
"s": 6958,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7011,
"s": 6993,
"text": " Packt Publishing"
},
{
"code": null,
"e": 7018,
"s": 7011,
"text": " Print"
},
{
"code": null,
"e": 7029,
"s": 7018,
"text": " Add Notes"
}
] |
How to perform arithmetic operations on two-dimensional array in C?
|
An array is a group of related data items that are stored with single name.
For example, int student[30]; //student is an array name that holds 30 collection of data items with a single variable name
Searching − It is used to find whether particular element is present or not
Searching − It is used to find whether particular element is present or not
Sorting − It helps in arranging the elements in an array either in ascending or descending order.
Sorting − It helps in arranging the elements in an array either in ascending or descending order.
Traversing − It processes every element in an array sequentially.
Traversing − It processes every element in an array sequentially.
Inserting − It helps in inserting the elements in an array.
Inserting − It helps in inserting the elements in an array.
Deleting − It helps in deleting an element in an array.
Deleting − It helps in deleting an element in an array.
The logic applied to perform arithmetic operation of two-dimensional array is as follows −
for(row = 0; row < i; row++){
for(col = 0;col < j;col++){
add[row][col] = A[row][col] + B[row][col];
sub[row][col] = A[row][col] - B[row][col];
mul[row][col] = A[row][col] * B[row][col];
div[row][col] = A[row][col] / B[row][col];
mod[row][col] = A[row][col] % B[row][col];
}
}
The logic applied to print all arithmetic operation of two-dimensional array is as follows −
printf("\nAdd\t Sub\t Mul\t Div\t Mod\n");
printf("-------------------------------\n");
for(row = 0; row < i; row++){
for(col = 0; col < j; col++){
printf("\n%d \t ", add[row][col]);
printf("%d \t ", sub[row][col]);
printf("%d \t ", mul[row][col]);
printf("%.2f \t ", div[row][col]);
printf("%d \t ", mod[row][col]);
}
}
Following is the C program to perform arithmetic operations on two-dimensional array −
Live Demo
#include<stdio.h>
int main(){
int i, j, row, col,A[20][20], B[20][20];
int add[10][10], sub[10][10], mul[10][10], mod[10][10];
float div[10][10];
printf("enter no: of rows and columns:\n");
scanf("%d %d", &i, &j);
printf("enter elements of 1st array:\n");
for(row= 0; row < i; row++){
for(col = 0;col < j;col++){
scanf("%d", &A[row][col]);
}
}
printf("enter elements of 2nd array:\n");
for(row = 0; row < i; row++){
for(col = 0;col < j;col++){
scanf("%d", &B[row][col]);
}
}
for(row = 0; row < i; row++){
for(col = 0;col < j;col++){
add[row][col] = A[row][col] + B[row][col];
sub[row][col] = A[row][col] - B[row][col];
mul[row][col] = A[row][col] * B[row][col];
div[row][col] = A[row][col] / B[row][col];
mod[row][col] = A[row][col] % B[row][col];
}
}
printf("\nAdd\t Sub\t Mul\t Div\t Mod\n");
printf("-------------------------------\n");
for(row = 0; row < i; row++){
for(col = 0; col < j; col++){
printf("\n%d \t ", add[row][col]);
printf("%d \t ", sub[row][col]);
printf("%d \t ", mul[row][col]);
printf("%.2f \t ", div[row][col]);
printf("%d \t ", mod[row][col]);
}
}
return 0;
}
When the above program is executed, it produces the following result −
enter no: of rows and columns:
3 4
enter elements of 1st array:
1 2 4 5 6 7 3 8 3 2 1 8
enter elements of 2nd array:
1 2 1 2 1 3 4 2 1 2 1 1
Add Sub Mul Div Mod
-------------------------------
2 0 1 1.00 0
4 0 4 1.00 0
5 3 4 4.00 0
7 3 10 2.00 1
7 5 6 6.00 0
10 4 21 2.00 1
7 -1 12 0.00 3
10 6 16 4.00 0
4 2 3 3.00 0
4 0 4 1.00 0
2 0 1 1.00 0
9 7 8 8.00 0
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "An array is a group of related data items that are stored with single name."
},
{
"code": null,
"e": 1262,
"s": 1138,
"text": "For example, int student[30]; //student is an array name that holds 30 collection of data items with a single variable name"
},
{
"code": null,
"e": 1338,
"s": 1262,
"text": "Searching − It is used to find whether particular element is present or not"
},
{
"code": null,
"e": 1414,
"s": 1338,
"text": "Searching − It is used to find whether particular element is present or not"
},
{
"code": null,
"e": 1512,
"s": 1414,
"text": "Sorting − It helps in arranging the elements in an array either in ascending or descending order."
},
{
"code": null,
"e": 1610,
"s": 1512,
"text": "Sorting − It helps in arranging the elements in an array either in ascending or descending order."
},
{
"code": null,
"e": 1676,
"s": 1610,
"text": "Traversing − It processes every element in an array sequentially."
},
{
"code": null,
"e": 1742,
"s": 1676,
"text": "Traversing − It processes every element in an array sequentially."
},
{
"code": null,
"e": 1802,
"s": 1742,
"text": "Inserting − It helps in inserting the elements in an array."
},
{
"code": null,
"e": 1862,
"s": 1802,
"text": "Inserting − It helps in inserting the elements in an array."
},
{
"code": null,
"e": 1918,
"s": 1862,
"text": "Deleting − It helps in deleting an element in an array."
},
{
"code": null,
"e": 1974,
"s": 1918,
"text": "Deleting − It helps in deleting an element in an array."
},
{
"code": null,
"e": 2065,
"s": 1974,
"text": "The logic applied to perform arithmetic operation of two-dimensional array is as follows −"
},
{
"code": null,
"e": 2378,
"s": 2065,
"text": "for(row = 0; row < i; row++){\n for(col = 0;col < j;col++){\n add[row][col] = A[row][col] + B[row][col];\n sub[row][col] = A[row][col] - B[row][col];\n mul[row][col] = A[row][col] * B[row][col];\n div[row][col] = A[row][col] / B[row][col];\n mod[row][col] = A[row][col] % B[row][col];\n }\n}"
},
{
"code": null,
"e": 2471,
"s": 2378,
"text": "The logic applied to print all arithmetic operation of two-dimensional array is as follows −"
},
{
"code": null,
"e": 2828,
"s": 2471,
"text": "printf(\"\\nAdd\\t Sub\\t Mul\\t Div\\t Mod\\n\");\nprintf(\"-------------------------------\\n\");\nfor(row = 0; row < i; row++){\n for(col = 0; col < j; col++){\n printf(\"\\n%d \\t \", add[row][col]);\n printf(\"%d \\t \", sub[row][col]);\n printf(\"%d \\t \", mul[row][col]);\n printf(\"%.2f \\t \", div[row][col]);\n printf(\"%d \\t \", mod[row][col]);\n }\n}"
},
{
"code": null,
"e": 2915,
"s": 2828,
"text": "Following is the C program to perform arithmetic operations on two-dimensional array −"
},
{
"code": null,
"e": 2926,
"s": 2915,
"text": " Live Demo"
},
{
"code": null,
"e": 4221,
"s": 2926,
"text": "#include<stdio.h>\nint main(){\n int i, j, row, col,A[20][20], B[20][20];\n int add[10][10], sub[10][10], mul[10][10], mod[10][10];\n float div[10][10];\n printf(\"enter no: of rows and columns:\\n\");\n scanf(\"%d %d\", &i, &j);\n printf(\"enter elements of 1st array:\\n\");\n for(row= 0; row < i; row++){\n for(col = 0;col < j;col++){\n scanf(\"%d\", &A[row][col]);\n }\n }\n printf(\"enter elements of 2nd array:\\n\");\n for(row = 0; row < i; row++){\n for(col = 0;col < j;col++){\n scanf(\"%d\", &B[row][col]);\n }\n }\n for(row = 0; row < i; row++){\n for(col = 0;col < j;col++){\n add[row][col] = A[row][col] + B[row][col];\n sub[row][col] = A[row][col] - B[row][col];\n mul[row][col] = A[row][col] * B[row][col];\n div[row][col] = A[row][col] / B[row][col];\n mod[row][col] = A[row][col] % B[row][col];\n }\n }\n printf(\"\\nAdd\\t Sub\\t Mul\\t Div\\t Mod\\n\");\n printf(\"-------------------------------\\n\");\n for(row = 0; row < i; row++){\n for(col = 0; col < j; col++){\n printf(\"\\n%d \\t \", add[row][col]);\n printf(\"%d \\t \", sub[row][col]);\n printf(\"%d \\t \", mul[row][col]);\n printf(\"%.2f \\t \", div[row][col]);\n printf(\"%d \\t \", mod[row][col]);\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 4292,
"s": 4221,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4774,
"s": 4292,
"text": "enter no: of rows and columns:\n3 4\nenter elements of 1st array:\n1 2 4 5 6 7 3 8 3 2 1 8\nenter elements of 2nd array:\n1 2 1 2 1 3 4 2 1 2 1 1\nAdd Sub Mul Div Mod\n-------------------------------\n2 0 1 1.00 0\n4 0 4 1.00 0\n5 3 4 4.00 0\n7 3 10 2.00 1\n7 5 6 6.00 0\n10 4 21 2.00 1\n7 -1 12 0.00 3\n10 6 16 4.00 0\n4 2 3 3.00 0\n4 0 4 1.00 0\n2 0 1 1.00 0\n9 7 8 8.00 0"
}
] |
Cassandra - Alter Table
|
You can alter a table using the command ALTER TABLE. Given below is the syntax for creating a table.
ALTER (TABLE | COLUMNFAMILY) <tablename> <instruction>
Using ALTER command, you can perform the following operations −
Add a column
Add a column
Drop a column
Drop a column
Using ALTER command, you can add a column to a table. While adding columns, you have to take care that the column name is not conflicting with the existing column names and that the table is not defined with compact storage option. Given below is the syntax to add a column to a table.
ALTER TABLE table name
ADD new column datatype;
Example
Given below is an example to add a column to an existing table. Here we are adding a column called emp_email of text datatype to the table named emp.
cqlsh:tutorialspoint> ALTER TABLE emp
... ADD emp_email text;
Verification
Use the SELECT statement to verify whether the column is added or not. Here you
can observe the newly added column emp_email.
cqlsh:tutorialspoint> select * from emp;
emp_id | emp_city | emp_email | emp_name | emp_phone | emp_sal
--------+----------+-----------+----------+-----------+---------
Using ALTER command, you can delete a column from a table. Before dropping a column from a table, check that the table is not defined with compact storage option. Given below is the syntax to delete a column from a table using ALTER command.
ALTER table name
DROP column name;
Example
Given below is an example to drop a column from a table. Here we are deleting
the column named emp_email.
cqlsh:tutorialspoint> ALTER TABLE emp DROP emp_email;
Verification
Verify whether the column is deleted using the select statement, as shown below.
cqlsh:tutorialspoint> select * from emp;
emp_id | emp_city | emp_name | emp_phone | emp_sal
--------+----------+----------+-----------+---------
(0 rows)
Since emp_email column has been deleted, you cannot find it anymore.
You can create a table using the execute() method of Session class. Follow the steps given below to alter a table using Java API.
First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.
//Creating Cluster.Builder object
Cluster.Builder builder1 = Cluster.builder();
Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.
//Adding contact point to the Cluster.Builder object
Cluster.Builder builder2 = build.addContactPoint( "127.0.0.1" );
Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object.
//Building a cluster
Cluster cluster = builder.build();
You can build a cluster object using a single line of code as shown below.
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Create an instance of Session object using the connect() method of Cluster class
as shown below.
Session session = cluster.connect( );
This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the KeySpace name in string format to this method as shown below.
Session session = cluster.connect(“ Your keyspace name ” );
Session session = cluster.connect(“ tp” );
Here we are using the KeySpace named tp. Therefore, create the session object
as shown below.
You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.
In the following example, we are adding a column to a table named emp. To do so, you have to store the query in a string variable and pass it to the execute() method as shown below.
//Query
String query1 = "ALTER TABLE emp ADD emp_email text";
session.execute(query);
Given below is the complete program to add a column to an existing table.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class Add_column {
public static void main(String args[]){
//Query
String query = "ALTER TABLE emp ADD emp_email text";
//Creating Cluster object
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
//Creating Session object
Session session = cluster.connect("tp");
//Executing the query
session.execute(query);
System.out.println("Column added");
}
}
Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.
$javac Add_Column.java
$java Add_Column
Under normal conditions, it should produce the following output −
Column added
Given below is the complete program to delete a column from an existing table.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class Delete_Column {
public static void main(String args[]){
//Query
String query = "ALTER TABLE emp DROP emp_email;";
//Creating Cluster object
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
//Creating Session object
Session session = cluster.connect("tp");
//executing the query
session.execute(query);
System.out.println("Column deleted");
}
}
Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.
$javac Delete_Column.java
$java Delete_Column
Under normal conditions, it should produce the following output −
Column deleted
27 Lectures
2 hours
Navdeep Kaur
34 Lectures
1.5 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2388,
"s": 2287,
"text": "You can alter a table using the command ALTER TABLE. Given below is the syntax for creating a table."
},
{
"code": null,
"e": 2444,
"s": 2388,
"text": "ALTER (TABLE | COLUMNFAMILY) <tablename> <instruction>\n"
},
{
"code": null,
"e": 2508,
"s": 2444,
"text": "Using ALTER command, you can perform the following operations −"
},
{
"code": null,
"e": 2521,
"s": 2508,
"text": "Add a column"
},
{
"code": null,
"e": 2534,
"s": 2521,
"text": "Add a column"
},
{
"code": null,
"e": 2548,
"s": 2534,
"text": "Drop a column"
},
{
"code": null,
"e": 2562,
"s": 2548,
"text": "Drop a column"
},
{
"code": null,
"e": 2848,
"s": 2562,
"text": "Using ALTER command, you can add a column to a table. While adding columns, you have to take care that the column name is not conflicting with the existing column names and that the table is not defined with compact storage option. Given below is the syntax to add a column to a table."
},
{
"code": null,
"e": 2898,
"s": 2848,
"text": "ALTER TABLE table name\nADD new column datatype;\n"
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Example"
},
{
"code": null,
"e": 3056,
"s": 2906,
"text": "Given below is an example to add a column to an existing table. Here we are adding a column called emp_email of text datatype to the table named emp."
},
{
"code": null,
"e": 3122,
"s": 3056,
"text": "cqlsh:tutorialspoint> ALTER TABLE emp\n ... ADD emp_email text;\n"
},
{
"code": null,
"e": 3135,
"s": 3122,
"text": "Verification"
},
{
"code": null,
"e": 3261,
"s": 3135,
"text": "Use the SELECT statement to verify whether the column is added or not. Here you\ncan observe the newly added column emp_email."
},
{
"code": null,
"e": 3433,
"s": 3261,
"text": "cqlsh:tutorialspoint> select * from emp;\n\n emp_id | emp_city | emp_email | emp_name | emp_phone | emp_sal\n--------+----------+-----------+----------+-----------+---------\n"
},
{
"code": null,
"e": 3675,
"s": 3433,
"text": "Using ALTER command, you can delete a column from a table. Before dropping a column from a table, check that the table is not defined with compact storage option. Given below is the syntax to delete a column from a table using ALTER command."
},
{
"code": null,
"e": 3711,
"s": 3675,
"text": "ALTER table name\nDROP column name;\n"
},
{
"code": null,
"e": 3719,
"s": 3711,
"text": "Example"
},
{
"code": null,
"e": 3825,
"s": 3719,
"text": "Given below is an example to drop a column from a table. Here we are deleting\nthe column named emp_email."
},
{
"code": null,
"e": 3880,
"s": 3825,
"text": "cqlsh:tutorialspoint> ALTER TABLE emp DROP emp_email;\n"
},
{
"code": null,
"e": 3893,
"s": 3880,
"text": "Verification"
},
{
"code": null,
"e": 3974,
"s": 3893,
"text": "Verify whether the column is deleted using the select statement, as shown below."
},
{
"code": null,
"e": 4131,
"s": 3974,
"text": "cqlsh:tutorialspoint> select * from emp;\n\n emp_id | emp_city | emp_name | emp_phone | emp_sal\n--------+----------+----------+-----------+---------\n(0 rows)\n"
},
{
"code": null,
"e": 4200,
"s": 4131,
"text": "Since emp_email column has been deleted, you cannot find it anymore."
},
{
"code": null,
"e": 4330,
"s": 4200,
"text": "You can create a table using the execute() method of Session class. Follow the steps given below to alter a table using Java API."
},
{
"code": null,
"e": 4440,
"s": 4330,
"text": "First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below."
},
{
"code": null,
"e": 4521,
"s": 4440,
"text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n"
},
{
"code": null,
"e": 4665,
"s": 4521,
"text": "Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder."
},
{
"code": null,
"e": 4784,
"s": 4665,
"text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint( \"127.0.0.1\" );\n"
},
{
"code": null,
"e": 4969,
"s": 4784,
"text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object."
},
{
"code": null,
"e": 5026,
"s": 4969,
"text": "//Building a cluster\nCluster cluster = builder.build();\n"
},
{
"code": null,
"e": 5101,
"s": 5026,
"text": "You can build a cluster object using a single line of code as shown below."
},
{
"code": null,
"e": 5176,
"s": 5101,
"text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n"
},
{
"code": null,
"e": 5273,
"s": 5176,
"text": "Create an instance of Session object using the connect() method of Cluster class\nas shown below."
},
{
"code": null,
"e": 5312,
"s": 5273,
"text": "Session session = cluster.connect( );\n"
},
{
"code": null,
"e": 5510,
"s": 5312,
"text": "This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the KeySpace name in string format to this method as shown below."
},
{
"code": null,
"e": 5614,
"s": 5510,
"text": "Session session = cluster.connect(“ Your keyspace name ” );\nSession session = cluster.connect(“ tp” );\n"
},
{
"code": null,
"e": 5708,
"s": 5614,
"text": "Here we are using the KeySpace named tp. Therefore, create the session object\nas shown below."
},
{
"code": null,
"e": 5957,
"s": 5708,
"text": "You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh."
},
{
"code": null,
"e": 6139,
"s": 5957,
"text": "In the following example, we are adding a column to a table named emp. To do so, you have to store the query in a string variable and pass it to the execute() method as shown below."
},
{
"code": null,
"e": 6226,
"s": 6139,
"text": "//Query\nString query1 = \"ALTER TABLE emp ADD emp_email text\";\nsession.execute(query);\n"
},
{
"code": null,
"e": 6300,
"s": 6226,
"text": "Given below is the complete program to add a column to an existing table."
},
{
"code": null,
"e": 6840,
"s": 6300,
"text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Add_column {\n\n public static void main(String args[]){\n\n //Query\n String query = \"ALTER TABLE emp ADD emp_email text\";\n\n //Creating Cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //Executing the query\n session.execute(query);\n \n System.out.println(\"Column added\");\n }\n}"
},
{
"code": null,
"e": 6992,
"s": 6840,
"text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below."
},
{
"code": null,
"e": 7033,
"s": 6992,
"text": "$javac Add_Column.java\n$java Add_Column\n"
},
{
"code": null,
"e": 7099,
"s": 7033,
"text": "Under normal conditions, it should produce the following output −"
},
{
"code": null,
"e": 7113,
"s": 7099,
"text": "Column added\n"
},
{
"code": null,
"e": 7192,
"s": 7113,
"text": "Given below is the complete program to delete a column from an existing table."
},
{
"code": null,
"e": 7730,
"s": 7192,
"text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Delete_Column {\n\n public static void main(String args[]){\n\n //Query\n String query = \"ALTER TABLE emp DROP emp_email;\";\n\n //Creating Cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //executing the query\n session.execute(query);\n \n System.out.println(\"Column deleted\");\n }\n }"
},
{
"code": null,
"e": 7882,
"s": 7730,
"text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below."
},
{
"code": null,
"e": 7929,
"s": 7882,
"text": "$javac Delete_Column.java\n$java Delete_Column\n"
},
{
"code": null,
"e": 7995,
"s": 7929,
"text": "Under normal conditions, it should produce the following output −"
},
{
"code": null,
"e": 8011,
"s": 7995,
"text": "Column deleted\n"
},
{
"code": null,
"e": 8044,
"s": 8011,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8058,
"s": 8044,
"text": " Navdeep Kaur"
},
{
"code": null,
"e": 8093,
"s": 8058,
"text": "\n 34 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8111,
"s": 8093,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 8118,
"s": 8111,
"text": " Print"
},
{
"code": null,
"e": 8129,
"s": 8118,
"text": " Add Notes"
}
] |
Show Matplotlib graphs to image as fullscreen
|
To show matplotlib graphs as full screen, we can use full_screen_toggle() method.
Create a figure or activate an existing figure using figure() method.
Create a figure or activate an existing figure using figure() method.
Plot a line using two lists.
Plot a line using two lists.
Return the figure manager of the current figure.
Return the figure manager of the current figure.
To toggle full screen image, use full_screen_toggle() method.
To toggle full screen image, use full_screen_toggle() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.figure()
plt.plot([1, 2], [1, 2])
manager = plt.get_current_fig_manager()
manager.full_screen_toggle()
plt.show()
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To show matplotlib graphs as full screen, we can use full_screen_toggle() method."
},
{
"code": null,
"e": 1214,
"s": 1144,
"text": "Create a figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1284,
"s": 1214,
"text": "Create a figure or activate an existing figure using figure() method."
},
{
"code": null,
"e": 1313,
"s": 1284,
"text": "Plot a line using two lists."
},
{
"code": null,
"e": 1342,
"s": 1313,
"text": "Plot a line using two lists."
},
{
"code": null,
"e": 1391,
"s": 1342,
"text": "Return the figure manager of the current figure."
},
{
"code": null,
"e": 1440,
"s": 1391,
"text": "Return the figure manager of the current figure."
},
{
"code": null,
"e": 1502,
"s": 1440,
"text": "To toggle full screen image, use full_screen_toggle() method."
},
{
"code": null,
"e": 1564,
"s": 1502,
"text": "To toggle full screen image, use full_screen_toggle() method."
},
{
"code": null,
"e": 1606,
"s": 1564,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1648,
"s": 1606,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1890,
"s": 1648,
"text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nplt.figure()\nplt.plot([1, 2], [1, 2])\nmanager = plt.get_current_fig_manager()\nmanager.full_screen_toggle()\nplt.show()"
}
] |
Conversions in LINQ
|
The operators change the type of input objects and are used in a diverse range of applications.
using System;
using System.Linq;
namespace Operators {
class Cast {
static void Main(string[] args) {
Plant[] plants = new Plant[] {new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" },
new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" },
new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" },
new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }};
var query = from CarnivorousPlant cPlant in plants
where cPlant.TrapType == "Snap Trap"
select cPlant;
foreach (var e in query) {
Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
class Plant {
public string Name { get; set; }
}
class CarnivorousPlant : Plant {
public string TrapType { get; set; }
}
}
Module Module1
Sub Main()
Dim plants() As Plant = {New CarnivorousPlant With {.Name = "Venus Fly Trap", .TrapType = "Snap Trap"},
New CarnivorousPlant With {.Name = "Pitcher Plant", .TrapType = "Pitfall Trap"},
New CarnivorousPlant With {.Name = "Sundew", .TrapType = "Flypaper Trap"},
New CarnivorousPlant With {.Name = "Waterwheel Plant", .TrapType = "Snap Trap"}}
Dim list = From cPlant As CarnivorousPlant In plants
Where cPlant.TrapType = "Snap Trap"
Select cPlant
For Each e In list
Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType)
Next
Console.WriteLine(vbLf & "Press any key to continue.")
Console.ReadKey()
End Sub
Class Plant
Public Property Name As String
End Class
Class CarnivorousPlant
Inherits Plant
Public Property TrapType As String
End Class
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
Name = Venus Fly Trap, TrapType = Snap Trap
Name = Waterwheel Plant, TrapType = Snap Trap
Press any key to continue.
23 Lectures
1.5 hours
Anadi Sharma
37 Lectures
13 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1832,
"s": 1736,
"text": "The operators change the type of input objects and are used in a diverse range of applications."
},
{
"code": null,
"e": 2902,
"s": 1832,
"text": "using System;\nusing System.Linq;\n\nnamespace Operators {\n class Cast {\n static void Main(string[] args) {\n \n Plant[] plants = new Plant[] {new CarnivorousPlant { Name = \"Venus Fly Trap\", TrapType = \"Snap Trap\" },\n new CarnivorousPlant { Name = \"Pitcher Plant\", TrapType = \"Pitfall Trap\" },\n new CarnivorousPlant { Name = \"Sundew\", TrapType = \"Flypaper Trap\" },\n new CarnivorousPlant { Name = \"Waterwheel Plant\", TrapType = \"Snap Trap\" }};\n\n var query = from CarnivorousPlant cPlant in plants\n where cPlant.TrapType == \"Snap Trap\"\n select cPlant;\n\n foreach (var e in query) {\n Console.WriteLine(\"Name = {0} , Trap Type = {1}\", e.Name, e.TrapType);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n\n class Plant {\n public string Name { get; set; }\n }\n\n class CarnivorousPlant : Plant {\n public string TrapType { get; set; }\n }\n}"
},
{
"code": null,
"e": 3906,
"s": 2902,
"text": "Module Module1\n Sub Main()\n\n Dim plants() As Plant = {New CarnivorousPlant With {.Name = \"Venus Fly Trap\", .TrapType = \"Snap Trap\"},\n New CarnivorousPlant With {.Name = \"Pitcher Plant\", .TrapType = \"Pitfall Trap\"},\n New CarnivorousPlant With {.Name = \"Sundew\", .TrapType = \"Flypaper Trap\"},\n New CarnivorousPlant With {.Name = \"Waterwheel Plant\", .TrapType = \"Snap Trap\"}}\n\n Dim list = From cPlant As CarnivorousPlant In plants\n Where cPlant.TrapType = \"Snap Trap\"\n Select cPlant\n\n For Each e In list\n Console.WriteLine(\"Name = {0} , Trap Type = {1}\", e.Name, e.TrapType)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n End Sub\n\n Class Plant\n Public Property Name As String\n End Class\n\n Class CarnivorousPlant\n Inherits Plant\n Public Property TrapType As String\n End Class\n\nEnd Module"
},
{
"code": null,
"e": 3999,
"s": 3906,
"text": "When the above code in C# or VB is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4118,
"s": 3999,
"text": "Name = Venus Fly Trap, TrapType = Snap Trap\nName = Waterwheel Plant, TrapType = Snap Trap\n\nPress any key to continue.\n"
},
{
"code": null,
"e": 4153,
"s": 4118,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4167,
"s": 4153,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4201,
"s": 4167,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4219,
"s": 4201,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4226,
"s": 4219,
"text": " Print"
},
{
"code": null,
"e": 4237,
"s": 4226,
"text": " Add Notes"
}
] |
Quick Sort
|
The quicksort technique is done by separating the list into two parts. Initially, a pivot element is chosen by partitioning algorithm. The left part of the pivot holds the smaller values than the pivot, and right part holds the larger value. After partitioning, each separate lists are partitioned using the same procedure.
Time Complexity: O(n log n) for best case and average case, O(n^2) for the worst case.
Space Complexity: O(log n)
Input:
The unsorted list: 90 45 22 11 22 50
Output:
Array before Sorting: 90 45 22 11 22 50
Array after Sorting: 11 22 22 45 50 90
partition(array, lower, upper)
Output: Pivot in the correct position
Begin
pivot := array[lower]
start := lower and end := upper
while start < end do
while array[start] <= pivot AND start < end do
start := start +1
done
while array[end] > pivot do
end := end – 1
done
if start < end then
swap array[start] with array[end]
done
array[lower] := array[end]
array[end] := pivot
return end
End
quickSort(array, left, right
Input − An array of data, and lower and upper bound of the array
Output − The sorted Array
Begin
if lower < right then
q = partition(arraym left, right)
quickSort(array, left, q-1)
quickSort(array, q+1, right)
End
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
int partition(int *array, int lower, int upper) {
//Hoare partitioning technique to find correct location for pivot
int pivot, start, end;
pivot = array[lower]; //first element as pivot
start = lower; end = upper;
while(start < end) {
while(array[start] <= pivot && start<end) {
start++; //start pointer moves to right
}
while(array[end] > pivot) {
end--; //end pointer moves to left
}
if(start < end) {
swap(array[start], array[end]); //swap smaller and bigger element
}
}
array[lower] = array[end];
array[end] = pivot;
return end;
}
void quickSort(int *array, int left, int right) {
int q;
if(left < right) {
q = partition(array, left, right);
quickSort(array, left, q-1); //sort left sub-array
quickSort(array, q+1, right); //sort right sub-array
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
quickSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}
Enter the number of elements: 6
Enter elements:
90 45 22 11 22 50
Array before Sorting: 90 45 22 11 22 50
Array after Sorting: 11 22 22 45 50 90
|
[
{
"code": null,
"e": 1386,
"s": 1062,
"text": "The quicksort technique is done by separating the list into two parts. Initially, a pivot element is chosen by partitioning algorithm. The left part of the pivot holds the smaller values than the pivot, and right part holds the larger value. After partitioning, each separate lists are partitioned using the same procedure."
},
{
"code": null,
"e": 1473,
"s": 1386,
"text": "Time Complexity: O(n log n) for best case and average case, O(n^2) for the worst case."
},
{
"code": null,
"e": 1500,
"s": 1473,
"text": "Space Complexity: O(log n)"
},
{
"code": null,
"e": 1631,
"s": 1500,
"text": "Input:\nThe unsorted list: 90 45 22 11 22 50\nOutput:\nArray before Sorting: 90 45 22 11 22 50\nArray after Sorting: 11 22 22 45 50 90"
},
{
"code": null,
"e": 1662,
"s": 1631,
"text": "partition(array, lower, upper)"
},
{
"code": null,
"e": 1700,
"s": 1662,
"text": "Output: Pivot in the correct position"
},
{
"code": null,
"e": 2100,
"s": 1700,
"text": "Begin\n pivot := array[lower]\n start := lower and end := upper\n while start < end do\n while array[start] <= pivot AND start < end do\n start := start +1\n done\n\n while array[end] > pivot do\n end := end – 1\n done\n if start < end then\n swap array[start] with array[end]\n done\n\n array[lower] := array[end]\n array[end] := pivot\n return end\nEnd"
},
{
"code": null,
"e": 2129,
"s": 2100,
"text": "quickSort(array, left, right"
},
{
"code": null,
"e": 2194,
"s": 2129,
"text": "Input − An array of data, and lower and upper bound of the array"
},
{
"code": null,
"e": 2220,
"s": 2194,
"text": "Output − The sorted Array"
},
{
"code": null,
"e": 2364,
"s": 2220,
"text": "Begin\n if lower < right then\n q = partition(arraym left, right)\n quickSort(array, left, q-1)\n quickSort(array, q+1, right)\nEnd"
},
{
"code": null,
"e": 3941,
"s": 2364,
"text": "#include<iostream>\nusing namespace std;\n\nvoid swapping(int &a, int &b) { //swap the content of a and b\n int temp;\n temp = a;\n a = b;\n b = temp;\n}\n\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nint partition(int *array, int lower, int upper) {\n //Hoare partitioning technique to find correct location for pivot\n int pivot, start, end;\n pivot = array[lower]; //first element as pivot\n start = lower; end = upper;\n\n while(start < end) {\n while(array[start] <= pivot && start<end) {\n start++; //start pointer moves to right\n }\n\n while(array[end] > pivot) {\n end--; //end pointer moves to left\n }\n\n if(start < end) {\n swap(array[start], array[end]); //swap smaller and bigger element\n }\n }\n\n array[lower] = array[end];\n array[end] = pivot;\n return end;\n}\n\nvoid quickSort(int *array, int left, int right) {\n int q;\n\n if(left < right) {\n q = partition(array, left, right);\n quickSort(array, left, q-1); //sort left sub-array\n quickSort(array, q+1, right); //sort right sub-array\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n quickSort(arr, 0, n-1); //(n-1) for last index\n cout << \"Array after Sorting: \";\n display(arr, n);\n}"
},
{
"code": null,
"e": 4087,
"s": 3941,
"text": "Enter the number of elements: 6\nEnter elements:\n90 45 22 11 22 50\nArray before Sorting: 90 45 22 11 22 50\nArray after Sorting: 11 22 22 45 50 90 "
}
] |
StandardScaler, MinMaxScaler and RobustScaler techniques - ML - GeeksforGeeks
|
20 Aug, 2021
StandardScaler follows Standard Normal Distribution (SND). Therefore, it makes mean = 0 and scales the data to unit variance. MinMaxScaler scales all the data features in the range [0, 1] or else in the range [-1, 1] if there are negative values in the dataset. This scaling compresses all the inliers in the narrow range [0, 0.005]. In the presence of outliers, StandardScaler does not guarantee balanced feature scales, due to the influence of the outliers while computing the empirical mean and standard deviation. This leads to the shrinkage in the range of the feature values. By using RobustScaler(), we can remove the outliers and then use either StandardScaler or MinMaxScaler for preprocessing the dataset. How RobustScaler works: class sklearn.preprocessing.RobustScaler( with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True, ) It scales features using statistics that are robust to outliers. This method removes the median and scales the data in the range between 1st quartile and 3rd quartile. i.e., in between 25th quantile and 75th quantile range. This range is also called an Interquartile range. The median and the interquartile range are then stored so that it could be used upon future data using the transform method. If outliers are present in the dataset, then the median and the interquartile range provide better results and outperform the sample mean and variance. RobustScaler uses the interquartile range so that it is robust to outliers. Therefore its formula is as follows: Code: comparison between StandardScaler, MinMaxScaler and RobustScaler.
Python3
# Importing librariesimport pandas as pdimport numpy as npfrom sklearn import preprocessingimport matplotlibimport matplotlib.pyplot as pltimport seaborn as sns % matplotlib inlinematplotlib.style.use('fivethirtyeight') # datax = pd.DataFrame({ # Distribution with lower outliers 'x1': np.concatenate([np.random.normal(20, 2, 1000), np.random.normal(1, 2, 25)]), # Distribution with higher outliers 'x2': np.concatenate([np.random.normal(30, 2, 1000), np.random.normal(50, 2, 25)]),})np.random.normal scaler = preprocessing.RobustScaler()robust_df = scaler.fit_transform(x)robust_df = pd.DataFrame(robust_df, columns =['x1', 'x2']) scaler = preprocessing.StandardScaler()standard_df = scaler.fit_transform(x)standard_df = pd.DataFrame(standard_df, columns =['x1', 'x2']) scaler = preprocessing.MinMaxScaler()minmax_df = scaler.fit_transform(x)minmax_df = pd.DataFrame(minmax_df, columns =['x1', 'x2']) fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols = 4, figsize =(20, 5))ax1.set_title('Before Scaling') sns.kdeplot(x['x1'], ax = ax1, color ='r')sns.kdeplot(x['x2'], ax = ax1, color ='b')ax2.set_title('After Robust Scaling') sns.kdeplot(robust_df['x1'], ax = ax2, color ='red')sns.kdeplot(robust_df['x2'], ax = ax2, color ='blue')ax3.set_title('After Standard Scaling') sns.kdeplot(standard_df['x1'], ax = ax3, color ='black')sns.kdeplot(standard_df['x2'], ax = ax3, color ='g')ax4.set_title('After Min-Max Scaling') sns.kdeplot(minmax_df['x1'], ax = ax4, color ='black')sns.kdeplot(minmax_df['x2'], ax = ax4, color ='g')plt.show()
Output:
Parameters of RobustScaler:
with_centering: boolean: It is True by default. If the value is True, the data is centred before scaling. When it is applied on sparse matrices, the transform will raise an exception because centring them requires building a dense matrix, which generally is too large to fit in the memory.
with_scaling: boolean: It is also set to True by default. It scales the data to the interquartile range.
quantile_range: tuple(q_min, q_max), 0.0 < q_min < q_max < 100.0 : Quantile range is used to calculate scale. By default, it is set as below. Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR.
copy: boolean It is an optional parameter. By default, it is True. If the input is already a NumPy array or a scipy.sparse CSC matrix and if axis = 1, avoid a copy by setting this parameter to False and instead perform inplace row normalization.
Attributes:
center_: array of floats: The median value for each feature in the training set.
scale_: array of floats: The scaled interquartile range for the feature in the training set.
ceydahamurcu95
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Python | Decision tree implementation
Difference between Informed and Uninformed Search in AI
Elbow Method for optimal value of k in KMeans
Deploy Machine Learning Model using Flask
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": 24065,
"s": 24037,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 25666,
"s": 24065,
"text": "StandardScaler follows Standard Normal Distribution (SND). Therefore, it makes mean = 0 and scales the data to unit variance. MinMaxScaler scales all the data features in the range [0, 1] or else in the range [-1, 1] if there are negative values in the dataset. This scaling compresses all the inliers in the narrow range [0, 0.005]. In the presence of outliers, StandardScaler does not guarantee balanced feature scales, due to the influence of the outliers while computing the empirical mean and standard deviation. This leads to the shrinkage in the range of the feature values. By using RobustScaler(), we can remove the outliers and then use either StandardScaler or MinMaxScaler for preprocessing the dataset. How RobustScaler works: class sklearn.preprocessing.RobustScaler( with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True, ) It scales features using statistics that are robust to outliers. This method removes the median and scales the data in the range between 1st quartile and 3rd quartile. i.e., in between 25th quantile and 75th quantile range. This range is also called an Interquartile range. The median and the interquartile range are then stored so that it could be used upon future data using the transform method. If outliers are present in the dataset, then the median and the interquartile range provide better results and outperform the sample mean and variance. RobustScaler uses the interquartile range so that it is robust to outliers. Therefore its formula is as follows: Code: comparison between StandardScaler, MinMaxScaler and RobustScaler. "
},
{
"code": null,
"e": 25674,
"s": 25666,
"text": "Python3"
},
{
"code": "# Importing librariesimport pandas as pdimport numpy as npfrom sklearn import preprocessingimport matplotlibimport matplotlib.pyplot as pltimport seaborn as sns % matplotlib inlinematplotlib.style.use('fivethirtyeight') # datax = pd.DataFrame({ # Distribution with lower outliers 'x1': np.concatenate([np.random.normal(20, 2, 1000), np.random.normal(1, 2, 25)]), # Distribution with higher outliers 'x2': np.concatenate([np.random.normal(30, 2, 1000), np.random.normal(50, 2, 25)]),})np.random.normal scaler = preprocessing.RobustScaler()robust_df = scaler.fit_transform(x)robust_df = pd.DataFrame(robust_df, columns =['x1', 'x2']) scaler = preprocessing.StandardScaler()standard_df = scaler.fit_transform(x)standard_df = pd.DataFrame(standard_df, columns =['x1', 'x2']) scaler = preprocessing.MinMaxScaler()minmax_df = scaler.fit_transform(x)minmax_df = pd.DataFrame(minmax_df, columns =['x1', 'x2']) fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols = 4, figsize =(20, 5))ax1.set_title('Before Scaling') sns.kdeplot(x['x1'], ax = ax1, color ='r')sns.kdeplot(x['x2'], ax = ax1, color ='b')ax2.set_title('After Robust Scaling') sns.kdeplot(robust_df['x1'], ax = ax2, color ='red')sns.kdeplot(robust_df['x2'], ax = ax2, color ='blue')ax3.set_title('After Standard Scaling') sns.kdeplot(standard_df['x1'], ax = ax3, color ='black')sns.kdeplot(standard_df['x2'], ax = ax3, color ='g')ax4.set_title('After Min-Max Scaling') sns.kdeplot(minmax_df['x1'], ax = ax4, color ='black')sns.kdeplot(minmax_df['x2'], ax = ax4, color ='g')plt.show()",
"e": 27218,
"s": 25674,
"text": null
},
{
"code": null,
"e": 27228,
"s": 27218,
"text": "Output: "
},
{
"code": null,
"e": 27258,
"s": 27228,
"text": "Parameters of RobustScaler: "
},
{
"code": null,
"e": 27548,
"s": 27258,
"text": "with_centering: boolean: It is True by default. If the value is True, the data is centred before scaling. When it is applied on sparse matrices, the transform will raise an exception because centring them requires building a dense matrix, which generally is too large to fit in the memory."
},
{
"code": null,
"e": 27653,
"s": 27548,
"text": "with_scaling: boolean: It is also set to True by default. It scales the data to the interquartile range."
},
{
"code": null,
"e": 27855,
"s": 27653,
"text": "quantile_range: tuple(q_min, q_max), 0.0 < q_min < q_max < 100.0 : Quantile range is used to calculate scale. By default, it is set as below. Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR."
},
{
"code": null,
"e": 28101,
"s": 27855,
"text": "copy: boolean It is an optional parameter. By default, it is True. If the input is already a NumPy array or a scipy.sparse CSC matrix and if axis = 1, avoid a copy by setting this parameter to False and instead perform inplace row normalization."
},
{
"code": null,
"e": 28115,
"s": 28101,
"text": "Attributes: "
},
{
"code": null,
"e": 28196,
"s": 28115,
"text": "center_: array of floats: The median value for each feature in the training set."
},
{
"code": null,
"e": 28289,
"s": 28196,
"text": "scale_: array of floats: The scaled interquartile range for the feature in the training set."
},
{
"code": null,
"e": 28306,
"s": 28291,
"text": "ceydahamurcu95"
},
{
"code": null,
"e": 28323,
"s": 28306,
"text": "Machine Learning"
},
{
"code": null,
"e": 28330,
"s": 28323,
"text": "Python"
},
{
"code": null,
"e": 28347,
"s": 28330,
"text": "Machine Learning"
},
{
"code": null,
"e": 28445,
"s": 28347,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28454,
"s": 28445,
"text": "Comments"
},
{
"code": null,
"e": 28467,
"s": 28454,
"text": "Old Comments"
},
{
"code": null,
"e": 28490,
"s": 28467,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28528,
"s": 28490,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28584,
"s": 28528,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 28630,
"s": 28584,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 28672,
"s": 28630,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 28700,
"s": 28672,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28750,
"s": 28700,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28772,
"s": 28750,
"text": "Python map() function"
}
] |
What is IGMP(Internet Group Management Protocol)?
|
07 Jul, 2022
IGMP is acronym for Internet Group Management Protocol. IGMP is a communication protocol used by hosts and adjacent routers for multicasting communication with IP networks and uses the resources efficiently to transmit the message/data packets. Multicast communication can have single or multiple senders and receivers and thus, IGMP can be used in streaming videos, gaming or web conferencing tools. This protocol is used on IPv4 networks and for using this on IPv6, multicasting is managed by Multicast Listener Discovery (MLD). Like other network protocols, IGMP is used on network layer. MLDv1 is almost same in functioning as IGMPv2 and MLDv2 is almost similar to IGMPv3. The communication protocol, IGMPv1 was developed in 1989 at Stanford University. IGMPv1 was updated to IGMPv2 in year 1997 and again updated to IGMPv3 in year 2002.
Applications:
Streaming – Multicast routing protocol are used for audio and video streaming over the network i.e., either one-to-many or many-to-many.
Gaming – Internet group management protocol is often used in simulation games which has multiple users over the network such as online games.
Web Conferencing tools – Video conferencing is a new method to meet people from your own convenience and IGMP connects to the users for conferencing and transfers the message/data packets efficiently.
Types: There are 3 versions of IGMP. These versions are backward compatible. Following are the versions of IGMP: 1. IGMPv1 : The version of IGMP communication protocol allows all the supporting hosts to join the multicast groups using membership request and include some basic features. But, host cannot leave the group on their own and have to wait for a timeout to leave the group. The message packet format in IGMPv1:
Version – Set to 1.
Type – 1 for Host Membership Query and Host Membership Report.
Unused – 8-bits of zero which are of no use.
Checksum – It is the one’s complement of the sum of IGMP messages.
Group Address – The group address field is zero when sent and ignored when received in membership query message. In a membership report message, the group address field takes the IP host group address of the group being reported.
2. IGMPv2 : IGMPv2 is the revised version of IGMPv1 communication protocol. It has added functionality of leaving the multicast group using group membership. The message packet format in IGMPv2:
Type:
0x11 for Membership Query
0x12 for IGMPv1 Membership Report
0x16 for IGMPv2 Membership Report
0x22 for IGMPv3 Membership Report
0x17 for Leave Group
Max Response Time – This field is ignored for message types other than membership query. For membership query type, it is the maximum time allowed before sending a response report. The value is in units of 0.1 seconds.
Checksum – It is the one’s complement of the sum of IGMP message.
Group Address – It is set as 0 when sending a general query. Otherwise, multicast address for group-specific or source-specific queries.
3. IGMPv3 : IGMPv2 was revised to IGMPv3 and added source-specific multicast and membership report aggregation. These reports are sent to 224.0.0.22. The message packet format in IGMPv3:
Max Response Time – This field is ignored for message types other than membership query. For membership query type, it is the maximum time allowed before sending a response report. The value is in units of 0.1 seconds.
Checksum – It is the one’s complement of the one’s complement of the sum of IGMP message.
Group Address – It is set as 0 when sending a general query. Otherwise, multicast address for group-specific or source-specific queries.
Resv – It is set zero of sent and ignored when received.
S flag – It represents Suppress Router-side Processing flag. When the flag is set, it indicates to suppress the timer updates that multicast routers perform upon receiving any query.
QRV – It represents Querier’s Robustness Variable. Routers keeps on retrieving the QRV value from the most recently received query as their own value until the most recently received QRV is zero.
QQIC – It represents Querier’s Query Interval Code.
Number of sources – It represents the number of source addresses present in the query. For general query or group-specific query, this field is zero and for group-and-source-specific query, this field is non-zero.
Source Address[i] – It represents the IP unicast address for N fields.
Working: IGMP works on devices that are capable of handling multicast groups and dynamic multicasting. These devices allows the host to join or leave the membership in the multicast group. These devices also allows to add and remove clients from the group. This communication protocol is operated between host and local multicast router. When a multicast group is created, the multicast group address is in range of class D (224-239) IP addresses and is forwarded as destination IP address in the packet. L2 or Level-2 devices such as switches are used in between host and multicast router for IGMP snooping. IGMP snooping is a process to listen to the IGMP network traffic in controlled manner. Switch receives the message from host and forwards the membership report to the local multicast router. The multicast traffic is further forwarded to remote routers from local multicast routers using PIM (Protocol Independent Multicast) so that clients can receive the message/data packets. Clients wishing to join the network sends join message in the query and switch intercepts the message and adds the ports of clients to its multicast routing table.
Advantages:
IGMP communication protocol efficiently transmits the multicast data to the receivers and so, no junk packets are transmitted to the host which shows optimized performance.
Bandwidth is consumed totally as all the shared links are connected.
Hosts can leave a multicast group and join another.
Disadvantages:
It does not provide good efficiency in filtering and security.
Due to lack of TCP, network congestion can occur.
IGMP is vulnerable to some attacks such as DOS attack (Denial-Of-Service).
krishna_97
Picked
Computer Networks
Full Form
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
Types of Network Topology
RSA Algorithm in Cryptography
Mobile Internet Protocol (or Mobile IP)
GSM in Wireless Communication
RDBMS Full Form
HTTP Full Form
FCFS Scheduling Full Form
DBA Full Form
CDMA Full Form
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 871,
"s": 28,
"text": "IGMP is acronym for Internet Group Management Protocol. IGMP is a communication protocol used by hosts and adjacent routers for multicasting communication with IP networks and uses the resources efficiently to transmit the message/data packets. Multicast communication can have single or multiple senders and receivers and thus, IGMP can be used in streaming videos, gaming or web conferencing tools. This protocol is used on IPv4 networks and for using this on IPv6, multicasting is managed by Multicast Listener Discovery (MLD). Like other network protocols, IGMP is used on network layer. MLDv1 is almost same in functioning as IGMPv2 and MLDv2 is almost similar to IGMPv3. The communication protocol, IGMPv1 was developed in 1989 at Stanford University. IGMPv1 was updated to IGMPv2 in year 1997 and again updated to IGMPv3 in year 2002. "
},
{
"code": null,
"e": 885,
"s": 871,
"text": "Applications:"
},
{
"code": null,
"e": 1022,
"s": 885,
"text": "Streaming – Multicast routing protocol are used for audio and video streaming over the network i.e., either one-to-many or many-to-many."
},
{
"code": null,
"e": 1164,
"s": 1022,
"text": "Gaming – Internet group management protocol is often used in simulation games which has multiple users over the network such as online games."
},
{
"code": null,
"e": 1365,
"s": 1164,
"text": "Web Conferencing tools – Video conferencing is a new method to meet people from your own convenience and IGMP connects to the users for conferencing and transfers the message/data packets efficiently."
},
{
"code": null,
"e": 1786,
"s": 1365,
"text": "Types: There are 3 versions of IGMP. These versions are backward compatible. Following are the versions of IGMP: 1. IGMPv1 : The version of IGMP communication protocol allows all the supporting hosts to join the multicast groups using membership request and include some basic features. But, host cannot leave the group on their own and have to wait for a timeout to leave the group. The message packet format in IGMPv1:"
},
{
"code": null,
"e": 1808,
"s": 1788,
"text": "Version – Set to 1."
},
{
"code": null,
"e": 1871,
"s": 1808,
"text": "Type – 1 for Host Membership Query and Host Membership Report."
},
{
"code": null,
"e": 1916,
"s": 1871,
"text": "Unused – 8-bits of zero which are of no use."
},
{
"code": null,
"e": 1983,
"s": 1916,
"text": "Checksum – It is the one’s complement of the sum of IGMP messages."
},
{
"code": null,
"e": 2213,
"s": 1983,
"text": "Group Address – The group address field is zero when sent and ignored when received in membership query message. In a membership report message, the group address field takes the IP host group address of the group being reported."
},
{
"code": null,
"e": 2408,
"s": 2213,
"text": "2. IGMPv2 : IGMPv2 is the revised version of IGMPv1 communication protocol. It has added functionality of leaving the multicast group using group membership. The message packet format in IGMPv2:"
},
{
"code": null,
"e": 2415,
"s": 2408,
"text": " Type:"
},
{
"code": null,
"e": 2566,
"s": 2415,
"text": "0x11 for Membership Query\n0x12 for IGMPv1 Membership Report\n0x16 for IGMPv2 Membership Report\n0x22 for IGMPv3 Membership Report\n0x17 for Leave Group "
},
{
"code": null,
"e": 2785,
"s": 2566,
"text": "Max Response Time – This field is ignored for message types other than membership query. For membership query type, it is the maximum time allowed before sending a response report. The value is in units of 0.1 seconds."
},
{
"code": null,
"e": 2851,
"s": 2785,
"text": "Checksum – It is the one’s complement of the sum of IGMP message."
},
{
"code": null,
"e": 2988,
"s": 2851,
"text": "Group Address – It is set as 0 when sending a general query. Otherwise, multicast address for group-specific or source-specific queries."
},
{
"code": null,
"e": 3175,
"s": 2988,
"text": "3. IGMPv3 : IGMPv2 was revised to IGMPv3 and added source-specific multicast and membership report aggregation. These reports are sent to 224.0.0.22. The message packet format in IGMPv3:"
},
{
"code": null,
"e": 3397,
"s": 3178,
"text": "Max Response Time – This field is ignored for message types other than membership query. For membership query type, it is the maximum time allowed before sending a response report. The value is in units of 0.1 seconds."
},
{
"code": null,
"e": 3487,
"s": 3397,
"text": "Checksum – It is the one’s complement of the one’s complement of the sum of IGMP message."
},
{
"code": null,
"e": 3624,
"s": 3487,
"text": "Group Address – It is set as 0 when sending a general query. Otherwise, multicast address for group-specific or source-specific queries."
},
{
"code": null,
"e": 3681,
"s": 3624,
"text": "Resv – It is set zero of sent and ignored when received."
},
{
"code": null,
"e": 3864,
"s": 3681,
"text": "S flag – It represents Suppress Router-side Processing flag. When the flag is set, it indicates to suppress the timer updates that multicast routers perform upon receiving any query."
},
{
"code": null,
"e": 4060,
"s": 3864,
"text": "QRV – It represents Querier’s Robustness Variable. Routers keeps on retrieving the QRV value from the most recently received query as their own value until the most recently received QRV is zero."
},
{
"code": null,
"e": 4112,
"s": 4060,
"text": "QQIC – It represents Querier’s Query Interval Code."
},
{
"code": null,
"e": 4326,
"s": 4112,
"text": "Number of sources – It represents the number of source addresses present in the query. For general query or group-specific query, this field is zero and for group-and-source-specific query, this field is non-zero."
},
{
"code": null,
"e": 4397,
"s": 4326,
"text": "Source Address[i] – It represents the IP unicast address for N fields."
},
{
"code": null,
"e": 5550,
"s": 4397,
"text": "Working: IGMP works on devices that are capable of handling multicast groups and dynamic multicasting. These devices allows the host to join or leave the membership in the multicast group. These devices also allows to add and remove clients from the group. This communication protocol is operated between host and local multicast router. When a multicast group is created, the multicast group address is in range of class D (224-239) IP addresses and is forwarded as destination IP address in the packet. L2 or Level-2 devices such as switches are used in between host and multicast router for IGMP snooping. IGMP snooping is a process to listen to the IGMP network traffic in controlled manner. Switch receives the message from host and forwards the membership report to the local multicast router. The multicast traffic is further forwarded to remote routers from local multicast routers using PIM (Protocol Independent Multicast) so that clients can receive the message/data packets. Clients wishing to join the network sends join message in the query and switch intercepts the message and adds the ports of clients to its multicast routing table. "
},
{
"code": null,
"e": 5562,
"s": 5550,
"text": "Advantages:"
},
{
"code": null,
"e": 5735,
"s": 5562,
"text": "IGMP communication protocol efficiently transmits the multicast data to the receivers and so, no junk packets are transmitted to the host which shows optimized performance."
},
{
"code": null,
"e": 5804,
"s": 5735,
"text": "Bandwidth is consumed totally as all the shared links are connected."
},
{
"code": null,
"e": 5856,
"s": 5804,
"text": "Hosts can leave a multicast group and join another."
},
{
"code": null,
"e": 5871,
"s": 5856,
"text": "Disadvantages:"
},
{
"code": null,
"e": 5934,
"s": 5871,
"text": "It does not provide good efficiency in filtering and security."
},
{
"code": null,
"e": 5984,
"s": 5934,
"text": "Due to lack of TCP, network congestion can occur."
},
{
"code": null,
"e": 6059,
"s": 5984,
"text": "IGMP is vulnerable to some attacks such as DOS attack (Denial-Of-Service)."
},
{
"code": null,
"e": 6070,
"s": 6059,
"text": "krishna_97"
},
{
"code": null,
"e": 6077,
"s": 6070,
"text": "Picked"
},
{
"code": null,
"e": 6095,
"s": 6077,
"text": "Computer Networks"
},
{
"code": null,
"e": 6105,
"s": 6095,
"text": "Full Form"
},
{
"code": null,
"e": 6123,
"s": 6105,
"text": "Computer Networks"
},
{
"code": null,
"e": 6221,
"s": 6123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6251,
"s": 6221,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 6277,
"s": 6251,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 6307,
"s": 6277,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 6347,
"s": 6307,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 6377,
"s": 6347,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 6393,
"s": 6377,
"text": "RDBMS Full Form"
},
{
"code": null,
"e": 6408,
"s": 6393,
"text": "HTTP Full Form"
},
{
"code": null,
"e": 6434,
"s": 6408,
"text": "FCFS Scheduling Full Form"
},
{
"code": null,
"e": 6448,
"s": 6434,
"text": "DBA Full Form"
}
] |
Tree Isomorphism Problem
|
21 Jun, 2022
Write a function to detect if two trees are isomorphic. Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.For example, following two trees are isomorphic with following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
We simultaneously traverse both trees. Let the current internal nodes of two trees being traversed be n1 and n2 respectively. There are following two conditions for subtrees rooted with n1 and n2 to be isomorphic.
Data of n1 and n2 is same. One of the following two is true for children of n1 and n2 ......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. ......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2.
Data of n1 and n2 is same.
One of the following two is true for children of n1 and n2 ......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. ......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2.
......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2.
......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2.
Implementation:
C++
Java
Python3
C#
Javascript
// A C++ program to check if two given trees are isomorphic#include <iostream>using namespace std; /* A binary tree node has data, pointer to left and right children */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, print its nodes in reverse level order */bool isIsomorphic(node* n1, node *n2){ // Both roots are NULL, trees isomorphic by definition if (n1 == NULL && n2 == NULL) return true; // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == NULL || n2 == NULL) return false; if (n1->data != n2->data) return false; // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been "Flipped". // Both of these subtrees have to be isomorphic, hence the && // Case 2: The subtrees rooted at these nodes have been "Flipped" return (isIsomorphic(n1->left,n2->left) && isIsomorphic(n1->right,n2->right))|| (isIsomorphic(n1->left,n2->right) && isIsomorphic(n1->right,n2->left));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return (temp);} /* Driver program to test above functions*/int main(){ // Let us create trees shown in above diagram struct node *n1 = newNode(1); n1->left = newNode(2); n1->right = newNode(3); n1->left->left = newNode(4); n1->left->right = newNode(5); n1->right->left = newNode(6); n1->left->right->left = newNode(7); n1->left->right->right = newNode(8); struct node *n2 = newNode(1); n2->left = newNode(3); n2->right = newNode(2); n2->right->left = newNode(4); n2->right->right = newNode(5); n2->left->right = newNode(6); n2->right->right->left = newNode(8); n2->right->right->right = newNode(7); if (isIsomorphic(n1, n2) == true) cout << "Yes"; else cout << "No"; return 0;}
// An iterative java program to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */class Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ Node root1, root2; /* Given a binary tree, print its nodes in reverse level order */ boolean isIsomorphic(Node n1, Node n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) return true; // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == null || n2 == null) return false; if (n1.data != n2.data) return false; // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been // "Flipped". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes have been "Flipped" return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code has been contributed by Mayank Jaiswal
# Python program to check if two given trees are isomorphic # A Binary tree nodeclass Node: # Constructor to create the node of binary tree def __init__(self, data): self.data = data self.left = None self.right = None # Check if the binary tree is isomorphic or notdef isIsomorphic(n1, n2): # Both roots are None, trees isomorphic by definition if n1 is None and n2 is None: return True # Exactly one of the n1 and n2 is None, trees are not # isomorphic if n1 is None or n2 is None: return False if n1.data != n2.data : return False # There are two possible cases for n1 and n2 to be isomorphic # Case 1: The subtrees rooted at these nodes have NOT # been "Flipped". # Both of these subtrees have to be isomorphic, hence the && # Case 2: The subtrees rooted at these nodes have # been "Flipped" return ((isIsomorphic(n1.left, n2.left)and isIsomorphic(n1.right, n2.right)) or (isIsomorphic(n1.left, n2.right) and isIsomorphic(n1.right, n2.left)) ) # Driver program to test above functionn1 = Node(1)n1.left = Node(2)n1.right = Node(3)n1.left.left = Node(4)n1.left.right = Node(5)n1.right.left = Node(6)n1.left.right.left = Node(7)n1.left.right.right = Node(8) n2 = Node(1)n2.left = Node(3)n2.right = Node(2)n2.right.left = Node(4)n2.right.right = Node(5)n2.left.right = Node(6)n2.right.right.left = Node(8)n2.right.right.right = Node(7) print ("Yes" if (isIsomorphic(n1, n2) == True) else "No") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // An iterative C# program to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ public Node root1, root2; /* Given a binary tree, print its nodes in reverse level order */ public virtual bool isIsomorphic(Node n1, Node n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) { return true; } // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == null || n2 == null) { return false; } if (n1.data != n2.data) { return false; } // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been // "Flipped". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes have been "Flipped" return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by Shrikant13
<script> // An iterative JavaScript program // to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */ class Node { constructor(item) { this.data = item; this.left = null; this.right = null; } } class BinaryTree { constructor() { this.root1 = null; this.root2 = null; } /* Given a binary tree, print its nodes in reverse level order */ isIsomorphic(n1, n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) { return true; } // Exactly one of the n1 and n2 is NULL, // trees not isomorphic if (n1 == null || n2 == null) { return false; } if (n1.data != n2.data) { return false; } // There are two possible cases for // n1 and n2 to be isomorphic // Case 1: The subtrees rooted at // these nodes have NOT been // "Flipped". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes // have been "Flipped" return ( (this.isIsomorphic(n1.left, n2.left) && this.isIsomorphic(n1.right, n2.right)) || (this.isIsomorphic(n1.left, n2.right) && this.isIsomorphic(n1.right, n2.left)) ); } } // Driver program to test above functions var tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) { document.write("Yes"); } else { document.write("No"); } </script>
Yes
Time Complexity: The above solution does a traversal of both trees. So time complexity is O(min(m,n)*2) or O(min(m,n)) where m and n are number of nodes in given trees.
Axone
shrikanth13
rdtank
amartyaghoshgfg
hardikkoriintern
Amazon
Microsoft
Tree
Amazon
Microsoft
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 480,
"s": 54,
"text": "Write a function to detect if two trees are isomorphic. Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.For example, following two trees are isomorphic with following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8. "
},
{
"code": null,
"e": 489,
"s": 480,
"text": "Chapters"
},
{
"code": null,
"e": 516,
"s": 489,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 566,
"s": 516,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 589,
"s": 566,
"text": "captions off, selected"
},
{
"code": null,
"e": 597,
"s": 589,
"text": "English"
},
{
"code": null,
"e": 621,
"s": 597,
"text": "This is a modal window."
},
{
"code": null,
"e": 690,
"s": 621,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 712,
"s": 690,
"text": "End of dialog window."
},
{
"code": null,
"e": 927,
"s": 712,
"text": "We simultaneously traverse both trees. Let the current internal nodes of two trees being traversed be n1 and n2 respectively. There are following two conditions for subtrees rooted with n1 and n2 to be isomorphic. "
},
{
"code": null,
"e": 1249,
"s": 927,
"text": "Data of n1 and n2 is same. One of the following two is true for children of n1 and n2 ......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. ......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2."
},
{
"code": null,
"e": 1277,
"s": 1249,
"text": "Data of n1 and n2 is same. "
},
{
"code": null,
"e": 1572,
"s": 1277,
"text": "One of the following two is true for children of n1 and n2 ......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. ......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2."
},
{
"code": null,
"e": 1691,
"s": 1572,
"text": "......a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2. "
},
{
"code": null,
"e": 1809,
"s": 1691,
"text": "......b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2."
},
{
"code": null,
"e": 1825,
"s": 1809,
"text": "Implementation:"
},
{
"code": null,
"e": 1829,
"s": 1825,
"text": "C++"
},
{
"code": null,
"e": 1834,
"s": 1829,
"text": "Java"
},
{
"code": null,
"e": 1842,
"s": 1834,
"text": "Python3"
},
{
"code": null,
"e": 1845,
"s": 1842,
"text": "C#"
},
{
"code": null,
"e": 1856,
"s": 1845,
"text": "Javascript"
},
{
"code": "// A C++ program to check if two given trees are isomorphic#include <iostream>using namespace std; /* A binary tree node has data, pointer to left and right children */struct node{ int data; struct node* left; struct node* right;}; /* Given a binary tree, print its nodes in reverse level order */bool isIsomorphic(node* n1, node *n2){ // Both roots are NULL, trees isomorphic by definition if (n1 == NULL && n2 == NULL) return true; // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == NULL || n2 == NULL) return false; if (n1->data != n2->data) return false; // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been \"Flipped\". // Both of these subtrees have to be isomorphic, hence the && // Case 2: The subtrees rooted at these nodes have been \"Flipped\" return (isIsomorphic(n1->left,n2->left) && isIsomorphic(n1->right,n2->right))|| (isIsomorphic(n1->left,n2->right) && isIsomorphic(n1->right,n2->left));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return (temp);} /* Driver program to test above functions*/int main(){ // Let us create trees shown in above diagram struct node *n1 = newNode(1); n1->left = newNode(2); n1->right = newNode(3); n1->left->left = newNode(4); n1->left->right = newNode(5); n1->right->left = newNode(6); n1->left->right->left = newNode(7); n1->left->right->right = newNode(8); struct node *n2 = newNode(1); n2->left = newNode(3); n2->right = newNode(2); n2->right->left = newNode(4); n2->right->right = newNode(5); n2->left->right = newNode(6); n2->right->right->left = newNode(8); n2->right->right->right = newNode(7); if (isIsomorphic(n1, n2) == true) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 3885,
"s": 1856,
"text": null
},
{
"code": "// An iterative java program to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */class Node{ int data; Node left, right; Node(int item) { data = item; left = right; }} class BinaryTree{ Node root1, root2; /* Given a binary tree, print its nodes in reverse level order */ boolean isIsomorphic(Node n1, Node n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) return true; // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == null || n2 == null) return false; if (n1.data != n2.data) return false; // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been // \"Flipped\". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes have been \"Flipped\" return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code has been contributed by Mayank Jaiswal",
"e": 6240,
"s": 3885,
"text": null
},
{
"code": "# Python program to check if two given trees are isomorphic # A Binary tree nodeclass Node: # Constructor to create the node of binary tree def __init__(self, data): self.data = data self.left = None self.right = None # Check if the binary tree is isomorphic or notdef isIsomorphic(n1, n2): # Both roots are None, trees isomorphic by definition if n1 is None and n2 is None: return True # Exactly one of the n1 and n2 is None, trees are not # isomorphic if n1 is None or n2 is None: return False if n1.data != n2.data : return False # There are two possible cases for n1 and n2 to be isomorphic # Case 1: The subtrees rooted at these nodes have NOT # been \"Flipped\". # Both of these subtrees have to be isomorphic, hence the && # Case 2: The subtrees rooted at these nodes have # been \"Flipped\" return ((isIsomorphic(n1.left, n2.left)and isIsomorphic(n1.right, n2.right)) or (isIsomorphic(n1.left, n2.right) and isIsomorphic(n1.right, n2.left)) ) # Driver program to test above functionn1 = Node(1)n1.left = Node(2)n1.right = Node(3)n1.left.left = Node(4)n1.left.right = Node(5)n1.right.left = Node(6)n1.left.right.left = Node(7)n1.left.right.right = Node(8) n2 = Node(1)n2.left = Node(3)n2.right = Node(2)n2.right.left = Node(4)n2.right.right = Node(5)n2.left.right = Node(6)n2.right.right.left = Node(8)n2.right.right.right = Node(7) print (\"Yes\" if (isIsomorphic(n1, n2) == True) else \"No\") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 7841,
"s": 6240,
"text": null
},
{
"code": "using System; // An iterative C# program to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right; }} public class BinaryTree{ public Node root1, root2; /* Given a binary tree, print its nodes in reverse level order */ public virtual bool isIsomorphic(Node n1, Node n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) { return true; } // Exactly one of the n1 and n2 is NULL, trees not isomorphic if (n1 == null || n2 == null) { return false; } if (n1.data != n2.data) { return false; } // There are two possible cases for n1 and n2 to be isomorphic // Case 1: The subtrees rooted at these nodes have NOT been // \"Flipped\". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes have been \"Flipped\" return (isIsomorphic(n1.left, n2.left) && isIsomorphic(n1.right, n2.right)) || (isIsomorphic(n1.left, n2.right) && isIsomorphic(n1.right, n2.left)); } // Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by Shrikant13",
"e": 10256,
"s": 7841,
"text": null
},
{
"code": "<script> // An iterative JavaScript program // to solve tree isomorphism problem /* A binary tree node has data, pointer to left and right children */ class Node { constructor(item) { this.data = item; this.left = null; this.right = null; } } class BinaryTree { constructor() { this.root1 = null; this.root2 = null; } /* Given a binary tree, print its nodes in reverse level order */ isIsomorphic(n1, n2) { // Both roots are NULL, trees isomorphic by definition if (n1 == null && n2 == null) { return true; } // Exactly one of the n1 and n2 is NULL, // trees not isomorphic if (n1 == null || n2 == null) { return false; } if (n1.data != n2.data) { return false; } // There are two possible cases for // n1 and n2 to be isomorphic // Case 1: The subtrees rooted at // these nodes have NOT been // \"Flipped\". // Both of these subtrees have to be isomorphic. // Case 2: The subtrees rooted at these nodes // have been \"Flipped\" return ( (this.isIsomorphic(n1.left, n2.left) && this.isIsomorphic(n1.right, n2.right)) || (this.isIsomorphic(n1.left, n2.right) && this.isIsomorphic(n1.right, n2.left)) ); } } // Driver program to test above functions var tree = new BinaryTree(); // Let us create trees shown in above diagram tree.root1 = new Node(1); tree.root1.left = new Node(2); tree.root1.right = new Node(3); tree.root1.left.left = new Node(4); tree.root1.left.right = new Node(5); tree.root1.right.left = new Node(6); tree.root1.left.right.left = new Node(7); tree.root1.left.right.right = new Node(8); tree.root2 = new Node(1); tree.root2.left = new Node(3); tree.root2.right = new Node(2); tree.root2.right.left = new Node(4); tree.root2.right.right = new Node(5); tree.root2.left.right = new Node(6); tree.root2.right.right.left = new Node(8); tree.root2.right.right.right = new Node(7); if (tree.isIsomorphic(tree.root1, tree.root2) == true) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>",
"e": 12702,
"s": 10256,
"text": null
},
{
"code": null,
"e": 12706,
"s": 12702,
"text": "Yes"
},
{
"code": null,
"e": 12875,
"s": 12706,
"text": "Time Complexity: The above solution does a traversal of both trees. So time complexity is O(min(m,n)*2) or O(min(m,n)) where m and n are number of nodes in given trees."
},
{
"code": null,
"e": 12881,
"s": 12875,
"text": "Axone"
},
{
"code": null,
"e": 12893,
"s": 12881,
"text": "shrikanth13"
},
{
"code": null,
"e": 12900,
"s": 12893,
"text": "rdtank"
},
{
"code": null,
"e": 12916,
"s": 12900,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 12933,
"s": 12916,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12940,
"s": 12933,
"text": "Amazon"
},
{
"code": null,
"e": 12950,
"s": 12940,
"text": "Microsoft"
},
{
"code": null,
"e": 12955,
"s": 12950,
"text": "Tree"
},
{
"code": null,
"e": 12962,
"s": 12955,
"text": "Amazon"
},
{
"code": null,
"e": 12972,
"s": 12962,
"text": "Microsoft"
},
{
"code": null,
"e": 12977,
"s": 12972,
"text": "Tree"
}
] |
Perl keys Function
|
This function returns all the keys of the HASH as a list. The keys are returned in random order but, in fact, share the same order as that used by values and each.
Following is the simple syntax for this function −
keys HASH
This function returns number of keys in the hash in scalar context and list of keys in list context.
Following is the example code showing its basic usage −
#!/usr/bin/perl
%hash = ('One' => 1,
'Two' => 2,
'Three' => 3,
'Four' => 4);
@values = values( %hash );
print("Values are ", join("-", @values), "\n");
@keys = keys( %hash );
print("Keys are ", join("-", @keys), "\n");
When above code is executed, it produces the following result −
Values are 4-3-2-1
Keys are Four-Three-Two-One
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2384,
"s": 2220,
"text": "This function returns all the keys of the HASH as a list. The keys are returned in random order but, in fact, share the same order as that used by values and each."
},
{
"code": null,
"e": 2435,
"s": 2384,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2446,
"s": 2435,
"text": "keys HASH\n"
},
{
"code": null,
"e": 2547,
"s": 2446,
"text": "This function returns number of keys in the hash in scalar context and list of keys in list context."
},
{
"code": null,
"e": 2603,
"s": 2547,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2853,
"s": 2603,
"text": "#!/usr/bin/perl\n\n%hash = ('One' => 1,\n 'Two' => 2,\n 'Three' => 3,\n 'Four' => 4);\n\n@values = values( %hash );\nprint(\"Values are \", join(\"-\", @values), \"\\n\");\n\n@keys = keys( %hash );\nprint(\"Keys are \", join(\"-\", @keys), \"\\n\");"
},
{
"code": null,
"e": 2917,
"s": 2853,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2966,
"s": 2917,
"text": "Values are 4-3-2-1\nKeys are Four-Three-Two-One\n"
},
{
"code": null,
"e": 3001,
"s": 2966,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3015,
"s": 3001,
"text": " Devi Killada"
},
{
"code": null,
"e": 3050,
"s": 3015,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3070,
"s": 3050,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3103,
"s": 3070,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3119,
"s": 3103,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3152,
"s": 3119,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3169,
"s": 3152,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3202,
"s": 3169,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3225,
"s": 3202,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3260,
"s": 3225,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3283,
"s": 3260,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3290,
"s": 3283,
"text": " Print"
},
{
"code": null,
"e": 3301,
"s": 3290,
"text": " Add Notes"
}
] |
Clean, Connect and Visualize Interactively with DataPrep | by Cornellius Yudha Wijaya | Towards Data Science
|
Data preparation is the initial step that any data professional does. Whether you want to analyze the data or preprocess the data for a machine learning model, you need to prepare the data.
Preparing data means you need to collect, clean, and explore the data. To do all the activities I have mentioned, there is a Python package developed called DataPrep. How did this package would help us? Let’s explore it together.
DataPrep is a Python Package developed to prepare your data. This package contains three main APIs for us to use, they are:
Data Exploration ( dataprep.eda )
Data Cleaning( dataprep.clean )
Data Collection ( dataprep.connector )
DataPrep packages are designed to have a fast data exploration and work well with Pandas and Dask DataFrame objects. To explore the DataPrep capability, we need to install the package first.
pip install -U dataprep
After we finish installing the package, let’s use the APIs to prepare our data.
DataPrep offers us to create an interactive profile report with one line of code. This report object is an HTML object separated from our Notebook with many choices of exploration. Let’s try the API with the sample data.
from dataprep.datasets import load_datasetfrom dataprep.eda import create_reportdf = load_dataset("titanic")df.head()
We would use the Titanic sample dataset for our data. After we have loaded our data, we would use the create_report function to produce the interactive report.
create_report(df).show_browser()
As we can see in the GIF above, API creates a nice interactive report for us to explore. Let’s try to dissect the information one by one.
From the overview tab, we can see all the overview information from our dataset. The information we could get included Missing data numbers and percentages, Duplicate data, variable data type, and detailed information for each variable.
The variables tab gives us detailed information for each variable within our dataset. Almost all the information you need is available, for example, unique, missing data, quantile and descriptive statistics, distribution, and normality.
The interactions tab would create a scatter plot from two numerical variables. We could set the X-axis and Y-axis ourselves, which gives us control over how we want to visualize it.
The correlations tab gives us the statistical correlation calculation heatmap plot between numerical values. Currently, there are three calculations we could use— Pearson, Spearman, and KendallTau.
The missing Values tab gives us all the detailed information regarding the missing values in our tab. We could choose the Bar Chart, Spectrum, Heat Map, and Dendrogram to fully explore the missing values information.
DataPrep Cleaning API collection offers more than 140 APIs to clean and validate our DataFrame. For example, the APIs we can use are:
Column Headers
Country Names
Dates and Times
Duplicate Values
Email Addresses
And many more. There are so many functions we could try, and this article could not cover all the APIs. If you are interested, you can check out the documentation here.
Let’s try the Columns Headers cleaning function with our Titanic dataset example.
from dataprep.clean import clean_headersclean_headers(df, case = 'const').head()
Using the ‘Const’ case, we would end up with all capitalized columns names. If we switch the case into ‘Camel.’
clean_headers(df, case = 'camel').head()
The result is all lower columns name except for the ‘sibSp’ column, where they have two words within their column name.
If you want to have a complete clean DataFrame, we could use the clean_df API from DataPrep. This API would have two outputs — the inferred data type and the cleaned DataFrame.
from dataprep.clean import clean_dfinferred_dtypes, cleaned_df = clean_df(df)
There are many parameters you could play around with the API. I suggest you read all the documentation to see which parameters suit your data preparation purposes.
DataPrep Collection APIs are used for collecting the data from Database or Web API. If we have access to the database such as MySQL or PostgreSQL, you could connect it with the DataPrep API, but it is also possible to access the public API using DataPrep connect API.
If you want to collect the data from the web, it would still need the API Code, but everything is simplified. If you want to read more about the collection API, you can read it all here.
DataPrep is a one-liner Python Package used to clean, connect, and explore the dataset you have. The capability includes:
Data Exploration ( dataprep.eda )
Data Cleaning( dataprep.clean )
Data Collection ( dataprep.connector )
I hope it helps!
Visit me on my LinkedIn or Twitter.
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 361,
"s": 171,
"text": "Data preparation is the initial step that any data professional does. Whether you want to analyze the data or preprocess the data for a machine learning model, you need to prepare the data."
},
{
"code": null,
"e": 591,
"s": 361,
"text": "Preparing data means you need to collect, clean, and explore the data. To do all the activities I have mentioned, there is a Python package developed called DataPrep. How did this package would help us? Let’s explore it together."
},
{
"code": null,
"e": 715,
"s": 591,
"text": "DataPrep is a Python Package developed to prepare your data. This package contains three main APIs for us to use, they are:"
},
{
"code": null,
"e": 749,
"s": 715,
"text": "Data Exploration ( dataprep.eda )"
},
{
"code": null,
"e": 781,
"s": 749,
"text": "Data Cleaning( dataprep.clean )"
},
{
"code": null,
"e": 820,
"s": 781,
"text": "Data Collection ( dataprep.connector )"
},
{
"code": null,
"e": 1011,
"s": 820,
"text": "DataPrep packages are designed to have a fast data exploration and work well with Pandas and Dask DataFrame objects. To explore the DataPrep capability, we need to install the package first."
},
{
"code": null,
"e": 1035,
"s": 1011,
"text": "pip install -U dataprep"
},
{
"code": null,
"e": 1115,
"s": 1035,
"text": "After we finish installing the package, let’s use the APIs to prepare our data."
},
{
"code": null,
"e": 1336,
"s": 1115,
"text": "DataPrep offers us to create an interactive profile report with one line of code. This report object is an HTML object separated from our Notebook with many choices of exploration. Let’s try the API with the sample data."
},
{
"code": null,
"e": 1454,
"s": 1336,
"text": "from dataprep.datasets import load_datasetfrom dataprep.eda import create_reportdf = load_dataset(\"titanic\")df.head()"
},
{
"code": null,
"e": 1614,
"s": 1454,
"text": "We would use the Titanic sample dataset for our data. After we have loaded our data, we would use the create_report function to produce the interactive report."
},
{
"code": null,
"e": 1647,
"s": 1614,
"text": "create_report(df).show_browser()"
},
{
"code": null,
"e": 1785,
"s": 1647,
"text": "As we can see in the GIF above, API creates a nice interactive report for us to explore. Let’s try to dissect the information one by one."
},
{
"code": null,
"e": 2022,
"s": 1785,
"text": "From the overview tab, we can see all the overview information from our dataset. The information we could get included Missing data numbers and percentages, Duplicate data, variable data type, and detailed information for each variable."
},
{
"code": null,
"e": 2259,
"s": 2022,
"text": "The variables tab gives us detailed information for each variable within our dataset. Almost all the information you need is available, for example, unique, missing data, quantile and descriptive statistics, distribution, and normality."
},
{
"code": null,
"e": 2441,
"s": 2259,
"text": "The interactions tab would create a scatter plot from two numerical variables. We could set the X-axis and Y-axis ourselves, which gives us control over how we want to visualize it."
},
{
"code": null,
"e": 2639,
"s": 2441,
"text": "The correlations tab gives us the statistical correlation calculation heatmap plot between numerical values. Currently, there are three calculations we could use— Pearson, Spearman, and KendallTau."
},
{
"code": null,
"e": 2856,
"s": 2639,
"text": "The missing Values tab gives us all the detailed information regarding the missing values in our tab. We could choose the Bar Chart, Spectrum, Heat Map, and Dendrogram to fully explore the missing values information."
},
{
"code": null,
"e": 2990,
"s": 2856,
"text": "DataPrep Cleaning API collection offers more than 140 APIs to clean and validate our DataFrame. For example, the APIs we can use are:"
},
{
"code": null,
"e": 3005,
"s": 2990,
"text": "Column Headers"
},
{
"code": null,
"e": 3019,
"s": 3005,
"text": "Country Names"
},
{
"code": null,
"e": 3035,
"s": 3019,
"text": "Dates and Times"
},
{
"code": null,
"e": 3052,
"s": 3035,
"text": "Duplicate Values"
},
{
"code": null,
"e": 3068,
"s": 3052,
"text": "Email Addresses"
},
{
"code": null,
"e": 3237,
"s": 3068,
"text": "And many more. There are so many functions we could try, and this article could not cover all the APIs. If you are interested, you can check out the documentation here."
},
{
"code": null,
"e": 3319,
"s": 3237,
"text": "Let’s try the Columns Headers cleaning function with our Titanic dataset example."
},
{
"code": null,
"e": 3400,
"s": 3319,
"text": "from dataprep.clean import clean_headersclean_headers(df, case = 'const').head()"
},
{
"code": null,
"e": 3512,
"s": 3400,
"text": "Using the ‘Const’ case, we would end up with all capitalized columns names. If we switch the case into ‘Camel.’"
},
{
"code": null,
"e": 3553,
"s": 3512,
"text": "clean_headers(df, case = 'camel').head()"
},
{
"code": null,
"e": 3673,
"s": 3553,
"text": "The result is all lower columns name except for the ‘sibSp’ column, where they have two words within their column name."
},
{
"code": null,
"e": 3850,
"s": 3673,
"text": "If you want to have a complete clean DataFrame, we could use the clean_df API from DataPrep. This API would have two outputs — the inferred data type and the cleaned DataFrame."
},
{
"code": null,
"e": 3928,
"s": 3850,
"text": "from dataprep.clean import clean_dfinferred_dtypes, cleaned_df = clean_df(df)"
},
{
"code": null,
"e": 4092,
"s": 3928,
"text": "There are many parameters you could play around with the API. I suggest you read all the documentation to see which parameters suit your data preparation purposes."
},
{
"code": null,
"e": 4360,
"s": 4092,
"text": "DataPrep Collection APIs are used for collecting the data from Database or Web API. If we have access to the database such as MySQL or PostgreSQL, you could connect it with the DataPrep API, but it is also possible to access the public API using DataPrep connect API."
},
{
"code": null,
"e": 4547,
"s": 4360,
"text": "If you want to collect the data from the web, it would still need the API Code, but everything is simplified. If you want to read more about the collection API, you can read it all here."
},
{
"code": null,
"e": 4669,
"s": 4547,
"text": "DataPrep is a one-liner Python Package used to clean, connect, and explore the dataset you have. The capability includes:"
},
{
"code": null,
"e": 4703,
"s": 4669,
"text": "Data Exploration ( dataprep.eda )"
},
{
"code": null,
"e": 4735,
"s": 4703,
"text": "Data Cleaning( dataprep.clean )"
},
{
"code": null,
"e": 4774,
"s": 4735,
"text": "Data Collection ( dataprep.connector )"
},
{
"code": null,
"e": 4791,
"s": 4774,
"text": "I hope it helps!"
},
{
"code": null,
"e": 4827,
"s": 4791,
"text": "Visit me on my LinkedIn or Twitter."
},
{
"code": null,
"e": 4997,
"s": 4827,
"text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here."
}
] |
An Introduction to Discretization Techniques for Data Scientists | by Rohan Gupta | Towards Data Science
|
Discretization is the process through which we can transform continuous variables, models or functions into a discrete form. We do this by creating a set of contiguous intervals (or bins) that go across the range of our desired variable/model/function.
Continuous data is Measured, while Discrete data is Counted.
Mathematical problems with continuous data have an infinite number of DoF. Such a problem would entail having limited degrees of freedom (DoF) since our calculations cannot go on forever. Data Scientists require using Discretization for a number of reasons. Many of the top contributions on Kaggle use discretization for some of the following reasons:
Often, it is easier to understand continuous data (such as weight) when divided and stored into meaningful categories or groups. For example, we can divide a continuous variable, weight, and store it in the following groups :Under 100 lbs (light), between 140–160 lbs (mid), and over 200 lbs (heavy)
We would consider the structure useful if we see no objective difference between variables falling under the same weight class. In our example, weights of 85 lbs and 56 lbs convey the same information (the object is light). Therefore, discretization helps make our data easier to understand if it fits the problem statement.
Continuous features have a smaller chance of correlating with the target variable due to infinite degrees of freedom and may have a complex non-linear relationship. Thus, it may be harder to interpret an such a function. After discretizing a variable, groups corresponding to the target can be interpreted.
Certain models may be incompatible with continuous data, for example, alternative decision-tree models such as a Random-Forest model is not suitable for continuous features.
Feature engineering methods, for example any entropy-based methods may not work with continuous data, thus we would discretize variables to work with different models & methods.
When we discretize a model, we are fitting it to bins and reducing the impact of small fluctuation in the data. Often, we would consider small fluctuations as noise. We can reduce this noise through discretization. This is the process of “smoothing”, wherein each bin smoothens fluctuations, thus reducing noise in the data.
Unsupervised: — Equal-Width — Equal-Frequency — K-Means
Supervised: — Decision Trees
Separating all possible values into ‘N’ number of bins, each having the same width. Formula for interval width:
Width = (maximum value - minimum value) / N* where N is the number of bins or intervals.
On python, you would want to import the following for discretization:
from sklearn.preprocessing import KBinsDiscretizerfrom feature_engine.discretisers import EqualWidthDiscretiser
Set up the Equal-Width Discretizer in the following way:
discretizer = EqualWidthDiscretiser(bins=10, variables = ['var1', 'var2'])#OR discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')
Equal Width doesn’t improve the value spread
It can handle outliers
Can be combined with categorical encodings
Separating all possible values into ‘N’ number of bins, each having the same amount of observations. Intervals may correspond to quantile values.
On python, you would want to import the following for discretization:
from sklearn.preprocessing import KBinsDiscretizerfrom feature_engine.discretisers import EqualFrequencyDiscretiser
Set up the Equal-Frequency Discretizer in the following way:
discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile')#OR discretizer = EqualFrequencyDiscretiser(q=10, variables = ['var1', 'var2'])
Equal Frequency does improve the value spread
It can handle outliers
Can be combined with categorical encoding
We apply K-Means clustering to the continuous variable, thus dividing it into discrete groups or clusters.
On python, you would want to import the following for discretization with K-means:
from sklearn.preprocessing import KBinsDiscretizer
Set up the K-means Discretizer in the following way:
discretizer = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='kmeans')
K-Means doesn’t improve the value spread
It can handle outliers, however a centroid bias may exist.
Can be combined with categorical encoding
We use a decision tree to identify the optimal number of bins. When the model makes a decision, it assigns an observation for each node. These observations are then classified into discrete output for our variable.
On python, you would want to import the following for discretization with decision trees:
from sklearn.model_selection import train_test_splitfrom feature_engine.discretisers import DecisionTreeDiscretiser
Your Discretizer should be set up in the following way:
# cross-validation number (cv)# how to evaluate model performance (scoring)# the variables we want to discretise (variables)# whether it is a target for regression or classification# and the grid with the parameters we want to testtreeDisc = DecisionTreeDiscretiser(cv=10, scoring='accuracy', variables=['var1', 'var2'], regression=False, param_grid={'max_depth': [1,2,3],'min_samples_leaf':[10,4]})
Decision Tree does not improve the value spread
It can handle outliers well as trees are robust to outliers.
Creates monotonic relationships
After discretizing variables, you can do either of the following:
Build decision tree algorithms and directly use the output of discretization as the number of bins. The decision trees can find non-linear relationships between the discretized variable and the target variables.
Use a linear model, while the bins do not have a linear relationship with the target variable. Improve the model by treating bins as categories with some sort of encoding.
Thanks for the read!
Follow me for more content on Data Science.
|
[
{
"code": null,
"e": 424,
"s": 171,
"text": "Discretization is the process through which we can transform continuous variables, models or functions into a discrete form. We do this by creating a set of contiguous intervals (or bins) that go across the range of our desired variable/model/function."
},
{
"code": null,
"e": 485,
"s": 424,
"text": "Continuous data is Measured, while Discrete data is Counted."
},
{
"code": null,
"e": 837,
"s": 485,
"text": "Mathematical problems with continuous data have an infinite number of DoF. Such a problem would entail having limited degrees of freedom (DoF) since our calculations cannot go on forever. Data Scientists require using Discretization for a number of reasons. Many of the top contributions on Kaggle use discretization for some of the following reasons:"
},
{
"code": null,
"e": 1137,
"s": 837,
"text": "Often, it is easier to understand continuous data (such as weight) when divided and stored into meaningful categories or groups. For example, we can divide a continuous variable, weight, and store it in the following groups :Under 100 lbs (light), between 140–160 lbs (mid), and over 200 lbs (heavy)"
},
{
"code": null,
"e": 1462,
"s": 1137,
"text": "We would consider the structure useful if we see no objective difference between variables falling under the same weight class. In our example, weights of 85 lbs and 56 lbs convey the same information (the object is light). Therefore, discretization helps make our data easier to understand if it fits the problem statement."
},
{
"code": null,
"e": 1769,
"s": 1462,
"text": "Continuous features have a smaller chance of correlating with the target variable due to infinite degrees of freedom and may have a complex non-linear relationship. Thus, it may be harder to interpret an such a function. After discretizing a variable, groups corresponding to the target can be interpreted."
},
{
"code": null,
"e": 1943,
"s": 1769,
"text": "Certain models may be incompatible with continuous data, for example, alternative decision-tree models such as a Random-Forest model is not suitable for continuous features."
},
{
"code": null,
"e": 2121,
"s": 1943,
"text": "Feature engineering methods, for example any entropy-based methods may not work with continuous data, thus we would discretize variables to work with different models & methods."
},
{
"code": null,
"e": 2446,
"s": 2121,
"text": "When we discretize a model, we are fitting it to bins and reducing the impact of small fluctuation in the data. Often, we would consider small fluctuations as noise. We can reduce this noise through discretization. This is the process of “smoothing”, wherein each bin smoothens fluctuations, thus reducing noise in the data."
},
{
"code": null,
"e": 2503,
"s": 2446,
"text": "Unsupervised: — Equal-Width — Equal-Frequency — K-Means"
},
{
"code": null,
"e": 2532,
"s": 2503,
"text": "Supervised: — Decision Trees"
},
{
"code": null,
"e": 2644,
"s": 2532,
"text": "Separating all possible values into ‘N’ number of bins, each having the same width. Formula for interval width:"
},
{
"code": null,
"e": 2733,
"s": 2644,
"text": "Width = (maximum value - minimum value) / N* where N is the number of bins or intervals."
},
{
"code": null,
"e": 2803,
"s": 2733,
"text": "On python, you would want to import the following for discretization:"
},
{
"code": null,
"e": 2915,
"s": 2803,
"text": "from sklearn.preprocessing import KBinsDiscretizerfrom feature_engine.discretisers import EqualWidthDiscretiser"
},
{
"code": null,
"e": 2972,
"s": 2915,
"text": "Set up the Equal-Width Discretizer in the following way:"
},
{
"code": null,
"e": 3130,
"s": 2972,
"text": "discretizer = EqualWidthDiscretiser(bins=10, variables = ['var1', 'var2'])#OR discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')"
},
{
"code": null,
"e": 3175,
"s": 3130,
"text": "Equal Width doesn’t improve the value spread"
},
{
"code": null,
"e": 3198,
"s": 3175,
"text": "It can handle outliers"
},
{
"code": null,
"e": 3241,
"s": 3198,
"text": "Can be combined with categorical encodings"
},
{
"code": null,
"e": 3387,
"s": 3241,
"text": "Separating all possible values into ‘N’ number of bins, each having the same amount of observations. Intervals may correspond to quantile values."
},
{
"code": null,
"e": 3457,
"s": 3387,
"text": "On python, you would want to import the following for discretization:"
},
{
"code": null,
"e": 3573,
"s": 3457,
"text": "from sklearn.preprocessing import KBinsDiscretizerfrom feature_engine.discretisers import EqualFrequencyDiscretiser"
},
{
"code": null,
"e": 3634,
"s": 3573,
"text": "Set up the Equal-Frequency Discretizer in the following way:"
},
{
"code": null,
"e": 3794,
"s": 3634,
"text": "discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile')#OR discretizer = EqualFrequencyDiscretiser(q=10, variables = ['var1', 'var2'])"
},
{
"code": null,
"e": 3840,
"s": 3794,
"text": "Equal Frequency does improve the value spread"
},
{
"code": null,
"e": 3863,
"s": 3840,
"text": "It can handle outliers"
},
{
"code": null,
"e": 3905,
"s": 3863,
"text": "Can be combined with categorical encoding"
},
{
"code": null,
"e": 4012,
"s": 3905,
"text": "We apply K-Means clustering to the continuous variable, thus dividing it into discrete groups or clusters."
},
{
"code": null,
"e": 4095,
"s": 4012,
"text": "On python, you would want to import the following for discretization with K-means:"
},
{
"code": null,
"e": 4146,
"s": 4095,
"text": "from sklearn.preprocessing import KBinsDiscretizer"
},
{
"code": null,
"e": 4199,
"s": 4146,
"text": "Set up the K-means Discretizer in the following way:"
},
{
"code": null,
"e": 4277,
"s": 4199,
"text": "discretizer = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='kmeans')"
},
{
"code": null,
"e": 4318,
"s": 4277,
"text": "K-Means doesn’t improve the value spread"
},
{
"code": null,
"e": 4377,
"s": 4318,
"text": "It can handle outliers, however a centroid bias may exist."
},
{
"code": null,
"e": 4419,
"s": 4377,
"text": "Can be combined with categorical encoding"
},
{
"code": null,
"e": 4634,
"s": 4419,
"text": "We use a decision tree to identify the optimal number of bins. When the model makes a decision, it assigns an observation for each node. These observations are then classified into discrete output for our variable."
},
{
"code": null,
"e": 4724,
"s": 4634,
"text": "On python, you would want to import the following for discretization with decision trees:"
},
{
"code": null,
"e": 4840,
"s": 4724,
"text": "from sklearn.model_selection import train_test_splitfrom feature_engine.discretisers import DecisionTreeDiscretiser"
},
{
"code": null,
"e": 4896,
"s": 4840,
"text": "Your Discretizer should be set up in the following way:"
},
{
"code": null,
"e": 5398,
"s": 4896,
"text": "# cross-validation number (cv)# how to evaluate model performance (scoring)# the variables we want to discretise (variables)# whether it is a target for regression or classification# and the grid with the parameters we want to testtreeDisc = DecisionTreeDiscretiser(cv=10, scoring='accuracy', variables=['var1', 'var2'], regression=False, param_grid={'max_depth': [1,2,3],'min_samples_leaf':[10,4]})"
},
{
"code": null,
"e": 5446,
"s": 5398,
"text": "Decision Tree does not improve the value spread"
},
{
"code": null,
"e": 5507,
"s": 5446,
"text": "It can handle outliers well as trees are robust to outliers."
},
{
"code": null,
"e": 5539,
"s": 5507,
"text": "Creates monotonic relationships"
},
{
"code": null,
"e": 5605,
"s": 5539,
"text": "After discretizing variables, you can do either of the following:"
},
{
"code": null,
"e": 5817,
"s": 5605,
"text": "Build decision tree algorithms and directly use the output of discretization as the number of bins. The decision trees can find non-linear relationships between the discretized variable and the target variables."
},
{
"code": null,
"e": 5989,
"s": 5817,
"text": "Use a linear model, while the bins do not have a linear relationship with the target variable. Improve the model by treating bins as categories with some sort of encoding."
},
{
"code": null,
"e": 6010,
"s": 5989,
"text": "Thanks for the read!"
}
] |
HSQLDB - Where Clause
|
Generally, we use SELECT command to fetch data from HSQLDB table. We can use WHERE conditional clause to filter the resultant data. Using WHERE we can specify the selection criteria to select the required records from a table.
Following is the syntax of SELECT command WHERE clause to fetch data from HSQLDB table.
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....
You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command.
You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command.
You can specify any condition using WHERE clause.
You can specify any condition using WHERE clause.
You can specify more than one conditions using AND or OR operators.
You can specify more than one conditions using AND or OR operators.
A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition.
A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition.
We can filter the record data by using conditions. We are using different operators in conditional WHERE clause. Here is the list of operators, which can be used with WHERE clause.
Here is an example that retrieves the details such as id, title, and the author of the book titled "Learn C". It is possible by using WHERE clause in the SELECT command. Following is the query for the same.
SELECT id, title, author FROM tutorials_tbl WHERE title = 'Learn C';
After execution of the above query, you will receive the following output.
+------+----------------+-----------------+
| id | title | author |
+------+----------------+-----------------+
| 101 | Learn C | Yaswanth |
+------+----------------+-----------------+
Here is the JDBC program that retrieves the record data from the table tutorials_tblhaving the title Learn C. Save the following code into WhereClause.java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class WhereClause {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet result = null;
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
con = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/testdb", "SA", "");
stmt = con.createStatement();
result = stmt.executeQuery(
"SELECT id, title, author FROM tutorials_tbl
WHERE title = 'Learn C'");
while(result.next()){
System.out.println(result.getInt("id")+" |
"+result.getString("title")+" |
"+result.getString("author"));
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
You can start the database using the following command.
\>cd C:\hsqldb-2.3.4\hsqldb
hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0
file:hsqldb/demodb --dbname.0 testdb
Compile and execute the above code using the following command.
\>javac WhereClause.java
\>java WhereClause
After execution of the above command, you will receive the following output.
101 | Learn C | Yaswanth
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2209,
"s": 1982,
"text": "Generally, we use SELECT command to fetch data from HSQLDB table. We can use WHERE conditional clause to filter the resultant data. Using WHERE we can specify the selection criteria to select the required records from a table."
},
{
"code": null,
"e": 2297,
"s": 2209,
"text": "Following is the syntax of SELECT command WHERE clause to fetch data from HSQLDB table."
},
{
"code": null,
"e": 2403,
"s": 2297,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE condition1 [AND [OR]] condition2.....\n"
},
{
"code": null,
"e": 2561,
"s": 2403,
"text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command."
},
{
"code": null,
"e": 2719,
"s": 2561,
"text": "You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command."
},
{
"code": null,
"e": 2769,
"s": 2719,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 2819,
"s": 2769,
"text": "You can specify any condition using WHERE clause."
},
{
"code": null,
"e": 2887,
"s": 2819,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 2955,
"s": 2887,
"text": "You can specify more than one conditions using AND or OR operators."
},
{
"code": null,
"e": 3051,
"s": 2955,
"text": "A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 3147,
"s": 3051,
"text": "A WHERE clause can also be used along with DELETE or UPDATE SQL command to specify a condition."
},
{
"code": null,
"e": 3328,
"s": 3147,
"text": "We can filter the record data by using conditions. We are using different operators in conditional WHERE clause. Here is the list of operators, which can be used with WHERE clause."
},
{
"code": null,
"e": 3535,
"s": 3328,
"text": "Here is an example that retrieves the details such as id, title, and the author of the book titled \"Learn C\". It is possible by using WHERE clause in the SELECT command. Following is the query for the same."
},
{
"code": null,
"e": 3605,
"s": 3535,
"text": "SELECT id, title, author FROM tutorials_tbl WHERE title = 'Learn C';\n"
},
{
"code": null,
"e": 3680,
"s": 3605,
"text": "After execution of the above query, you will receive the following output."
},
{
"code": null,
"e": 3901,
"s": 3680,
"text": "+------+----------------+-----------------+\n| id | title | author |\n+------+----------------+-----------------+\n| 101 | Learn C | Yaswanth |\n+------+----------------+-----------------+\n"
},
{
"code": null,
"e": 4058,
"s": 3901,
"text": "Here is the JDBC program that retrieves the record data from the table tutorials_tblhaving the title Learn C. Save the following code into WhereClause.java."
},
{
"code": null,
"e": 4966,
"s": 4058,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\n\npublic class WhereClause {\n \n public static void main(String[] args) {\n Connection con = null;\n Statement stmt = null;\n ResultSet result = null;\n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\n \"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n result = stmt.executeQuery(\n \"SELECT id, title, author FROM tutorials_tbl\n WHERE title = 'Learn C'\");\n \n while(result.next()){\n System.out.println(result.getInt(\"id\")+\" |\n \"+result.getString(\"title\")+\" |\n \"+result.getString(\"author\"));\n }\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n }\n\n}"
},
{
"code": null,
"e": 5022,
"s": 4966,
"text": "You can start the database using the following command."
},
{
"code": null,
"e": 5164,
"s": 5022,
"text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb\n"
},
{
"code": null,
"e": 5228,
"s": 5164,
"text": "Compile and execute the above code using the following command."
},
{
"code": null,
"e": 5273,
"s": 5228,
"text": "\\>javac WhereClause.java\n\\>java WhereClause\n"
},
{
"code": null,
"e": 5350,
"s": 5273,
"text": "After execution of the above command, you will receive the following output."
},
{
"code": null,
"e": 5376,
"s": 5350,
"text": "101 | Learn C | Yaswanth\n"
},
{
"code": null,
"e": 5383,
"s": 5376,
"text": " Print"
},
{
"code": null,
"e": 5394,
"s": 5383,
"text": " Add Notes"
}
] |
jQuery Effect - Clip Effect
|
The Clip effect can be used with show/hide/toggle. This clips the element on or off, vertically or horizontally.
Here is the simple syntax to use this effect −
selector.hide|show|toggle( "clip", {arguments}, speed );
Here is the description of all the arguments −
direction − The direction of the effect. Can be "vertical" or "horizontal". Default is vertical.
direction − The direction of the effect. Can be "vertical" or "horizontal". Default is vertical.
mode − The mode of the effect. Can be "show" or "hide". Default is hide.
mode − The mode of the effect. Can be "show" or "hide". Default is hide.
Following is a simple example a simple showing the usage of this effect −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#hide").click(function(){
$(".target").hide( "clip", {direction: "horizontal"}, 1000 );
});
$("#show").click(function(){
$(".target").show( "clip", {direction: "vertical"}, 1000 );
});
});
</script>
<style>
p {background-color:#bca; width:200px; border:1px solid green;}
</style>
</head>
<body>
<p>Click on any of the buttons</p>
<button id = "hide"> Hide </button>
<button id = "show"> Show</button>
<div class = "target">
<img src = "../images/jquery.jpg" alt = "jQuery" />
</div>
</body>
</html>
This will produce following result −
Click on any of the buttons
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2435,
"s": 2322,
"text": "The Clip effect can be used with show/hide/toggle. This clips the element on or off, vertically or horizontally."
},
{
"code": null,
"e": 2482,
"s": 2435,
"text": "Here is the simple syntax to use this effect −"
},
{
"code": null,
"e": 2540,
"s": 2482,
"text": "selector.hide|show|toggle( \"clip\", {arguments}, speed );\n"
},
{
"code": null,
"e": 2587,
"s": 2540,
"text": "Here is the description of all the arguments −"
},
{
"code": null,
"e": 2684,
"s": 2587,
"text": "direction − The direction of the effect. Can be \"vertical\" or \"horizontal\". Default is vertical."
},
{
"code": null,
"e": 2781,
"s": 2684,
"text": "direction − The direction of the effect. Can be \"vertical\" or \"horizontal\". Default is vertical."
},
{
"code": null,
"e": 2854,
"s": 2781,
"text": "mode − The mode of the effect. Can be \"show\" or \"hide\". Default is hide."
},
{
"code": null,
"e": 2927,
"s": 2854,
"text": "mode − The mode of the effect. Can be \"show\" or \"hide\". Default is hide."
},
{
"code": null,
"e": 3001,
"s": 2927,
"text": "Following is a simple example a simple showing the usage of this effect −"
},
{
"code": null,
"e": 4143,
"s": 3001,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n \n $(document).ready(function() {\n\n $(\"#hide\").click(function(){\n $(\".target\").hide( \"clip\", {direction: \"horizontal\"}, 1000 );\n });\n\n $(\"#show\").click(function(){\n $(\".target\").show( \"clip\", {direction: \"vertical\"}, 1000 );\n });\n\t\t\t\t\n });\n\t\t\t\n </script>\n\t\t\n <style>\n p {background-color:#bca; width:200px; border:1px solid green;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any of the buttons</p>\n\t\t\n <button id = \"hide\"> Hide </button>\n <button id = \"show\"> Show</button> \n\t\t\n <div class = \"target\">\n <img src = \"../images/jquery.jpg\" alt = \"jQuery\" />\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4180,
"s": 4143,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4208,
"s": 4180,
"text": "Click on any of the buttons"
},
{
"code": null,
"e": 4241,
"s": 4208,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4255,
"s": 4241,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4290,
"s": 4255,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4304,
"s": 4290,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4339,
"s": 4304,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4356,
"s": 4339,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4389,
"s": 4356,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4417,
"s": 4389,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4450,
"s": 4417,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4471,
"s": 4450,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4503,
"s": 4471,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4520,
"s": 4503,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4527,
"s": 4520,
"text": " Print"
},
{
"code": null,
"e": 4538,
"s": 4527,
"text": " Add Notes"
}
] |
PyTorch - Datasets
|
In this chapter, we will focus more on torchvision.datasets and its various types. PyTorch includes following dataset loaders −
MNIST
COCO (Captioning and Detection)
Dataset includes majority of two types of functions given below −
Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms.
Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms.
Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices.
Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices.
The following is the sample code for MNIST dataset −
dset.MNIST(root, train = TRUE, transform = NONE,
target_transform = None, download = FALSE)
The parameters are as follows −
root − root directory of the dataset where processed data exist.
root − root directory of the dataset where processed data exist.
train − True = Training set, False = Test set
train − True = Training set, False = Test set
download − True = downloads the dataset from the internet and puts it in the root.
download − True = downloads the dataset from the internet and puts it in the root.
This requires the COCO API to be installed. The following example is used to demonstrate the COCO implementation of dataset using PyTorch −
import torchvision.dataset as dset
import torchvision.transforms as transforms
cap = dset.CocoCaptions(root = ‘ dir where images are’,
annFile = ’json annotation file’,
transform = transforms.ToTensor())
print(‘Number of samples: ‘, len(cap))
print(target)
The output achieved is as follows −
Number of samples: 82783
Image Size: (3L, 427L, 640L)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2387,
"s": 2259,
"text": "In this chapter, we will focus more on torchvision.datasets and its various types. PyTorch includes following dataset loaders −"
},
{
"code": null,
"e": 2393,
"s": 2387,
"text": "MNIST"
},
{
"code": null,
"e": 2425,
"s": 2393,
"text": "COCO (Captioning and Detection)"
},
{
"code": null,
"e": 2491,
"s": 2425,
"text": "Dataset includes majority of two types of functions given below −"
},
{
"code": null,
"e": 2635,
"s": 2491,
"text": "Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms."
},
{
"code": null,
"e": 2779,
"s": 2635,
"text": "Transform − a function that takes in an image and returns a modified version of standard stuff. These can be composed together with transforms."
},
{
"code": null,
"e": 2930,
"s": 2779,
"text": "Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices."
},
{
"code": null,
"e": 3081,
"s": 2930,
"text": "Target_transform − a function that takes the target and transforms it. For example, takes in the caption string and returns a tensor of world indices."
},
{
"code": null,
"e": 3134,
"s": 3081,
"text": "The following is the sample code for MNIST dataset −"
},
{
"code": null,
"e": 3227,
"s": 3134,
"text": "dset.MNIST(root, train = TRUE, transform = NONE, \ntarget_transform = None, download = FALSE)"
},
{
"code": null,
"e": 3259,
"s": 3227,
"text": "The parameters are as follows −"
},
{
"code": null,
"e": 3324,
"s": 3259,
"text": "root − root directory of the dataset where processed data exist."
},
{
"code": null,
"e": 3389,
"s": 3324,
"text": "root − root directory of the dataset where processed data exist."
},
{
"code": null,
"e": 3435,
"s": 3389,
"text": "train − True = Training set, False = Test set"
},
{
"code": null,
"e": 3481,
"s": 3435,
"text": "train − True = Training set, False = Test set"
},
{
"code": null,
"e": 3564,
"s": 3481,
"text": "download − True = downloads the dataset from the internet and puts it in the root."
},
{
"code": null,
"e": 3647,
"s": 3564,
"text": "download − True = downloads the dataset from the internet and puts it in the root."
},
{
"code": null,
"e": 3787,
"s": 3647,
"text": "This requires the COCO API to be installed. The following example is used to demonstrate the COCO implementation of dataset using PyTorch −"
},
{
"code": null,
"e": 4045,
"s": 3787,
"text": "import torchvision.dataset as dset\nimport torchvision.transforms as transforms\ncap = dset.CocoCaptions(root = ‘ dir where images are’, \nannFile = ’json annotation file’,\ntransform = transforms.ToTensor())\nprint(‘Number of samples: ‘, len(cap))\nprint(target)"
},
{
"code": null,
"e": 4081,
"s": 4045,
"text": "The output achieved is as follows −"
},
{
"code": null,
"e": 4136,
"s": 4081,
"text": "Number of samples: 82783\nImage Size: (3L, 427L, 640L)\n"
},
{
"code": null,
"e": 4143,
"s": 4136,
"text": " Print"
},
{
"code": null,
"e": 4154,
"s": 4143,
"text": " Add Notes"
}
] |
How to open External Programs using Tkinter?
|
Sometimes, while creating an application, we need to interact with external programs and applications. In order to interact with the system's applications and programs, we have to use os Module in python.
In this article, we will see how we can interact with external programs and open
files using the OS module in Python.
First, we will define a function that will open the chosen file using the filedialog library in Python. Then, we will print the path and open the file using the os module.
# Import the required Libraries
from tkinter import *
from tkinter import filedialog
import os
#Create an instance of tkinter frame
win= Tk()
#Set the geometry for the window or frame
win.geometry("600x400")
#Define a function to open the application
def app():
file= filedialog.askopenfilename()
text.config(text= file)
#Open the program
os.system('"%s"' %file)
#Create a button
Button(win, text='Click to Open a Program',font=('Poppins bold', 10),
command=app).pack(pady=20)
#Create a Label after button event
text= Label(win, text= "", font= ('Poppins bold', 10))
text.pack(pady=20)
#Keep running the window or frame
win.mainloop()
Running the above code will produce the following window as the output −
Now, click the button and it will open the “My Documents” folder from where you
can open a program.
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "Sometimes, while creating an application, we need to interact with external programs and applications. In order to interact with the system's applications and programs, we have to use os Module in python."
},
{
"code": null,
"e": 1385,
"s": 1267,
"text": "In this article, we will see how we can interact with external programs and open\nfiles using the OS module in Python."
},
{
"code": null,
"e": 1557,
"s": 1385,
"text": "First, we will define a function that will open the chosen file using the filedialog library in Python. Then, we will print the path and open the file using the os module."
},
{
"code": null,
"e": 2211,
"s": 1557,
"text": "# Import the required Libraries\nfrom tkinter import *\nfrom tkinter import filedialog\nimport os\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry for the window or frame\nwin.geometry(\"600x400\")\n\n#Define a function to open the application\n\ndef app():\n file= filedialog.askopenfilename()\n text.config(text= file)\n #Open the program\n os.system('\"%s\"' %file)\n\n#Create a button\nButton(win, text='Click to Open a Program',font=('Poppins bold', 10),\ncommand=app).pack(pady=20)\n\n#Create a Label after button event\ntext= Label(win, text= \"\", font= ('Poppins bold', 10))\ntext.pack(pady=20)\n\n#Keep running the window or frame\nwin.mainloop()"
},
{
"code": null,
"e": 2284,
"s": 2211,
"text": "Running the above code will produce the following window as the output −"
},
{
"code": null,
"e": 2384,
"s": 2284,
"text": "Now, click the button and it will open the “My Documents” folder from where you\ncan open a program."
}
] |
Bootstrap Glyphicons
|
Bootstrap provides 260 glyphicons from the Glyphicons
Halflings set.
Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc.
Here are some examples of glyphicons:
Envelope glyphicon:
Print glyphicon:
Search glyphicon:
Download glyphicon:
A glyphicon is inserted with the following syntax:
The name part in the syntax above must be replaced with the proper name of the glyphicon.
The following example shows different ways to use glyphicons:
Use a Glyphicon class value to make the span display as a "search" icon.
<span class=""></span>
Start the Exercise
For a complete reference of all glyphicons, go to our complete
Bootstrap Glyphicon Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 69,
"s": 0,
"text": "Bootstrap provides 260 glyphicons from the Glyphicons\nHalflings set."
},
{
"code": null,
"e": 144,
"s": 69,
"text": "Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc."
},
{
"code": null,
"e": 182,
"s": 144,
"text": "Here are some examples of glyphicons:"
},
{
"code": null,
"e": 203,
"s": 182,
"text": "Envelope glyphicon: "
},
{
"code": null,
"e": 221,
"s": 203,
"text": "Print glyphicon: "
},
{
"code": null,
"e": 240,
"s": 221,
"text": "Search glyphicon: "
},
{
"code": null,
"e": 261,
"s": 240,
"text": "Download glyphicon: "
},
{
"code": null,
"e": 312,
"s": 261,
"text": "A glyphicon is inserted with the following syntax:"
},
{
"code": null,
"e": 402,
"s": 312,
"text": "The name part in the syntax above must be replaced with the proper name of the glyphicon."
},
{
"code": null,
"e": 464,
"s": 402,
"text": "The following example shows different ways to use glyphicons:"
},
{
"code": null,
"e": 537,
"s": 464,
"text": "Use a Glyphicon class value to make the span display as a \"search\" icon."
},
{
"code": null,
"e": 561,
"s": 537,
"text": "<span class=\"\"></span>\n"
},
{
"code": null,
"e": 580,
"s": 561,
"text": "Start the Exercise"
},
{
"code": null,
"e": 674,
"s": 580,
"text": "For a complete reference of all glyphicons, go to our complete\nBootstrap Glyphicon Reference."
},
{
"code": null,
"e": 707,
"s": 674,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 749,
"s": 707,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 856,
"s": 749,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 875,
"s": 856,
"text": "help@w3schools.com"
}
] |
Cypress - Alerts
|
Cypress can work with alerts by default. The pop-up can be an alert or confirmation popup.Cypress is designed in such a way that it shall always click on the OK button on the pop-up. Moreover, Cypress has the ability to fire the browser events.
An alert is triggered by window:alert event. This is by default handled by Cypress and the OK button on the alert gets clicked, without being visible during execution.
However, the execution logs will show the presence of the alert.
The implementation of alerts in Cypress is given below −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch url
cy.visit("https://register.rediff.com/register/register.php");
// click submit
cy.get('input[type="submit"]').click();
});
});
Execution Results
The output is as follows −
The alert message gets displayed on the Cypress execution logs.
Cypress has the ability to fire the window:alert event by utilising the method on. Then, we can verify the alert text.
However, this event shall happen in the back end and will not be visible during the execution.
Given below is the implementation for the alert text verification in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch url
cy.visit("https://register.rediff.com/register/register.php");
// click submit
cy.get('input[type="submit"]').click();
// fire event with method on
cy.on('window:alert',(t)=>{
//assertions
expect(t).to.contains('Your full name');
})
});
});
Execution Results
The output is mentioned below −
The output logs show the successful verification of the alert text, produced by firing the alert event by Cypress.
For a confirmation pop-up, the browser event window:confirm is triggered. Just like alert pop-ups, Cypress can fire this event with the method on and clicks on the OK button by default.
Example
Let us have a look at the below example. Here, on clicking the Click for JS Confirm button, a confirmation pop up gets displayed.
The following confirmation pop-up with OK and Cancel buttons getting displayed.
On clicking the OK button, the following is displayed −
You clicked: Ok
An image like the one given below will be displayed −
On clicking the Cancel button, the following is displayed below Result −
You clicked: Cancel
An image like the one given below will be displayed −
Given below is an implementation for the confirmation verification of alerts in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event and accept
cy.get(':nth-child(2) > button').click()
cy.on("window:confirm", (t) => {
//verify text on pop-up
expect(t).to.equal("I am a JS Confirm");
});
});
});
Execution Results
The output is stated below −
Given below is an implementation for the confirmation verification of alerts in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event and accept
cy.get(':nth-child(2) > button').click()
cy.on("window:confirm", (t) => {
//verify text on pop-up
expect(t).to.equal("I am a JS Confirm");
});
});
});
Execution Results
The output is stated below −
The output logs show the successful verification of the confirmation text, produced by firing the confirm event by Cypress.
The implementation of cancel click on confirmation pop up in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
// URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event
cy.on("window:confirm", (s) => {
return false;
});
// click on Click for JS Confirm button
cy.get(':nth-child(2) > button').click()
// verify application message on Cancel button click
cy.get('#result').should('have.text', 'You clicked: Cancel')
});
});
Execution Results
The output is given below −
The output logs show the successful verification of the text You clicked: Cancel, which is produced on clicking the Cancel button on the confirmation pop up.
73 Lectures
12 hours
Rahul Shetty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2742,
"s": 2497,
"text": "Cypress can work with alerts by default. The pop-up can be an alert or confirmation popup.Cypress is designed in such a way that it shall always click on the OK button on the pop-up. Moreover, Cypress has the ability to fire the browser events."
},
{
"code": null,
"e": 2910,
"s": 2742,
"text": "An alert is triggered by window:alert event. This is by default handled by Cypress and the OK button on the alert gets clicked, without being visible during execution."
},
{
"code": null,
"e": 2975,
"s": 2910,
"text": "However, the execution logs will show the presence of the alert."
},
{
"code": null,
"e": 3032,
"s": 2975,
"text": "The implementation of alerts in Cypress is given below −"
},
{
"code": null,
"e": 3295,
"s": 3032,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Scenario 1', function (){\n // launch url\n cy.visit(\"https://register.rediff.com/register/register.php\");\n // click submit\n cy.get('input[type=\"submit\"]').click();\n });\n});"
},
{
"code": null,
"e": 3313,
"s": 3295,
"text": "Execution Results"
},
{
"code": null,
"e": 3340,
"s": 3313,
"text": "The output is as follows −"
},
{
"code": null,
"e": 3404,
"s": 3340,
"text": "The alert message gets displayed on the Cypress execution logs."
},
{
"code": null,
"e": 3523,
"s": 3404,
"text": "Cypress has the ability to fire the window:alert event by utilising the method on. Then, we can verify the alert text."
},
{
"code": null,
"e": 3618,
"s": 3523,
"text": "However, this event shall happen in the back end and will not be visible during the execution."
},
{
"code": null,
"e": 3697,
"s": 3618,
"text": "Given below is the implementation for the alert text verification in Cypress −"
},
{
"code": null,
"e": 4110,
"s": 3697,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Scenario 1', function (){\n // launch url\n cy.visit(\"https://register.rediff.com/register/register.php\");\n // click submit\n cy.get('input[type=\"submit\"]').click();\n // fire event with method on\n cy.on('window:alert',(t)=>{\n //assertions\n expect(t).to.contains('Your full name');\n })\n });\n});"
},
{
"code": null,
"e": 4128,
"s": 4110,
"text": "Execution Results"
},
{
"code": null,
"e": 4160,
"s": 4128,
"text": "The output is mentioned below −"
},
{
"code": null,
"e": 4275,
"s": 4160,
"text": "The output logs show the successful verification of the alert text, produced by firing the alert event by Cypress."
},
{
"code": null,
"e": 4461,
"s": 4275,
"text": "For a confirmation pop-up, the browser event window:confirm is triggered. Just like alert pop-ups, Cypress can fire this event with the method on and clicks on the OK button by default."
},
{
"code": null,
"e": 4469,
"s": 4461,
"text": "Example"
},
{
"code": null,
"e": 4599,
"s": 4469,
"text": "Let us have a look at the below example. Here, on clicking the Click for JS Confirm button, a confirmation pop up gets displayed."
},
{
"code": null,
"e": 4679,
"s": 4599,
"text": "The following confirmation pop-up with OK and Cancel buttons getting displayed."
},
{
"code": null,
"e": 4735,
"s": 4679,
"text": "On clicking the OK button, the following is displayed −"
},
{
"code": null,
"e": 4752,
"s": 4735,
"text": "You clicked: Ok\n"
},
{
"code": null,
"e": 4806,
"s": 4752,
"text": "An image like the one given below will be displayed −"
},
{
"code": null,
"e": 4879,
"s": 4806,
"text": "On clicking the Cancel button, the following is displayed below Result −"
},
{
"code": null,
"e": 4900,
"s": 4879,
"text": "You clicked: Cancel\n"
},
{
"code": null,
"e": 4954,
"s": 4900,
"text": "An image like the one given below will be displayed −"
},
{
"code": null,
"e": 5044,
"s": 4954,
"text": "Given below is an implementation for the confirmation verification of alerts in Cypress −"
},
{
"code": null,
"e": 5468,
"s": 5044,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it(\"Scenario 1\", function () {\n //URL launched\n cy.visit(\"https://the-internet.herokuapp.com/javascript_alerts\")\n //fire confirm browser event and accept\n cy.get(':nth-child(2) > button').click()\n cy.on(\"window:confirm\", (t) => {\n //verify text on pop-up\n expect(t).to.equal(\"I am a JS Confirm\");\n });\n });\n});"
},
{
"code": null,
"e": 5486,
"s": 5468,
"text": "Execution Results"
},
{
"code": null,
"e": 5515,
"s": 5486,
"text": "The output is stated below −"
},
{
"code": null,
"e": 5605,
"s": 5515,
"text": "Given below is an implementation for the confirmation verification of alerts in Cypress −"
},
{
"code": null,
"e": 6029,
"s": 5605,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it(\"Scenario 1\", function () {\n //URL launched\n cy.visit(\"https://the-internet.herokuapp.com/javascript_alerts\")\n //fire confirm browser event and accept\n cy.get(':nth-child(2) > button').click()\n cy.on(\"window:confirm\", (t) => {\n //verify text on pop-up\n expect(t).to.equal(\"I am a JS Confirm\");\n });\n });\n});"
},
{
"code": null,
"e": 6047,
"s": 6029,
"text": "Execution Results"
},
{
"code": null,
"e": 6076,
"s": 6047,
"text": "The output is stated below −"
},
{
"code": null,
"e": 6200,
"s": 6076,
"text": "The output logs show the successful verification of the confirmation text, produced by firing the confirm event by Cypress."
},
{
"code": null,
"e": 6285,
"s": 6200,
"text": "The implementation of cancel click on confirmation pop up in Cypress is as follows −"
},
{
"code": null,
"e": 6811,
"s": 6285,
"text": "describe('Tutorialspoint Test', function () {\n // test case\n it(\"Scenario 1\", function () {\n // URL launched\n cy.visit(\"https://the-internet.herokuapp.com/javascript_alerts\")\n //fire confirm browser event\n cy.on(\"window:confirm\", (s) => {\n return false;\n });\n // click on Click for JS Confirm button\n cy.get(':nth-child(2) > button').click()\n // verify application message on Cancel button click\n cy.get('#result').should('have.text', 'You clicked: Cancel')\n });\n});"
},
{
"code": null,
"e": 6829,
"s": 6811,
"text": "Execution Results"
},
{
"code": null,
"e": 6857,
"s": 6829,
"text": "The output is given below −"
},
{
"code": null,
"e": 7015,
"s": 6857,
"text": "The output logs show the successful verification of the text You clicked: Cancel, which is produced on clicking the Cancel button on the confirmation pop up."
},
{
"code": null,
"e": 7049,
"s": 7015,
"text": "\n 73 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 7063,
"s": 7049,
"text": " Rahul Shetty"
},
{
"code": null,
"e": 7070,
"s": 7063,
"text": " Print"
},
{
"code": null,
"e": 7081,
"s": 7070,
"text": " Add Notes"
}
] |
Abstract vs Sealed Classes vs Class Members in C#
|
The abstract class includes abstract and non-abstract methods. You cannot instantiate an abstract class.
The sealed class prevents inheritance and you cannot use it as a base class.
To declare an abstract class, you need to place the keyword abstract before the class definition. An example of class members in an abstract class can be the following that defines an abstract method −
public abstract class Vehicle {
public abstract void display();
}
The abstract method definition is followed by a semi-colon since it has no implementation.
To declare a sealed class, you need to place the keyword sealed before the class definition. The sealed class prevents inheritance and you cannot use it as a base class.
public sealed class Test {
// Class members comes here
}
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "The abstract class includes abstract and non-abstract methods. You cannot instantiate an abstract class."
},
{
"code": null,
"e": 1244,
"s": 1167,
"text": "The sealed class prevents inheritance and you cannot use it as a base class."
},
{
"code": null,
"e": 1446,
"s": 1244,
"text": "To declare an abstract class, you need to place the keyword abstract before the class definition. An example of class members in an abstract class can be the following that defines an abstract method −"
},
{
"code": null,
"e": 1515,
"s": 1446,
"text": "public abstract class Vehicle {\n public abstract void display();\n}"
},
{
"code": null,
"e": 1606,
"s": 1515,
"text": "The abstract method definition is followed by a semi-colon since it has no implementation."
},
{
"code": null,
"e": 1776,
"s": 1606,
"text": "To declare a sealed class, you need to place the keyword sealed before the class definition. The sealed class prevents inheritance and you cannot use it as a base class."
},
{
"code": null,
"e": 1836,
"s": 1776,
"text": "public sealed class Test {\n // Class members comes here\n}"
}
] |
How to compare Enum values in C#? - GeeksforGeeks
|
23 Jul, 2019
Enum.CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values.
Syntax:
public int CompareTo (object target);
Here, the target is an object to compare or it may be null.
Returns: This method returns a signed number which shows the relative values of the current instance and target as follows:
Less than zero: If the value of the current instance is less than the value of target.
Zero: If the value of the current instance is equal to the value of the target.
Greater than zero: If the value of the current instance is greater than the value of the target or the target is null.
Exceptions:
ArgumentException: If the target and current instance are not the same types.
InvalidOperationException: If the instance is not type SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64.
NullReferenceException: If the current instance is null.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the // Enum.CompareTo(Object) Methodusing System; public class GFG { enum Color { RED, GREEN, BLUE }; // Driver method public static void Main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; Console.Write("Comparing {0} with {1} : ", c1, c2); // CompareTo method Console.WriteLine(c1.CompareTo(c2)); Console.Write("Comparing {0} with {1} : ", c1, c3); // CompareTo method Console.WriteLine(c1.CompareTo(c3)); Console.Write("Comparing {0} with {1} : ", c4, c2); // CompareTo method Console.WriteLine(c4.CompareTo(c2)); } }
Comparing RED with GREEN : -1
Comparing RED with RED : 0
Comparing BLUE with GREEN : 1
Example 2:
// C# program to demonstrate the // Enum.CompareTo(Object) Methodusing System; public class GFG { enum Color{Red, Blue}; enum Seasons {Winter, Summer}; // Driver method public static void Main(String[] args) { Color c1 = Color.Red; Color c2 = Color.Blue; Seasons s1 = Seasons.Winter; Seasons s2 = Seasons.Summer; Console.Write("Comparing {0} with {1} : ", c1, c2); // CompareTo method Console.WriteLine(c1.CompareTo(c2)); Console.Write("Comparing {0} with {1} : ", c1, s1); // using CompareTo method // it will give exception // as target and the current // instance are not the same // types Console.WriteLine(c1.CompareTo(s1)); } }
Runtime Error:
Unhandled Exception:System.ArgumentException: Object must be the same type as the enum. The type passed in was ‘GFG+Seasons’; the enum type was ‘GFG+Color’.at System.Enum.CompareTo (System.Object target) <0x7ff9d1544610 + 0x000da> in <0f8aeac9d63d4b8aa575761bb4e65b79>:0
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.enum.compareto?view=netframework-4.8
CSharp-Enum-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Constructors
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
Introduction to .NET Framework
Partial Classes in C#
Top 50 C# Interview Questions & Answers
C# | Data Types
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
|
[
{
"code": null,
"e": 24396,
"s": 24368,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 24540,
"s": 24396,
"text": "Enum.CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values."
},
{
"code": null,
"e": 24548,
"s": 24540,
"text": "Syntax:"
},
{
"code": null,
"e": 24586,
"s": 24548,
"text": "public int CompareTo (object target);"
},
{
"code": null,
"e": 24646,
"s": 24586,
"text": "Here, the target is an object to compare or it may be null."
},
{
"code": null,
"e": 24770,
"s": 24646,
"text": "Returns: This method returns a signed number which shows the relative values of the current instance and target as follows:"
},
{
"code": null,
"e": 24857,
"s": 24770,
"text": "Less than zero: If the value of the current instance is less than the value of target."
},
{
"code": null,
"e": 24937,
"s": 24857,
"text": "Zero: If the value of the current instance is equal to the value of the target."
},
{
"code": null,
"e": 25056,
"s": 24937,
"text": "Greater than zero: If the value of the current instance is greater than the value of the target or the target is null."
},
{
"code": null,
"e": 25068,
"s": 25056,
"text": "Exceptions:"
},
{
"code": null,
"e": 25146,
"s": 25068,
"text": "ArgumentException: If the target and current instance are not the same types."
},
{
"code": null,
"e": 25262,
"s": 25146,
"text": "InvalidOperationException: If the instance is not type SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64."
},
{
"code": null,
"e": 25319,
"s": 25262,
"text": "NullReferenceException: If the current instance is null."
},
{
"code": null,
"e": 25384,
"s": 25319,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 25395,
"s": 25384,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the // Enum.CompareTo(Object) Methodusing System; public class GFG { enum Color { RED, GREEN, BLUE }; // Driver method public static void Main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; Console.Write(\"Comparing {0} with {1} : \", c1, c2); // CompareTo method Console.WriteLine(c1.CompareTo(c2)); Console.Write(\"Comparing {0} with {1} : \", c1, c3); // CompareTo method Console.WriteLine(c1.CompareTo(c3)); Console.Write(\"Comparing {0} with {1} : \", c4, c2); // CompareTo method Console.WriteLine(c4.CompareTo(c2)); } } ",
"e": 26224,
"s": 25395,
"text": null
},
{
"code": null,
"e": 26312,
"s": 26224,
"text": "Comparing RED with GREEN : -1\nComparing RED with RED : 0\nComparing BLUE with GREEN : 1\n"
},
{
"code": null,
"e": 26323,
"s": 26312,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the // Enum.CompareTo(Object) Methodusing System; public class GFG { enum Color{Red, Blue}; enum Seasons {Winter, Summer}; // Driver method public static void Main(String[] args) { Color c1 = Color.Red; Color c2 = Color.Blue; Seasons s1 = Seasons.Winter; Seasons s2 = Seasons.Summer; Console.Write(\"Comparing {0} with {1} : \", c1, c2); // CompareTo method Console.WriteLine(c1.CompareTo(c2)); Console.Write(\"Comparing {0} with {1} : \", c1, s1); // using CompareTo method // it will give exception // as target and the current // instance are not the same // types Console.WriteLine(c1.CompareTo(s1)); } } ",
"e": 27166,
"s": 26323,
"text": null
},
{
"code": null,
"e": 27181,
"s": 27166,
"text": "Runtime Error:"
},
{
"code": null,
"e": 27452,
"s": 27181,
"text": "Unhandled Exception:System.ArgumentException: Object must be the same type as the enum. The type passed in was ‘GFG+Seasons’; the enum type was ‘GFG+Color’.at System.Enum.CompareTo (System.Object target) <0x7ff9d1544610 + 0x000da> in <0f8aeac9d63d4b8aa575761bb4e65b79>:0"
},
{
"code": null,
"e": 27463,
"s": 27452,
"text": "Reference:"
},
{
"code": null,
"e": 27551,
"s": 27463,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.enum.compareto?view=netframework-4.8"
},
{
"code": null,
"e": 27569,
"s": 27551,
"text": "CSharp-Enum-Class"
},
{
"code": null,
"e": 27583,
"s": 27569,
"text": "CSharp-method"
},
{
"code": null,
"e": 27586,
"s": 27583,
"text": "C#"
},
{
"code": null,
"e": 27684,
"s": 27586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27693,
"s": 27684,
"text": "Comments"
},
{
"code": null,
"e": 27706,
"s": 27693,
"text": "Old Comments"
},
{
"code": null,
"e": 27724,
"s": 27706,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27746,
"s": 27724,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27792,
"s": 27746,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27807,
"s": 27792,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27830,
"s": 27807,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27861,
"s": 27830,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27883,
"s": 27861,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27923,
"s": 27883,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27939,
"s": 27923,
"text": "C# | Data Types"
}
] |
Set a MySQL field with the current date (UNIX_TIMESTAMP(now))
|
For this, use unix_timestamp(). Let us first create a table −
mysql> create table DemoTable1894
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
DueTime int
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1894 values();
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1894;
This will produce the following output −
+----+---------+
| Id | DueTime |
+----+---------+
| 1 | NULL |
| 2 | NULL |
| 3 | NULL |
+----+---------+
3 rows in set (0.00 sec)
Here is the query to set a field with UNIX Timestamp −
mysql> update DemoTable1894 set DueTime=unix_timestamp(now());
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1894;
This will produce the following output −
+----+------------+
| Id | DueTime |
+----+------------+
| 1 | 1576042722 |
| 2 | 1576042722 |
| 3 | 1576042722 |
+----+------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "For this, use unix_timestamp(). Let us first create a table −"
},
{
"code": null,
"e": 1268,
"s": 1124,
"text": "mysql> create table DemoTable1894\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n DueTime int\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1324,
"s": 1268,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1561,
"s": 1324,
"text": "mysql> insert into DemoTable1894 values();\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1894 values();\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1894 values();\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1621,
"s": 1561,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1657,
"s": 1621,
"text": "mysql> select * from DemoTable1894;"
},
{
"code": null,
"e": 1698,
"s": 1657,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1842,
"s": 1698,
"text": "+----+---------+\n| Id | DueTime |\n+----+---------+\n| 1 | NULL |\n| 2 | NULL |\n| 3 | NULL |\n+----+---------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1897,
"s": 1842,
"text": "Here is the query to set a field with UNIX Timestamp −"
},
{
"code": null,
"e": 2037,
"s": 1897,
"text": "mysql> update DemoTable1894 set DueTime=unix_timestamp(now());\nQuery OK, 3 rows affected (0.00 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2081,
"s": 2037,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2117,
"s": 2081,
"text": "mysql> select * from DemoTable1894;"
},
{
"code": null,
"e": 2158,
"s": 2117,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2323,
"s": 2158,
"text": "+----+------------+\n| Id | DueTime |\n+----+------------+\n| 1 | 1576042722 |\n| 2 | 1576042722 |\n| 3 | 1576042722 |\n+----+------------+\n3 rows in set (0.00 sec)"
}
] |
Check if a line touches or intersects a circle in C++
|
Suppose we have a circle and another straight line. Our task is to find if the line touches the circle or intersects it, otherwise, it passes through outside. So there are three different cases like below −
Here we will solve it by following steps. These are like below −
Find perpendicular P between the center and given a line
Compare P with radius r −if P > r, then outsideif P = r, then touchesotherwise inside
if P > r, then outside
if P = r, then touches
otherwise inside
To get the perpendicular distance, we have to use this formula (a center point is (h, k))
ah+bk+ca2+b2
Live Demo
#include <iostream>
#include <cmath>
using namespace std;
void isTouchOrIntersect(int a, int b, int c, int h, int k, int radius) {
int dist = (abs(a * h + b * k + c)) / sqrt(a * a + b * b);
if (radius == dist)
cout << "Touching the circle" << endl;
else if (radius > dist)
cout << "Intersecting the circle" << endl;
else
cout << "Outside the circle" << endl;
}
int main() {
int radius = 5;
int h = 0, k = 0;
int a = 3, b = 4, c = 25;
isTouchOrIntersect(a, b, c, h, k, radius);
}
Touching the circle
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "Suppose we have a circle and another straight line. Our task is to find if the line touches the circle or intersects it, otherwise, it passes through outside. So there are three different cases like below −"
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "Here we will solve it by following steps. These are like below −"
},
{
"code": null,
"e": 1391,
"s": 1334,
"text": "Find perpendicular P between the center and given a line"
},
{
"code": null,
"e": 1477,
"s": 1391,
"text": "Compare P with radius r −if P > r, then outsideif P = r, then touchesotherwise inside"
},
{
"code": null,
"e": 1500,
"s": 1477,
"text": "if P > r, then outside"
},
{
"code": null,
"e": 1523,
"s": 1500,
"text": "if P = r, then touches"
},
{
"code": null,
"e": 1540,
"s": 1523,
"text": "otherwise inside"
},
{
"code": null,
"e": 1630,
"s": 1540,
"text": "To get the perpendicular distance, we have to use this formula (a center point is (h, k))"
},
{
"code": null,
"e": 1643,
"s": 1630,
"text": "ah+bk+ca2+b2"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": " Live Demo"
},
{
"code": null,
"e": 2175,
"s": 1654,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nvoid isTouchOrIntersect(int a, int b, int c, int h, int k, int radius) {\n int dist = (abs(a * h + b * k + c)) / sqrt(a * a + b * b);\n if (radius == dist)\n cout << \"Touching the circle\" << endl;\n else if (radius > dist)\n cout << \"Intersecting the circle\" << endl;\n else\n cout << \"Outside the circle\" << endl;\n}\nint main() {\n int radius = 5;\n int h = 0, k = 0;\n int a = 3, b = 4, c = 25;\n isTouchOrIntersect(a, b, c, h, k, radius);\n}"
},
{
"code": null,
"e": 2195,
"s": 2175,
"text": "Touching the circle"
}
] |
Program to count number of elements are placed at correct position in Python
|
Suppose we have a list of numbers called nums, we have to find the number of elements that are present in the correct indices, when the list was to be sorted.
So, if the input is like [2, 8, 4, 5, 11], then the output will be 2, as the elements 2 and 11 are in their correct positions. The sorted sequence will be [2, 4, 5, 8, 11]
To solve this, we will follow these steps −
s := sort the list nums
count := 0
for i in range 0 to size of nums, doif s[i] is same as nums[i], thencount := count + 1
if s[i] is same as nums[i], thencount := count + 1
count := count + 1
return count
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
s = sorted(nums)
count = 0
for i in range(len(nums)):
if s[i] == nums[i]:
count += 1
return count
ob = Solution()
print(ob.solve([2, 8, 4, 5, 11]))
[2, 8, 4, 5, 11]
2
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find the number of elements that are present in the correct indices, when the list was to be sorted."
},
{
"code": null,
"e": 1393,
"s": 1221,
"text": "So, if the input is like [2, 8, 4, 5, 11], then the output will be 2, as the elements 2 and 11 are in their correct positions. The sorted sequence will be [2, 4, 5, 8, 11]"
},
{
"code": null,
"e": 1437,
"s": 1393,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1461,
"s": 1437,
"text": "s := sort the list nums"
},
{
"code": null,
"e": 1472,
"s": 1461,
"text": "count := 0"
},
{
"code": null,
"e": 1559,
"s": 1472,
"text": "for i in range 0 to size of nums, doif s[i] is same as nums[i], thencount := count + 1"
},
{
"code": null,
"e": 1610,
"s": 1559,
"text": "if s[i] is same as nums[i], thencount := count + 1"
},
{
"code": null,
"e": 1629,
"s": 1610,
"text": "count := count + 1"
},
{
"code": null,
"e": 1642,
"s": 1629,
"text": "return count"
},
{
"code": null,
"e": 1712,
"s": 1642,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1723,
"s": 1712,
"text": " Live Demo"
},
{
"code": null,
"e": 1958,
"s": 1723,
"text": "class Solution:\n def solve(self, nums):\n s = sorted(nums)\n count = 0\n for i in range(len(nums)):\n if s[i] == nums[i]:\n count += 1\n return count\nob = Solution()\nprint(ob.solve([2, 8, 4, 5, 11]))"
},
{
"code": null,
"e": 1975,
"s": 1958,
"text": "[2, 8, 4, 5, 11]"
},
{
"code": null,
"e": 1977,
"s": 1975,
"text": "2"
}
] |
ExpressJS - Sessions
|
HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID.
We will need the Express-session, so install it using the following code.
npm install --save express-session
We will put the session and cookie-parser middleware in place. In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object.
Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client.
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use(session({secret: "Shh, its a secret!"}));
app.get('/', function(req, res){
if(req.session.page_views){
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
app.listen(3000);
What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly.
Now if you run the app and go to localhost:3000, the following output will be displayed.
If you revisit the page, the page counter will increase. The page in the following screenshot was refreshed 42 times.
16 Lectures
1 hours
Anadi Sharma
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2541,
"s": 2061,
"text": "HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID."
},
{
"code": null,
"e": 2615,
"s": 2541,
"text": "We will need the Express-session, so install it using the following code."
},
{
"code": null,
"e": 2651,
"s": 2615,
"text": "npm install --save express-session\n"
},
{
"code": null,
"e": 2998,
"s": 2651,
"text": "We will put the session and cookie-parser middleware in place. In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object."
},
{
"code": null,
"e": 3270,
"s": 2998,
"text": "Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client."
},
{
"code": null,
"e": 3797,
"s": 3270,
"text": "var express = require('express');\nvar cookieParser = require('cookie-parser');\nvar session = require('express-session');\n\nvar app = express();\n\napp.use(cookieParser());\napp.use(session({secret: \"Shh, its a secret!\"}));\n\napp.get('/', function(req, res){\n if(req.session.page_views){\n req.session.page_views++;\n res.send(\"You visited this page \" + req.session.page_views + \" times\");\n } else {\n req.session.page_views = 1;\n res.send(\"Welcome to this page for the first time!\");\n }\n});\napp.listen(3000);"
},
{
"code": null,
"e": 4027,
"s": 3797,
"text": "What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly."
},
{
"code": null,
"e": 4116,
"s": 4027,
"text": "Now if you run the app and go to localhost:3000, the following output will be displayed."
},
{
"code": null,
"e": 4234,
"s": 4116,
"text": "If you revisit the page, the page counter will increase. The page in the following screenshot was refreshed 42 times."
},
{
"code": null,
"e": 4267,
"s": 4234,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4281,
"s": 4267,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4288,
"s": 4281,
"text": " Print"
},
{
"code": null,
"e": 4299,
"s": 4288,
"text": " Add Notes"
}
] |
Can you change size of Array in Java once created?
|
An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.
For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −
System.out.println(myArray[3]);
//25
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
The size of an array is fixed, if you create an array using the new keyword you need to specify the length/size of it in the constructor as −
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
You can also directly assign values within flower braces separating them with commas (,) as −
int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524}; //size 7
If you create an array by initializing its values directly, the size will be the number of elements in it.
Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.
In the following example we are creating an array with 7 elements and alter we are trying to assign value to the 8th element.
public class Test {
public static void main(String[] args) {
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
myArray[7] = 4238;
System.out.println(Arrays.toString(myArray));
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Test.main(Test.java:13)
You can change the size of the existing array by reassigning it to the new one as −
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[7];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
System.out.println(Arrays.toString(myArray));
myArray = new int[8];
myArray[0] = 1254;
myArray[1] = 1458;
myArray[2] = 5687;
myArray[3] = 1457;
myArray[4] = 4554;
myArray[5] = 5445;
myArray[6] = 7524;
myArray[7] = 3165;
System.out.println(Arrays.toString(myArray));
}
}
[1254, 1458, 5687, 1457, 4554, 5445, 7524]
[1254, 1458, 5687, 1457, 4554, 5445, 7524, 3165]
In this scenario the earlier array object will be left out for garbage collection. Thus, when used extensively this approach causes memory issues therefore, it is not recommended.
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation."
},
{
"code": null,
"e": 1437,
"s": 1253,
"text": "The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on."
},
{
"code": null,
"e": 1597,
"s": 1437,
"text": "Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets."
},
{
"code": null,
"e": 1722,
"s": 1597,
"text": "For example, if an array of 6 elements is created with name myArray, you can access the element of the array at index 3 as −"
},
{
"code": null,
"e": 1759,
"s": 1722,
"text": "System.out.println(myArray[3]);\n//25"
},
{
"code": null,
"e": 1911,
"s": 1759,
"text": "In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −"
},
{
"code": null,
"e": 2053,
"s": 1911,
"text": "The size of an array is fixed, if you create an array using the new keyword you need to specify the length/size of it in the constructor as −"
},
{
"code": null,
"e": 2214,
"s": 2053,
"text": "int myArray[] = new int[7];\nmyArray[0] = 1254;\nmyArray[1] = 1458;\nmyArray[2] = 5687;\nmyArray[3] = 1457;\nmyArray[4] = 4554;\nmyArray[5] = 5445;\nmyArray[6] = 7524;"
},
{
"code": null,
"e": 2308,
"s": 2214,
"text": "You can also directly assign values within flower braces separating them with commas (,) as −"
},
{
"code": null,
"e": 2375,
"s": 2308,
"text": "int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524}; //size 7"
},
{
"code": null,
"e": 2482,
"s": 2375,
"text": "If you create an array by initializing its values directly, the size will be the number of elements in it."
},
{
"code": null,
"e": 2627,
"s": 2482,
"text": "Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array."
},
{
"code": null,
"e": 2744,
"s": 2627,
"text": "Still if you try to assign value to the element of the array beyond its size a run time exception will be generated."
},
{
"code": null,
"e": 2870,
"s": 2744,
"text": "In the following example we are creating an array with 7 elements and alter we are trying to assign value to the 8th element."
},
{
"code": null,
"e": 3227,
"s": 2870,
"text": "public class Test {\n public static void main(String[] args) {\n int myArray[] = new int[7];\n myArray[0] = 1254;\n myArray[1] = 1458;\n myArray[2] = 5687;\n myArray[3] = 1457;\n myArray[4] = 4554;\n myArray[5] = 5445;\n myArray[6] = 7524;\n myArray[7] = 4238;\n System.out.println(Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 3325,
"s": 3227,
"text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 7\nat Test.main(Test.java:13)"
},
{
"code": null,
"e": 3409,
"s": 3325,
"text": "You can change the size of the existing array by reassigning it to the new one as −"
},
{
"code": null,
"e": 4046,
"s": 3409,
"text": "import java.util.Arrays;\npublic class Test {\n public static void main(String[] args) {\n int myArray[] = new int[7];\n myArray[0] = 1254;\n myArray[1] = 1458;\n myArray[2] = 5687;\n myArray[3] = 1457;\n myArray[4] = 4554;\n myArray[5] = 5445;\n myArray[6] = 7524;\n System.out.println(Arrays.toString(myArray));\n myArray = new int[8];\n myArray[0] = 1254;\n myArray[1] = 1458;\n myArray[2] = 5687;\n myArray[3] = 1457;\n myArray[4] = 4554;\n myArray[5] = 5445;\n myArray[6] = 7524;\n myArray[7] = 3165;\n System.out.println(Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 4138,
"s": 4046,
"text": "[1254, 1458, 5687, 1457, 4554, 5445, 7524]\n[1254, 1458, 5687, 1457, 4554, 5445, 7524, 3165]"
},
{
"code": null,
"e": 4318,
"s": 4138,
"text": "In this scenario the earlier array object will be left out for garbage collection. Thus, when used extensively this approach causes memory issues therefore, it is not recommended."
}
] |
How to download mp3 tracks from youtube video using youtube dl
|
There are several ways to download MP3 tracks from Youtube such as web applications, windows applications and command line tools in Linux. Youtube-DL is one of the best available tools in the market to download tracks from youtube. It is developed in Python programming language. This program can be used in almost all Linux distributions. If you haven’t heard about this tool then this article is for you.
To install youtube-DL, use the following command –
$ sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl
The sample output should be like this –
--2016-03-08 11:41:21-- https://yt-dl.org/downloads/latest/youtube-dl
Resolving yt-dl.org (yt-dl.org)... 95.143.172.170, 2001:1a50:11:0:5f:8f:acaa:177
Connecting to yt-dl.org (yt-dl.org)|95.143.172.170|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://yt-dl.org/downloads/2016.03.06/youtube-dl [following]
--2016-03-08 11:41:23-- https://yt-dl.org/downloads/2016.03.06/youtube-dl
Connecting to yt-dl.org (yt-dl.org)|95.143.172.170|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1133512 (1.1M) [application/octet-stream]
Saving to: ‘/usr/local/bin/youtube-dl’
100%[======================================>] 11,33,512 218KB/s in 6.2s
2016-03-08 11:41:30 (180 KB/s) - ‘/usr/local/bin/youtube-dl’ saved [1133512/1133512]
Change youtube-dl directory permission to access youtube-dl command. To change the directory permission, use the following command –
$ sudo chmod a+rx /usr/local/bin/youtube-dl
To get more information about youtube-DL use the following command –
# youtube-dl --help
The above command should require root permission and its output should be like this –
Options:
-h, --help Print this help text and exit
--version Print program version and exit
-U, --update Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)
-i, --ignore-errors Continue on download errors, for example to skip unavailable videos in a playlist
--abort-on-error Abort downloading of further videos (in the playlist or the command line) if an error occurs
--dump-user-agent Display the current browser identification
--list-extractors List all supported extractors
--extractor-descriptions Output descriptions of all supported extractors
--force-generic-extractor Force extraction to use the generic extractor
--default-search PREFIX Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.
--ignore-config Do not read configuration files. When given in the global configuration file /etc /youtube-dl.conf: Do not read the user configuration in ~/.config/youtube- dl/config (%APPDATA%/youtube-dl/config.txt on Windows)
--flat-playlist Do not extract the videos of a playlist, only list them.
--mark-watched Mark videos watched (YouTube only)
--no-mark-watched Do not mark videos watched (YouTube only)
--no-color Do not emit color codes in output
.........................
To convert music to different audio formats, youtube-dl needs either ffmpeg or avconv, and their help programs ffprobe or avprobe.
To install one of them, use the following command –
$ sudo apt-get install ffmpeg
The sample output should be like this –
Building dependency tree
Reading state information... Done
ffmpeg is already the newest version.
The following packages were automatically installed and are no longer required:
gcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386
libasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386
libavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl
libcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl
libcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl
libdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386
libdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386
libffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386
libgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386
libgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386
libglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386
libgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386
libgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386
libgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386
libhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386
libhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386
..........................
To download MP3 track, use the following command –
$ youtube-dl -x --audio-format mp3 --prefer-ffmpeg https://www.youtube.com/watch?v=jwD4AEVBL6Q
The sample output should be like this –
[youtube] jwD4AEVBL6Q: Downloading webpage
[youtube] jwD4AEVBL6Q: Downloading video info webpage
[youtube] jwD4AEVBL6Q: Extracting video information
[youtube] jwD4AEVBL6Q: Downloading MPD manifest
[download] Destination: Bad Style - Time back-jwD4AEVBL6Q.m4a
[download] 100% of 7.45MiB in 00:08
[ffmpeg] Correcting container in "Bad Style - Time back-jwD4AEVBL6Q.m4a"
[ffmpeg] Destination: Bad Style - Time back-jwD4AEVBL6Q.mp3
Deleting original file Bad Style - Time back-jwD4AEVBL6Q.m4a (pass -k to keep)
The above command uses the below two options –
–extract-audio (short option -x) – Convert video files to audio-only files. –audio-format – specifies the audio format in which the file will be downloaded. The supported audio formats are “best”, “aac”, “vorbis”, “mp3”, “m4a”, “opus”, or “wav”; “best” is set by default.
To download multiple files from playlist, use the following command –
[youtube:playlist] PL9LUD5Kp855InMnKTaRy3LH3kTIYJyBzs: Downloading webpage
[download] Downloading playlist: Top Tracks - Imagine Dragons
[youtube:playlist] playlist Top Tracks - Imagine Dragons: Downloading 5 videos
[download] Downloading video 1 of 5
[youtube] mWRsgZuwf_8: Downloading webpage
[youtube] mWRsgZuwf_8: Downloading video info webpage
[youtube] mWRsgZuwf_8: Extracting video information
[youtube] mWRsgZuwf_8: Downloading js player en_US-vflteKQR7
[youtube] mWRsgZuwf_8: Downloading js player en_US-vflteKQR7
[download] Destination: Imagine Dragons - Demons (Official)-mWRsgZuwf_8.webm
[download] 100% of 3.38MiB in 00:06
[ffmpeg] Destination: Imagine Dragons - Demons (Official)-mWRsgZuwf_8.mp3
Deleting original file Imagine Dragons - Demons (Official)-mWRsgZuwf_8.webm (pass -k to keep)
[download] Downloading video 2 of 5
[youtube] ktvTqknDobU: Downloading webpage
[youtube] ktvTqknDobU: Downloading video info webpage
[youtube] ktvTqknDobU: Extracting video information
[youtube] ktvTqknDobU: Downloading js player en_US-vflteKQR7
[download] Destination: Imagine Dragons - Radioactive-ktvTqknDobU.webm
[download] 100% of 3.81MiB in 00:01
[ffmpeg] Destination: Imagine Dragons - Radioactive-ktvTqknDobU.mp3
Deleting original file Imagine Dragons - Radioactive-ktvTqknDobU.webm (pass -k to keep)
[download] Downloading video 3 of 5
[youtube] sENM2wA_FTg: Downloading webpage
[youtube] sENM2wA_FTg: Downloading video info webpage
[youtube] sENM2wA_FTg: Extracting video information
[download] Destination: Imagine Dragons - It's Time-sENM2wA_FTg.webm
[download] 100% of 3.81MiB in 00:01
[ffmpeg] Destination: Imagine Dragons - It's Time-sENM2wA_FTg.mp3
Deleting original file Imagine Dragons - It's Time-sENM2wA_FTg.webm (pass -k to keep)
[download] Downloading video 4 of 5
[youtube] w5tWYmIOWGk: Downloading webpage
[youtube] w5tWYmIOWGk: Downloading video info webpage
[youtube] w5tWYmIOWGk: Extracting video information
[download] Destination: Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.webm
[download] 100% of 3.92MiB in 00:03
[ffmpeg] Destination: Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.mp3
Deleting original file Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.webm (pass -k to keep)
[download] Downloading video 5 of 5
[youtube] VP9I8ZUwKpc: Downloading webpage
[youtube] VP9I8ZUwKpc: Downloading video info webpage
[youtube] VP9I8ZUwKpc: Extracting video information
[download] Destination: Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.webm
[download] 100% of 2.57MiB in 00:01
[ffmpeg] Destination: Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.mp3
Deleting original file Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.webm (pass -k to keep)
[download] Finished downloading playlist: Top Tracks - Imagine Dragons
Congratulations! Now, you know “How to Download MP3 Tracks from a YouTube Video Using YouTube-DL”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
|
[
{
"code": null,
"e": 1469,
"s": 1062,
"text": "There are several ways to download MP3 tracks from Youtube such as web applications, windows applications and command line tools in Linux. Youtube-DL is one of the best available tools in the market to download tracks from youtube. It is developed in Python programming language. This program can be used in almost all Linux distributions. If you haven’t heard about this tool then this article is for you."
},
{
"code": null,
"e": 1520,
"s": 1469,
"text": "To install youtube-DL, use the following command –"
},
{
"code": null,
"e": 1607,
"s": 1520,
"text": "$ sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl"
},
{
"code": null,
"e": 1647,
"s": 1607,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 2427,
"s": 1647,
"text": "--2016-03-08 11:41:21-- https://yt-dl.org/downloads/latest/youtube-dl\nResolving yt-dl.org (yt-dl.org)... 95.143.172.170, 2001:1a50:11:0:5f:8f:acaa:177\nConnecting to yt-dl.org (yt-dl.org)|95.143.172.170|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://yt-dl.org/downloads/2016.03.06/youtube-dl [following]\n--2016-03-08 11:41:23-- https://yt-dl.org/downloads/2016.03.06/youtube-dl\nConnecting to yt-dl.org (yt-dl.org)|95.143.172.170|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1133512 (1.1M) [application/octet-stream]\nSaving to: ‘/usr/local/bin/youtube-dl’\n100%[======================================>] 11,33,512 218KB/s in 6.2s\n2016-03-08 11:41:30 (180 KB/s) - ‘/usr/local/bin/youtube-dl’ saved [1133512/1133512]"
},
{
"code": null,
"e": 2560,
"s": 2427,
"text": "Change youtube-dl directory permission to access youtube-dl command. To change the directory permission, use the following command –"
},
{
"code": null,
"e": 2604,
"s": 2560,
"text": "$ sudo chmod a+rx /usr/local/bin/youtube-dl"
},
{
"code": null,
"e": 2673,
"s": 2604,
"text": "To get more information about youtube-DL use the following command –"
},
{
"code": null,
"e": 2693,
"s": 2673,
"text": "# youtube-dl --help"
},
{
"code": null,
"e": 2779,
"s": 2693,
"text": "The above command should require root permission and its output should be like this –"
},
{
"code": null,
"e": 4516,
"s": 2779,
"text": "Options:\n\n-h, --help Print this help text and exit\n--version Print program version and exit\n-U, --update Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)\n-i, --ignore-errors Continue on download errors, for example to skip unavailable videos in a playlist\n--abort-on-error Abort downloading of further videos (in the playlist or the command line) if an error occurs\n--dump-user-agent Display the current browser identification\n--list-extractors List all supported extractors\n--extractor-descriptions Output descriptions of all supported extractors\n--force-generic-extractor Force extraction to use the generic extractor\n--default-search PREFIX Use this prefix for unqualified URLs. For example \"gvsearch2:\" downloads two videos from google videos for youtube-dl \"large apple\". Use the value \"auto\" to let youtube-dl guess (\"auto_warning\" to emit a warning when guessing). \"error\" just throws an error. The default value \"fixup_error\" repairs broken URLs, but emits an error if this is not possible instead of searching.\n--ignore-config Do not read configuration files. When given in the global configuration file /etc /youtube-dl.conf: Do not read the user configuration in ~/.config/youtube- dl/config (%APPDATA%/youtube-dl/config.txt on Windows)\n--flat-playlist Do not extract the videos of a playlist, only list them.\n--mark-watched Mark videos watched (YouTube only)\n--no-mark-watched Do not mark videos watched (YouTube only)\n--no-color Do not emit color codes in output\n........................."
},
{
"code": null,
"e": 4647,
"s": 4516,
"text": "To convert music to different audio formats, youtube-dl needs either ffmpeg or avconv, and their help programs ffprobe or avprobe."
},
{
"code": null,
"e": 4699,
"s": 4647,
"text": "To install one of them, use the following command –"
},
{
"code": null,
"e": 4729,
"s": 4699,
"text": "$ sudo apt-get install ffmpeg"
},
{
"code": null,
"e": 4769,
"s": 4729,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6016,
"s": 4769,
"text": "Building dependency tree\nReading state information... Done\nffmpeg is already the newest version.\nThe following packages were automatically installed and are no longer required:\ngcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386\nlibasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386\nlibavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl\nlibcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl\nlibcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl\nlibdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386\nlibdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386\nlibffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386\nlibgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386\nlibgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386\nlibglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386\nlibgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386\nlibgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386\nlibgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386\nlibhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386\nlibhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386\n.........................."
},
{
"code": null,
"e": 6067,
"s": 6016,
"text": "To download MP3 track, use the following command –"
},
{
"code": null,
"e": 6162,
"s": 6067,
"text": "$ youtube-dl -x --audio-format mp3 --prefer-ffmpeg https://www.youtube.com/watch?v=jwD4AEVBL6Q"
},
{
"code": null,
"e": 6202,
"s": 6162,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6709,
"s": 6202,
"text": "[youtube] jwD4AEVBL6Q: Downloading webpage\n[youtube] jwD4AEVBL6Q: Downloading video info webpage\n[youtube] jwD4AEVBL6Q: Extracting video information\n[youtube] jwD4AEVBL6Q: Downloading MPD manifest\n[download] Destination: Bad Style - Time back-jwD4AEVBL6Q.m4a\n[download] 100% of 7.45MiB in 00:08\n[ffmpeg] Correcting container in \"Bad Style - Time back-jwD4AEVBL6Q.m4a\"\n[ffmpeg] Destination: Bad Style - Time back-jwD4AEVBL6Q.mp3\nDeleting original file Bad Style - Time back-jwD4AEVBL6Q.m4a (pass -k to keep)"
},
{
"code": null,
"e": 6756,
"s": 6709,
"text": "The above command uses the below two options –"
},
{
"code": null,
"e": 7028,
"s": 6756,
"text": "–extract-audio (short option -x) – Convert video files to audio-only files. –audio-format – specifies the audio format in which the file will be downloaded. The supported audio formats are “best”, “aac”, “vorbis”, “mp3”, “m4a”, “opus”, or “wav”; “best” is set by default."
},
{
"code": null,
"e": 7098,
"s": 7028,
"text": "To download multiple files from playlist, use the following command –"
},
{
"code": null,
"e": 9946,
"s": 7098,
"text": "[youtube:playlist] PL9LUD5Kp855InMnKTaRy3LH3kTIYJyBzs: Downloading webpage\n[download] Downloading playlist: Top Tracks - Imagine Dragons\n[youtube:playlist] playlist Top Tracks - Imagine Dragons: Downloading 5 videos\n[download] Downloading video 1 of 5\n[youtube] mWRsgZuwf_8: Downloading webpage\n[youtube] mWRsgZuwf_8: Downloading video info webpage\n[youtube] mWRsgZuwf_8: Extracting video information\n[youtube] mWRsgZuwf_8: Downloading js player en_US-vflteKQR7\n[youtube] mWRsgZuwf_8: Downloading js player en_US-vflteKQR7\n[download] Destination: Imagine Dragons - Demons (Official)-mWRsgZuwf_8.webm\n[download] 100% of 3.38MiB in 00:06\n[ffmpeg] Destination: Imagine Dragons - Demons (Official)-mWRsgZuwf_8.mp3\nDeleting original file Imagine Dragons - Demons (Official)-mWRsgZuwf_8.webm (pass -k to keep)\n[download] Downloading video 2 of 5\n[youtube] ktvTqknDobU: Downloading webpage\n[youtube] ktvTqknDobU: Downloading video info webpage\n[youtube] ktvTqknDobU: Extracting video information\n[youtube] ktvTqknDobU: Downloading js player en_US-vflteKQR7\n[download] Destination: Imagine Dragons - Radioactive-ktvTqknDobU.webm\n[download] 100% of 3.81MiB in 00:01\n[ffmpeg] Destination: Imagine Dragons - Radioactive-ktvTqknDobU.mp3\nDeleting original file Imagine Dragons - Radioactive-ktvTqknDobU.webm (pass -k to keep)\n[download] Downloading video 3 of 5\n[youtube] sENM2wA_FTg: Downloading webpage\n[youtube] sENM2wA_FTg: Downloading video info webpage\n[youtube] sENM2wA_FTg: Extracting video information\n[download] Destination: Imagine Dragons - It's Time-sENM2wA_FTg.webm\n[download] 100% of 3.81MiB in 00:01\n[ffmpeg] Destination: Imagine Dragons - It's Time-sENM2wA_FTg.mp3\nDeleting original file Imagine Dragons - It's Time-sENM2wA_FTg.webm (pass -k to keep)\n[download] Downloading video 4 of 5\n[youtube] w5tWYmIOWGk: Downloading webpage\n[youtube] w5tWYmIOWGk: Downloading video info webpage\n[youtube] w5tWYmIOWGk: Extracting video information\n[download] Destination: Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.webm\n[download] 100% of 3.92MiB in 00:03\n[ffmpeg] Destination: Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.mp3\nDeleting original file Imagine Dragons - On Top Of The World (Official Music Video)-w5tWYmIOWGk.webm (pass -k to keep)\n[download] Downloading video 5 of 5\n[youtube] VP9I8ZUwKpc: Downloading webpage\n[youtube] VP9I8ZUwKpc: Downloading video info webpage\n[youtube] VP9I8ZUwKpc: Extracting video information\n[download] Destination: Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.webm\n[download] 100% of 2.57MiB in 00:01\n[ffmpeg] Destination: Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.mp3\nDeleting original file Imagine Dragons - Warriors (Lyric Video)-VP9I8ZUwKpc.webm (pass -k to keep)\n[download] Finished downloading playlist: Top Tracks - Imagine Dragons"
},
{
"code": null,
"e": 10130,
"s": 9946,
"text": "Congratulations! Now, you know “How to Download MP3 Tracks from a YouTube Video Using YouTube-DL”. We’ll learn more about these types of commands in our next Linux post. Keep reading!"
}
] |
Decimal.Remainder() Method in C# - GeeksforGeeks
|
30 Jan, 2019
This method is used to compute the remainder when the division is done between two specified decimal values.
Syntax: public static decimal Remainder (decimal a1, decimal a2);
Parameters:a1: This parameter specifies the dividend.a2: This parameter specifies the divisor.
Return Value: It returns the remainder of the after dividing a1 by a2.
Exceptions:
DivideByZeroException: This occurs when a2 is zero.
OverflowException: If the return value is less than MinValue or greater than MaxValue.
Below programs illustrate the use of Decimal.Remainder(Decimal, Decimal) Method:
Example 1:
// C# program to demonstrate the// Decimal.Remainder(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 1.11m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine("Remainder is : {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Remainder is : 0.69
Example 2: For OverflowException
// C# program to demonstrate the// Decimal.Remainder(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = Decimal.MaxValue; Decimal a2 = 0.02m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine("Remainder is : {0}", value); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.OverflowException
Example 3: Program for DivideByZeroException
// C# program to demonstrate the// Decimal.Remainder(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 0.00m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine("Remainder is : {0}", value); } catch (DivideByZeroException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.DivideByZeroException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal.remainder?view=netframework-4.7.2
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 25656,
"s": 25547,
"text": "This method is used to compute the remainder when the division is done between two specified decimal values."
},
{
"code": null,
"e": 25722,
"s": 25656,
"text": "Syntax: public static decimal Remainder (decimal a1, decimal a2);"
},
{
"code": null,
"e": 25817,
"s": 25722,
"text": "Parameters:a1: This parameter specifies the dividend.a2: This parameter specifies the divisor."
},
{
"code": null,
"e": 25888,
"s": 25817,
"text": "Return Value: It returns the remainder of the after dividing a1 by a2."
},
{
"code": null,
"e": 25900,
"s": 25888,
"text": "Exceptions:"
},
{
"code": null,
"e": 25952,
"s": 25900,
"text": "DivideByZeroException: This occurs when a2 is zero."
},
{
"code": null,
"e": 26039,
"s": 25952,
"text": "OverflowException: If the return value is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 26120,
"s": 26039,
"text": "Below programs illustrate the use of Decimal.Remainder(Decimal, Decimal) Method:"
},
{
"code": null,
"e": 26131,
"s": 26120,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Decimal.Remainder(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 1.11m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine(\"Remainder is : {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26872,
"s": 26131,
"text": null
},
{
"code": null,
"e": 26893,
"s": 26872,
"text": "Remainder is : 0.69\n"
},
{
"code": null,
"e": 26926,
"s": 26893,
"text": "Example 2: For OverflowException"
},
{
"code": "// C# program to demonstrate the// Decimal.Remainder(Decimal, // Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = Decimal.MaxValue; Decimal a2 = 0.02m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine(\"Remainder is : {0}\", value); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 27678,
"s": 26926,
"text": null
},
{
"code": null,
"e": 27722,
"s": 27678,
"text": "Exception Thrown: System.OverflowException\n"
},
{
"code": null,
"e": 27767,
"s": 27722,
"text": "Example 3: Program for DivideByZeroException"
},
{
"code": "// C# program to demonstrate the// Decimal.Remainder(Decimal,// Decimal) Methodusing System; class GFG { // Main Method public static void Main() { try { // Declaring the decimal variables Decimal a1 = 4.02m; Decimal a2 = 0.00m; // dividing and getting the remainder // of the two Decimal value // using Remainder() method; Decimal value = Decimal.Remainder(a1, a2); // Display the remainder Console.WriteLine(\"Remainder is : {0}\", value); } catch (DivideByZeroException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 28511,
"s": 27767,
"text": null
},
{
"code": null,
"e": 28559,
"s": 28511,
"text": "Exception Thrown: System.DivideByZeroException\n"
},
{
"code": null,
"e": 28570,
"s": 28559,
"text": "Reference:"
},
{
"code": null,
"e": 28663,
"s": 28570,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.decimal.remainder?view=netframework-4.7.2"
},
{
"code": null,
"e": 28685,
"s": 28663,
"text": "CSharp-Decimal-Struct"
},
{
"code": null,
"e": 28699,
"s": 28685,
"text": "CSharp-method"
},
{
"code": null,
"e": 28702,
"s": 28699,
"text": "C#"
},
{
"code": null,
"e": 28800,
"s": 28702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28823,
"s": 28800,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28851,
"s": 28823,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28868,
"s": 28851,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28890,
"s": 28868,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28919,
"s": 28890,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28959,
"s": 28919,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28982,
"s": 28959,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 29025,
"s": 28982,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29065,
"s": 29025,
"text": "Convert String to Character Array in C#"
}
] |
Count of K length subarrays containing only 1s in given Binary String - GeeksforGeeks
|
04 Jan, 2022
Given a binary string str, the task is to find the count of K length subarrays containing only 1s.
Examples:
Input: str = “0101000”, K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones
Input: str = “11111001”, K=3Output: 3
Approach: The task can be solved by keeping track of the group sizes of consecutive ones. Once, we get the groupSize, we can deduce that number of possible subarrays of length k, and all 1s, are groupSize – k + 1.
Follow the below steps to solve the problem:
Iterate over the binary string from the start
Increment the count, if 1 is encountered, and at a point where 0 comes.
Store the current count to get the groupSize of consecutive 1s, and re-initialize the count to 0.
Add the count of possible subarrays of size k in this groupSize using relation groupSize – k + 1
Return the final sum of count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of all possible// k length subarraysint get(string s, int k){ // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; int n = s.length(); int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans;} // Driver codeint main(){ string str = "0101000"; int K = 1; cout << get(str, K) << endl; return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the count of all possible// k length subarraysstatic int get(String s, int k){ // Add dummy character at last to handle // edge cases, where String ends with '1' s += '0'; int n = s.length(); int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans;} // Driver codepublic static void main(String[] args){ String str = "0101000"; int K = 1; System.out.print(get(str, K) +"\n");}} // This code is contributed by Rajput-Ji
# Python code for the above approach # Function to find the count of all possible# k length subarraysdef get(s, k): # Add dummy character at last to handle # edge cases, where string ends with '1' s += '0' n = len(s) cnt = 0 ans = 0 for i in range(n): if (s[i] == '1'): cnt += 1 else: if (cnt >= k): ans += (cnt - k + 1) cnt = 0 return ans # Driver codestr = "0101000"K = 1print(get(str, K)) # This code is contributed by Saurabh Jaiswal
// C# program for the above approachusing System;class GFG{ // Function to find the count of all possible // k length subarrays static int get(string s, int k) { // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; int n = s.Length; int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans; } // Driver code public static void Main() { string str = "0101000"; int K = 1; Console.WriteLine(get(str, K)); }} // This code is contributed by ukasp.
<script> // JavaScript code for the above approach // Function to find the count of all possible // k length subarrays function get(s, k) { // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; let n = s.length; let cnt = 0, ans = 0; for (let i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans; } // Driver code let str = "0101000"; let K = 1; document.write(get(str, K) + '<br>'); // This code is contributed by Potta Lokesh </script>
2
Time Complexity: O(N) Auxiliary Space: O(1)
lokeshpotta20
gfgking
ukasp
Rajput-Ji
Algo-Geek 2021
binary-string
subarray
Algo Geek
Combinatorial
Strings
Strings
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Divide given number into two even parts
Sort strings on the basis of their numeric part
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Count of Palindrome Strings in given Array of strings
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number
|
[
{
"code": null,
"e": 27535,
"s": 27507,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 27634,
"s": 27535,
"text": "Given a binary string str, the task is to find the count of K length subarrays containing only 1s."
},
{
"code": null,
"e": 27644,
"s": 27634,
"text": "Examples:"
},
{
"code": null,
"e": 27738,
"s": 27644,
"text": "Input: str = “0101000”, K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones"
},
{
"code": null,
"e": 27776,
"s": 27738,
"text": "Input: str = “11111001”, K=3Output: 3"
},
{
"code": null,
"e": 27990,
"s": 27776,
"text": "Approach: The task can be solved by keeping track of the group sizes of consecutive ones. Once, we get the groupSize, we can deduce that number of possible subarrays of length k, and all 1s, are groupSize – k + 1."
},
{
"code": null,
"e": 28035,
"s": 27990,
"text": "Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 28081,
"s": 28035,
"text": "Iterate over the binary string from the start"
},
{
"code": null,
"e": 28153,
"s": 28081,
"text": "Increment the count, if 1 is encountered, and at a point where 0 comes."
},
{
"code": null,
"e": 28251,
"s": 28153,
"text": "Store the current count to get the groupSize of consecutive 1s, and re-initialize the count to 0."
},
{
"code": null,
"e": 28348,
"s": 28251,
"text": "Add the count of possible subarrays of size k in this groupSize using relation groupSize – k + 1"
},
{
"code": null,
"e": 28379,
"s": 28348,
"text": "Return the final sum of count."
},
{
"code": null,
"e": 28430,
"s": 28379,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28434,
"s": 28430,
"text": "C++"
},
{
"code": null,
"e": 28439,
"s": 28434,
"text": "Java"
},
{
"code": null,
"e": 28447,
"s": 28439,
"text": "Python3"
},
{
"code": null,
"e": 28450,
"s": 28447,
"text": "C#"
},
{
"code": null,
"e": 28461,
"s": 28450,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the count of all possible// k length subarraysint get(string s, int k){ // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; int n = s.length(); int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans;} // Driver codeint main(){ string str = \"0101000\"; int K = 1; cout << get(str, K) << endl; return 0;}",
"e": 29115,
"s": 28461,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the count of all possible// k length subarraysstatic int get(String s, int k){ // Add dummy character at last to handle // edge cases, where String ends with '1' s += '0'; int n = s.length(); int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans;} // Driver codepublic static void main(String[] args){ String str = \"0101000\"; int K = 1; System.out.print(get(str, K) +\"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 29838,
"s": 29115,
"text": null
},
{
"code": "# Python code for the above approach # Function to find the count of all possible# k length subarraysdef get(s, k): # Add dummy character at last to handle # edge cases, where string ends with '1' s += '0' n = len(s) cnt = 0 ans = 0 for i in range(n): if (s[i] == '1'): cnt += 1 else: if (cnt >= k): ans += (cnt - k + 1) cnt = 0 return ans # Driver codestr = \"0101000\"K = 1print(get(str, K)) # This code is contributed by Saurabh Jaiswal",
"e": 30364,
"s": 29838,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the count of all possible // k length subarrays static int get(string s, int k) { // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; int n = s.Length; int cnt = 0, ans = 0; for (int i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans; } // Driver code public static void Main() { string str = \"0101000\"; int K = 1; Console.WriteLine(get(str, K)); }} // This code is contributed by ukasp.",
"e": 31166,
"s": 30364,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find the count of all possible // k length subarrays function get(s, k) { // Add dummy character at last to handle // edge cases, where string ends with '1' s += '0'; let n = s.length; let cnt = 0, ans = 0; for (let i = 0; i < n; i++) { if (s[i] == '1') cnt++; else { if (cnt >= k) { ans += (cnt - k + 1); } cnt = 0; } } return ans; } // Driver code let str = \"0101000\"; let K = 1; document.write(get(str, K) + '<br>'); // This code is contributed by Potta Lokesh </script>",
"e": 31855,
"s": 31166,
"text": null
},
{
"code": null,
"e": 31860,
"s": 31858,
"text": "2"
},
{
"code": null,
"e": 31905,
"s": 31860,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31921,
"s": 31907,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31929,
"s": 31921,
"text": "gfgking"
},
{
"code": null,
"e": 31935,
"s": 31929,
"text": "ukasp"
},
{
"code": null,
"e": 31945,
"s": 31935,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31960,
"s": 31945,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 31974,
"s": 31960,
"text": "binary-string"
},
{
"code": null,
"e": 31983,
"s": 31974,
"text": "subarray"
},
{
"code": null,
"e": 31993,
"s": 31983,
"text": "Algo Geek"
},
{
"code": null,
"e": 32007,
"s": 31993,
"text": "Combinatorial"
},
{
"code": null,
"e": 32015,
"s": 32007,
"text": "Strings"
},
{
"code": null,
"e": 32023,
"s": 32015,
"text": "Strings"
},
{
"code": null,
"e": 32037,
"s": 32023,
"text": "Combinatorial"
},
{
"code": null,
"e": 32135,
"s": 32037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32190,
"s": 32135,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 32230,
"s": 32190,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 32278,
"s": 32230,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 32358,
"s": 32278,
"text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64"
},
{
"code": null,
"e": 32412,
"s": 32358,
"text": "Count of Palindrome Strings in given Array of strings"
},
{
"code": null,
"e": 32472,
"s": 32412,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32510,
"s": 32472,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 32587,
"s": 32510,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 32605,
"s": 32587,
"text": "Combinational Sum"
}
] |
AngularJS | ng-class Directive - GeeksforGeeks
|
29 Mar, 2019
The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. If the expression inside the ng-class directive returns true then only the class is added else it is not added. It is supported by all HTML elements.
Syntax:
<element ng-class="expression"> Contents... </element>
Example 1: This example uses ng-class Directive to set and reset CSS class.
<!DOCTYPE html><html> <head> <title>ng-class Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> <style> .edit { color: green; font-size: 1.5em; } </style></head> <body ng-app="" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-class Directive</h2> <div> <input type="button" ng-click="edit=true" value="Style" /> <input type="button" ng-click="edit=false" value="Reset" /> <br><br> <span ng-class="{true:'edit'}[edit]"> GeeksforGeeks </span> is the computer science portal for geeks. </div></body> </html>
Output:Before Clicking the button:After Clicking the style button:
Example 2: This example uses ng-class Directive to set the CSS style to the class.
<!DOCTYPE html><html> <head> <title>ng-class Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> <style type="text/css"> .index { color: white; background-color: green; } </style></head> <body ng-app="app" style="padding:20px"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-class Directive</h2> <div ng-controller="geek"> <table> <thead> <th>Select any sorting technique:</th> <tr ng-repeat="i in sort"> <td ng-class="{index:$index==row}" ng-click="sel($index)"> {{i.name}} </td> </tr> </thead> </table> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.sort = [ { name: "Merge sort" }, { name: "Quick sort" }, { name: "Bubble sort" } ]; $scope.sel = function (index) { $scope.row = index; }; }]); </script></body> </html>
Output:Before Selecting the element:After Selecting the element:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular | keyup event
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
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": 29626,
"s": 29598,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 29924,
"s": 29626,
"text": "The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. If the expression inside the ng-class directive returns true then only the class is added else it is not added. It is supported by all HTML elements."
},
{
"code": null,
"e": 29932,
"s": 29924,
"text": "Syntax:"
},
{
"code": null,
"e": 29987,
"s": 29932,
"text": "<element ng-class=\"expression\"> Contents... </element>"
},
{
"code": null,
"e": 30063,
"s": 29987,
"text": "Example 1: This example uses ng-class Directive to set and reset CSS class."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-class Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> <style> .edit { color: green; font-size: 1.5em; } </style></head> <body ng-app=\"\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-class Directive</h2> <div> <input type=\"button\" ng-click=\"edit=true\" value=\"Style\" /> <input type=\"button\" ng-click=\"edit=false\" value=\"Reset\" /> <br><br> <span ng-class=\"{true:'edit'}[edit]\"> GeeksforGeeks </span> is the computer science portal for geeks. </div></body> </html> ",
"e": 30838,
"s": 30063,
"text": null
},
{
"code": null,
"e": 30905,
"s": 30838,
"text": "Output:Before Clicking the button:After Clicking the style button:"
},
{
"code": null,
"e": 30988,
"s": 30905,
"text": "Example 2: This example uses ng-class Directive to set the CSS style to the class."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-class Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> <style type=\"text/css\"> .index { color: white; background-color: green; } </style></head> <body ng-app=\"app\" style=\"padding:20px\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-class Directive</h2> <div ng-controller=\"geek\"> <table> <thead> <th>Select any sorting technique:</th> <tr ng-repeat=\"i in sort\"> <td ng-class=\"{index:$index==row}\" ng-click=\"sel($index)\"> {{i.name}} </td> </tr> </thead> </table> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.sort = [ { name: \"Merge sort\" }, { name: \"Quick sort\" }, { name: \"Bubble sort\" } ]; $scope.sel = function (index) { $scope.row = index; }; }]); </script></body> </html> ",
"e": 32268,
"s": 30988,
"text": null
},
{
"code": null,
"e": 32333,
"s": 32268,
"text": "Output:Before Selecting the element:After Selecting the element:"
},
{
"code": null,
"e": 32354,
"s": 32333,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 32364,
"s": 32354,
"text": "AngularJS"
},
{
"code": null,
"e": 32381,
"s": 32364,
"text": "Web Technologies"
},
{
"code": null,
"e": 32479,
"s": 32381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32499,
"s": 32479,
"text": "Angular File Upload"
},
{
"code": null,
"e": 32521,
"s": 32499,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 32556,
"s": 32521,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 32587,
"s": 32556,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 32622,
"s": 32587,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 32662,
"s": 32622,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32695,
"s": 32662,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32740,
"s": 32695,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32783,
"s": 32740,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to check for Peterson number - GeeksforGeeks
|
31 Aug, 2021
A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself.
Example:
Input : n = 145
Output = Yes
Explanation:
145 = 5! + 4! + 1!
= 120 + 24 +1
= 145
Input : n = 55
Output : No
Explanation: 5! + 5!
= 120 + 120
= 240
Since 55 is not equal to 240
It is not a Peterson number.
We will pick each digit (Starting from the last digit) of the given number and find its factorial. And add all factorials. Finally, we check if the sum of factorials is equal to number or not.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to determine whether the number is// Peterson number or not#include <iostream>using namespace std; // To quickly find factorial of digitsint fact[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to check if a number is Peterson// or notbool peterson(int n){ int num = n, sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { int digit = n % 10; sum += fact[digit]; n = n / 10; } // Condition check for a number to // be a Peterson Number return (sum == num);} // Driver Programint main(){ int n = 145; if (peterson(n)) cout << "Yes"; else cout << "No"; return 0;}
//checks whether a number entered by user is peterson number or notimport java.util.*;class GFG{ public static void main(String args[]) { Scanner sc=new Scanner(System.in); //taking input from the user System.out.println("Enter the number"); int num=sc.nextInt(); int temp=num;//storing the number in a temporary variable int f=1,sum=0; while(num!=0)//running while loop until number becomes zero { f=1; //extracting last digit of the number //and storing in r int r=num%10; //for loop to find the factorial of a digit for(int i=1;i<=r;i++) { f=f*i; } sum=sum+f;//adding the factotial of the digits num=num/10; } //checking if the sum of the factorial of digits //is equal to the number or not if(sum==temp) System.out.println("PETERSON NUMBER"); else System.out.println("NOT PETERSON NUMBER"); } }
# Python3 code to determine whether the# number is Peterson number or not # To quickly find factorial of digitsfact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] # Function to check if a number# is Peterson or not def peterson(n): num = n sum = 0 # stores the sum of factorials of # each digit of the number. while n > 0: digit = int(n % 10) sum += fact[digit] n = int(n / 10) # Condition check for a number # to be a Peterson Number return (sum == num) # Driver Coden = 145print("Yes" if peterson(n) else "No") # This code is contributed by "Sharad_Bhardwaj"..
// C# program to determine whether the// number is Peterson number or notusing System; public class GFG { // To quickly find factorial of digits static int[] fact = new int[10] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to check if a number is // Peterson or not static bool peterson(int n) { int num = n; int sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { int digit = n % 10; sum += fact[digit]; n = n / 10; } // Condition check for a number to // be a Peterson Number return (sum == num); } // Driver Program static public void Main() { int n = 145; if (peterson(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to determine// whether the number is// Peterson number or not // To quickly find// factorial of digits$fact =array (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880); // Function to check if// a number is Peterson// or notfunction peterson($n){ $num = $n; $sum = 0; // stores the sum of factorials of // each digit of the number. while ($n > 0) { $digit = $n % 10; $n = $n / 10; } // Condition check for // a number to be a // Peterson Number return ($sum == $num);} // Driver Code $n = 145; if (peterson($n)) echo "Yes"; else echo"No"; // This code is contributed by ajit?>
<script> // Javascript program to determine whether// the number is Peterson number or not // To quickly find factorial of digitslet fact = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 ]; // Function to check if a number is// Peterson or notfunction peterson(n){ let num = n, sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { let digit = n % 10; sum += fact[digit]; n = parseInt(n / 10); } // Condition check for a number to // be a Peterson Number return (sum == num);} // Driver codelet n = 145;if (peterson(n)) document.write("Yes");else document.write("No"); // This code is contributed by souravmahato348 </script>
Output:
vt_m
jit_t
rayvantsahni
souravmahato348
abhishekinvestment0209
factorial
number-digits
School Programming
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exceptions in Java
Constructors in Java
Ternary Operator in Python
Inline Functions in C++
Destructors in C++
Pure Virtual Functions and Abstract Classes in C++
Difference between Abstract Class and Interface in Java
Python Exception Handling
Exception Handling in C++
Taking input from console in Python
|
[
{
"code": null,
"e": 25575,
"s": 25547,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 25700,
"s": 25575,
"text": "A number is said to be a Peterson number if the sum of factorials of each digit of the number is equal to the number itself."
},
{
"code": null,
"e": 25710,
"s": 25700,
"text": "Example: "
},
{
"code": null,
"e": 25957,
"s": 25710,
"text": "Input : n = 145\nOutput = Yes\nExplanation:\n 145 = 5! + 4! + 1!\n = 120 + 24 +1\n = 145\n\nInput : n = 55\nOutput : No\nExplanation: 5! + 5!\n = 120 + 120\n = 240\nSince 55 is not equal to 240\nIt is not a Peterson number. "
},
{
"code": null,
"e": 26151,
"s": 25957,
"text": "We will pick each digit (Starting from the last digit) of the given number and find its factorial. And add all factorials. Finally, we check if the sum of factorials is equal to number or not. "
},
{
"code": null,
"e": 26155,
"s": 26151,
"text": "C++"
},
{
"code": null,
"e": 26160,
"s": 26155,
"text": "Java"
},
{
"code": null,
"e": 26168,
"s": 26160,
"text": "Python3"
},
{
"code": null,
"e": 26171,
"s": 26168,
"text": "C#"
},
{
"code": null,
"e": 26175,
"s": 26171,
"text": "PHP"
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "Javascript"
},
{
"code": "// C++ program to determine whether the number is// Peterson number or not#include <iostream>using namespace std; // To quickly find factorial of digitsint fact[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to check if a number is Peterson// or notbool peterson(int n){ int num = n, sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { int digit = n % 10; sum += fact[digit]; n = n / 10; } // Condition check for a number to // be a Peterson Number return (sum == num);} // Driver Programint main(){ int n = 145; if (peterson(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26896,
"s": 26186,
"text": null
},
{
"code": "//checks whether a number entered by user is peterson number or notimport java.util.*;class GFG{ public static void main(String args[]) { Scanner sc=new Scanner(System.in); //taking input from the user System.out.println(\"Enter the number\"); int num=sc.nextInt(); int temp=num;//storing the number in a temporary variable int f=1,sum=0; while(num!=0)//running while loop until number becomes zero { f=1; //extracting last digit of the number //and storing in r int r=num%10; //for loop to find the factorial of a digit for(int i=1;i<=r;i++) { f=f*i; } sum=sum+f;//adding the factotial of the digits num=num/10; } //checking if the sum of the factorial of digits //is equal to the number or not if(sum==temp) System.out.println(\"PETERSON NUMBER\"); else System.out.println(\"NOT PETERSON NUMBER\"); } }",
"e": 27923,
"s": 26896,
"text": null
},
{
"code": "# Python3 code to determine whether the# number is Peterson number or not # To quickly find factorial of digitsfact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] # Function to check if a number# is Peterson or not def peterson(n): num = n sum = 0 # stores the sum of factorials of # each digit of the number. while n > 0: digit = int(n % 10) sum += fact[digit] n = int(n / 10) # Condition check for a number # to be a Peterson Number return (sum == num) # Driver Coden = 145print(\"Yes\" if peterson(n) else \"No\") # This code is contributed by \"Sharad_Bhardwaj\"..",
"e": 28545,
"s": 27923,
"text": null
},
{
"code": "// C# program to determine whether the// number is Peterson number or notusing System; public class GFG { // To quickly find factorial of digits static int[] fact = new int[10] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; // Function to check if a number is // Peterson or not static bool peterson(int n) { int num = n; int sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { int digit = n % 10; sum += fact[digit]; n = n / 10; } // Condition check for a number to // be a Peterson Number return (sum == num); } // Driver Program static public void Main() { int n = 145; if (peterson(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 29491,
"s": 28545,
"text": null
},
{
"code": "<?php// PHP program to determine// whether the number is// Peterson number or not // To quickly find// factorial of digits$fact =array (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880); // Function to check if// a number is Peterson// or notfunction peterson($n){ $num = $n; $sum = 0; // stores the sum of factorials of // each digit of the number. while ($n > 0) { $digit = $n % 10; $n = $n / 10; } // Condition check for // a number to be a // Peterson Number return ($sum == $num);} // Driver Code $n = 145; if (peterson($n)) echo \"Yes\"; else echo\"No\"; // This code is contributed by ajit?>",
"e": 30181,
"s": 29491,
"text": null
},
{
"code": "<script> // Javascript program to determine whether// the number is Peterson number or not // To quickly find factorial of digitslet fact = [ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 ]; // Function to check if a number is// Peterson or notfunction peterson(n){ let num = n, sum = 0; // stores the sum of factorials of // each digit of the number. while (n > 0) { let digit = n % 10; sum += fact[digit]; n = parseInt(n / 10); } // Condition check for a number to // be a Peterson Number return (sum == num);} // Driver codelet n = 145;if (peterson(n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by souravmahato348 </script>",
"e": 30915,
"s": 30181,
"text": null
},
{
"code": null,
"e": 30924,
"s": 30915,
"text": "Output: "
},
{
"code": null,
"e": 30931,
"s": 30926,
"text": "vt_m"
},
{
"code": null,
"e": 30937,
"s": 30931,
"text": "jit_t"
},
{
"code": null,
"e": 30950,
"s": 30937,
"text": "rayvantsahni"
},
{
"code": null,
"e": 30966,
"s": 30950,
"text": "souravmahato348"
},
{
"code": null,
"e": 30989,
"s": 30966,
"text": "abhishekinvestment0209"
},
{
"code": null,
"e": 30999,
"s": 30989,
"text": "factorial"
},
{
"code": null,
"e": 31013,
"s": 30999,
"text": "number-digits"
},
{
"code": null,
"e": 31032,
"s": 31013,
"text": "School Programming"
},
{
"code": null,
"e": 31042,
"s": 31032,
"text": "factorial"
},
{
"code": null,
"e": 31140,
"s": 31042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31159,
"s": 31140,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31180,
"s": 31159,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31207,
"s": 31180,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 31231,
"s": 31207,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 31250,
"s": 31231,
"text": "Destructors in C++"
},
{
"code": null,
"e": 31301,
"s": 31250,
"text": "Pure Virtual Functions and Abstract Classes in C++"
},
{
"code": null,
"e": 31357,
"s": 31301,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 31383,
"s": 31357,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 31409,
"s": 31383,
"text": "Exception Handling in C++"
}
] |
Implement your own word2vec(skip-gram) model in Python - GeeksforGeeks
|
02 Dec, 2021
Prerequisite: Introduction to word2vecNatural language processing (NLP) is a subfield of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages. In NLP techniques, we map the words and phrases (from vocabulary or corpus) to vectors of numbers to make the processing easier. These types of language modeling techniques are called word embeddings. In 2013, Google announched word2vec, a group of related models that are used to produce word embeddings.Let’s implement our own skip-gram model (in Python) by deriving the backpropagation equations of our neural network.In skip gram architecture of word2vec, the input is the center word and the predictions are the context words. Consider an array of words W, if W(i) is the input (center word), then W(i-2), W(i-1), W(i+1), and W(i+2) are the context words, if the sliding window size is 2.
Let's define some variables :
V Number of unique words in our corpus of text ( Vocabulary )
x Input layer (One hot encoding of our input word ).
N Number of neurons in the hidden layer of neural network
W Weights between input layer and hidden layer
W' Weights between hidden layer and output layer
y A softmax output layer having probabilities of every word in our vocabulary
Skip gram architecture
Our neural network architecture is defined, now let’s do some math to derive the equations needed for gradient descent.
Multiplying one hot encoding of centre word (denoted by x) with the first weight matrix W to get hidden layer matrix h (of size N x 1). ( Vx1 ) ( NxV ) ( Vx1 ) Now we multiply the hidden layer vector h with second weight matrix W’ to get a new matrix u( Vx1 ) ( VxN ) ( Nx1 ) Note that we have to apply a softmax> to layer u to get our output layer y.Let uj be jth neuron of layer u Let wj be the jth word in our vocabulary where j is any index Let Vwj be the jth column of matrix W’(column corresponding to a word wj)( 1×1 ) ( 1xN ) ( Nx1 ) y = softmax(u) yj = softmax(uj) yj denotes the probability that wj is a context word P(wj|wi) is the probability that wj is a context word, given wi is the input word.Thus, our goal is to maximise P( wj* | wi ), where j* represents the indices of context wordsClearly we want to maximise where j*c are the vocabulary indexes of context words . Context words range from c = 1, 2, 3..C Let’s take a negative log likelihood of this function to get our loss function, which we want to minimise Let t be actual output vector from our training data, for a particular centre word. It will have 1’s at the positions of context words and 0’s at all other places. tj*c are the 1’s of the context words. We can multiply with Solving this equation we get our loss function as –
The parameters to be adjusted are in the matrices W and W’, hence we have to find the partial derivatives of our loss function with respect to W and W’ to apply gradient descent algorithm. We have to find Now, Finding Below is the implementation :
Python3
import numpy as npimport stringfrom nltk.corpus import stopwords def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() class word2vec(object): def __init__(self): self.N = 10 self.X_train = [] self.y_train = [] self.window_size = 2 self.alpha = 0.001 self.words = [] self.word_index = {} def initialize(self,V,data): self.V = V self.W = np.random.uniform(-0.8, 0.8, (self.V, self.N)) self.W1 = np.random.uniform(-0.8, 0.8, (self.N, self.V)) self.words = data for i in range(len(data)): self.word_index[data[i]] = i def feed_forward(self,X): self.h = np.dot(self.W.T,X).reshape(self.N,1) self.u = np.dot(self.W1.T,self.h) #print(self.u) self.y = softmax(self.u) return self.y def backpropagate(self,x,t): e = self.y - np.asarray(t).reshape(self.V,1) # e.shape is V x 1 dLdW1 = np.dot(self.h,e.T) X = np.array(x).reshape(self.V,1) dLdW = np.dot(X, np.dot(self.W1,e).T) self.W1 = self.W1 - self.alpha*dLdW1 self.W = self.W - self.alpha*dLdW def train(self,epochs): for x in range(1,epochs): self.loss = 0 for j in range(len(self.X_train)): self.feed_forward(self.X_train[j]) self.backpropagate(self.X_train[j],self.y_train[j]) C = 0 for m in range(self.V): if(self.y_train[j][m]): self.loss += -1*self.u[m][0] C += 1 self.loss += C*np.log(np.sum(np.exp(self.u))) print("epoch ",x, " loss = ",self.loss) self.alpha *= 1/( (1+self.alpha*x) ) def predict(self,word,number_of_predictions): if word in self.words: index = self.word_index[word] X = [0 for i in range(self.V)] X[index] = 1 prediction = self.feed_forward(X) output = {} for i in range(self.V): output[prediction[i][0]] = i top_context_words = [] for k in sorted(output,reverse=True): top_context_words.append(self.words[output[k]]) if(len(top_context_words)>=number_of_predictions): break return top_context_words else: print("Word not found in dictionary")
Python3
def preprocessing(corpus): stop_words = set(stopwords.words('english')) training_data = [] sentences = corpus.split(".") for i in range(len(sentences)): sentences[i] = sentences[i].strip() sentence = sentences[i].split() x = [word.strip(string.punctuation) for word in sentence if word not in stop_words] x = [word.lower() for word in x] training_data.append(x) return training_data def prepare_data_for_training(sentences,w2v): data = {} for sentence in sentences: for word in sentence: if word not in data: data[word] = 1 else: data[word] += 1 V = len(data) data = sorted(list(data.keys())) vocab = {} for i in range(len(data)): vocab[data[i]] = i #for i in range(len(words)): for sentence in sentences: for i in range(len(sentence)): center_word = [0 for x in range(V)] center_word[vocab[sentence[i]]] = 1 context = [0 for x in range(V)] for j in range(i-w2v.window_size,i+w2v.window_size): if i!=j and j>=0 and j<len(sentence): context[vocab[sentence[j]]] += 1 w2v.X_train.append(center_word) w2v.y_train.append(context) w2v.initialize(V,data) return w2v.X_train,w2v.y_train
Python3
corpus = ""corpus += "The earth revolves around the sun. The moon revolves around the earth"epochs = 1000 training_data = preprocessing(corpus)w2v = word2vec() prepare_data_for_training(training_data,w2v)w2v.train(epochs) print(w2v.predict("around",3))
Output:
sumitgumber28
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Copying Files to and from Docker Containers
System Design Tutorial
Python | Decision tree implementation
ML | Underfitting and Overfitting
ML | Linear Regression
Agents in Artificial Intelligence
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
|
[
{
"code": null,
"e": 26238,
"s": 26210,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 27149,
"s": 26238,
"text": "Prerequisite: Introduction to word2vecNatural language processing (NLP) is a subfield of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages. In NLP techniques, we map the words and phrases (from vocabulary or corpus) to vectors of numbers to make the processing easier. These types of language modeling techniques are called word embeddings. In 2013, Google announched word2vec, a group of related models that are used to produce word embeddings.Let’s implement our own skip-gram model (in Python) by deriving the backpropagation equations of our neural network.In skip gram architecture of word2vec, the input is the center word and the predictions are the context words. Consider an array of words W, if W(i) is the input (center word), then W(i-2), W(i-1), W(i+1), and W(i+2) are the context words, if the sliding window size is 2. "
},
{
"code": null,
"e": 27547,
"s": 27151,
"text": "Let's define some variables :\n\nV Number of unique words in our corpus of text ( Vocabulary )\nx Input layer (One hot encoding of our input word ). \nN Number of neurons in the hidden layer of neural network\nW Weights between input layer and hidden layer\nW' Weights between hidden layer and output layer\ny A softmax output layer having probabilities of every word in our vocabulary"
},
{
"code": null,
"e": 27572,
"s": 27549,
"text": "Skip gram architecture"
},
{
"code": null,
"e": 27693,
"s": 27572,
"text": "Our neural network architecture is defined, now let’s do some math to derive the equations needed for gradient descent. "
},
{
"code": null,
"e": 29030,
"s": 27693,
"text": "Multiplying one hot encoding of centre word (denoted by x) with the first weight matrix W to get hidden layer matrix h (of size N x 1). ( Vx1 ) ( NxV ) ( Vx1 ) Now we multiply the hidden layer vector h with second weight matrix W’ to get a new matrix u( Vx1 ) ( VxN ) ( Nx1 ) Note that we have to apply a softmax> to layer u to get our output layer y.Let uj be jth neuron of layer u Let wj be the jth word in our vocabulary where j is any index Let Vwj be the jth column of matrix W’(column corresponding to a word wj)( 1×1 ) ( 1xN ) ( Nx1 ) y = softmax(u) yj = softmax(uj) yj denotes the probability that wj is a context word P(wj|wi) is the probability that wj is a context word, given wi is the input word.Thus, our goal is to maximise P( wj* | wi ), where j* represents the indices of context wordsClearly we want to maximise where j*c are the vocabulary indexes of context words . Context words range from c = 1, 2, 3..C Let’s take a negative log likelihood of this function to get our loss function, which we want to minimise Let t be actual output vector from our training data, for a particular centre word. It will have 1’s at the positions of context words and 0’s at all other places. tj*c are the 1’s of the context words. We can multiply with Solving this equation we get our loss function as – "
},
{
"code": null,
"e": 29282,
"s": 29030,
"text": "The parameters to be adjusted are in the matrices W and W’, hence we have to find the partial derivatives of our loss function with respect to W and W’ to apply gradient descent algorithm. We have to find Now, Finding Below is the implementation : "
},
{
"code": null,
"e": 29290,
"s": 29282,
"text": "Python3"
},
{
"code": "import numpy as npimport stringfrom nltk.corpus import stopwords def softmax(x): \"\"\"Compute softmax values for each sets of scores in x.\"\"\" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum() class word2vec(object): def __init__(self): self.N = 10 self.X_train = [] self.y_train = [] self.window_size = 2 self.alpha = 0.001 self.words = [] self.word_index = {} def initialize(self,V,data): self.V = V self.W = np.random.uniform(-0.8, 0.8, (self.V, self.N)) self.W1 = np.random.uniform(-0.8, 0.8, (self.N, self.V)) self.words = data for i in range(len(data)): self.word_index[data[i]] = i def feed_forward(self,X): self.h = np.dot(self.W.T,X).reshape(self.N,1) self.u = np.dot(self.W1.T,self.h) #print(self.u) self.y = softmax(self.u) return self.y def backpropagate(self,x,t): e = self.y - np.asarray(t).reshape(self.V,1) # e.shape is V x 1 dLdW1 = np.dot(self.h,e.T) X = np.array(x).reshape(self.V,1) dLdW = np.dot(X, np.dot(self.W1,e).T) self.W1 = self.W1 - self.alpha*dLdW1 self.W = self.W - self.alpha*dLdW def train(self,epochs): for x in range(1,epochs): self.loss = 0 for j in range(len(self.X_train)): self.feed_forward(self.X_train[j]) self.backpropagate(self.X_train[j],self.y_train[j]) C = 0 for m in range(self.V): if(self.y_train[j][m]): self.loss += -1*self.u[m][0] C += 1 self.loss += C*np.log(np.sum(np.exp(self.u))) print(\"epoch \",x, \" loss = \",self.loss) self.alpha *= 1/( (1+self.alpha*x) ) def predict(self,word,number_of_predictions): if word in self.words: index = self.word_index[word] X = [0 for i in range(self.V)] X[index] = 1 prediction = self.feed_forward(X) output = {} for i in range(self.V): output[prediction[i][0]] = i top_context_words = [] for k in sorted(output,reverse=True): top_context_words.append(self.words[output[k]]) if(len(top_context_words)>=number_of_predictions): break return top_context_words else: print(\"Word not found in dictionary\")",
"e": 31844,
"s": 29290,
"text": null
},
{
"code": null,
"e": 31852,
"s": 31844,
"text": "Python3"
},
{
"code": "def preprocessing(corpus): stop_words = set(stopwords.words('english')) training_data = [] sentences = corpus.split(\".\") for i in range(len(sentences)): sentences[i] = sentences[i].strip() sentence = sentences[i].split() x = [word.strip(string.punctuation) for word in sentence if word not in stop_words] x = [word.lower() for word in x] training_data.append(x) return training_data def prepare_data_for_training(sentences,w2v): data = {} for sentence in sentences: for word in sentence: if word not in data: data[word] = 1 else: data[word] += 1 V = len(data) data = sorted(list(data.keys())) vocab = {} for i in range(len(data)): vocab[data[i]] = i #for i in range(len(words)): for sentence in sentences: for i in range(len(sentence)): center_word = [0 for x in range(V)] center_word[vocab[sentence[i]]] = 1 context = [0 for x in range(V)] for j in range(i-w2v.window_size,i+w2v.window_size): if i!=j and j>=0 and j<len(sentence): context[vocab[sentence[j]]] += 1 w2v.X_train.append(center_word) w2v.y_train.append(context) w2v.initialize(V,data) return w2v.X_train,w2v.y_train ",
"e": 33253,
"s": 31852,
"text": null
},
{
"code": null,
"e": 33261,
"s": 33253,
"text": "Python3"
},
{
"code": "corpus = \"\"corpus += \"The earth revolves around the sun. The moon revolves around the earth\"epochs = 1000 training_data = preprocessing(corpus)w2v = word2vec() prepare_data_for_training(training_data,w2v)w2v.train(epochs) print(w2v.predict(\"around\",3)) ",
"e": 33517,
"s": 33261,
"text": null
},
{
"code": null,
"e": 33527,
"s": 33517,
"text": "Output: "
},
{
"code": null,
"e": 33543,
"s": 33529,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33569,
"s": 33543,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 33586,
"s": 33569,
"text": "Machine Learning"
},
{
"code": null,
"e": 33593,
"s": 33586,
"text": "Python"
},
{
"code": null,
"e": 33610,
"s": 33593,
"text": "Machine Learning"
},
{
"code": null,
"e": 33708,
"s": 33610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33731,
"s": 33708,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 33775,
"s": 33731,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 33798,
"s": 33775,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 33836,
"s": 33798,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 33870,
"s": 33836,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 33893,
"s": 33870,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 33927,
"s": 33893,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 33965,
"s": 33927,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 33998,
"s": 33965,
"text": "Support Vector Machine Algorithm"
}
] |
PHP | pi( ) Function - GeeksforGeeks
|
08 Mar, 2018
While solving mathematical problems we often come across questions which requires the value of π. Manually inserting the value of PI (π) can be time-consuming and erroneous. It is also not considered as a good programming practice. To solve this issue a built-in function of PHP pi() comes to aid.
The pi() function in PHP is used to return the value of π . Also, M_PI is a named constant PHP which gives identical value to that of returned by pi() function. It is slightly faster than the pi() function.
Some other predefined named constants related to π are :
M_PI_2 : It describes π/2. Its value is 1.570796.
M_PI_4 : It describes π/4. Its value is 0.785398.
M_1_PI : It describes 1/π. Its value is 0.318309.
M_PI : It describes π. Its value is 3.141592.
M_2_PI : It describes 2/π. Its value is 0.636619.
M_SQRTPI : It describes sqrt(π). Its value is 1.772453.
M_2_SQRTPI : It describes 2/sqrt(π). Its value is 1.128379.
Syntax:
float pi()
Parameters: This function does not accept any parameter.
Return Value: It returns a floating point value which is an approximate value of PI.
Examples:
Input : echo(pi())
Output : 3.1415926535898
Input : echo M_PI
Output : 3.1415926535898
Below programs illustrate the pi() function in PHP:
When pi() function is used:<?php echo(pi()); ?>Output:3.1415926535898When M_PI is used for finding the value of PI:<?php echo M_PI; ?>Output:3.1415926535898
When pi() function is used:<?php echo(pi()); ?>Output:3.1415926535898
<?php echo(pi()); ?>
Output:
3.1415926535898
When M_PI is used for finding the value of PI:<?php echo M_PI; ?>Output:3.1415926535898
<?php echo M_PI; ?>
Output:
3.1415926535898
Important Points To Note:
The pi() function can be used to return the value of π.
M_PI is a named constant which is slightly faster than the pi() function.
pi() function returns the value of pi as float.
Reference:http://php.net/manual/en/function.pi.php
PHP-function
PHP-math
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24784,
"s": 24756,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 25082,
"s": 24784,
"text": "While solving mathematical problems we often come across questions which requires the value of π. Manually inserting the value of PI (π) can be time-consuming and erroneous. It is also not considered as a good programming practice. To solve this issue a built-in function of PHP pi() comes to aid."
},
{
"code": null,
"e": 25289,
"s": 25082,
"text": "The pi() function in PHP is used to return the value of π . Also, M_PI is a named constant PHP which gives identical value to that of returned by pi() function. It is slightly faster than the pi() function."
},
{
"code": null,
"e": 25346,
"s": 25289,
"text": "Some other predefined named constants related to π are :"
},
{
"code": null,
"e": 25396,
"s": 25346,
"text": "M_PI_2 : It describes π/2. Its value is 1.570796."
},
{
"code": null,
"e": 25446,
"s": 25396,
"text": "M_PI_4 : It describes π/4. Its value is 0.785398."
},
{
"code": null,
"e": 25496,
"s": 25446,
"text": "M_1_PI : It describes 1/π. Its value is 0.318309."
},
{
"code": null,
"e": 25542,
"s": 25496,
"text": "M_PI : It describes π. Its value is 3.141592."
},
{
"code": null,
"e": 25592,
"s": 25542,
"text": "M_2_PI : It describes 2/π. Its value is 0.636619."
},
{
"code": null,
"e": 25648,
"s": 25592,
"text": "M_SQRTPI : It describes sqrt(π). Its value is 1.772453."
},
{
"code": null,
"e": 25708,
"s": 25648,
"text": "M_2_SQRTPI : It describes 2/sqrt(π). Its value is 1.128379."
},
{
"code": null,
"e": 25716,
"s": 25708,
"text": "Syntax:"
},
{
"code": null,
"e": 25727,
"s": 25716,
"text": "float pi()"
},
{
"code": null,
"e": 25784,
"s": 25727,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 25869,
"s": 25784,
"text": "Return Value: It returns a floating point value which is an approximate value of PI."
},
{
"code": null,
"e": 25879,
"s": 25869,
"text": "Examples:"
},
{
"code": null,
"e": 25968,
"s": 25879,
"text": "Input : echo(pi())\nOutput : 3.1415926535898\n\nInput : echo M_PI\nOutput : 3.1415926535898\n"
},
{
"code": null,
"e": 26020,
"s": 25968,
"text": "Below programs illustrate the pi() function in PHP:"
},
{
"code": null,
"e": 26181,
"s": 26020,
"text": "When pi() function is used:<?php echo(pi()); ?>Output:3.1415926535898When M_PI is used for finding the value of PI:<?php echo M_PI; ?>Output:3.1415926535898"
},
{
"code": null,
"e": 26253,
"s": 26181,
"text": "When pi() function is used:<?php echo(pi()); ?>Output:3.1415926535898"
},
{
"code": "<?php echo(pi()); ?>",
"e": 26276,
"s": 26253,
"text": null
},
{
"code": null,
"e": 26284,
"s": 26276,
"text": "Output:"
},
{
"code": null,
"e": 26300,
"s": 26284,
"text": "3.1415926535898"
},
{
"code": null,
"e": 26390,
"s": 26300,
"text": "When M_PI is used for finding the value of PI:<?php echo M_PI; ?>Output:3.1415926535898"
},
{
"code": "<?php echo M_PI; ?>",
"e": 26412,
"s": 26390,
"text": null
},
{
"code": null,
"e": 26420,
"s": 26412,
"text": "Output:"
},
{
"code": null,
"e": 26436,
"s": 26420,
"text": "3.1415926535898"
},
{
"code": null,
"e": 26462,
"s": 26436,
"text": "Important Points To Note:"
},
{
"code": null,
"e": 26518,
"s": 26462,
"text": "The pi() function can be used to return the value of π."
},
{
"code": null,
"e": 26592,
"s": 26518,
"text": "M_PI is a named constant which is slightly faster than the pi() function."
},
{
"code": null,
"e": 26640,
"s": 26592,
"text": "pi() function returns the value of pi as float."
},
{
"code": null,
"e": 26691,
"s": 26640,
"text": "Reference:http://php.net/manual/en/function.pi.php"
},
{
"code": null,
"e": 26704,
"s": 26691,
"text": "PHP-function"
},
{
"code": null,
"e": 26713,
"s": 26704,
"text": "PHP-math"
},
{
"code": null,
"e": 26717,
"s": 26713,
"text": "PHP"
},
{
"code": null,
"e": 26734,
"s": 26717,
"text": "Web Technologies"
},
{
"code": null,
"e": 26738,
"s": 26734,
"text": "PHP"
},
{
"code": null,
"e": 26836,
"s": 26738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26886,
"s": 26836,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26926,
"s": 26886,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 26971,
"s": 26926,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 26998,
"s": 26971,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 27034,
"s": 26998,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 27074,
"s": 27034,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27107,
"s": 27074,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27152,
"s": 27107,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27195,
"s": 27152,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Arabic NLP: Unique Challenges and Their Solutions | by Richard Pelgrim | Towards Data Science
|
In this article, I provide a concise and to-the-point overview of the challenges of working with Arabic text in NLP projects...and the tools available to overcome them. I rely heavily on the camel-tools Python package developed at the NYU Abu Dhabi CAMeL Lab and this excellent webinar by its director, Dr. Nizar Habash. Big shout-out to them for doing groundbreaking work in the field and making their tools accessible to the public!
Working with Arabic text in NLP projects presents (at least) 5 unique challenges:
The form of characters and spelling of words can vary depending on their context (fancy term: Orthographic Ambiguity)The same verb can have thousands (literally) of different forms (fancy term: Morphological Richness)There are many dialects of Arabic and there are big differences between them (Dialectal Variation)Since Arabic is a phonetic language (what you write is what you say), there can be different ways to write the same word when writing in dialectal Arabic, for which there is no agreed-upon standard (Orthographic Inconsistency).
The form of characters and spelling of words can vary depending on their context (fancy term: Orthographic Ambiguity)
The same verb can have thousands (literally) of different forms (fancy term: Morphological Richness)
There are many dialects of Arabic and there are big differences between them (Dialectal Variation)
Since Arabic is a phonetic language (what you write is what you say), there can be different ways to write the same word when writing in dialectal Arabic, for which there is no agreed-upon standard (Orthographic Inconsistency).
These four different characteristics of the Arabic language all contribute to data sparsity. Because of the many different forms of words, the potential different spellings, and the high number of dialects, one could end up with an NLP vocabulary running into the millions of words. This is not an overstatement: a single verb in Arabic can have up to 5400 forms (!) compared to a maximum of 6 in English and only 1 in Chinese.
But fear not! Right when you’re stuck in the Desert of Low-Resource Languages and your pipeline perched for some Liquid Code to keep you going...there materialises a magical, user-friendly CAMeL** to help you out:
pip install camel-tools
** we’ll save our post-colonial commentary on the blatantly self-orientalising name of this package for another day, shall we?
Below I’ll share the steps I took to pre-process my Arabic text and deal with the unique challenges posed by the Arabic language using the camel-tools package.
NOTE: I’m assuming that you’ve already done all the basic, universal NLP pre-processing such as removing repeating characters, stop words, emoji, hashtags, digits, and any of the other best-practice data cleaning tasks that are part of any NLP project. The Github repo referenced below contains a comprehensive list of Arabic stop words that account for the orthographic ambiguity mentioned earlier. Important note: make sure to add the word “يا” to the file as this is not currently included and is a very common stop word.
Note that NLTK also contains a library of Arabic stop words but this collection misses many of these common spelling inconsistencies.
github.com
Alright, now let’s get crackin’!
The first step is to cut down some serious data sparsity by removing the diacritics of the text. Diacritics are the symbols (in some cases comparable to vowels in the English language) that are located above or below the letters of your Arabic text — the blue marks in the image below.
The same word may have different diacritics depending on its context and therefore it is common practice to remove these symbols to reduce data sparsity.
Technically, this actually creates a new problem because the same word-root can have totally different meanings depending on the diacritics you give it...but we’ll deal with that in STEP 4.
To account for a number of common spelling inconsistencies across dialects (and because of the gap between spoken and written Arabic in general), the next step is to reduce orthographic ambiguity. Specifically, camel-tools does this by removing particular symbols from particular letters (the dots from the teh-marbuta and the hamza from the alef).
The next step is just a simple word tokenizer. We need this in order to be able to input our text into the functions of our next step.
Now this is where things get interesting. Remember how I said at the end of STEP 1 that removing the diacritics actually creates a new problem? We now have just the root characters but, technically, no way of knowing which of the many different words it could be. For example, the word below could alternatively mean: ‘and with our contract / necklace / psychoses’ or ‘and he stresses us out’ — depending on the diacritics used, the context and the dialect it’s written in.
So...which form of the word should we choose?
The camel-tools package comes with a nifty ‘morphological analyzer’ which — in a nutshell — compares any word you give it to a morphological database (it comes with one built-in) and outputs a complete analysis of the possible forms and meanings of the word, including the lemma, part of speech, English translation if available, etc.
Below we run a morphological analysis on the word ‘وبعقدنا’.
I’ve included a portion of the output below; these are only the top 3 of over 20 analyses that it returns. Notice that it also ‘disambiguates’ the word by restoring diacritics.
{'diac': 'وَبِعُقَدُنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+ُ/CASE_DEF_NOM+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'n', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3ُنا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدُنا', 'd1tok': 'وَ+_بِعُقَدُنا', 'atbseg': 'وَ+_بِ+_عُقَدُ_+نا', 'd3seg': 'وَ+_بِ+_عُقَدُ_+نا', 'd2seg': 'وَ+_بِ+_عُقَدُنا', 'd2tok': 'وَ+_بِ+_عُقَدُنا', 'atbtok': 'وَ+_بِ+_عُقَدُ_+نا', 'd3tok': 'وَ+_بِ+_عُقَدُ_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+ُ_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_u_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'} {'diac': 'وَبِعُقَدنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'u', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3نا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدنا', 'd1tok': 'وَ+_بِعُقَدنا', 'atbseg': 'وَ+_بِ+_عُقَد_+نا', 'd3seg': 'وَ+_بِ+_عُقَد_+نا', 'd2seg': 'وَ+_بِ+_عُقَدنا', 'd2tok': 'وَ+_بِ+_عُقَدنا', 'atbtok': 'وَ+_بِ+_عُقَد_+نا', 'd3tok': 'وَ+_بِ+_عُقَد_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'} {'diac': 'وَبِعُقَدِنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+ِ/CASE_DEF_GEN+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'g', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3ِنا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدِنا', 'd1tok': 'وَ+_بِعُقَدِنا', 'atbseg': 'وَ+_بِ+_عُقَدِ_+نا', 'd3seg': 'وَ+_بِ+_عُقَدِ_+نا', 'd2seg': 'وَ+_بِ+_عُقَدِنا', 'd2tok': 'وَ+_بِ+_عُقَدِنا', 'atbtok': 'وَ+_بِ+_عُقَدِ_+نا', 'd3tok': 'وَ+_بِ+_عُقَدِ_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+ِ_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_i_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'}
Now, in my case I’m working with over 6 million Tweets so running a word-by-word analysis is not going to be very informative or effective. Instead, we can use the Morphological Disambiguator (watch out, Arnold!) to do this for us. This will take a list of tokens as input (hence the simple word tokenizer in STEP 3) and output all the disambiguated forms of the tokens. Each analysis is a dictionary and we can access the forms and components we want using the dictionary keys. The analyses are listed from most likely to least likely, so common practice is to simplify specify the first analysis as your output.
Which outputs the diacritized form, Part-Of-Speech tag, and lemma for each word in our sentence:
('نَجَحَ', 'verb', 'نَجَح-a_1')('بايدن', 'noun_prop', 'بايدن_0')('فِي', 'prep', 'فِي_1')('الاِنْتِخاباتِ', 'noun', 'ٱِنْتِخاب_1')
This means we could, for example, get all of the lemmas of our Arabic text using a function such as the one below:
For my project which conducts Topic Modelling, this is the way I chose to conduct my tokenization. Other projects may call for different approaches using the Morphological Tokenizer, which will tokenize the strings differently depending on the scheme you select.
So... just find the tokenization / lemmatization approach that best fits your project, execute it, and then you’re all done pre-processing your Arabic text!
The camel-tools package offers more features for pre-processing (such as transliteration, unicode normalization, etc.) that may be useful for your project. Check out the complete documentation for more info.
camel-tools.readthedocs.io
Also, I just want to point out that I did my fair share of research trying to find the best tool for pre-processing Arabic text for NLP. And while there are a number of other good options out there (like Farasa, MADAMIRA and Stanford CoreNLP) I found camel-tools to be the most versatile, comprehensive, and easy to use. Besides the core pre-processing functions for dealing with the challenges mentioned above, it also comes with some cool bonus features: it can perform sentiment analysis and — this is really one of the coolest features —it can identify the dialect in which the text is written (out of a maximum of 25 dialects). I’ll definitely be using the Dialect Identifier to add ‘dialect’ as a feature in my NLP pipeline.
Thank you for reading! Follow me on LinkedIn for regular distributed computing updates and hacks.
And please consider becoming a Medium member to support the writing community:
|
[
{
"code": null,
"e": 606,
"s": 171,
"text": "In this article, I provide a concise and to-the-point overview of the challenges of working with Arabic text in NLP projects...and the tools available to overcome them. I rely heavily on the camel-tools Python package developed at the NYU Abu Dhabi CAMeL Lab and this excellent webinar by its director, Dr. Nizar Habash. Big shout-out to them for doing groundbreaking work in the field and making their tools accessible to the public!"
},
{
"code": null,
"e": 688,
"s": 606,
"text": "Working with Arabic text in NLP projects presents (at least) 5 unique challenges:"
},
{
"code": null,
"e": 1231,
"s": 688,
"text": "The form of characters and spelling of words can vary depending on their context (fancy term: Orthographic Ambiguity)The same verb can have thousands (literally) of different forms (fancy term: Morphological Richness)There are many dialects of Arabic and there are big differences between them (Dialectal Variation)Since Arabic is a phonetic language (what you write is what you say), there can be different ways to write the same word when writing in dialectal Arabic, for which there is no agreed-upon standard (Orthographic Inconsistency)."
},
{
"code": null,
"e": 1349,
"s": 1231,
"text": "The form of characters and spelling of words can vary depending on their context (fancy term: Orthographic Ambiguity)"
},
{
"code": null,
"e": 1450,
"s": 1349,
"text": "The same verb can have thousands (literally) of different forms (fancy term: Morphological Richness)"
},
{
"code": null,
"e": 1549,
"s": 1450,
"text": "There are many dialects of Arabic and there are big differences between them (Dialectal Variation)"
},
{
"code": null,
"e": 1777,
"s": 1549,
"text": "Since Arabic is a phonetic language (what you write is what you say), there can be different ways to write the same word when writing in dialectal Arabic, for which there is no agreed-upon standard (Orthographic Inconsistency)."
},
{
"code": null,
"e": 2205,
"s": 1777,
"text": "These four different characteristics of the Arabic language all contribute to data sparsity. Because of the many different forms of words, the potential different spellings, and the high number of dialects, one could end up with an NLP vocabulary running into the millions of words. This is not an overstatement: a single verb in Arabic can have up to 5400 forms (!) compared to a maximum of 6 in English and only 1 in Chinese."
},
{
"code": null,
"e": 2419,
"s": 2205,
"text": "But fear not! Right when you’re stuck in the Desert of Low-Resource Languages and your pipeline perched for some Liquid Code to keep you going...there materialises a magical, user-friendly CAMeL** to help you out:"
},
{
"code": null,
"e": 2443,
"s": 2419,
"text": "pip install camel-tools"
},
{
"code": null,
"e": 2570,
"s": 2443,
"text": "** we’ll save our post-colonial commentary on the blatantly self-orientalising name of this package for another day, shall we?"
},
{
"code": null,
"e": 2730,
"s": 2570,
"text": "Below I’ll share the steps I took to pre-process my Arabic text and deal with the unique challenges posed by the Arabic language using the camel-tools package."
},
{
"code": null,
"e": 3255,
"s": 2730,
"text": "NOTE: I’m assuming that you’ve already done all the basic, universal NLP pre-processing such as removing repeating characters, stop words, emoji, hashtags, digits, and any of the other best-practice data cleaning tasks that are part of any NLP project. The Github repo referenced below contains a comprehensive list of Arabic stop words that account for the orthographic ambiguity mentioned earlier. Important note: make sure to add the word “يا” to the file as this is not currently included and is a very common stop word."
},
{
"code": null,
"e": 3389,
"s": 3255,
"text": "Note that NLTK also contains a library of Arabic stop words but this collection misses many of these common spelling inconsistencies."
},
{
"code": null,
"e": 3400,
"s": 3389,
"text": "github.com"
},
{
"code": null,
"e": 3433,
"s": 3400,
"text": "Alright, now let’s get crackin’!"
},
{
"code": null,
"e": 3719,
"s": 3433,
"text": "The first step is to cut down some serious data sparsity by removing the diacritics of the text. Diacritics are the symbols (in some cases comparable to vowels in the English language) that are located above or below the letters of your Arabic text — the blue marks in the image below."
},
{
"code": null,
"e": 3873,
"s": 3719,
"text": "The same word may have different diacritics depending on its context and therefore it is common practice to remove these symbols to reduce data sparsity."
},
{
"code": null,
"e": 4063,
"s": 3873,
"text": "Technically, this actually creates a new problem because the same word-root can have totally different meanings depending on the diacritics you give it...but we’ll deal with that in STEP 4."
},
{
"code": null,
"e": 4412,
"s": 4063,
"text": "To account for a number of common spelling inconsistencies across dialects (and because of the gap between spoken and written Arabic in general), the next step is to reduce orthographic ambiguity. Specifically, camel-tools does this by removing particular symbols from particular letters (the dots from the teh-marbuta and the hamza from the alef)."
},
{
"code": null,
"e": 4547,
"s": 4412,
"text": "The next step is just a simple word tokenizer. We need this in order to be able to input our text into the functions of our next step."
},
{
"code": null,
"e": 5021,
"s": 4547,
"text": "Now this is where things get interesting. Remember how I said at the end of STEP 1 that removing the diacritics actually creates a new problem? We now have just the root characters but, technically, no way of knowing which of the many different words it could be. For example, the word below could alternatively mean: ‘and with our contract / necklace / psychoses’ or ‘and he stresses us out’ — depending on the diacritics used, the context and the dialect it’s written in."
},
{
"code": null,
"e": 5067,
"s": 5021,
"text": "So...which form of the word should we choose?"
},
{
"code": null,
"e": 5402,
"s": 5067,
"text": "The camel-tools package comes with a nifty ‘morphological analyzer’ which — in a nutshell — compares any word you give it to a morphological database (it comes with one built-in) and outputs a complete analysis of the possible forms and meanings of the word, including the lemma, part of speech, English translation if available, etc."
},
{
"code": null,
"e": 5463,
"s": 5402,
"text": "Below we run a morphological analysis on the word ‘وبعقدنا’."
},
{
"code": null,
"e": 5640,
"s": 5463,
"text": "I’ve included a portion of the output below; these are only the top 3 of over 20 analyses that it returns. Notice that it also ‘disambiguates’ the word by restoring diacritics."
},
{
"code": null,
"e": 8508,
"s": 5640,
"text": "{'diac': 'وَبِعُقَدُنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+ُ/CASE_DEF_NOM+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'n', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3ُنا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدُنا', 'd1tok': 'وَ+_بِعُقَدُنا', 'atbseg': 'وَ+_بِ+_عُقَدُ_+نا', 'd3seg': 'وَ+_بِ+_عُقَدُ_+نا', 'd2seg': 'وَ+_بِ+_عُقَدُنا', 'd2tok': 'وَ+_بِ+_عُقَدُنا', 'atbtok': 'وَ+_بِ+_عُقَدُ_+نا', 'd3tok': 'وَ+_بِ+_عُقَدُ_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+ُ_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_u_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'} {'diac': 'وَبِعُقَدنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'u', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3نا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدنا', 'd1tok': 'وَ+_بِعُقَدنا', 'atbseg': 'وَ+_بِ+_عُقَد_+نا', 'd3seg': 'وَ+_بِ+_عُقَد_+نا', 'd2seg': 'وَ+_بِ+_عُقَدنا', 'd2tok': 'وَ+_بِ+_عُقَدنا', 'atbtok': 'وَ+_بِ+_عُقَد_+نا', 'd3tok': 'وَ+_بِ+_عُقَد_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'} {'diac': 'وَبِعُقَدِنا', 'lex': 'عُقْدَة_1', 'bw': 'وَ/PART+بِ/PREP+عُقَد/NOUN+ِ/CASE_DEF_GEN+نا/POSS_PRON_1P', 'gloss': '[part.]_+_by;with+complexes+our', 'pos': 'noun', 'prc3': '0', 'prc2': 'wa_part', 'prc1': 'bi_prep', 'prc0': '0', 'per': 'na', 'asp': 'na', 'vox': 'na', 'mod': 'na', 'stt': 'c', 'cas': 'g', 'enc0': '1p_poss', 'rat': 'i', 'source': 'lex', 'form_gen': 'm', 'form_num': 's', 'pattern': 'وَبِ1ُ2َ3ِنا', 'root': 'ع.ق.د', 'catib6': 'PRT+PRT+NOM+NOM', 'ud': 'PART+ADP+NOUN+PRON', 'd1seg': 'وَبِعُقَدِنا', 'd1tok': 'وَ+_بِعُقَدِنا', 'atbseg': 'وَ+_بِ+_عُقَدِ_+نا', 'd3seg': 'وَ+_بِ+_عُقَدِ_+نا', 'd2seg': 'وَ+_بِ+_عُقَدِنا', 'd2tok': 'وَ+_بِ+_عُقَدِنا', 'atbtok': 'وَ+_بِ+_عُقَدِ_+نا', 'd3tok': 'وَ+_بِ+_عُقَدِ_+نا', 'bwtok': 'وَ+_بِ+_عُقَد_+ِ_+نا', 'pos_lex_logprob': -4.923429, 'caphi': 'w_a_b_i_3_u_q_a_d_i_n_aa', 'pos_logprob': -0.4344233, 'gen': 'f', 'lex_logprob': -4.923429, 'num': 'p', 'stem': 'عُقَد', 'stemgloss': 'complexes', 'stemcat': 'N'}"
},
{
"code": null,
"e": 9122,
"s": 8508,
"text": "Now, in my case I’m working with over 6 million Tweets so running a word-by-word analysis is not going to be very informative or effective. Instead, we can use the Morphological Disambiguator (watch out, Arnold!) to do this for us. This will take a list of tokens as input (hence the simple word tokenizer in STEP 3) and output all the disambiguated forms of the tokens. Each analysis is a dictionary and we can access the forms and components we want using the dictionary keys. The analyses are listed from most likely to least likely, so common practice is to simplify specify the first analysis as your output."
},
{
"code": null,
"e": 9219,
"s": 9122,
"text": "Which outputs the diacritized form, Part-Of-Speech tag, and lemma for each word in our sentence:"
},
{
"code": null,
"e": 9349,
"s": 9219,
"text": "('نَجَحَ', 'verb', 'نَجَح-a_1')('بايدن', 'noun_prop', 'بايدن_0')('فِي', 'prep', 'فِي_1')('الاِنْتِخاباتِ', 'noun', 'ٱِنْتِخاب_1')"
},
{
"code": null,
"e": 9464,
"s": 9349,
"text": "This means we could, for example, get all of the lemmas of our Arabic text using a function such as the one below:"
},
{
"code": null,
"e": 9727,
"s": 9464,
"text": "For my project which conducts Topic Modelling, this is the way I chose to conduct my tokenization. Other projects may call for different approaches using the Morphological Tokenizer, which will tokenize the strings differently depending on the scheme you select."
},
{
"code": null,
"e": 9884,
"s": 9727,
"text": "So... just find the tokenization / lemmatization approach that best fits your project, execute it, and then you’re all done pre-processing your Arabic text!"
},
{
"code": null,
"e": 10092,
"s": 9884,
"text": "The camel-tools package offers more features for pre-processing (such as transliteration, unicode normalization, etc.) that may be useful for your project. Check out the complete documentation for more info."
},
{
"code": null,
"e": 10119,
"s": 10092,
"text": "camel-tools.readthedocs.io"
},
{
"code": null,
"e": 10850,
"s": 10119,
"text": "Also, I just want to point out that I did my fair share of research trying to find the best tool for pre-processing Arabic text for NLP. And while there are a number of other good options out there (like Farasa, MADAMIRA and Stanford CoreNLP) I found camel-tools to be the most versatile, comprehensive, and easy to use. Besides the core pre-processing functions for dealing with the challenges mentioned above, it also comes with some cool bonus features: it can perform sentiment analysis and — this is really one of the coolest features —it can identify the dialect in which the text is written (out of a maximum of 25 dialects). I’ll definitely be using the Dialect Identifier to add ‘dialect’ as a feature in my NLP pipeline."
},
{
"code": null,
"e": 10948,
"s": 10850,
"text": "Thank you for reading! Follow me on LinkedIn for regular distributed computing updates and hacks."
}
] |
HTML DOM Input Number type Property
|
The HTML DOM Input number type property is associated with the input element having its type=”number”. It will always return number for the input number element.
Following is the syntax for number type property −
numberObject.type
Let us look at an example for the HTML DOM Input Number type property −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Input Number type property</h1>
PHONE NO: <input type="number" id="NUMBER1">
<p>Get the above element type by clicking the below button</p>
<button onclick="getType()">Get Type</button>
<p id="Sample"></p>
<script>
function getType() {
var t = document.getElementById("NUMBER1").type;
document.getElementById("Sample").innerHTML = "The type for the input field is : "+t;
}
</script>
</body>
</html>
This will produce the following output −
On clicking the “Get Type” button −
In the above example −
We have created an input field with type number and its id set to “NUMBER1”.
PHONE NO: <input type="number" id="NUMBER1">
We have then created the “Get Type” button that will execute the getType() method when clicked by the user −
<button onclick="getType()">Get Type</button>
The getType() method gets the input element using the getElementById() method and assigns its type attribute value to variable t. This variable is then displayed in the paragraph with id “Sample” using its innerHTML property −
function getType() {
var t = document.getElementById("NUMBER1").type;
document.getElementById("Sample").innerHTML = "The type for the input field is : "+t;
}
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "The HTML DOM Input number type property is associated with the input element having its type=”number”. It will always return number for the input number element."
},
{
"code": null,
"e": 1275,
"s": 1224,
"text": "Following is the syntax for number type property −"
},
{
"code": null,
"e": 1293,
"s": 1275,
"text": "numberObject.type"
},
{
"code": null,
"e": 1365,
"s": 1293,
"text": "Let us look at an example for the HTML DOM Input Number type property −"
},
{
"code": null,
"e": 1375,
"s": 1365,
"text": "Live Demo"
},
{
"code": null,
"e": 1826,
"s": 1375,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>Input Number type property</h1>\nPHONE NO: <input type=\"number\" id=\"NUMBER1\">\n<p>Get the above element type by clicking the below button</p>\n<button onclick=\"getType()\">Get Type</button>\n<p id=\"Sample\"></p>\n<script>\n function getType() {\n var t = document.getElementById(\"NUMBER1\").type;\n document.getElementById(\"Sample\").innerHTML = \"The type for the input field is : \"+t;\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1867,
"s": 1826,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1903,
"s": 1867,
"text": "On clicking the “Get Type” button −"
},
{
"code": null,
"e": 1926,
"s": 1903,
"text": "In the above example −"
},
{
"code": null,
"e": 2003,
"s": 1926,
"text": "We have created an input field with type number and its id set to “NUMBER1”."
},
{
"code": null,
"e": 2048,
"s": 2003,
"text": "PHONE NO: <input type=\"number\" id=\"NUMBER1\">"
},
{
"code": null,
"e": 2157,
"s": 2048,
"text": "We have then created the “Get Type” button that will execute the getType() method when clicked by the user −"
},
{
"code": null,
"e": 2203,
"s": 2157,
"text": "<button onclick=\"getType()\">Get Type</button>"
},
{
"code": null,
"e": 2430,
"s": 2203,
"text": "The getType() method gets the input element using the getElementById() method and assigns its type attribute value to variable t. This variable is then displayed in the paragraph with id “Sample” using its innerHTML property −"
},
{
"code": null,
"e": 2594,
"s": 2430,
"text": "function getType() {\n var t = document.getElementById(\"NUMBER1\").type;\n document.getElementById(\"Sample\").innerHTML = \"The type for the input field is : \"+t;\n}"
}
] |
Use MLflow to better track ML experiments | Towards Data Science
|
We all know how painful keeping track of your machine learning experiments can be.
You train a bunch of models of different flavours: Random Forests, XGBoost, Neural Networks...
For each model, you explore a range of hyper-parameters. Then you compute the performance metrics on some test data.
Sometimes you change the training data by adding or removing features and retraining your models again.
Some other times, you have to work in a team and compare your results with other data scientists.
How do you manage these experiments in such a way they are easily traceable and reproducible? How do you compare your results?
MLflow is perfectly suited to these tasks. We’ll see in this post how to use it locally and how to set it up on AWS.
Let’s have a look!
PS*: for a more in-depth live use of MLflow, have a look at my video tutorial:
PS**: you can find the code on my Github repo.
“MLflow is an open-source platform to manage the ML lifecycle, including experimentation, reproducibility, deployment, and a central model registry. ” — mlflow.org
Put it simply, MLflow is a package that you can install in your python environment to:
Perform experiment tracking (the topic of this article)
Package data science code in a reproducible way
Deploy models
Manage models from development to production
MLflow integrates with any machine learning or deep learning framework such as Scikit-learn, TensorFlow, PyTorch, h2o.ai, XGBoost, etc.
Besides, it’s also cloud-agnostic. You can run it everywhere: AWS, Google Cloud Platform or Azure Machine Learning. We’ll see in this post how to set it up on AWS. Wait till the end to see how it’s done 😉.
MLflow tracking is a component that’ll help you log your machine learning experiments very easily.
It’s organized into experiments and each experiment is split into runs.
An example of an experiment could be “Training a binary classifier”. In that case, each run corresponds to a single model fit.
While fitting different models on different runs, you can use MLflow to track a lot of data:
parameters: what you use to tune your models (e.g. n_estimators, max_depth, epochs, kernel_size, dropout, batch_size, etc.)
the metrics of your models (loss, AUC, MAE, MSE; F1 score, accuracy, R-squared (r2))
data: the different versions of the data your model used in each run.
saved models: binary outputs (think pickle files) related to each run
other outputs such as images, CSV, text, HTML that results from your code
source: the script/notebook filename responsible for the run + the git commit
tags and comments: individual or team annotations
Quite easy.
Start by installing mlflow using pip :
pip install mlflow
Import mlflow and use the set_tracking_uri method to set the path to where MLflow will store the results of each run
Call the create_experiment method with an appropriate name
To be able to log your parameters, metrics and save your models on each run, you’ll have to wrap your code inside the mlflow.start_runcontext by specifying the experiment_id as argument.
Inside this context, MLflow creates a run with a unique id (run_id). This run will wait for any information to be tracked.
Saving a parameter can be done using the mlflow.log_param method
Saving a metric can be done using the mlflow.log_metric method
Saving a (scikit-learn) model as artifcat can be done in a simple way by calling the mlflow.sklearn.log_model
MLflow provides a great UI to visualize the results of each run as well as compare runs between each other.
To start the UI, run the following command at the same location of the mlruns directory:
mlflow ui
This will start a local server at port 5000.
On the left side, you’ll see the experiments. On the right side, you’ll see the runs. The table is interactive, you can sort the runs, search them by specifying queries and even compare them (in a second view).
Once you click on a run, you are redirected to another page with more details.
Metrics, parameters, duration, status, git commit:
as well as model output and artifacts:
So far, we’ve used MLflow locally. This is not ideal if we want to collaborate with other colleagues and track experiments in a team.
Fortunately, setting up a remote MLflow tracking server is quite easy. Let’s see how this done.
In this section I’ll be using AWS, so make sure you have an account if you want to reproduce these steps.
1 — Set up a remote EC2 machine with MLflow
Create an IAM user. Grab the Access key ID and Secret access key credentials and store them somewhere safe. We’ll need them later.
With this same user, create an s3 bucket to store future artifacts: give this bucket a name. Mine is mlflow-artifact-store-demo but you cannot pick it. Note that you don’t need custom configuration for your bucket (it doesn’t need to be public for instance)
Launch an EC2 instance: it doesn’t have to be big. At2.micro eligible to free tier does perfectly the job
Configure the security group of this instance to accept inbound HTTP traffic on port 5000 and any IP address so that the MLflow server is accessible from the outside
Connect to your instance using SSH and run the following commands to install pip, pipenv and mlflow
# install pipsudo apt updatesudo apt install python3-pip# install sudo pip3 install pipenvsudo pip3 install virtualenvexport PATH=$PATH:/home/[your_user]/.local/bin/# install mlflow, awscli and boto3pipenv install mlflowpipenv install awsclipipenv install boto3
On the EC2 machine, configure AWS with the user’s credentials so that the tracking server can have access to s3 and display the artifacts on the UI. Enter aws configure then follow the instructions to enter the credentials
Start an MLflow server on the EC2 instance by defining the host as 0.0.0.0 and the --default-artifact-root as the S3 bucket
mlflow server -h 0.0.0.0 --default-artifact-root s3://mlflow-artifact-store-demo
Now your EC2 machine is properly configured.
2 — Set up your environment
To allow MLflow to push runs from your local environment to EC2 and S3, you’ll have to:
Install boto3 locally via pip install boto3
Set the AWS credentials as environment variables so that MLflow has the right permissions of S3 read and write access
export AWS_ACCESS_KEY_ID=<your-aws-access-key-id>export AWS_SECRET_ACCESS_KEY = <your-aws-secret-access-key>
change the tracking URI in your code to the HTTP://<public-dns>:5000
Now everything should be set up correctly.
If you execute your code again, the runs will no longer be saved locally but on the remote tracking server, which you can check by visiting the URL.
Setting up MLflow as we did is fine for small projects within relatively small teams. It’s however not production-ready. In fact, you’ll have to secure access to the MLflow UI and create a service on EC2 to start MLflow in the background at the startup
You can use a managed version of MLFlow on databricks
MLflow Tracking is agnostic to the type of work you’re doing be it NLP, computer vision or unsupervised learning. As long as you have metrics and parameters to track, MLFlow is a good fit.
Thanks for reading! All the code is accessible on my Github repo.
|
[
{
"code": null,
"e": 255,
"s": 172,
"text": "We all know how painful keeping track of your machine learning experiments can be."
},
{
"code": null,
"e": 350,
"s": 255,
"text": "You train a bunch of models of different flavours: Random Forests, XGBoost, Neural Networks..."
},
{
"code": null,
"e": 467,
"s": 350,
"text": "For each model, you explore a range of hyper-parameters. Then you compute the performance metrics on some test data."
},
{
"code": null,
"e": 571,
"s": 467,
"text": "Sometimes you change the training data by adding or removing features and retraining your models again."
},
{
"code": null,
"e": 669,
"s": 571,
"text": "Some other times, you have to work in a team and compare your results with other data scientists."
},
{
"code": null,
"e": 796,
"s": 669,
"text": "How do you manage these experiments in such a way they are easily traceable and reproducible? How do you compare your results?"
},
{
"code": null,
"e": 913,
"s": 796,
"text": "MLflow is perfectly suited to these tasks. We’ll see in this post how to use it locally and how to set it up on AWS."
},
{
"code": null,
"e": 932,
"s": 913,
"text": "Let’s have a look!"
},
{
"code": null,
"e": 1011,
"s": 932,
"text": "PS*: for a more in-depth live use of MLflow, have a look at my video tutorial:"
},
{
"code": null,
"e": 1058,
"s": 1011,
"text": "PS**: you can find the code on my Github repo."
},
{
"code": null,
"e": 1222,
"s": 1058,
"text": "“MLflow is an open-source platform to manage the ML lifecycle, including experimentation, reproducibility, deployment, and a central model registry. ” — mlflow.org"
},
{
"code": null,
"e": 1309,
"s": 1222,
"text": "Put it simply, MLflow is a package that you can install in your python environment to:"
},
{
"code": null,
"e": 1365,
"s": 1309,
"text": "Perform experiment tracking (the topic of this article)"
},
{
"code": null,
"e": 1413,
"s": 1365,
"text": "Package data science code in a reproducible way"
},
{
"code": null,
"e": 1427,
"s": 1413,
"text": "Deploy models"
},
{
"code": null,
"e": 1472,
"s": 1427,
"text": "Manage models from development to production"
},
{
"code": null,
"e": 1608,
"s": 1472,
"text": "MLflow integrates with any machine learning or deep learning framework such as Scikit-learn, TensorFlow, PyTorch, h2o.ai, XGBoost, etc."
},
{
"code": null,
"e": 1814,
"s": 1608,
"text": "Besides, it’s also cloud-agnostic. You can run it everywhere: AWS, Google Cloud Platform or Azure Machine Learning. We’ll see in this post how to set it up on AWS. Wait till the end to see how it’s done 😉."
},
{
"code": null,
"e": 1913,
"s": 1814,
"text": "MLflow tracking is a component that’ll help you log your machine learning experiments very easily."
},
{
"code": null,
"e": 1985,
"s": 1913,
"text": "It’s organized into experiments and each experiment is split into runs."
},
{
"code": null,
"e": 2112,
"s": 1985,
"text": "An example of an experiment could be “Training a binary classifier”. In that case, each run corresponds to a single model fit."
},
{
"code": null,
"e": 2205,
"s": 2112,
"text": "While fitting different models on different runs, you can use MLflow to track a lot of data:"
},
{
"code": null,
"e": 2329,
"s": 2205,
"text": "parameters: what you use to tune your models (e.g. n_estimators, max_depth, epochs, kernel_size, dropout, batch_size, etc.)"
},
{
"code": null,
"e": 2414,
"s": 2329,
"text": "the metrics of your models (loss, AUC, MAE, MSE; F1 score, accuracy, R-squared (r2))"
},
{
"code": null,
"e": 2484,
"s": 2414,
"text": "data: the different versions of the data your model used in each run."
},
{
"code": null,
"e": 2554,
"s": 2484,
"text": "saved models: binary outputs (think pickle files) related to each run"
},
{
"code": null,
"e": 2628,
"s": 2554,
"text": "other outputs such as images, CSV, text, HTML that results from your code"
},
{
"code": null,
"e": 2706,
"s": 2628,
"text": "source: the script/notebook filename responsible for the run + the git commit"
},
{
"code": null,
"e": 2756,
"s": 2706,
"text": "tags and comments: individual or team annotations"
},
{
"code": null,
"e": 2768,
"s": 2756,
"text": "Quite easy."
},
{
"code": null,
"e": 2807,
"s": 2768,
"text": "Start by installing mlflow using pip :"
},
{
"code": null,
"e": 2826,
"s": 2807,
"text": "pip install mlflow"
},
{
"code": null,
"e": 2943,
"s": 2826,
"text": "Import mlflow and use the set_tracking_uri method to set the path to where MLflow will store the results of each run"
},
{
"code": null,
"e": 3002,
"s": 2943,
"text": "Call the create_experiment method with an appropriate name"
},
{
"code": null,
"e": 3189,
"s": 3002,
"text": "To be able to log your parameters, metrics and save your models on each run, you’ll have to wrap your code inside the mlflow.start_runcontext by specifying the experiment_id as argument."
},
{
"code": null,
"e": 3312,
"s": 3189,
"text": "Inside this context, MLflow creates a run with a unique id (run_id). This run will wait for any information to be tracked."
},
{
"code": null,
"e": 3377,
"s": 3312,
"text": "Saving a parameter can be done using the mlflow.log_param method"
},
{
"code": null,
"e": 3440,
"s": 3377,
"text": "Saving a metric can be done using the mlflow.log_metric method"
},
{
"code": null,
"e": 3550,
"s": 3440,
"text": "Saving a (scikit-learn) model as artifcat can be done in a simple way by calling the mlflow.sklearn.log_model"
},
{
"code": null,
"e": 3658,
"s": 3550,
"text": "MLflow provides a great UI to visualize the results of each run as well as compare runs between each other."
},
{
"code": null,
"e": 3747,
"s": 3658,
"text": "To start the UI, run the following command at the same location of the mlruns directory:"
},
{
"code": null,
"e": 3757,
"s": 3747,
"text": "mlflow ui"
},
{
"code": null,
"e": 3802,
"s": 3757,
"text": "This will start a local server at port 5000."
},
{
"code": null,
"e": 4013,
"s": 3802,
"text": "On the left side, you’ll see the experiments. On the right side, you’ll see the runs. The table is interactive, you can sort the runs, search them by specifying queries and even compare them (in a second view)."
},
{
"code": null,
"e": 4092,
"s": 4013,
"text": "Once you click on a run, you are redirected to another page with more details."
},
{
"code": null,
"e": 4143,
"s": 4092,
"text": "Metrics, parameters, duration, status, git commit:"
},
{
"code": null,
"e": 4182,
"s": 4143,
"text": "as well as model output and artifacts:"
},
{
"code": null,
"e": 4316,
"s": 4182,
"text": "So far, we’ve used MLflow locally. This is not ideal if we want to collaborate with other colleagues and track experiments in a team."
},
{
"code": null,
"e": 4412,
"s": 4316,
"text": "Fortunately, setting up a remote MLflow tracking server is quite easy. Let’s see how this done."
},
{
"code": null,
"e": 4518,
"s": 4412,
"text": "In this section I’ll be using AWS, so make sure you have an account if you want to reproduce these steps."
},
{
"code": null,
"e": 4562,
"s": 4518,
"text": "1 — Set up a remote EC2 machine with MLflow"
},
{
"code": null,
"e": 4693,
"s": 4562,
"text": "Create an IAM user. Grab the Access key ID and Secret access key credentials and store them somewhere safe. We’ll need them later."
},
{
"code": null,
"e": 4951,
"s": 4693,
"text": "With this same user, create an s3 bucket to store future artifacts: give this bucket a name. Mine is mlflow-artifact-store-demo but you cannot pick it. Note that you don’t need custom configuration for your bucket (it doesn’t need to be public for instance)"
},
{
"code": null,
"e": 5057,
"s": 4951,
"text": "Launch an EC2 instance: it doesn’t have to be big. At2.micro eligible to free tier does perfectly the job"
},
{
"code": null,
"e": 5223,
"s": 5057,
"text": "Configure the security group of this instance to accept inbound HTTP traffic on port 5000 and any IP address so that the MLflow server is accessible from the outside"
},
{
"code": null,
"e": 5323,
"s": 5223,
"text": "Connect to your instance using SSH and run the following commands to install pip, pipenv and mlflow"
},
{
"code": null,
"e": 5585,
"s": 5323,
"text": "# install pipsudo apt updatesudo apt install python3-pip# install sudo pip3 install pipenvsudo pip3 install virtualenvexport PATH=$PATH:/home/[your_user]/.local/bin/# install mlflow, awscli and boto3pipenv install mlflowpipenv install awsclipipenv install boto3"
},
{
"code": null,
"e": 5808,
"s": 5585,
"text": "On the EC2 machine, configure AWS with the user’s credentials so that the tracking server can have access to s3 and display the artifacts on the UI. Enter aws configure then follow the instructions to enter the credentials"
},
{
"code": null,
"e": 5932,
"s": 5808,
"text": "Start an MLflow server on the EC2 instance by defining the host as 0.0.0.0 and the --default-artifact-root as the S3 bucket"
},
{
"code": null,
"e": 6013,
"s": 5932,
"text": "mlflow server -h 0.0.0.0 --default-artifact-root s3://mlflow-artifact-store-demo"
},
{
"code": null,
"e": 6058,
"s": 6013,
"text": "Now your EC2 machine is properly configured."
},
{
"code": null,
"e": 6086,
"s": 6058,
"text": "2 — Set up your environment"
},
{
"code": null,
"e": 6174,
"s": 6086,
"text": "To allow MLflow to push runs from your local environment to EC2 and S3, you’ll have to:"
},
{
"code": null,
"e": 6218,
"s": 6174,
"text": "Install boto3 locally via pip install boto3"
},
{
"code": null,
"e": 6336,
"s": 6218,
"text": "Set the AWS credentials as environment variables so that MLflow has the right permissions of S3 read and write access"
},
{
"code": null,
"e": 6445,
"s": 6336,
"text": "export AWS_ACCESS_KEY_ID=<your-aws-access-key-id>export AWS_SECRET_ACCESS_KEY = <your-aws-secret-access-key>"
},
{
"code": null,
"e": 6514,
"s": 6445,
"text": "change the tracking URI in your code to the HTTP://<public-dns>:5000"
},
{
"code": null,
"e": 6557,
"s": 6514,
"text": "Now everything should be set up correctly."
},
{
"code": null,
"e": 6706,
"s": 6557,
"text": "If you execute your code again, the runs will no longer be saved locally but on the remote tracking server, which you can check by visiting the URL."
},
{
"code": null,
"e": 6959,
"s": 6706,
"text": "Setting up MLflow as we did is fine for small projects within relatively small teams. It’s however not production-ready. In fact, you’ll have to secure access to the MLflow UI and create a service on EC2 to start MLflow in the background at the startup"
},
{
"code": null,
"e": 7013,
"s": 6959,
"text": "You can use a managed version of MLFlow on databricks"
},
{
"code": null,
"e": 7202,
"s": 7013,
"text": "MLflow Tracking is agnostic to the type of work you’re doing be it NLP, computer vision or unsupervised learning. As long as you have metrics and parameters to track, MLFlow is a good fit."
}
] |
HTML - <script> Tag
|
The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document.
<!DOCTYPE html>
<html>
<head>
<title>HTML script Tag</title>
</head>
<body>
<script type = "text/JavaScript">
document.write("You're visiting tutorialspoint!")
</script>
</body>
</html>
This will produce the following result −
For more detail on <script> tag please check HTML Scripts chapter.
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <script> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2475,
"s": 2374,
"text": "The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document."
},
{
"code": null,
"e": 2704,
"s": 2475,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML script Tag</title>\n </head>\n\n <body>\n <script type = \"text/JavaScript\">\n document.write(\"You're visiting tutorialspoint!\")\n </script>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 2745,
"s": 2704,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2812,
"s": 2745,
"text": "For more detail on <script> tag please check HTML Scripts chapter."
},
{
"code": null,
"e": 2896,
"s": 2812,
"text": "This tag supports all the global attributes described in − HTML Attribute Reference"
},
{
"code": null,
"e": 2971,
"s": 2896,
"text": "The HTML <script> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 3051,
"s": 2971,
"text": "This tag supports all the event attributes described in − HTML Events Reference"
},
{
"code": null,
"e": 3084,
"s": 3051,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3098,
"s": 3084,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3133,
"s": 3098,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3147,
"s": 3133,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3182,
"s": 3147,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3199,
"s": 3182,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3234,
"s": 3199,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3265,
"s": 3234,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3298,
"s": 3265,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3329,
"s": 3298,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3364,
"s": 3329,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3395,
"s": 3364,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3402,
"s": 3395,
"text": " Print"
},
{
"code": null,
"e": 3413,
"s": 3402,
"text": " Add Notes"
}
] |
PHP | popen( ) Function
|
04 Jun, 2018
The popen() function used to open a pipe to the program specified by the user using the command parameter. It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature i.e it can be only used for reading or writing. The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer initiated by the popen() function must be closed with pclose().The command and the mode are sent as parameters to the popen() function and it returns a unidirectional file pointer on success or FALSE on failure.
Syntax:
popen(command, mode)
Parameters Used:The popen() function in PHP accepts two parameters.
command : It is a mandatory parameter which specifies the command to be executed.mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w).
command : It is a mandatory parameter which specifies the command to be executed.
mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w).
Return Value:It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature.
Errors And Exceptions:
The file pointer initiated by the popen() function must be closed with pclose().If the command to be executed could not be found, then the popen() function returns a valid resource.
The file pointer initiated by the popen() function must be closed with pclose().
If the command to be executed could not be found, then the popen() function returns a valid resource.
Examples:
Input : $my_file= popen("/bin/ls", "r");
Output : 1
Input : $my_file= popen('/executable/gfg.exe', 'r');
echo "'my_file'; " . get_class($my_handle) . "\n";
$file_read = fread($my_file, 4192);
echo $file_read;
pclose($my_file);
Output : 1
Below programs illustrate the popen() function.
Program 1
<?php // opening a pipe $my_file= popen("/bin/ls", "r");?>
Output:
1
Program 2
<?php // opening a pipe$my_file= popen('/executable/gfg.exe', 'r'); // returning name of class of an object using get_class() echo "'$my_file'; " . get_class($my_file) . "\n"; // reading file using fread()$filereader = fread($my_file, 4192); echo $filereader; // closing the pipepclose($my_file);?>
Output:
1
Related Article: PHP | pclose( ) Function
Reference:http://php.net/manual/en/function.popen.php
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2018"
},
{
"code": null,
"e": 591,
"s": 28,
"text": "The popen() function used to open a pipe to the program specified by the user using the command parameter. It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature i.e it can be only used for reading or writing. The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer initiated by the popen() function must be closed with pclose().The command and the mode are sent as parameters to the popen() function and it returns a unidirectional file pointer on success or FALSE on failure."
},
{
"code": null,
"e": 599,
"s": 591,
"text": "Syntax:"
},
{
"code": null,
"e": 620,
"s": 599,
"text": "popen(command, mode)"
},
{
"code": null,
"e": 688,
"s": 620,
"text": "Parameters Used:The popen() function in PHP accepts two parameters."
},
{
"code": null,
"e": 879,
"s": 688,
"text": "command : It is a mandatory parameter which specifies the command to be executed.mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w)."
},
{
"code": null,
"e": 961,
"s": 879,
"text": "command : It is a mandatory parameter which specifies the command to be executed."
},
{
"code": null,
"e": 1071,
"s": 961,
"text": "mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w)."
},
{
"code": null,
"e": 1194,
"s": 1071,
"text": "Return Value:It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature."
},
{
"code": null,
"e": 1217,
"s": 1194,
"text": "Errors And Exceptions:"
},
{
"code": null,
"e": 1399,
"s": 1217,
"text": "The file pointer initiated by the popen() function must be closed with pclose().If the command to be executed could not be found, then the popen() function returns a valid resource."
},
{
"code": null,
"e": 1480,
"s": 1399,
"text": "The file pointer initiated by the popen() function must be closed with pclose()."
},
{
"code": null,
"e": 1582,
"s": 1480,
"text": "If the command to be executed could not be found, then the popen() function returns a valid resource."
},
{
"code": null,
"e": 1592,
"s": 1582,
"text": "Examples:"
},
{
"code": null,
"e": 1864,
"s": 1592,
"text": "Input : $my_file= popen(\"/bin/ls\", \"r\");\nOutput : 1\n\nInput : $my_file= popen('/executable/gfg.exe', 'r');\n echo \"'my_file'; \" . get_class($my_handle) . \"\\n\";\n $file_read = fread($my_file, 4192);\n echo $file_read;\n pclose($my_file);\nOutput : 1\n"
},
{
"code": null,
"e": 1912,
"s": 1864,
"text": "Below programs illustrate the popen() function."
},
{
"code": null,
"e": 1922,
"s": 1912,
"text": "Program 1"
},
{
"code": "<?php // opening a pipe $my_file= popen(\"/bin/ls\", \"r\");?>",
"e": 1982,
"s": 1922,
"text": null
},
{
"code": null,
"e": 1990,
"s": 1982,
"text": "Output:"
},
{
"code": null,
"e": 1992,
"s": 1990,
"text": "1"
},
{
"code": null,
"e": 2002,
"s": 1992,
"text": "Program 2"
},
{
"code": "<?php // opening a pipe$my_file= popen('/executable/gfg.exe', 'r'); // returning name of class of an object using get_class() echo \"'$my_file'; \" . get_class($my_file) . \"\\n\"; // reading file using fread()$filereader = fread($my_file, 4192); echo $filereader; // closing the pipepclose($my_file);?>",
"e": 2307,
"s": 2002,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2307,
"text": "Output:"
},
{
"code": null,
"e": 2317,
"s": 2315,
"text": "1"
},
{
"code": null,
"e": 2359,
"s": 2317,
"text": "Related Article: PHP | pclose( ) Function"
},
{
"code": null,
"e": 2413,
"s": 2359,
"text": "Reference:http://php.net/manual/en/function.popen.php"
},
{
"code": null,
"e": 2431,
"s": 2413,
"text": "PHP-file-handling"
},
{
"code": null,
"e": 2444,
"s": 2431,
"text": "PHP-function"
},
{
"code": null,
"e": 2448,
"s": 2444,
"text": "PHP"
},
{
"code": null,
"e": 2465,
"s": 2448,
"text": "Web Technologies"
},
{
"code": null,
"e": 2469,
"s": 2465,
"text": "PHP"
}
] |
Solving Linear Regression in Python
|
16 Jul, 2020
Linear regression is a common method to model the relationship between a dependent variable and one or more independent variables. Linear models are developed using the parameters which are estimated from the data. Linear regression is useful in prediction and forecasting where a predictive model is fit to an observed data set of values to determine the response. Linear regression models are often fitted using the least-squares approach where the goal is to minimize the error.
Consider a dataset where the independent attribute is represented by x and the dependent attribute is represented by y.
It is known that the equation of a straight line is y = mx + b where m is the slope and b is the intercept.In order to prepare a simple regression model of the given dataset, we need to calculate the slope and intercept of the line which best fits the data points.
How to calculate slope and intercept?
Mathematical formula to calculate slope and intercept are given below
Slope = Sxy/Sxx
where Sxy and Sxx are sample covariance and sample variance respectively.
Intercept = ymean – slope* xmean
Let us use these relations to determine the linear regression for the above dataset. For this we calculate the xmean, ymean, Sxy, Sxx as shown in the table.
As per the above formulae,Slope = 28/10 = 2.8Intercept = 14.6 – 2.8 * 3 = 6.2Therefore,
The desired equation of the regression model is y = 2.8 x + 6.2
We shall use these values to predict the values of y for the given values of x. The performance of the model can be analyzed by calculating the root mean square error and R2 value.
Calculations are shown below.
Squared Error=10.8 which means that mean squared error =3.28Coefficient of Determination (R2) = 1- 10.8 / 89.2 = 0.878
Low value of error and high value of R2 signify that the
linear regression fits data well
Let us see the Python Implementation of linear regression for this dataset.
Code 1: Import all the necessary Libraries.
import numpy as npimport matplotlib.pyplot as plt from sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_scoreimport statsmodels.api as sm
Code 2: Generate the data. Calculate xmean, ymean, Sxx, Sxy to find the value of slope and intercept of regression line.
x = np.array([1,2,3,4,5]) y = np.array([7,14,15,18,19])n = np.size(x) x_mean = np.mean(x)y_mean = np.mean(y)x_mean,y_mean Sxy = np.sum(x*y)- n*x_mean*y_meanSxx = np.sum(x*x)-n*x_mean*x_mean b1 = Sxy/Sxxb0 = y_mean-b1*x_meanprint('slope b1 is', b1)print('intercept b0 is', b0) plt.scatter(x,y)plt.xlabel('Independent variable X')plt.ylabel('Dependent variable y')
Output:
slope b1 is 2.8
intercept b0 is 6.200000000000001
Code 3: Plot the given data points and fit the regression line.
y_pred = b1 * x + b0 plt.scatter(x, y, color = 'red')plt.plot(x, y_pred, color = 'green')plt.xlabel('X')plt.ylabel('y')
error = y - y_predse = np.sum(error**2)print('squared error is', se) mse = se/n print('mean squared error is', mse) rmse = np.sqrt(mse)print('root mean square error is', rmse) SSt = np.sum((y - y_mean)**2)R2 = 1- (se/SSt)print('R square is', R2)
Output:
squared error is 10.800000000000004
mean squared error is 2.160000000000001
root mean square error is 1.4696938456699071
R square is 0.8789237668161435
Code 5: Use scikit library to confirm the above steps.
x = x.reshape(-1,1)regression_model = LinearRegression() # Fit the data(train the model)regression_model.fit(x, y) # Predicty_predicted = regression_model.predict(x) # model evaluationmse=mean_squared_error(y,y_predicted) rmse = np.sqrt(mean_squared_error(y, y_predicted))r2 = r2_score(y, y_predicted) # printing valuesprint('Slope:' ,regression_model.coef_)print('Intercept:', regression_model.intercept_)print('MSE:',mse)print('Root mean squared error: ', rmse)print('R2 score: ', r2)
Output:
Slope: [2.8]
Intercept: 6.199999999999999
MSE: 2.160000000000001
Root mean squared error: 1.4696938456699071
R2 score: 0.8789237668161435
Conclusion: This article helps to understand the mathematics behind simple regression and implement the same using Python.
ML-Regression
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 536,
"s": 54,
"text": "Linear regression is a common method to model the relationship between a dependent variable and one or more independent variables. Linear models are developed using the parameters which are estimated from the data. Linear regression is useful in prediction and forecasting where a predictive model is fit to an observed data set of values to determine the response. Linear regression models are often fitted using the least-squares approach where the goal is to minimize the error."
},
{
"code": null,
"e": 656,
"s": 536,
"text": "Consider a dataset where the independent attribute is represented by x and the dependent attribute is represented by y."
},
{
"code": null,
"e": 921,
"s": 656,
"text": "It is known that the equation of a straight line is y = mx + b where m is the slope and b is the intercept.In order to prepare a simple regression model of the given dataset, we need to calculate the slope and intercept of the line which best fits the data points."
},
{
"code": null,
"e": 959,
"s": 921,
"text": "How to calculate slope and intercept?"
},
{
"code": null,
"e": 1029,
"s": 959,
"text": "Mathematical formula to calculate slope and intercept are given below"
},
{
"code": null,
"e": 1156,
"s": 1029,
"text": "Slope = Sxy/Sxx \nwhere Sxy and Sxx are sample covariance and sample variance respectively.\n\nIntercept = ymean – slope* xmean"
},
{
"code": null,
"e": 1313,
"s": 1156,
"text": "Let us use these relations to determine the linear regression for the above dataset. For this we calculate the xmean, ymean, Sxy, Sxx as shown in the table."
},
{
"code": null,
"e": 1401,
"s": 1313,
"text": "As per the above formulae,Slope = 28/10 = 2.8Intercept = 14.6 – 2.8 * 3 = 6.2Therefore,"
},
{
"code": null,
"e": 1465,
"s": 1401,
"text": "The desired equation of the regression model is y = 2.8 x + 6.2"
},
{
"code": null,
"e": 1646,
"s": 1465,
"text": "We shall use these values to predict the values of y for the given values of x. The performance of the model can be analyzed by calculating the root mean square error and R2 value."
},
{
"code": null,
"e": 1676,
"s": 1646,
"text": "Calculations are shown below."
},
{
"code": null,
"e": 1795,
"s": 1676,
"text": "Squared Error=10.8 which means that mean squared error =3.28Coefficient of Determination (R2) = 1- 10.8 / 89.2 = 0.878"
},
{
"code": null,
"e": 1887,
"s": 1795,
"text": " Low value of error and high value of R2 signify that the \nlinear regression fits data well"
},
{
"code": null,
"e": 1963,
"s": 1887,
"text": "Let us see the Python Implementation of linear regression for this dataset."
},
{
"code": null,
"e": 2007,
"s": 1963,
"text": "Code 1: Import all the necessary Libraries."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt from sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_error, r2_scoreimport statsmodels.api as sm",
"e": 2192,
"s": 2007,
"text": null
},
{
"code": null,
"e": 2313,
"s": 2192,
"text": "Code 2: Generate the data. Calculate xmean, ymean, Sxx, Sxy to find the value of slope and intercept of regression line."
},
{
"code": "x = np.array([1,2,3,4,5]) y = np.array([7,14,15,18,19])n = np.size(x) x_mean = np.mean(x)y_mean = np.mean(y)x_mean,y_mean Sxy = np.sum(x*y)- n*x_mean*y_meanSxx = np.sum(x*x)-n*x_mean*x_mean b1 = Sxy/Sxxb0 = y_mean-b1*x_meanprint('slope b1 is', b1)print('intercept b0 is', b0) plt.scatter(x,y)plt.xlabel('Independent variable X')plt.ylabel('Dependent variable y')",
"e": 2680,
"s": 2313,
"text": null
},
{
"code": null,
"e": 2688,
"s": 2680,
"text": "Output:"
},
{
"code": null,
"e": 2738,
"s": 2688,
"text": "slope b1 is 2.8\nintercept b0 is 6.200000000000001"
},
{
"code": null,
"e": 2802,
"s": 2738,
"text": "Code 3: Plot the given data points and fit the regression line."
},
{
"code": "y_pred = b1 * x + b0 plt.scatter(x, y, color = 'red')plt.plot(x, y_pred, color = 'green')plt.xlabel('X')plt.ylabel('y')",
"e": 2923,
"s": 2802,
"text": null
},
{
"code": "error = y - y_predse = np.sum(error**2)print('squared error is', se) mse = se/n print('mean squared error is', mse) rmse = np.sqrt(mse)print('root mean square error is', rmse) SSt = np.sum((y - y_mean)**2)R2 = 1- (se/SSt)print('R square is', R2)",
"e": 3172,
"s": 2923,
"text": null
},
{
"code": null,
"e": 3180,
"s": 3172,
"text": "Output:"
},
{
"code": null,
"e": 3332,
"s": 3180,
"text": "squared error is 10.800000000000004\nmean squared error is 2.160000000000001\nroot mean square error is 1.4696938456699071\nR square is 0.8789237668161435"
},
{
"code": null,
"e": 3387,
"s": 3332,
"text": "Code 5: Use scikit library to confirm the above steps."
},
{
"code": "x = x.reshape(-1,1)regression_model = LinearRegression() # Fit the data(train the model)regression_model.fit(x, y) # Predicty_predicted = regression_model.predict(x) # model evaluationmse=mean_squared_error(y,y_predicted) rmse = np.sqrt(mean_squared_error(y, y_predicted))r2 = r2_score(y, y_predicted) # printing valuesprint('Slope:' ,regression_model.coef_)print('Intercept:', regression_model.intercept_)print('MSE:',mse)print('Root mean squared error: ', rmse)print('R2 score: ', r2)",
"e": 3879,
"s": 3387,
"text": null
},
{
"code": null,
"e": 3887,
"s": 3879,
"text": "Output:"
},
{
"code": null,
"e": 4027,
"s": 3887,
"text": "Slope: [2.8]\nIntercept: 6.199999999999999\nMSE: 2.160000000000001\nRoot mean squared error: 1.4696938456699071\nR2 score: 0.8789237668161435"
},
{
"code": null,
"e": 4150,
"s": 4027,
"text": "Conclusion: This article helps to understand the mathematics behind simple regression and implement the same using Python."
},
{
"code": null,
"e": 4164,
"s": 4150,
"text": "ML-Regression"
},
{
"code": null,
"e": 4181,
"s": 4164,
"text": "Machine Learning"
},
{
"code": null,
"e": 4188,
"s": 4181,
"text": "Python"
},
{
"code": null,
"e": 4205,
"s": 4188,
"text": "Machine Learning"
}
] |
How to use Avatar Component in ReactJS?
|
05 Mar, 2021
Avatars are found throughout material design with uses in everything from tables to dialog menus. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Avatar Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import Avatar from "@material-ui/core/Avatar"; export default function App() { return ( <div style={{ display: "flex" }}> <h4>How to use Avatar Component in ReactJS?</h4> <Avatar style={{ border: "2px solid gray", margin: 10 }} alt="GeeksforGeeks Pic 1" src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" /> <Avatar style={{ border: "1px solid black", margin: 20 }} alt="GeeksforGeeks Pic 2" src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/avatars/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Mar, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "Avatars are found throughout material design with uses in everything from tables to dialog menus. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Avatar Component in ReactJS using the following approach."
},
{
"code": null,
"e": 342,
"s": 292,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 406,
"s": 342,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 438,
"s": 406,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 538,
"s": 438,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 552,
"s": 538,
"text": "cd foldername"
},
{
"code": null,
"e": 661,
"s": 552,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 691,
"s": 661,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 743,
"s": 691,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 761,
"s": 743,
"text": "Project Structure"
},
{
"code": null,
"e": 891,
"s": 761,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 898,
"s": 891,
"text": "App.js"
},
{
"code": "import React from \"react\";import Avatar from \"@material-ui/core/Avatar\"; export default function App() { return ( <div style={{ display: \"flex\" }}> <h4>How to use Avatar Component in ReactJS?</h4> <Avatar style={{ border: \"2px solid gray\", margin: 10 }} alt=\"GeeksforGeeks Pic 1\" src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" /> <Avatar style={{ border: \"1px solid black\", margin: 20 }} alt=\"GeeksforGeeks Pic 2\" src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" /> </div> );}",
"e": 1507,
"s": 898,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1507,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 1630,
"s": 1620,
"text": "npm start"
},
{
"code": null,
"e": 1729,
"s": 1630,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 1784,
"s": 1729,
"text": "Reference: https://material-ui.com/components/avatars/"
},
{
"code": null,
"e": 1796,
"s": 1784,
"text": "Material-UI"
},
{
"code": null,
"e": 1812,
"s": 1796,
"text": "React-Questions"
},
{
"code": null,
"e": 1820,
"s": 1812,
"text": "ReactJS"
},
{
"code": null,
"e": 1837,
"s": 1820,
"text": "Web Technologies"
}
] |
Python | Visualize graphs generated in NetworkX using Matplotlib
|
14 Aug, 2021
Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package.
Step 1 : Import networkx and matplotlib.pyplot in the project file.
Python3
# importing networkximport networkx as nx # importing matplotlib.pyplotimport matplotlib.pyplot as plt
Step 2 : Generate a graph using networkx. Step 3 : Now use draw() function of networkx.drawing to draw the graph. Step 4 : Use savefig(“filename.png”) function of matplotlib.pyplot to save the drawing of graph in filename.png file.
Below is the Python code:
Python3
# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5) nx.draw(g)plt.savefig("filename.png")
Output:
To add numbering in the node add one argument with_labels=True in draw() function.
Python3
# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5) nx.draw(g, with_labels = True)plt.savefig("filename.png")
Output:
Different graph types and plotting can be done using networkx drawing and matplotlib.
Note** : Here keywords is referred to optional keywords that we can mention use to format the graph plotting. Some of the general graph layouts are :
draw_circular(G, keywords) : This gives circular layout of the graph G.draw_planar(G, keywords) :] This gives a planar layout of a planar networkx graph G.draw_random(G, keywords) : This gives a random layout of the graph G.draw_spectral(G, keywords) : This gives a spectral 2D layout of the graph G.draw_spring(G, keywords) : This gives a spring layout of the graph G.draw_shell(G, keywords) : This gives a shell layout of the graph G.
draw_circular(G, keywords) : This gives circular layout of the graph G.
draw_planar(G, keywords) :] This gives a planar layout of a planar networkx graph G.
draw_random(G, keywords) : This gives a random layout of the graph G.
draw_spectral(G, keywords) : This gives a spectral 2D layout of the graph G.
draw_spring(G, keywords) : This gives a spring layout of the graph G.
draw_shell(G, keywords) : This gives a shell layout of the graph G.
Example :
Python3
# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5)g.add_edge(5, 6)g.add_edge(5, 7)g.add_edge(4, 8)g.add_edge(3, 8) # drawing in circular layoutnx.draw_circular(g, with_labels = True)plt.savefig("filename1.png") # clearing the current plotplt.clf() # drawing in planar layoutnx.draw_planar(g, with_labels = True)plt.savefig("filename2.png") # clearing the current plotplt.clf() # drawing in random layoutnx.draw_random(g, with_labels = True)plt.savefig("filename3.png") # clearing the current plotplt.clf() # drawing in spectral layoutnx.draw_spectral(g, with_labels = True)plt.savefig("filename4.png") # clearing the current plotplt.clf() # drawing in spring layoutnx.draw_spring(g, with_labels = True)plt.savefig("filename5.png") # clearing the current plotplt.clf() # drawing in shell layoutnx.draw_shell(g, with_labels = True)plt.savefig("filename6.png") # clearing the current plotplt.clf()
Outputs : Circular Layout
Planar Layout
Random Layout
Spectral Layout
Spring Layout
Shell Layout
Reference : NetworkX Drawing Documentation
simranarora5sos
surinderdawra388
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package."
},
{
"code": null,
"e": 386,
"s": 317,
"text": "Step 1 : Import networkx and matplotlib.pyplot in the project file. "
},
{
"code": null,
"e": 394,
"s": 386,
"text": "Python3"
},
{
"code": "# importing networkximport networkx as nx # importing matplotlib.pyplotimport matplotlib.pyplot as plt",
"e": 497,
"s": 394,
"text": null
},
{
"code": null,
"e": 729,
"s": 497,
"text": "Step 2 : Generate a graph using networkx. Step 3 : Now use draw() function of networkx.drawing to draw the graph. Step 4 : Use savefig(“filename.png”) function of matplotlib.pyplot to save the drawing of graph in filename.png file."
},
{
"code": null,
"e": 757,
"s": 729,
"text": "Below is the Python code: "
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Python3"
},
{
"code": "# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5) nx.draw(g)plt.savefig(\"filename.png\")",
"e": 1001,
"s": 765,
"text": null
},
{
"code": null,
"e": 1010,
"s": 1001,
"text": "Output: "
},
{
"code": null,
"e": 1095,
"s": 1010,
"text": "To add numbering in the node add one argument with_labels=True in draw() function. "
},
{
"code": null,
"e": 1103,
"s": 1095,
"text": "Python3"
},
{
"code": "# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5) nx.draw(g, with_labels = True)plt.savefig(\"filename.png\")",
"e": 1359,
"s": 1103,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1359,
"text": "Output: "
},
{
"code": null,
"e": 1455,
"s": 1368,
"text": "Different graph types and plotting can be done using networkx drawing and matplotlib. "
},
{
"code": null,
"e": 1607,
"s": 1455,
"text": "Note** : Here keywords is referred to optional keywords that we can mention use to format the graph plotting. Some of the general graph layouts are : "
},
{
"code": null,
"e": 2046,
"s": 1607,
"text": "draw_circular(G, keywords) : This gives circular layout of the graph G.draw_planar(G, keywords) :] This gives a planar layout of a planar networkx graph G.draw_random(G, keywords) : This gives a random layout of the graph G.draw_spectral(G, keywords) : This gives a spectral 2D layout of the graph G.draw_spring(G, keywords) : This gives a spring layout of the graph G.draw_shell(G, keywords) : This gives a shell layout of the graph G. "
},
{
"code": null,
"e": 2118,
"s": 2046,
"text": "draw_circular(G, keywords) : This gives circular layout of the graph G."
},
{
"code": null,
"e": 2203,
"s": 2118,
"text": "draw_planar(G, keywords) :] This gives a planar layout of a planar networkx graph G."
},
{
"code": null,
"e": 2273,
"s": 2203,
"text": "draw_random(G, keywords) : This gives a random layout of the graph G."
},
{
"code": null,
"e": 2350,
"s": 2273,
"text": "draw_spectral(G, keywords) : This gives a spectral 2D layout of the graph G."
},
{
"code": null,
"e": 2420,
"s": 2350,
"text": "draw_spring(G, keywords) : This gives a spring layout of the graph G."
},
{
"code": null,
"e": 2490,
"s": 2420,
"text": "draw_shell(G, keywords) : This gives a shell layout of the graph G. "
},
{
"code": null,
"e": 2502,
"s": 2490,
"text": "Example : "
},
{
"code": null,
"e": 2510,
"s": 2502,
"text": "Python3"
},
{
"code": "# importing networkximport networkx as nx# importing matplotlib.pyplotimport matplotlib.pyplot as plt g = nx.Graph() g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 4)g.add_edge(1, 4)g.add_edge(1, 5)g.add_edge(5, 6)g.add_edge(5, 7)g.add_edge(4, 8)g.add_edge(3, 8) # drawing in circular layoutnx.draw_circular(g, with_labels = True)plt.savefig(\"filename1.png\") # clearing the current plotplt.clf() # drawing in planar layoutnx.draw_planar(g, with_labels = True)plt.savefig(\"filename2.png\") # clearing the current plotplt.clf() # drawing in random layoutnx.draw_random(g, with_labels = True)plt.savefig(\"filename3.png\") # clearing the current plotplt.clf() # drawing in spectral layoutnx.draw_spectral(g, with_labels = True)plt.savefig(\"filename4.png\") # clearing the current plotplt.clf() # drawing in spring layoutnx.draw_spring(g, with_labels = True)plt.savefig(\"filename5.png\") # clearing the current plotplt.clf() # drawing in shell layoutnx.draw_shell(g, with_labels = True)plt.savefig(\"filename6.png\") # clearing the current plotplt.clf()",
"e": 3552,
"s": 2510,
"text": null
},
{
"code": null,
"e": 3579,
"s": 3552,
"text": "Outputs : Circular Layout "
},
{
"code": null,
"e": 3594,
"s": 3579,
"text": "Planar Layout "
},
{
"code": null,
"e": 3609,
"s": 3594,
"text": "Random Layout "
},
{
"code": null,
"e": 3626,
"s": 3609,
"text": "Spectral Layout "
},
{
"code": null,
"e": 3641,
"s": 3626,
"text": "Spring Layout "
},
{
"code": null,
"e": 3655,
"s": 3641,
"text": "Shell Layout "
},
{
"code": null,
"e": 3699,
"s": 3655,
"text": "Reference : NetworkX Drawing Documentation "
},
{
"code": null,
"e": 3715,
"s": 3699,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3732,
"s": 3715,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3747,
"s": 3732,
"text": "python-modules"
},
{
"code": null,
"e": 3754,
"s": 3747,
"text": "Python"
}
] |
SQL Trigger | Book Management Database
|
01 Feb, 2019
Prerequisite – SQL Trigger | Student DatabaseFor example, given Library Book Management database schema with Student database schema. In these databases, if any student borrows a book from library then the count of that specified book should be decremented. To do so,
Suppose the schema with some data,
mysql> select * from book_det;
+-----+-------------+--------+
| bid | btitle | copies |
+-----+-------------+--------+
| 1 | Java | 10 |
| 2 | C++ | 5 |
| 3 | MySql | 10 |
| 4 | Oracle DBMS | 5 |
+-----+-------------+--------+
4 rows in set (0.00 sec)
mysql> select * from book_issue;
+------+------+--------+
| bid | sid | btitle |
+------+------+--------+
1 row in set (0.00 sec)
To implement such procedure, in which if the system inserts the data into the book_issue database a trigger should automatically invoke and decrements the copies attribute by 1 so that a proper track of book can be maintained.
Trigger for the system –
create trigger book_copies_deducts
after INSERT
on book_issue
for each row
update book_det set copies = copies - 1 where bid = new.bid;
Above trigger, will be activated whenever an insertion operation performed in a book_issue database, it will update the book_det schema setting copies decrements by 1 of current book id(bid).
Results –
mysql> insert into book_issue values(1, 100, "Java");
Query OK, 1 row affected (0.09 sec)
mysql> select * from book_det;
+-----+-------------+--------+
| bid | btitle | copies |
+-----+-------------+--------+
| 1 | Java | 9 |
| 2 | C++ | 5 |
| 3 | MySql | 10 |
| 4 | Oracle DBMS | 5 |
+-----+-------------+--------+
4 rows in set (0.00 sec)
mysql> select * from book_issue;
+------+------+--------+
| bid | sid | btitle |
+------+------+--------+
| 1 | 100 | Java |
+------+------+--------+
1 row in set (0.00 sec)
As above results show that as soon as data is inserted, copies of the book deducts from the book schema in the system.
mayankchauhan
DBMS-SQL
SQL-basics
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 320,
"s": 52,
"text": "Prerequisite – SQL Trigger | Student DatabaseFor example, given Library Book Management database schema with Student database schema. In these databases, if any student borrows a book from library then the count of that specified book should be decremented. To do so,"
},
{
"code": null,
"e": 355,
"s": 320,
"text": "Suppose the schema with some data,"
},
{
"code": null,
"e": 806,
"s": 355,
"text": "mysql> select * from book_det; \n+-----+-------------+--------+ \n| bid | btitle | copies | \n+-----+-------------+--------+ \n| 1 | Java | 10 | \n| 2 | C++ | 5 | \n| 3 | MySql | 10 | \n| 4 | Oracle DBMS | 5 | \n+-----+-------------+--------+ \n4 rows in set (0.00 sec) \n\nmysql> select * from book_issue; \n+------+------+--------+ \n| bid | sid | btitle | \n+------+------+--------+ \n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1033,
"s": 806,
"text": "To implement such procedure, in which if the system inserts the data into the book_issue database a trigger should automatically invoke and decrements the copies attribute by 1 so that a proper track of book can be maintained."
},
{
"code": null,
"e": 1058,
"s": 1033,
"text": "Trigger for the system –"
},
{
"code": null,
"e": 1199,
"s": 1058,
"text": "create trigger book_copies_deducts \nafter INSERT \non book_issue \nfor each row \nupdate book_det set copies = copies - 1 where bid = new.bid; "
},
{
"code": null,
"e": 1391,
"s": 1199,
"text": "Above trigger, will be activated whenever an insertion operation performed in a book_issue database, it will update the book_det schema setting copies decrements by 1 of current book id(bid)."
},
{
"code": null,
"e": 1401,
"s": 1391,
"text": "Results –"
},
{
"code": null,
"e": 1996,
"s": 1401,
"text": "mysql> insert into book_issue values(1, 100, \"Java\");\nQuery OK, 1 row affected (0.09 sec) \n\nmysql> select * from book_det; \n+-----+-------------+--------+ \n| bid | btitle | copies | \n+-----+-------------+--------+ \n| 1 | Java | 9 | \n| 2 | C++ | 5 | \n| 3 | MySql | 10 | \n| 4 | Oracle DBMS | 5 | \n+-----+-------------+--------+ \n4 rows in set (0.00 sec) \n\nmysql> select * from book_issue; \n+------+------+--------+ \n| bid | sid | btitle | \n+------+------+--------+ \n| 1 | 100 | Java | \n+------+------+--------+ \n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2115,
"s": 1996,
"text": "As above results show that as soon as data is inserted, copies of the book deducts from the book schema in the system."
},
{
"code": null,
"e": 2129,
"s": 2115,
"text": "mayankchauhan"
},
{
"code": null,
"e": 2138,
"s": 2129,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2149,
"s": 2138,
"text": "SQL-basics"
},
{
"code": null,
"e": 2154,
"s": 2149,
"text": "DBMS"
},
{
"code": null,
"e": 2158,
"s": 2154,
"text": "SQL"
},
{
"code": null,
"e": 2163,
"s": 2158,
"text": "DBMS"
},
{
"code": null,
"e": 2167,
"s": 2163,
"text": "SQL"
}
] |
Python | Convert mixed data types tuple list to string list
|
29 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + tuple() + str() + generator expressionThe combination of above functions can be used to perform this task. In this, we extract each tuple element using generation expression and perform the conversion using str(). The iteration to each tuple is done by list comprehension.
# Python3 code to demonstrate working of# Convert tuple mixed list to string list# using list comprehension + tuple() + str() + generator expression # initialize list test_list = [('gfg', 1, True), ('is', False), ('best', 2)] # printing original list print("The original list : " + str(test_list)) # Convert tuple mixed list to string list# using list comprehension + tuple() + str() + generator expressionres = [tuple(str(ele) for ele in sub) for sub in test_list] # printing resultprint("The tuple list after conversion : " + str(res))
The original list : [('gfg', 1, True), ('is', False), ('best', 2)]
The tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]
Method #2 : Using map() + tuple() + str() + list comprehensionThe combination of above functions can be used to perform this task. In this, we perform the task performed by generator expression above using map().
# Python3 code to demonstrate working of# Convert tuple mixed list to string list# using map() + tuple() + str() + list comprehension # initialize list test_list = [('gfg', 1, True), ('is', False), ('best', 2)] # printing original list print("The original list : " + str(test_list)) # Convert tuple mixed list to string list# using map() + tuple() + str() + list comprehensionres = [tuple(map(str, sub)) for sub in test_list] # printing resultprint("The tuple list after conversion : " + str(res))
The original list : [('gfg', 1, True), ('is', False), ('best', 2)]
The tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 318,
"s": 52,
"text": "Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 630,
"s": 318,
"text": "Method #1 : Using list comprehension + tuple() + str() + generator expressionThe combination of above functions can be used to perform this task. In this, we extract each tuple element using generation expression and perform the conversion using str(). The iteration to each tuple is done by list comprehension."
},
{
"code": "# Python3 code to demonstrate working of# Convert tuple mixed list to string list# using list comprehension + tuple() + str() + generator expression # initialize list test_list = [('gfg', 1, True), ('is', False), ('best', 2)] # printing original list print(\"The original list : \" + str(test_list)) # Convert tuple mixed list to string list# using list comprehension + tuple() + str() + generator expressionres = [tuple(str(ele) for ele in sub) for sub in test_list] # printing resultprint(\"The tuple list after conversion : \" + str(res))",
"e": 1172,
"s": 630,
"text": null
},
{
"code": null,
"e": 1329,
"s": 1172,
"text": "The original list : [('gfg', 1, True), ('is', False), ('best', 2)]\nThe tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]\n"
},
{
"code": null,
"e": 1544,
"s": 1331,
"text": "Method #2 : Using map() + tuple() + str() + list comprehensionThe combination of above functions can be used to perform this task. In this, we perform the task performed by generator expression above using map()."
},
{
"code": "# Python3 code to demonstrate working of# Convert tuple mixed list to string list# using map() + tuple() + str() + list comprehension # initialize list test_list = [('gfg', 1, True), ('is', False), ('best', 2)] # printing original list print(\"The original list : \" + str(test_list)) # Convert tuple mixed list to string list# using map() + tuple() + str() + list comprehensionres = [tuple(map(str, sub)) for sub in test_list] # printing resultprint(\"The tuple list after conversion : \" + str(res))",
"e": 2046,
"s": 1544,
"text": null
},
{
"code": null,
"e": 2203,
"s": 2046,
"text": "The original list : [('gfg', 1, True), ('is', False), ('best', 2)]\nThe tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]\n"
},
{
"code": null,
"e": 2224,
"s": 2203,
"text": "Python list-programs"
},
{
"code": null,
"e": 2231,
"s": 2224,
"text": "Python"
},
{
"code": null,
"e": 2247,
"s": 2231,
"text": "Python Programs"
},
{
"code": null,
"e": 2345,
"s": 2247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2377,
"s": 2345,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2404,
"s": 2377,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2425,
"s": 2404,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2448,
"s": 2425,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2479,
"s": 2448,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2501,
"s": 2479,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2540,
"s": 2501,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2578,
"s": 2540,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2615,
"s": 2578,
"text": "Python Program for Fibonacci numbers"
}
] |
ES6 | Classes
|
15 Feb, 2022
There are three concepts in Object-Oriented Programming Object, Class and Methods. The ES6 JavaScript supports the Object-Oriented programming components.
Object: A real-time object entity means the presentation of any entity in real-time.
Class: It is the before the plan of creating any objects which are known as blueprint of any objects which you want to create.
Methods: It communicates between the objects.
The class contains the Constructors and Functions. The Constructors take responsibility for allocating memory for the objects of the class. The function takes the responsibility of the action of the objects. Combing these two Constructor and Function to make the Class. In the ES6 to create any class, you need to use the class keyword.Syntax: Declaring Class:
class Class_name {
}
Class Expressions:
var var_name = new Class_name {
}
Below example will illustrate the ES6 Classes:Example:
javascript
<script>class gfg { // Constructor constructor(name, estd, rank){ this.n = name; this.e = estd; this.r = rank; } // Function decreaserank(){ this.r -= 1; }}const geeks = new gfg("geeks", 2009, 43) geeks.decreaserank(); document.write(geeks.r); //Output 42</script>
Output:
42
The example given above declares a class ‘gfg’. The class’s constructor takes three arguments – name, estd, and rank respectively. The ‘this’ keyword refers to the current instance of the class. The geeks() function in the class, print the values of the rank.Class inheritance: The ES6 Class supports the inheritance. Inheritance has the courage to create entities from existing entities. There are two types of Class in ES6:
parent class/super class: The class extended to create new class are know as a parent class or super class.
child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor
Syntax:
class child_name extends parent_name
Example:
javascript
<script>class geeks { constructor(g) { this.Character = g }}class GeeksforGeeks extends geeks { disp() { console.log("No of Character: "+this.Character) }}var obj = new GeeksforGeeks(13);obj.disp()</script>
Output:
No of Character: 13
Inheritance divided into three types:
Single Inheritance: Every class can be extend from one parent class.
Multiple Inheritance: A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance.
Multi-level Inheritance: A class can inherit from another class (via) which inherit from the parent class.
class Child extends Root
class Leaf extends Child
// So the leaf extends root indirectly
Super Keyword: This keyword helps child class to invoke the parent class data.
super.object
Example:
JavaScript
<script>class GeeksforGeeks { doPrint() { console.log("This doPrint() from Parent called.") }} class gfg extends GeeksforGeeks { doPrint() { super.doPrint() console.log("This doPrint() is printing a string.") }}var obj = new gfg()obj.doPrint()</script>
Output:
This doPrint() from Parent called.
This doPrint() is printing a string.
arorakashish0911
rkbhola5
ES6
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 211,
"s": 54,
"text": "There are three concepts in Object-Oriented Programming Object, Class and Methods. The ES6 JavaScript supports the Object-Oriented programming components. "
},
{
"code": null,
"e": 296,
"s": 211,
"text": "Object: A real-time object entity means the presentation of any entity in real-time."
},
{
"code": null,
"e": 423,
"s": 296,
"text": "Class: It is the before the plan of creating any objects which are known as blueprint of any objects which you want to create."
},
{
"code": null,
"e": 469,
"s": 423,
"text": "Methods: It communicates between the objects."
},
{
"code": null,
"e": 832,
"s": 469,
"text": "The class contains the Constructors and Functions. The Constructors take responsibility for allocating memory for the objects of the class. The function takes the responsibility of the action of the objects. Combing these two Constructor and Function to make the Class. In the ES6 to create any class, you need to use the class keyword.Syntax: Declaring Class: "
},
{
"code": null,
"e": 855,
"s": 832,
"text": "class Class_name { \n}"
},
{
"code": null,
"e": 876,
"s": 855,
"text": "Class Expressions: "
},
{
"code": null,
"e": 912,
"s": 876,
"text": "var var_name = new Class_name { \n}"
},
{
"code": null,
"e": 969,
"s": 912,
"text": "Below example will illustrate the ES6 Classes:Example: "
},
{
"code": null,
"e": 980,
"s": 969,
"text": "javascript"
},
{
"code": "<script>class gfg { // Constructor constructor(name, estd, rank){ this.n = name; this.e = estd; this.r = rank; } // Function decreaserank(){ this.r -= 1; }}const geeks = new gfg(\"geeks\", 2009, 43) geeks.decreaserank(); document.write(geeks.r); //Output 42</script>",
"e": 1301,
"s": 980,
"text": null
},
{
"code": null,
"e": 1311,
"s": 1301,
"text": "Output: "
},
{
"code": null,
"e": 1314,
"s": 1311,
"text": "42"
},
{
"code": null,
"e": 1742,
"s": 1314,
"text": "The example given above declares a class ‘gfg’. The class’s constructor takes three arguments – name, estd, and rank respectively. The ‘this’ keyword refers to the current instance of the class. The geeks() function in the class, print the values of the rank.Class inheritance: The ES6 Class supports the inheritance. Inheritance has the courage to create entities from existing entities. There are two types of Class in ES6: "
},
{
"code": null,
"e": 1850,
"s": 1742,
"text": "parent class/super class: The class extended to create new class are know as a parent class or super class."
},
{
"code": null,
"e": 2004,
"s": 1850,
"text": "child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor"
},
{
"code": null,
"e": 2014,
"s": 2004,
"text": "Syntax: "
},
{
"code": null,
"e": 2051,
"s": 2014,
"text": "class child_name extends parent_name"
},
{
"code": null,
"e": 2062,
"s": 2051,
"text": "Example: "
},
{
"code": null,
"e": 2073,
"s": 2062,
"text": "javascript"
},
{
"code": "<script>class geeks { constructor(g) { this.Character = g }}class GeeksforGeeks extends geeks { disp() { console.log(\"No of Character: \"+this.Character) }}var obj = new GeeksforGeeks(13);obj.disp()</script>",
"e": 2299,
"s": 2073,
"text": null
},
{
"code": null,
"e": 2309,
"s": 2299,
"text": "Output: "
},
{
"code": null,
"e": 2329,
"s": 2309,
"text": "No of Character: 13"
},
{
"code": null,
"e": 2369,
"s": 2329,
"text": "Inheritance divided into three types: "
},
{
"code": null,
"e": 2438,
"s": 2369,
"text": "Single Inheritance: Every class can be extend from one parent class."
},
{
"code": null,
"e": 2545,
"s": 2438,
"text": "Multiple Inheritance: A class can inherit from multiple classes. ES6 doesn’t support multiple inheritance."
},
{
"code": null,
"e": 2654,
"s": 2545,
"text": "Multi-level Inheritance: A class can inherit from another class (via) which inherit from the parent class. "
},
{
"code": null,
"e": 2744,
"s": 2654,
"text": "class Child extends Root\nclass Leaf extends Child \n// So the leaf extends root indirectly"
},
{
"code": null,
"e": 2825,
"s": 2744,
"text": "Super Keyword: This keyword helps child class to invoke the parent class data. "
},
{
"code": null,
"e": 2838,
"s": 2825,
"text": "super.object"
},
{
"code": null,
"e": 2849,
"s": 2838,
"text": "Example: "
},
{
"code": null,
"e": 2860,
"s": 2849,
"text": "JavaScript"
},
{
"code": "<script>class GeeksforGeeks { doPrint() { console.log(\"This doPrint() from Parent called.\") }} class gfg extends GeeksforGeeks { doPrint() { super.doPrint() console.log(\"This doPrint() is printing a string.\") }}var obj = new gfg()obj.doPrint()</script>",
"e": 3136,
"s": 2860,
"text": null
},
{
"code": null,
"e": 3146,
"s": 3136,
"text": "Output: "
},
{
"code": null,
"e": 3218,
"s": 3146,
"text": "This doPrint() from Parent called.\nThis doPrint() is printing a string."
},
{
"code": null,
"e": 3237,
"s": 3220,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3246,
"s": 3237,
"text": "rkbhola5"
},
{
"code": null,
"e": 3250,
"s": 3246,
"text": "ES6"
},
{
"code": null,
"e": 3257,
"s": 3250,
"text": "Picked"
},
{
"code": null,
"e": 3268,
"s": 3257,
"text": "JavaScript"
},
{
"code": null,
"e": 3285,
"s": 3268,
"text": "Web Technologies"
}
] |
Java Program to Rename a File
|
09 Nov, 2020
Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java.
A. renameTo() Method
The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false.
Approach
Create an object of the File class and replace the file path with the path of the directory.Create another object of the File class and replace the file path with the renaming path of the directory.Use renameTo() method.If rename operation successful then the function returns true.Else returns false.
Create an object of the File class and replace the file path with the path of the directory.
Create another object of the File class and replace the file path with the renaming path of the directory.
Use renameTo() method.
If rename operation successful then the function returns true.
Else returns false.
Below is the implementation of the above approach.
Java
// Java Program to rename a fileimport java.io.File;public class GFG { public static void main(String[] args) { // Create an object of the File class // Replace the file path with path of the directory File file = new File("/home/mayur/Folder/GFG.java"); // Create an object of the File class // Replace the file path with path of the directory File rename = new File("/home/mayur/Folder/HelloWorld.java"); // store the return value of renameTo() method in // flag boolean flag = file.renameTo(rename); // if renameTo() return true then if block is // executed if (flag == true) { System.out.println("File Successfully Rename"); } // if renameTo() return false then else block is // executed else { System.out.println("Operation Failed"); } }}
Output:
File Successfully Rename
Before Program Execution
After Program Execution
B. move() Method
Rename of file can be done using move the contents of the first file to a new file and deleting the previous file. Java is handling this operation using resolveSibiling method. It is used to resolve the given path against this path’s parent path
Java
// Java Program to rename a fileimport java.nio.file.*;import java.io.IOException; public class GFG { public static void main(String[] args) throws IOException { Path oldFile = Paths.get("/home/mayur/Folder/GFG.java"); try { Files.move(oldFile, oldFile.resolveSibling( "HelloWorld.java")); System.out.println("File Successfully Rename"); } catch (IOException e) { System.out.println("operation failed"); } }}
Output:
File Successfully Rename
Before Program Execution
After Program Execution
Java-Files
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Nov, 2020"
},
{
"code": null,
"e": 203,
"s": 54,
"text": "Changing the name of the file is known as Renaming the file. Rename operation is possible using renameTo() method belongs to the File class in java."
},
{
"code": null,
"e": 224,
"s": 203,
"text": "A. renameTo() Method"
},
{
"code": null,
"e": 413,
"s": 224,
"text": "The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false."
},
{
"code": null,
"e": 422,
"s": 413,
"text": "Approach"
},
{
"code": null,
"e": 724,
"s": 422,
"text": "Create an object of the File class and replace the file path with the path of the directory.Create another object of the File class and replace the file path with the renaming path of the directory.Use renameTo() method.If rename operation successful then the function returns true.Else returns false."
},
{
"code": null,
"e": 817,
"s": 724,
"text": "Create an object of the File class and replace the file path with the path of the directory."
},
{
"code": null,
"e": 924,
"s": 817,
"text": "Create another object of the File class and replace the file path with the renaming path of the directory."
},
{
"code": null,
"e": 947,
"s": 924,
"text": "Use renameTo() method."
},
{
"code": null,
"e": 1010,
"s": 947,
"text": "If rename operation successful then the function returns true."
},
{
"code": null,
"e": 1030,
"s": 1010,
"text": "Else returns false."
},
{
"code": null,
"e": 1081,
"s": 1030,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1086,
"s": 1081,
"text": "Java"
},
{
"code": "// Java Program to rename a fileimport java.io.File;public class GFG { public static void main(String[] args) { // Create an object of the File class // Replace the file path with path of the directory File file = new File(\"/home/mayur/Folder/GFG.java\"); // Create an object of the File class // Replace the file path with path of the directory File rename = new File(\"/home/mayur/Folder/HelloWorld.java\"); // store the return value of renameTo() method in // flag boolean flag = file.renameTo(rename); // if renameTo() return true then if block is // executed if (flag == true) { System.out.println(\"File Successfully Rename\"); } // if renameTo() return false then else block is // executed else { System.out.println(\"Operation Failed\"); } }}",
"e": 1986,
"s": 1086,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1986,
"text": "Output:"
},
{
"code": null,
"e": 2019,
"s": 1994,
"text": "File Successfully Rename"
},
{
"code": null,
"e": 2044,
"s": 2019,
"text": "Before Program Execution"
},
{
"code": null,
"e": 2068,
"s": 2044,
"text": "After Program Execution"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "B. move() Method"
},
{
"code": null,
"e": 2331,
"s": 2085,
"text": "Rename of file can be done using move the contents of the first file to a new file and deleting the previous file. Java is handling this operation using resolveSibiling method. It is used to resolve the given path against this path’s parent path"
},
{
"code": null,
"e": 2336,
"s": 2331,
"text": "Java"
},
{
"code": "// Java Program to rename a fileimport java.nio.file.*;import java.io.IOException; public class GFG { public static void main(String[] args) throws IOException { Path oldFile = Paths.get(\"/home/mayur/Folder/GFG.java\"); try { Files.move(oldFile, oldFile.resolveSibling( \"HelloWorld.java\")); System.out.println(\"File Successfully Rename\"); } catch (IOException e) { System.out.println(\"operation failed\"); } }}",
"e": 2880,
"s": 2336,
"text": null
},
{
"code": null,
"e": 2888,
"s": 2880,
"text": "Output:"
},
{
"code": null,
"e": 2913,
"s": 2888,
"text": "File Successfully Rename"
},
{
"code": null,
"e": 2938,
"s": 2913,
"text": "Before Program Execution"
},
{
"code": null,
"e": 2962,
"s": 2938,
"text": "After Program Execution"
},
{
"code": null,
"e": 2973,
"s": 2962,
"text": "Java-Files"
},
{
"code": null,
"e": 2997,
"s": 2973,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3002,
"s": 2997,
"text": "Java"
},
{
"code": null,
"e": 3016,
"s": 3002,
"text": "Java Programs"
},
{
"code": null,
"e": 3035,
"s": 3016,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3040,
"s": 3035,
"text": "Java"
}
] |
Package getImplementationVersion() method in Java with Examples
|
25 Jan, 2022
The getImplementationVersion() method of java.lang.Package class is used to get the version of the implementation of this package. The method returns the implementation version of the package as a String.Syntax:
public String getImplementationVersion()
Parameter: This method does not accept any parameter.Return Value: This method returns the implementation version of the package as a String, if known. Else it returns nullBelow programs demonstrate the getImplementationVersion() method.Example 1:
Java
// Java program to demonstrate// getImplementationVersion() method public class Test { public static void main(String[] args) { // returns the Package object // for this package Package myPackage = Package.getPackage("java.lang"); System.out.println( "Package represented by myPackage: " + myPackage.toString()); // Get the implementation version of myPackage // using getImplementationVersion() method System.out.println( "Implementation version of myPackage: " + myPackage.getImplementationVersion()); }}
Package represented by myPackage: package java.lang, Java Platform API Specification, version 1.8
Implementation version of myPackage: 1.8.0_181
Example 2:
Java
// Java program to demonstrate// getImplementationVersion() method public class Test { public static void main(String[] args) { // returns the Package object // for this package Package myPackage = Package.getPackage("java.io"); System.out.println( "Package represented by myPackage: " + myPackage.toString()); // Get the name of myPackage // using getImplementationVersion() method System.out.println( "Implementation version of myPackage: " + myPackage.getImplementationVersion()); }}
Package represented by myPackage: package java.io, Java Platform API Specification, version 1.8
Implementation version of myPackage: 1.8.0_181
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Package.html#getImplementationVersion–
adnanirshad158
Java-Functions
Java-lang package
java.lang.Package Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "The getImplementationVersion() method of java.lang.Package class is used to get the version of the implementation of this package. The method returns the implementation version of the package as a String.Syntax: "
},
{
"code": null,
"e": 283,
"s": 242,
"text": "public String getImplementationVersion()"
},
{
"code": null,
"e": 532,
"s": 283,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the implementation version of the package as a String, if known. Else it returns nullBelow programs demonstrate the getImplementationVersion() method.Example 1: "
},
{
"code": null,
"e": 537,
"s": 532,
"text": "Java"
},
{
"code": "// Java program to demonstrate// getImplementationVersion() method public class Test { public static void main(String[] args) { // returns the Package object // for this package Package myPackage = Package.getPackage(\"java.lang\"); System.out.println( \"Package represented by myPackage: \" + myPackage.toString()); // Get the implementation version of myPackage // using getImplementationVersion() method System.out.println( \"Implementation version of myPackage: \" + myPackage.getImplementationVersion()); }}",
"e": 1160,
"s": 537,
"text": null
},
{
"code": null,
"e": 1305,
"s": 1160,
"text": "Package represented by myPackage: package java.lang, Java Platform API Specification, version 1.8\nImplementation version of myPackage: 1.8.0_181"
},
{
"code": null,
"e": 1319,
"s": 1307,
"text": "Example 2: "
},
{
"code": null,
"e": 1324,
"s": 1319,
"text": "Java"
},
{
"code": "// Java program to demonstrate// getImplementationVersion() method public class Test { public static void main(String[] args) { // returns the Package object // for this package Package myPackage = Package.getPackage(\"java.io\"); System.out.println( \"Package represented by myPackage: \" + myPackage.toString()); // Get the name of myPackage // using getImplementationVersion() method System.out.println( \"Implementation version of myPackage: \" + myPackage.getImplementationVersion()); }}",
"e": 1927,
"s": 1324,
"text": null
},
{
"code": null,
"e": 2070,
"s": 1927,
"text": "Package represented by myPackage: package java.io, Java Platform API Specification, version 1.8\nImplementation version of myPackage: 1.8.0_181"
},
{
"code": null,
"e": 2175,
"s": 2072,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Package.html#getImplementationVersion– "
},
{
"code": null,
"e": 2190,
"s": 2175,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2205,
"s": 2190,
"text": "Java-Functions"
},
{
"code": null,
"e": 2223,
"s": 2205,
"text": "Java-lang package"
},
{
"code": null,
"e": 2247,
"s": 2223,
"text": "java.lang.Package Class"
},
{
"code": null,
"e": 2252,
"s": 2247,
"text": "Java"
},
{
"code": null,
"e": 2257,
"s": 2252,
"text": "Java"
}
] |
Local Classes in C++
|
16 Nov, 2021
A class declared inside a function becomes local to that function and is called Local Class in C++.
A local class name can only be used locally i.e., inside the function and not outside it.
The methods of a local class must be defined inside it only.
A local class can have static functions but, not static data members.
For example, in the following program, Test is a local class in fun().
CPP
// C++ program without any compilation error// to demonstrate a Local Class#include <iostream>using namespace std; // Creating the classvoid fun(){ // local to fun class Test { // members of Test class };} // Driver Codeint main() { return 0; }
1) A local class type name can only be used in the enclosing function.
For example, in the following program, declarations of t and tp are valid in fun(), but invalid in main().
CPP
// A program without any compilation error to demonstrate// that a local class type name can only be used// in the enclosing function #include <iostream>using namespace std; void fun(){ // Local class class Test { // Body }; Test t; // Fine Test* tp; // Fine} int main(){ Test t; // Error Test* tp; // Error return 0;}
2) All the methods of Local classes must be defined inside the class only. For example, program 1 works fine and program 2 fails in the compilation.
Program 1:
CPP
// C++ program without any compilation error to demonstrate// that all the methods of Local classes must be defined// inside the class only#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: // Fine as the method is defined // inside the local class void method() { cout << "Local Class method() called"; } }; Test t; t.method();} int main(){ fun(); return 0;}
Local Class method() called
Program 2:
CPP
// C++ program with compilation error to demonstrate that// all the methods of Local classes must be defined inside// the class only#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: void method(); }; // Error as the method is defined outside the local // class void Test::method() { cout << "Local Class method()"; }} int main() { return 0; }
Output
Compiler Error:
In function 'void fun()':
error: a function-definition is not allowed here before '{' token
3) A Local class cannot contain static data members. It may contain static functions though. For example, program 1 fails in compilation, but program 2 works fine.
Program 1:
CPP
// A program with compilation error to demonstrate that// a Local class cannot contain static data members#include <iostream>using namespace std; void fun(){ class Test // local to fun { static int i; };} int main() { return 0; }
Output
Compiler Error:
In function 'void fun()':
error: local class 'class fun()::Test' shall not have static data member 'int fun()::Test::i'
Program 2:
CPP
// C++ program without any compilation error to demonstrate// that a Local class cannot contain static data members#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: static void method() { cout << "Local Class method() called"; } }; Test::method();} int main(){ fun(); return 0;}
Local Class method() called
4) Member methods of the local class can only access static and enum variables of the enclosing function. Non-static variables of the enclosing function are not accessible inside local classes. For example, program 1 compiles and runs fine. But, program 2 fails in the compilation.
Program 1:
CPP
// C++ program without any compilation error to demonstrate// that member methods of local class can only access static// and enum variables of the enclosing function#include <iostream>using namespace std; void fun(){ static int x; enum { i = 1, j = 2 }; // Local class class Test { public: void method() { cout << "x = " << x << endl; // fine as x is static cout << "i = " << i << endl; // fine as i is enum } }; Test t; t.method();} int main(){ fun(); return 0;}
x = 0
i = 1
Program 2:
CPP
// C++ program with compilation error to demonstrate that// member methods of local class can only access static// and enum variables of the enclosing function#include <iostream>using namespace std; void fun(){ int x; // Local class class Test { public: void method() { cout << "x = " << x << endl; } }; Test t; t.method();} int main(){ fun(); return 0;}
Error:
prog.cpp: In member function ‘void fun()::Test::method()’:
prog.cpp:14:43: error: use of local variable with automatic storage from containing function
void method() { cout << “x = ” << x << endl; }
^
prog.cpp:9:9: note: ‘int x’ declared here
int x;
^
5) Local classes can access global types, variables, and functions. Also, local classes can access other local classes of the same function. For example, the following program works fine.
CPP
// C++ program without any compilation error to demonstrate// that Local classes can access global types, variables and// functions#include <iostream>using namespace std; int x; void fun(){ // First Local class class Test1 { public: Test1() { cout << "Test1::Test1()" << endl; } }; // Second Local class class Test2 { // Fine: A local class can use other local classes // of same function Test1 t1; public: void method() { // Fine: Local class member methods can access // global variables. cout << "x = " << x << endl; } }; Test2 t; t.method();} int main(){ fun(); return 0;}
Test1::Test1()
x = 0
Must Read: Nested Classes in C++
anshikajain26
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "A class declared inside a function becomes local to that function and is called Local Class in C++."
},
{
"code": null,
"e": 244,
"s": 154,
"text": "A local class name can only be used locally i.e., inside the function and not outside it."
},
{
"code": null,
"e": 305,
"s": 244,
"text": "The methods of a local class must be defined inside it only."
},
{
"code": null,
"e": 375,
"s": 305,
"text": "A local class can have static functions but, not static data members."
},
{
"code": null,
"e": 447,
"s": 375,
"text": "For example, in the following program, Test is a local class in fun(). "
},
{
"code": null,
"e": 451,
"s": 447,
"text": "CPP"
},
{
"code": "// C++ program without any compilation error// to demonstrate a Local Class#include <iostream>using namespace std; // Creating the classvoid fun(){ // local to fun class Test { // members of Test class };} // Driver Codeint main() { return 0; }",
"e": 714,
"s": 451,
"text": null
},
{
"code": null,
"e": 785,
"s": 714,
"text": "1) A local class type name can only be used in the enclosing function."
},
{
"code": null,
"e": 893,
"s": 785,
"text": "For example, in the following program, declarations of t and tp are valid in fun(), but invalid in main(). "
},
{
"code": null,
"e": 897,
"s": 893,
"text": "CPP"
},
{
"code": "// A program without any compilation error to demonstrate// that a local class type name can only be used// in the enclosing function #include <iostream>using namespace std; void fun(){ // Local class class Test { // Body }; Test t; // Fine Test* tp; // Fine} int main(){ Test t; // Error Test* tp; // Error return 0;}",
"e": 1252,
"s": 897,
"text": null
},
{
"code": null,
"e": 1401,
"s": 1252,
"text": "2) All the methods of Local classes must be defined inside the class only. For example, program 1 works fine and program 2 fails in the compilation."
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": "Program 1:"
},
{
"code": null,
"e": 1416,
"s": 1412,
"text": "CPP"
},
{
"code": "// C++ program without any compilation error to demonstrate// that all the methods of Local classes must be defined// inside the class only#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: // Fine as the method is defined // inside the local class void method() { cout << \"Local Class method() called\"; } }; Test t; t.method();} int main(){ fun(); return 0;}",
"e": 1888,
"s": 1416,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1888,
"text": "Local Class method() called"
},
{
"code": null,
"e": 1927,
"s": 1916,
"text": "Program 2:"
},
{
"code": null,
"e": 1931,
"s": 1927,
"text": "CPP"
},
{
"code": "// C++ program with compilation error to demonstrate that// all the methods of Local classes must be defined inside// the class only#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: void method(); }; // Error as the method is defined outside the local // class void Test::method() { cout << \"Local Class method()\"; }} int main() { return 0; }",
"e": 2345,
"s": 1931,
"text": null
},
{
"code": null,
"e": 2353,
"s": 2345,
"text": "Output "
},
{
"code": null,
"e": 2463,
"s": 2353,
"text": "Compiler Error:\n In function 'void fun()':\n error: a function-definition is not allowed here before '{' token"
},
{
"code": null,
"e": 2628,
"s": 2463,
"text": "3) A Local class cannot contain static data members. It may contain static functions though. For example, program 1 fails in compilation, but program 2 works fine. "
},
{
"code": null,
"e": 2639,
"s": 2628,
"text": "Program 1:"
},
{
"code": null,
"e": 2643,
"s": 2639,
"text": "CPP"
},
{
"code": "// A program with compilation error to demonstrate that// a Local class cannot contain static data members#include <iostream>using namespace std; void fun(){ class Test // local to fun { static int i; };} int main() { return 0; }",
"e": 2891,
"s": 2643,
"text": null
},
{
"code": null,
"e": 2898,
"s": 2891,
"text": "Output"
},
{
"code": null,
"e": 3036,
"s": 2898,
"text": "Compiler Error:\n In function 'void fun()':\n error: local class 'class fun()::Test' shall not have static data member 'int fun()::Test::i'"
},
{
"code": null,
"e": 3047,
"s": 3036,
"text": "Program 2:"
},
{
"code": null,
"e": 3051,
"s": 3047,
"text": "CPP"
},
{
"code": "// C++ program without any compilation error to demonstrate// that a Local class cannot contain static data members#include <iostream>using namespace std; void fun(){ class Test // local to fun { public: static void method() { cout << \"Local Class method() called\"; } }; Test::method();} int main(){ fun(); return 0;}",
"e": 3426,
"s": 3051,
"text": null
},
{
"code": null,
"e": 3454,
"s": 3426,
"text": "Local Class method() called"
},
{
"code": null,
"e": 3736,
"s": 3454,
"text": "4) Member methods of the local class can only access static and enum variables of the enclosing function. Non-static variables of the enclosing function are not accessible inside local classes. For example, program 1 compiles and runs fine. But, program 2 fails in the compilation."
},
{
"code": null,
"e": 3747,
"s": 3736,
"text": "Program 1:"
},
{
"code": null,
"e": 3751,
"s": 3747,
"text": "CPP"
},
{
"code": "// C++ program without any compilation error to demonstrate// that member methods of local class can only access static// and enum variables of the enclosing function#include <iostream>using namespace std; void fun(){ static int x; enum { i = 1, j = 2 }; // Local class class Test { public: void method() { cout << \"x = \" << x << endl; // fine as x is static cout << \"i = \" << i << endl; // fine as i is enum } }; Test t; t.method();} int main(){ fun(); return 0;}",
"e": 4327,
"s": 3751,
"text": null
},
{
"code": null,
"e": 4339,
"s": 4327,
"text": "x = 0\ni = 1"
},
{
"code": null,
"e": 4350,
"s": 4339,
"text": "Program 2:"
},
{
"code": null,
"e": 4354,
"s": 4350,
"text": "CPP"
},
{
"code": "// C++ program with compilation error to demonstrate that// member methods of local class can only access static// and enum variables of the enclosing function#include <iostream>using namespace std; void fun(){ int x; // Local class class Test { public: void method() { cout << \"x = \" << x << endl; } }; Test t; t.method();} int main(){ fun(); return 0;}",
"e": 4749,
"s": 4354,
"text": null
},
{
"code": null,
"e": 4756,
"s": 4749,
"text": "Error:"
},
{
"code": null,
"e": 4815,
"s": 4756,
"text": "prog.cpp: In member function ‘void fun()::Test::method()’:"
},
{
"code": null,
"e": 4908,
"s": 4815,
"text": "prog.cpp:14:43: error: use of local variable with automatic storage from containing function"
},
{
"code": null,
"e": 4964,
"s": 4908,
"text": " void method() { cout << “x = ” << x << endl; }"
},
{
"code": null,
"e": 5009,
"s": 4964,
"text": " ^"
},
{
"code": null,
"e": 5051,
"s": 5009,
"text": "prog.cpp:9:9: note: ‘int x’ declared here"
},
{
"code": null,
"e": 5063,
"s": 5051,
"text": " int x;"
},
{
"code": null,
"e": 5074,
"s": 5063,
"text": " ^"
},
{
"code": null,
"e": 5263,
"s": 5074,
"text": "5) Local classes can access global types, variables, and functions. Also, local classes can access other local classes of the same function. For example, the following program works fine. "
},
{
"code": null,
"e": 5267,
"s": 5263,
"text": "CPP"
},
{
"code": "// C++ program without any compilation error to demonstrate// that Local classes can access global types, variables and// functions#include <iostream>using namespace std; int x; void fun(){ // First Local class class Test1 { public: Test1() { cout << \"Test1::Test1()\" << endl; } }; // Second Local class class Test2 { // Fine: A local class can use other local classes // of same function Test1 t1; public: void method() { // Fine: Local class member methods can access // global variables. cout << \"x = \" << x << endl; } }; Test2 t; t.method();} int main(){ fun(); return 0;}",
"e": 5973,
"s": 5267,
"text": null
},
{
"code": null,
"e": 5994,
"s": 5973,
"text": "Test1::Test1()\nx = 0"
},
{
"code": null,
"e": 6027,
"s": 5994,
"text": "Must Read: Nested Classes in C++"
},
{
"code": null,
"e": 6041,
"s": 6027,
"text": "anshikajain26"
},
{
"code": null,
"e": 6045,
"s": 6041,
"text": "C++"
},
{
"code": null,
"e": 6049,
"s": 6045,
"text": "CPP"
}
] |
Number of common tangents between two circles if their centers and radius is given
|
30 May, 2022
Given two circles with a given radius and centers. The task is to find the number of common tangents between these circles.Examples:
Input: x1 = -10, y1 = 8, x2 = 14, y2 = -24, r1 = 30, r2 = 10
Output: 3
Input: x1 = 40, y1 = 8, x2 = 14, y2 = 54, r1 = 39, r2 = 51
Output: 2
Approach:
First of all we will check whether the circles touch each other externally, intersect each other or do not touch each other at all.(Please refer here)
Then if the circles do not touch each other externally, then obviously they will have 4 common tangents, two direct and two transverse.
If the circles touch each other externally, then they will have 3 common tangents, two direct and one transverse. The tangent in between can be thought of as the transverse tangents coinciding together.
If the circles intersect each other, then they will have 2 common tangents, both of them will be direct.
If one circle is inside another circle, then they will have only one common tangent.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find// the number of common tangents// between the two circles #include <bits/stdc++.h>using namespace std; int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codeint main(){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) cout << "There are 3 common tangents" << " between the circles."; else if (t < 0) cout << "There are 4 common tangents" << " between the circles."; else cout << "There are 2 common tangents" << " between the circles."; return 0;}
// Java program to find// the number of common tangents// between the two circlesimport java.io.*; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codepublic static void main (String[] args){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) System.out.println ("There are 3 common tangents"+ " between the circles."); else if (t < 0) System.out.println ("There are 4 common tangents"+ " between the circles."); else System.out.println ("There are 2 common tangents" + " between the circles."); }} // This code is contributed by ajit.
# Python3 program to find# the number of common tangents# between the two circles def circle(x1, y1, x2,y2, r1, r2): distSq = (x1 - x2) * (x1 - x2)+ (y1 - y2) * (y1 - y2) radSumSq = (r1 + r2) * (r1 + r2) if (distSq == radSumSq): return 1 elif (distSq > radSumSq): return -1 else: return 0 # Driver codex1,y1 = -10,8;x2,y2 = 14,-24;r1,r2 = 30,10; t = circle(x1, y1, x2,y2, r1, r2); if (t == 1): print("There are 3 common tangents between the circles.")elif (t < 0): print("There are 4 common tangents between the circles.")else: print("There are 2 common tangents between the circles.") # This code is contributed by mohit kumar 29
// C# program to find// the number of common tangents// between the two circlesusing System; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codepublic static void Main (String []args){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) Console.WriteLine ("There are 3 common tangents"+ " between the circles."); else if (t < 0) Console.WriteLine ("There are 4 common tangents"+ " between the circles."); else Console.WriteLine ("There are 2 common tangents" + " between the circles."); }} // This code is contributed by Arnab Kundu
<?php// PHP program to find// the number of common tangents// between the two circles function circle($x1, $y1, $x2, $y2, $r1, $r2){ $distSq = ($x1 - $x2) * ($x1 - $x2) + ($y1 - $y2) * ($y1 - $y2); $radSumSq = ($r1 + $r2) * ($r1 + $r2); if ($distSq == $radSumSq) return 1; else if ($distSq > $radSumSq) return -1; else return 0;} // Driver code $x1 = -10; $y1 = 8; $x2 = 14; $y2 = -24; $r1 = 30; $r2 = 10; $t = circle($x1, $y1, $x2, $y2, $r1, $r2); if ($t == 1) echo "There are 3 common tangents" ," between the circles."; else if ($t < 0) echo "There are 4 common tangents" , " between the circles."; else echo "There are 2 common tangents" , " between the circles."; // This code is contributed by AnkitRai01?>
<script> // Javascript program to find// the number of common tangents// between the two circles function circle(x1, y1, x2, y2, r1, r2){ var distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); var radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver code var x1 = -10, y1 = 8; var x2 = 14, y2 = -24; var r1 = 30, r2 = 10; var t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) document.write("There are 3 common tangents between the circles."); else if (t < 0) document.write("There are 4 common tangents between the circles."); else document.write("There are 2 common tangents between the circles."); </script>
Output:
There are 3 common tangents between the circles.
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
jit_t
andrew1234
bgangwar59
ManasChhabra2
souravkumar29
circle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 163,
"s": 28,
"text": "Given two circles with a given radius and centers. The task is to find the number of common tangents between these circles.Examples: "
},
{
"code": null,
"e": 304,
"s": 163,
"text": "Input: x1 = -10, y1 = 8, x2 = 14, y2 = -24, r1 = 30, r2 = 10\nOutput: 3\n\nInput: x1 = 40, y1 = 8, x2 = 14, y2 = 54, r1 = 39, r2 = 51\nOutput: 2"
},
{
"code": null,
"e": 316,
"s": 304,
"text": "Approach: "
},
{
"code": null,
"e": 467,
"s": 316,
"text": "First of all we will check whether the circles touch each other externally, intersect each other or do not touch each other at all.(Please refer here)"
},
{
"code": null,
"e": 603,
"s": 467,
"text": "Then if the circles do not touch each other externally, then obviously they will have 4 common tangents, two direct and two transverse."
},
{
"code": null,
"e": 806,
"s": 603,
"text": "If the circles touch each other externally, then they will have 3 common tangents, two direct and one transverse. The tangent in between can be thought of as the transverse tangents coinciding together."
},
{
"code": null,
"e": 912,
"s": 806,
"text": "If the circles intersect each other, then they will have 2 common tangents, both of them will be direct. "
},
{
"code": null,
"e": 999,
"s": 914,
"text": "If one circle is inside another circle, then they will have only one common tangent."
},
{
"code": null,
"e": 1050,
"s": 999,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1054,
"s": 1050,
"text": "C++"
},
{
"code": null,
"e": 1059,
"s": 1054,
"text": "Java"
},
{
"code": null,
"e": 1067,
"s": 1059,
"text": "Python3"
},
{
"code": null,
"e": 1070,
"s": 1067,
"text": "C#"
},
{
"code": null,
"e": 1074,
"s": 1070,
"text": "PHP"
},
{
"code": null,
"e": 1085,
"s": 1074,
"text": "Javascript"
},
{
"code": "// C++ program to find// the number of common tangents// between the two circles #include <bits/stdc++.h>using namespace std; int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codeint main(){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) cout << \"There are 3 common tangents\" << \" between the circles.\"; else if (t < 0) cout << \"There are 4 common tangents\" << \" between the circles.\"; else cout << \"There are 2 common tangents\" << \" between the circles.\"; return 0;}",
"e": 1988,
"s": 1085,
"text": null
},
{
"code": "// Java program to find// the number of common tangents// between the two circlesimport java.io.*; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codepublic static void main (String[] args){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) System.out.println (\"There are 3 common tangents\"+ \" between the circles.\"); else if (t < 0) System.out.println (\"There are 4 common tangents\"+ \" between the circles.\"); else System.out.println (\"There are 2 common tangents\" + \" between the circles.\"); }} // This code is contributed by ajit.",
"e": 2992,
"s": 1988,
"text": null
},
{
"code": "# Python3 program to find# the number of common tangents# between the two circles def circle(x1, y1, x2,y2, r1, r2): distSq = (x1 - x2) * (x1 - x2)+ (y1 - y2) * (y1 - y2) radSumSq = (r1 + r2) * (r1 + r2) if (distSq == radSumSq): return 1 elif (distSq > radSumSq): return -1 else: return 0 # Driver codex1,y1 = -10,8;x2,y2 = 14,-24;r1,r2 = 30,10; t = circle(x1, y1, x2,y2, r1, r2); if (t == 1): print(\"There are 3 common tangents between the circles.\")elif (t < 0): print(\"There are 4 common tangents between the circles.\")else: print(\"There are 2 common tangents between the circles.\") # This code is contributed by mohit kumar 29",
"e": 3673,
"s": 2992,
"text": null
},
{
"code": "// C# program to find// the number of common tangents// between the two circlesusing System; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codepublic static void Main (String []args){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) Console.WriteLine (\"There are 3 common tangents\"+ \" between the circles.\"); else if (t < 0) Console.WriteLine (\"There are 4 common tangents\"+ \" between the circles.\"); else Console.WriteLine (\"There are 2 common tangents\" + \" between the circles.\"); }} // This code is contributed by Arnab Kundu",
"e": 4669,
"s": 3673,
"text": null
},
{
"code": "<?php// PHP program to find// the number of common tangents// between the two circles function circle($x1, $y1, $x2, $y2, $r1, $r2){ $distSq = ($x1 - $x2) * ($x1 - $x2) + ($y1 - $y2) * ($y1 - $y2); $radSumSq = ($r1 + $r2) * ($r1 + $r2); if ($distSq == $radSumSq) return 1; else if ($distSq > $radSumSq) return -1; else return 0;} // Driver code $x1 = -10; $y1 = 8; $x2 = 14; $y2 = -24; $r1 = 30; $r2 = 10; $t = circle($x1, $y1, $x2, $y2, $r1, $r2); if ($t == 1) echo \"There are 3 common tangents\" ,\" between the circles.\"; else if ($t < 0) echo \"There are 4 common tangents\" , \" between the circles.\"; else echo \"There are 2 common tangents\" , \" between the circles.\"; // This code is contributed by AnkitRai01?>",
"e": 5557,
"s": 4669,
"text": null
},
{
"code": "<script> // Javascript program to find// the number of common tangents// between the two circles function circle(x1, y1, x2, y2, r1, r2){ var distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); var radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver code var x1 = -10, y1 = 8; var x2 = 14, y2 = -24; var r1 = 30, r2 = 10; var t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) document.write(\"There are 3 common tangents between the circles.\"); else if (t < 0) document.write(\"There are 4 common tangents between the circles.\"); else document.write(\"There are 2 common tangents between the circles.\"); </script>",
"e": 6369,
"s": 5557,
"text": null
},
{
"code": null,
"e": 6377,
"s": 6369,
"text": "Output:"
},
{
"code": null,
"e": 6426,
"s": 6377,
"text": "There are 3 common tangents between the circles."
},
{
"code": null,
"e": 6448,
"s": 6426,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 6470,
"s": 6448,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6485,
"s": 6470,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 6493,
"s": 6485,
"text": "ankthon"
},
{
"code": null,
"e": 6499,
"s": 6493,
"text": "jit_t"
},
{
"code": null,
"e": 6510,
"s": 6499,
"text": "andrew1234"
},
{
"code": null,
"e": 6521,
"s": 6510,
"text": "bgangwar59"
},
{
"code": null,
"e": 6535,
"s": 6521,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 6549,
"s": 6535,
"text": "souravkumar29"
},
{
"code": null,
"e": 6556,
"s": 6549,
"text": "circle"
},
{
"code": null,
"e": 6566,
"s": 6556,
"text": "Geometric"
},
{
"code": null,
"e": 6579,
"s": 6566,
"text": "Mathematical"
},
{
"code": null,
"e": 6592,
"s": 6579,
"text": "Mathematical"
},
{
"code": null,
"e": 6602,
"s": 6592,
"text": "Geometric"
}
] |
Luhn algorithm
|
26 May, 2021
The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, Canadian Social Insurance Numbers. The LUHN formula was created in the late 1960s by a group of mathematicians. Shortly thereafter, credit card companies adopted it. Because the algorithm is in the public domain, it can be used by anyone. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. It was designed to protect against accidental errors, not malicious attacks.
Let’s understand the algorithm with an example: Consider the example of an account number “79927398713“. Step 1 – Starting from the rightmost digit, double the value of every second digit,
Step 2 – If doubling of a number results in a two digit number i.e greater than 9(e.g., 6 × 2 = 12), then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), to get a single digit number.
Step 3 – Now take the sum of all the digits.
Step 4 – If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
Since the sum is 70 which is a multiple of 10, the account number is possibly valid.
The idea is simple; we traverse from the end. For every second digit, we double it before adding it. We add two digits of the number obtained after doubling.
C++
Java
Python3
C#
Javascript
// C++ program to implement Luhn algorithm#include <bits/stdc++.h>using namespace std; // Returns true if given card number is validbool checkLuhn(const string& cardNo){ int nDigits = cardNo.length(); int nSum = 0, isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo[i] - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits after // doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver codeint main(){ string cardNo = "79927398713"; if (checkLuhn(cardNo)) printf("This is a valid card"); else printf("This is not a valid card"); return 0;}
// Java program to implement// Luhn algorithmimport java.io.*; class GFG { // Returns true if given// card number is validstatic boolean checkLuhn(String cardNo){ int nDigits = cardNo.length(); int nSum = 0; boolean isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo.charAt(i) - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver code static public void main (String[] args) { String cardNo = "79927398713"; if (checkLuhn(cardNo)) System.out.println("This is a valid card"); else System.out.println("This is not a valid card"); }} // This Code is contributed by vt_m.
# Python3 program to implement# Luhn algorithm # Returns true if given card# number is validdef checkLuhn(cardNo): nDigits = len(cardNo) nSum = 0 isSecond = False for i in range(nDigits - 1, -1, -1): d = ord(cardNo[i]) - ord('0') if (isSecond == True): d = d * 2 # We add two digits to handle # cases that make two digits after # doubling nSum += d // 10 nSum += d % 10 isSecond = not isSecond if (nSum % 10 == 0): return True else: return False # Driver code if __name__=="__main__": cardNo = "79927398713" if (checkLuhn(cardNo)): print("This is a valid card") else: print("This is not a valid card") # This code is contributed by rutvik_56
// C# program to implement// Luhn algorithmusing System; class GFG { // Returns true if given// card number is validstatic bool checkLuhn(String cardNo){ int nDigits = cardNo.Length; int nSum = 0; bool isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo[i] - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver code static public void Main() { String cardNo = "79927398713"; if (checkLuhn(cardNo)) Console.WriteLine("This is a valid card"); else Console.WriteLine("This is not a valid card"); }} // This Code is contributed by vt_m.
<script> // Javascript program to implement Luhn algorithm // Returns true if given // card number is valid function checkLuhn(cardNo) { let nDigits = cardNo.length; let nSum = 0; let isSecond = false; for (let i = nDigits - 1; i >= 0; i--) { let d = cardNo[i].charCodeAt() - '0'.charCodeAt(); if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += parseInt(d / 10, 10); nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0); } let cardNo = "79927398713"; if (checkLuhn(cardNo)) document.write("This is a valid card"); else document.write("This is not a valid card"); </script>
Output:
This is a valid card
The Luhn algorithm detects any single-digit error, as well as almost all transpositions of adjacent digits.
This article is contributed by Vishal Kumar Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Shubham Bansal 13
networksofp
rutvik_56
suresh07
cryptography
Strings
Strings
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 742,
"s": 54,
"text": "The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, Canadian Social Insurance Numbers. The LUHN formula was created in the late 1960s by a group of mathematicians. Shortly thereafter, credit card companies adopted it. Because the algorithm is in the public domain, it can be used by anyone. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. It was designed to protect against accidental errors, not malicious attacks."
},
{
"code": null,
"e": 932,
"s": 742,
"text": "Let’s understand the algorithm with an example: Consider the example of an account number “79927398713“. Step 1 – Starting from the rightmost digit, double the value of every second digit, "
},
{
"code": null,
"e": 1137,
"s": 932,
"text": "Step 2 – If doubling of a number results in a two digit number i.e greater than 9(e.g., 6 × 2 = 12), then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), to get a single digit number. "
},
{
"code": null,
"e": 1182,
"s": 1137,
"text": "Step 3 – Now take the sum of all the digits."
},
{
"code": null,
"e": 1335,
"s": 1182,
"text": "Step 4 – If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid. "
},
{
"code": null,
"e": 1421,
"s": 1335,
"text": "Since the sum is 70 which is a multiple of 10, the account number is possibly valid. "
},
{
"code": null,
"e": 1581,
"s": 1421,
"text": "The idea is simple; we traverse from the end. For every second digit, we double it before adding it. We add two digits of the number obtained after doubling. "
},
{
"code": null,
"e": 1585,
"s": 1581,
"text": "C++"
},
{
"code": null,
"e": 1590,
"s": 1585,
"text": "Java"
},
{
"code": null,
"e": 1598,
"s": 1590,
"text": "Python3"
},
{
"code": null,
"e": 1601,
"s": 1598,
"text": "C#"
},
{
"code": null,
"e": 1612,
"s": 1601,
"text": "Javascript"
},
{
"code": "// C++ program to implement Luhn algorithm#include <bits/stdc++.h>using namespace std; // Returns true if given card number is validbool checkLuhn(const string& cardNo){ int nDigits = cardNo.length(); int nSum = 0, isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo[i] - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits after // doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver codeint main(){ string cardNo = \"79927398713\"; if (checkLuhn(cardNo)) printf(\"This is a valid card\"); else printf(\"This is not a valid card\"); return 0;}",
"e": 2382,
"s": 1612,
"text": null
},
{
"code": "// Java program to implement// Luhn algorithmimport java.io.*; class GFG { // Returns true if given// card number is validstatic boolean checkLuhn(String cardNo){ int nDigits = cardNo.length(); int nSum = 0; boolean isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo.charAt(i) - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver code static public void main (String[] args) { String cardNo = \"79927398713\"; if (checkLuhn(cardNo)) System.out.println(\"This is a valid card\"); else System.out.println(\"This is not a valid card\"); }} // This Code is contributed by vt_m.",
"e": 3289,
"s": 2382,
"text": null
},
{
"code": "# Python3 program to implement# Luhn algorithm # Returns true if given card# number is validdef checkLuhn(cardNo): nDigits = len(cardNo) nSum = 0 isSecond = False for i in range(nDigits - 1, -1, -1): d = ord(cardNo[i]) - ord('0') if (isSecond == True): d = d * 2 # We add two digits to handle # cases that make two digits after # doubling nSum += d // 10 nSum += d % 10 isSecond = not isSecond if (nSum % 10 == 0): return True else: return False # Driver code if __name__==\"__main__\": cardNo = \"79927398713\" if (checkLuhn(cardNo)): print(\"This is a valid card\") else: print(\"This is not a valid card\") # This code is contributed by rutvik_56",
"e": 4088,
"s": 3289,
"text": null
},
{
"code": "// C# program to implement// Luhn algorithmusing System; class GFG { // Returns true if given// card number is validstatic bool checkLuhn(String cardNo){ int nDigits = cardNo.Length; int nSum = 0; bool isSecond = false; for (int i = nDigits - 1; i >= 0; i--) { int d = cardNo[i] - '0'; if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += d / 10; nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0);} // Driver code static public void Main() { String cardNo = \"79927398713\"; if (checkLuhn(cardNo)) Console.WriteLine(\"This is a valid card\"); else Console.WriteLine(\"This is not a valid card\"); }} // This Code is contributed by vt_m.",
"e": 4959,
"s": 4088,
"text": null
},
{
"code": "<script> // Javascript program to implement Luhn algorithm // Returns true if given // card number is valid function checkLuhn(cardNo) { let nDigits = cardNo.length; let nSum = 0; let isSecond = false; for (let i = nDigits - 1; i >= 0; i--) { let d = cardNo[i].charCodeAt() - '0'.charCodeAt(); if (isSecond == true) d = d * 2; // We add two digits to handle // cases that make two digits // after doubling nSum += parseInt(d / 10, 10); nSum += d % 10; isSecond = !isSecond; } return (nSum % 10 == 0); } let cardNo = \"79927398713\"; if (checkLuhn(cardNo)) document.write(\"This is a valid card\"); else document.write(\"This is not a valid card\"); </script>",
"e": 5820,
"s": 4959,
"text": null
},
{
"code": null,
"e": 5829,
"s": 5820,
"text": "Output: "
},
{
"code": null,
"e": 5850,
"s": 5829,
"text": "This is a valid card"
},
{
"code": null,
"e": 5960,
"s": 5850,
"text": "The Luhn algorithm detects any single-digit error, as well as almost all transpositions of adjacent digits. "
},
{
"code": null,
"e": 6386,
"s": 5960,
"text": "This article is contributed by Vishal Kumar Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6391,
"s": 6386,
"text": "vt_m"
},
{
"code": null,
"e": 6409,
"s": 6391,
"text": "Shubham Bansal 13"
},
{
"code": null,
"e": 6421,
"s": 6409,
"text": "networksofp"
},
{
"code": null,
"e": 6431,
"s": 6421,
"text": "rutvik_56"
},
{
"code": null,
"e": 6440,
"s": 6431,
"text": "suresh07"
},
{
"code": null,
"e": 6453,
"s": 6440,
"text": "cryptography"
},
{
"code": null,
"e": 6461,
"s": 6453,
"text": "Strings"
},
{
"code": null,
"e": 6469,
"s": 6461,
"text": "Strings"
},
{
"code": null,
"e": 6482,
"s": 6469,
"text": "cryptography"
}
] |
Pattern searching | Practice | GeeksforGeeks
|
Given a string str and a pattern pat. You need to check whether pattern is present or not in the given string.
Input Format: The input line contains T, denoting the number of testcases. Each testcase contains two lines. First line contains string str. Second line contains patter text.
Output format: For each testcase in new line you have to print the "Present" if found otherwise "Not present".
User task: You need to complete the function searchPattern() containing string and text as an argument. You don't have to worry about input.
Constraints:
1 <= T <= 100
1 <= |str| <= 30
1 <= |text| <= 30
Sample Input:
2
abcdefh
bcd
axzy
xy
Sample Output:
Present
Not present
0
hrithikraina20011 week ago
int a= str.find(pat);
return a==-1?0:1;
0
luffysama11 month ago
bool searchPattern(string str, string pat){ // your code here // your code here int d = 256; int q = 101; int p = 0; int t = 0 ; int n = str.size(); int m = pat.size(); int i; int j; int h = 1; for(i = 0 ; i< m-1 ; i++){ h=(h*d)%q; } for(i = 0 ; i < m ; i++){ p = (d*p + pat[i])%q; t = (d*t + str[i])%q; } for(i = 0 ; i <= n-m ; i++){ if(p==t){ bool flag =true; for(j = 0 ; j < m ; j++){ if(str[i+j]!=pat[j]){ flag = false; break; } } if(j==m) return true; } if(i<n-m){ t = (d*(t-str[i]*h)+str[i+m])%q; if(t<0){ t+=q; } } } return false;}
0
luffysama11 month ago
Can anyone show using Rabin Karp algorithm?
0
ram210320011 month ago
bool searchPattern(string str, string pat){ // your code here int a=-1; a=str.find(pat); if(a!=-1) return 1; else return 0;}
0
pappukumarmat212 months ago
bool searchPattern(string str, string pat)
{
// your code here
if(strstr(str.c_str(),pat.c_str())){
return 1;
}
return false;
}
0
minturajmdb19993 months ago
bool searchPattern(string str, string pat){ int a=-1; a=str.find(pat); if(a!=-1) return 1; else return 0;}
0
ayushnautiyal11104 months ago
C++ IMPLEMENTATION :)
TIME 0.0/1.1
IF/ELSE CODE :)
😁😂😂😂😂😂😂😂😂😂😂😂😂😂😁
bool searchPattern(string str, string pat){ if(str.find(pat)==string::npos){ return false; } else{ return true; }}
0
praveen marandi4 months ago
Why is Node driver program typecasting it to number? When the desired output is a string>
0
moninmodi4 months ago
int m=str.length(); int n=pat.length(); int t[m+1][n+1]; for(int i=0;i<m+1;i++){ for(int j=0;j<n+1;j++){ if(i==0||j==0) t[i][j]=0; else{ if(str[i-1]==pat[j-1]){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=0; } } } } int max=0; for(int i=0;i<m+1;i++){ for(int j=0;j<n+1;j++){ if(t[i][j]>max){ max=t[i][j]; } } } if(max==n) return true; else return false;
0
kumarnitesh884414 months ago
bool searchPattern(string str, string pat){ // your code here int n=str.length(); int m=pat.length(); for(int i=0;i<=n-m;i++){ int j; for(j=0;j<m;j++){ if(str[i+j]!=pat[j]){ break; } } if(m==j){ return true; } } return false;}
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": 338,
"s": 226,
"text": "Given a string str and a pattern pat. You need to check whether pattern is present or not in the given string. "
},
{
"code": null,
"e": 513,
"s": 338,
"text": "Input Format: The input line contains T, denoting the number of testcases. Each testcase contains two lines. First line contains string str. Second line contains patter text."
},
{
"code": null,
"e": 624,
"s": 513,
"text": "Output format: For each testcase in new line you have to print the \"Present\" if found otherwise \"Not present\"."
},
{
"code": null,
"e": 766,
"s": 624,
"text": "User task: You need to complete the function searchPattern() containing string and text as an argument. You don't have to worry about input. "
},
{
"code": null,
"e": 828,
"s": 766,
"text": "Constraints:\n1 <= T <= 100\n1 <= |str| <= 30\n1 <= |text| <= 30"
},
{
"code": null,
"e": 864,
"s": 828,
"text": "Sample Input:\n2\nabcdefh\nbcd\naxzy\nxy"
},
{
"code": null,
"e": 901,
"s": 864,
"text": "Sample Output:\nPresent\nNot present\n "
},
{
"code": null,
"e": 903,
"s": 901,
"text": "0"
},
{
"code": null,
"e": 930,
"s": 903,
"text": "hrithikraina20011 week ago"
},
{
"code": null,
"e": 974,
"s": 930,
"text": "int a= str.find(pat);\n return a==-1?0:1;"
},
{
"code": null,
"e": 976,
"s": 974,
"text": "0"
},
{
"code": null,
"e": 998,
"s": 976,
"text": "luffysama11 month ago"
},
{
"code": null,
"e": 1847,
"s": 998,
"text": "bool searchPattern(string str, string pat){ // your code here // your code here int d = 256; int q = 101; int p = 0; int t = 0 ; int n = str.size(); int m = pat.size(); int i; int j; int h = 1; for(i = 0 ; i< m-1 ; i++){ h=(h*d)%q; } for(i = 0 ; i < m ; i++){ p = (d*p + pat[i])%q; t = (d*t + str[i])%q; } for(i = 0 ; i <= n-m ; i++){ if(p==t){ bool flag =true; for(j = 0 ; j < m ; j++){ if(str[i+j]!=pat[j]){ flag = false; break; } } if(j==m) return true; } if(i<n-m){ t = (d*(t-str[i]*h)+str[i+m])%q; if(t<0){ t+=q; } } } return false;} "
},
{
"code": null,
"e": 1849,
"s": 1847,
"text": "0"
},
{
"code": null,
"e": 1871,
"s": 1849,
"text": "luffysama11 month ago"
},
{
"code": null,
"e": 1915,
"s": 1871,
"text": "Can anyone show using Rabin Karp algorithm?"
},
{
"code": null,
"e": 1919,
"s": 1917,
"text": "0"
},
{
"code": null,
"e": 1942,
"s": 1919,
"text": "ram210320011 month ago"
},
{
"code": null,
"e": 2079,
"s": 1942,
"text": "bool searchPattern(string str, string pat){ // your code here int a=-1; a=str.find(pat); if(a!=-1) return 1; else return 0;}"
},
{
"code": null,
"e": 2081,
"s": 2079,
"text": "0"
},
{
"code": null,
"e": 2109,
"s": 2081,
"text": "pappukumarmat212 months ago"
},
{
"code": null,
"e": 2261,
"s": 2109,
"text": "bool searchPattern(string str, string pat)\n{\n // your code here\n if(strstr(str.c_str(),pat.c_str())){\n return 1;\n }\n return false;\n}"
},
{
"code": null,
"e": 2263,
"s": 2261,
"text": "0"
},
{
"code": null,
"e": 2291,
"s": 2263,
"text": "minturajmdb19993 months ago"
},
{
"code": null,
"e": 2412,
"s": 2291,
"text": "bool searchPattern(string str, string pat){ int a=-1; a=str.find(pat); if(a!=-1) return 1; else return 0;}"
},
{
"code": null,
"e": 2414,
"s": 2412,
"text": "0"
},
{
"code": null,
"e": 2444,
"s": 2414,
"text": "ayushnautiyal11104 months ago"
},
{
"code": null,
"e": 2466,
"s": 2444,
"text": "C++ IMPLEMENTATION :)"
},
{
"code": null,
"e": 2479,
"s": 2466,
"text": "TIME 0.0/1.1"
},
{
"code": null,
"e": 2496,
"s": 2479,
"text": "IF/ELSE CODE :) "
},
{
"code": null,
"e": 2512,
"s": 2496,
"text": "😁😂😂😂😂😂😂😂😂😂😂😂😂😂😁"
},
{
"code": null,
"e": 2647,
"s": 2512,
"text": "bool searchPattern(string str, string pat){ if(str.find(pat)==string::npos){ return false; } else{ return true; }}"
},
{
"code": null,
"e": 2649,
"s": 2647,
"text": "0"
},
{
"code": null,
"e": 2677,
"s": 2649,
"text": "praveen marandi4 months ago"
},
{
"code": null,
"e": 2767,
"s": 2677,
"text": "Why is Node driver program typecasting it to number? When the desired output is a string>"
},
{
"code": null,
"e": 2769,
"s": 2767,
"text": "0"
},
{
"code": null,
"e": 2791,
"s": 2769,
"text": "moninmodi4 months ago"
},
{
"code": null,
"e": 3352,
"s": 2791,
"text": "int m=str.length(); int n=pat.length(); int t[m+1][n+1]; for(int i=0;i<m+1;i++){ for(int j=0;j<n+1;j++){ if(i==0||j==0) t[i][j]=0; else{ if(str[i-1]==pat[j-1]){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=0; } } } } int max=0; for(int i=0;i<m+1;i++){ for(int j=0;j<n+1;j++){ if(t[i][j]>max){ max=t[i][j]; } } } if(max==n) return true; else return false;"
},
{
"code": null,
"e": 3354,
"s": 3352,
"text": "0"
},
{
"code": null,
"e": 3383,
"s": 3354,
"text": "kumarnitesh884414 months ago"
},
{
"code": null,
"e": 3704,
"s": 3383,
"text": "bool searchPattern(string str, string pat){ // your code here int n=str.length(); int m=pat.length(); for(int i=0;i<=n-m;i++){ int j; for(j=0;j<m;j++){ if(str[i+j]!=pat[j]){ break; } } if(m==j){ return true; } } return false;} "
},
{
"code": null,
"e": 3850,
"s": 3704,
"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": 3886,
"s": 3850,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3896,
"s": 3886,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3906,
"s": 3896,
"text": "\nContest\n"
},
{
"code": null,
"e": 3969,
"s": 3906,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4117,
"s": 3969,
"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": 4325,
"s": 4117,
"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": 4431,
"s": 4325,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Difference Between Traits and Abstract Classes in Scala - GeeksforGeeks
|
13 Feb, 2019
In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances.Example:
// Scala program to illustrate how to // create an abstract class // Abstract classabstract class Abstclass{ // Abstract and non-abstract method def portal def tutorial() { println("Scala tutorial") } } // GFG class extends abstract classclass GFG extends Abstclass{ def portal() { println("Welcome!! GeeksforGeeks") }} object Main { // Main method def main(args: Array[String]) { // object of GFG class var obj = new GFG (); obj.tutorial() obj.portal() }}
Output:
Scala tutorial
Welcome!! GeeksforGeeks
Like a class, Traits can have methods(both abstract and non-abstract), and fields as its members. Traits are just like interfaces in Java. But they are more powerful than the interface in Java because in the traits we are allowed to implement the members.Example:
// Scala program to illustrate how to // create traits // traitstrait mytrait{ // Abstract and non-abstract method def portal def tutorial() { println("Scala tutorial") } } // GFG class extends traitclass GFG extends mytrait{ def portal() { println("Welcome!! GeeksforGeeks") }} object Main { // Main method def main(args: Array[String]) { // object of GFG class var obj = new GFG (); obj.tutorial() obj.portal() }}
Output:
Scala tutorial
Welcome!! GeeksforGeeks
Scala
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Lists
Scala List filter() method with example
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Map
Type Casting in Scala
Scala List contains() method with example
Throw Keyword in Scala
Scala String substring() method with example
Lambda Expression in Scala
Scala | Option
|
[
{
"code": null,
"e": 23738,
"s": 23710,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 23910,
"s": 23738,
"text": "In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances.Example:"
},
{
"code": "// Scala program to illustrate how to // create an abstract class // Abstract classabstract class Abstclass{ // Abstract and non-abstract method def portal def tutorial() { println(\"Scala tutorial\") } } // GFG class extends abstract classclass GFG extends Abstclass{ def portal() { println(\"Welcome!! GeeksforGeeks\") }} object Main { // Main method def main(args: Array[String]) { // object of GFG class var obj = new GFG (); obj.tutorial() obj.portal() }}",
"e": 24463,
"s": 23910,
"text": null
},
{
"code": null,
"e": 24471,
"s": 24463,
"text": "Output:"
},
{
"code": null,
"e": 24511,
"s": 24471,
"text": "Scala tutorial\nWelcome!! GeeksforGeeks\n"
},
{
"code": null,
"e": 24775,
"s": 24511,
"text": "Like a class, Traits can have methods(both abstract and non-abstract), and fields as its members. Traits are just like interfaces in Java. But they are more powerful than the interface in Java because in the traits we are allowed to implement the members.Example:"
},
{
"code": "// Scala program to illustrate how to // create traits // traitstrait mytrait{ // Abstract and non-abstract method def portal def tutorial() { println(\"Scala tutorial\") } } // GFG class extends traitclass GFG extends mytrait{ def portal() { println(\"Welcome!! GeeksforGeeks\") }} object Main { // Main method def main(args: Array[String]) { // object of GFG class var obj = new GFG (); obj.tutorial() obj.portal() }}",
"e": 25297,
"s": 24775,
"text": null
},
{
"code": null,
"e": 25305,
"s": 25297,
"text": "Output:"
},
{
"code": null,
"e": 25345,
"s": 25305,
"text": "Scala tutorial\nWelcome!! GeeksforGeeks\n"
},
{
"code": null,
"e": 25351,
"s": 25345,
"text": "Scala"
},
{
"code": null,
"e": 25362,
"s": 25351,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 25368,
"s": 25362,
"text": "Scala"
},
{
"code": null,
"e": 25466,
"s": 25368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25475,
"s": 25466,
"text": "Comments"
},
{
"code": null,
"e": 25488,
"s": 25475,
"text": "Old Comments"
},
{
"code": null,
"e": 25500,
"s": 25488,
"text": "Scala Lists"
},
{
"code": null,
"e": 25540,
"s": 25500,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 25593,
"s": 25540,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 25603,
"s": 25593,
"text": "Scala Map"
},
{
"code": null,
"e": 25625,
"s": 25603,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 25667,
"s": 25625,
"text": "Scala List contains() method with example"
},
{
"code": null,
"e": 25690,
"s": 25667,
"text": "Throw Keyword in Scala"
},
{
"code": null,
"e": 25735,
"s": 25690,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 25762,
"s": 25735,
"text": "Lambda Expression in Scala"
}
] |
How to delete all the tags of the azure resource using PowerShell?
|
To delete all the tags of the Azure VM using PowerShell, we need to use the Remove-AZTag command.
To delete the azure resource tags, we need its resource ID but before that, it is always better to take azure resource tags backup. You can search the question on the TutorialPoints site or google,
Site − TutorialsPoint.com How to Export the Azure VM tags using PowerShell?
To delete the azure Resource Tags,
PS C:\> $vm = Get-AzVM -Name Testmachine2k16
PS C:\> Remove-AzTag -ResourceId $vm.Id -Verbose
To remove the azure resourceGroup tags,
PS C:\> $rg = Get-AzResourceGroup AnsibleTestRG
PS C:\> Remove-AzTag -ResourceId $rg.ResourceId -Verbose
To remove the individual tag, you can directly apply the tag name but be cautious as it will remove the given tag name across all the subscriptions.
The below command will remove the tag from the entire subscription if it is not associated with multiple resources.
Remove-AzTag -Name 'Owner' -Value 'Chirag' -Verbose
If you have done something wrong while removing tags and if you have already a TAGS backup, you can search on the google article to import the tags again.
Site − TutorialsPoint.com How to import tags in Azure?
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "To delete all the tags of the Azure VM using PowerShell, we need to use the Remove-AZTag command."
},
{
"code": null,
"e": 1358,
"s": 1160,
"text": "To delete the azure resource tags, we need its resource ID but before that, it is always better to take azure resource tags backup. You can search the question on the TutorialPoints site or google,"
},
{
"code": null,
"e": 1434,
"s": 1358,
"text": "Site − TutorialsPoint.com How to Export the Azure VM tags using PowerShell?"
},
{
"code": null,
"e": 1469,
"s": 1434,
"text": "To delete the azure Resource Tags,"
},
{
"code": null,
"e": 1563,
"s": 1469,
"text": "PS C:\\> $vm = Get-AzVM -Name Testmachine2k16\nPS C:\\> Remove-AzTag -ResourceId $vm.Id -Verbose"
},
{
"code": null,
"e": 1603,
"s": 1563,
"text": "To remove the azure resourceGroup tags,"
},
{
"code": null,
"e": 1708,
"s": 1603,
"text": "PS C:\\> $rg = Get-AzResourceGroup AnsibleTestRG\nPS C:\\> Remove-AzTag -ResourceId $rg.ResourceId -Verbose"
},
{
"code": null,
"e": 1857,
"s": 1708,
"text": "To remove the individual tag, you can directly apply the tag name but be cautious as it will remove the given tag name across all the subscriptions."
},
{
"code": null,
"e": 1973,
"s": 1857,
"text": "The below command will remove the tag from the entire subscription if it is not associated with multiple resources."
},
{
"code": null,
"e": 2025,
"s": 1973,
"text": "Remove-AzTag -Name 'Owner' -Value 'Chirag' -Verbose"
},
{
"code": null,
"e": 2180,
"s": 2025,
"text": "If you have done something wrong while removing tags and if you have already a TAGS backup, you can search on the google article to import the tags again."
},
{
"code": null,
"e": 2235,
"s": 2180,
"text": "Site − TutorialsPoint.com How to import tags in Azure?"
}
] |
How to Handle Imbalance Data and Small Training Sets in ML | by Ege Hosgungor | Towards Data Science
|
Imbalanced data refers to where the number of observations per class is not equally distributed and often there is a major class that has a much larger percentage of the dataset and minor classes which doesn’t have enough examples.
Small Training Sets also suffer from not having enough examples. Both of the problems are very common in real-world applications but luckily there are several ways to overcome this problem. This article will walk through many different techniques and perspectives to combat Imbalance data. In particular, you will learn about:
Sampling Techniques (Upsampling & Downsampling)
Weighted Loss
Data Augmentation Techniques
Transfer Learning
Imbalanced data is a common problem in data science. From image classification to fraud detection or medical diagnosis, data scientists face imbalanced datasets. Having an imbalanced dataset decreases the sensitivity of the model towards minority classes. Lets put this on with simple maths:
Imagine you have 10000 lung X-Ray images and only 100 of them are diagnosed with Pneumonia which is an infectious disease that inflames the air sacs in one or both lungs and fills them with liquid. If you train a model that predicts every example as healthy you will get 99% accuracy. Wow, how awesome is that? Wrong, you just killed many people with your model.
Usually, we look at accuracy to measure our model’s performance but imbalanced data can mislead us like the example above. This article is focused on how to handle these kinds of situations and I am not going into details of how to measure your model but bear in mind to change the measurement metrics from Accuracy to Precision, Recall, F1 Score. But even they are not actually that great. I would recommend going for:AUC Curves, Average Precision while dealing with imbalance data. Here is an amazing github repository which goes into very details of these metrics by talking about a particular imbalance dataset example: credit card frauds.
Let’s say, we have an imbalanced dataset and we do not have access to more data. So we should create our own data. The following chapter will present techniques on a high abstract level and I also added some great references for implementing each of them in Python.
You can balance your data by resampling them. The followings are two different techniques for resampling:
Upsampling (increase your minority class)
Downsample (decrease your majority class)
For both of these, we will use the Sklearn Resample function. Let’s import the libraries and define our data as df:
# Importing the librariesimport numpy as npimport pandas as pdfrom sklearn.utils import resample# Importing the dataset# Read datasetdf= pd.read_csv('data.csv')
In this example, we have a binary classification problem where the majority is represented as 1 and the minority class is represented as 0. Let’s separate them:
# Separate majority and minority classesdf_majority = df[df.iloc[:,4608]==1]df_minority = df[df.iloc[:,4608]==0]
We can downsample the majority class, upsample the minority class or we can do both. You should try them to find which one is the most suitable for you. One other hyperparameter that you can tune is n_samples which is the number of samples that you resample.
# Separate majority and minority classesdf_majority = df[df.iloc[:,4608]==1]df_minority = df[df.iloc[:,4608]==0] # Downsample majority classdf_majority_downsampled = resample(df_majority, replace=False, n_samples=1000)#Upsample minority classdf_minority_upsampled = resample(df_minority, replace=True, n_samples=1000)# Combine minority class with downsampled majority classdf_up_down_sampled = pd.concat([df_majority_downsampled, df_minority_upsampled])
Lastly display new class counts with:
df_downsampled.prediction.value_counts()
Congratulations, you brought balance to the power. 🎉
Edit:An interview question which I got asked lately: How would you make sure that your upsampled & downsampled data comes from a good distribution/ how would you measure the performance of these methods ?
One easy way to measure the performance of these methods are getting the test results for your new model which is trained with this additional data. Most of the time while upsampling you might first see an increase on the performance and then plateau or even decrease afterwards. I would pick the least number of upsampled data with the top performance.
But sometimes resampling doesn’t enough on its own. The article continues with more advanced techniques.
One other way to avoid having class imbalance is to weight the losses differently. To choose the weights, you first need to calculate the class frequencies.
# Count up the number of instances of each class (drop non-class columns from the counts)class_counts = df_classes.sum()#print the class frequenciesfor column in class_counts.keys(): print(f"The class {column} has {df_classes[column].sum()} samples")
Changing the weights in the loss function allows data scientists to balance the contribution of each class. One way of doing this is by multiplying each example from each class by a class-specific weight factor so that the overall contribution of each class is the same.
Thanks to the Sklearn, there is a built-in parameter called class_weight in most of the ML algorithms which helps you to balance the contribution of each class. For example, in the Sklearn’s RandomForestClassifier you have options as balanced, balanced_subsample or you can give weights for each class manually as a dictionary.
#Fitting RandomForestClassifierfrom sklearn.ensemble import RandomForestClassifiermodel = RandomForestClassifier(n_estimators=1000, class_weight={0:0.10, 1:0.90})
Amazing🥳, now you learned a very common technique that you can apply almost every kind of data with every ML algorithms. Let’s dive in even more advanced techniques.
From now onwards, the techniques that I’m going to mention are suitable mostly for Computer Vision and images. There are ways to generate data when you are working with images.
Data Augmentation is known as a very powerful technique used to artificially create variations in existing images to expand an existing image data set. This creates new and different images from the existing image data set that represents a comprehensive set of possible images. Here are several ways that you can do to increase your dataset.
Flipping
Zoom
Rotating
Shearing
Cropping
And lastly generating new images with Generative Adversarial Networks.
Note: Sometimes using these techniques can harm your model more than helping it. Let’s assume the same Lung X-Ray dataset case where we have many different X-rays. If you flip the images you will have a heart in the right which can be seen as a cist. Again you killed people =( So be careful about using these augmentation techniques.
You can learn more about this here
If you don’t have enough data to generalize your model you can use pre-trained models and tune them for your own task. This is called Transfer Learning and it is very common in the Computer Vision field. Since the training, huge models take so much time and resources, and people are getting pre-trained models like DenseNet and use them. The approach is as follows:
Find a model which suits your requirements
Re-use the model. This may involve using all or parts of the model or the first layers of the neural network. Since the complexity of features increases with the number of layers, the first layers always have more generic features that can be used successfully.
Fine-tuning: By going deeper, the neural network gets specialized on the task so you may want to tune the last couple of layers for your own task which is called Fine-tuning.
You can learn more from here
We learned 4 different techniques that you can apply to your imbalanced data / small training set. Now you know how to increase your model’s performance with:
Using Sampling Techniques
changing the Class Weights of Loss Function
Using Data Augmentation Techniques
and using Transfer Learning
The last two of them are more specific to Computer Vision. I hope this article helps you to understand how to overcome imbalance data problems with different techniques. Congratulations on finishing this article and thanks for reading all along.
|
[
{
"code": null,
"e": 404,
"s": 172,
"text": "Imbalanced data refers to where the number of observations per class is not equally distributed and often there is a major class that has a much larger percentage of the dataset and minor classes which doesn’t have enough examples."
},
{
"code": null,
"e": 731,
"s": 404,
"text": "Small Training Sets also suffer from not having enough examples. Both of the problems are very common in real-world applications but luckily there are several ways to overcome this problem. This article will walk through many different techniques and perspectives to combat Imbalance data. In particular, you will learn about:"
},
{
"code": null,
"e": 779,
"s": 731,
"text": "Sampling Techniques (Upsampling & Downsampling)"
},
{
"code": null,
"e": 793,
"s": 779,
"text": "Weighted Loss"
},
{
"code": null,
"e": 822,
"s": 793,
"text": "Data Augmentation Techniques"
},
{
"code": null,
"e": 840,
"s": 822,
"text": "Transfer Learning"
},
{
"code": null,
"e": 1132,
"s": 840,
"text": "Imbalanced data is a common problem in data science. From image classification to fraud detection or medical diagnosis, data scientists face imbalanced datasets. Having an imbalanced dataset decreases the sensitivity of the model towards minority classes. Lets put this on with simple maths:"
},
{
"code": null,
"e": 1495,
"s": 1132,
"text": "Imagine you have 10000 lung X-Ray images and only 100 of them are diagnosed with Pneumonia which is an infectious disease that inflames the air sacs in one or both lungs and fills them with liquid. If you train a model that predicts every example as healthy you will get 99% accuracy. Wow, how awesome is that? Wrong, you just killed many people with your model."
},
{
"code": null,
"e": 2139,
"s": 1495,
"text": "Usually, we look at accuracy to measure our model’s performance but imbalanced data can mislead us like the example above. This article is focused on how to handle these kinds of situations and I am not going into details of how to measure your model but bear in mind to change the measurement metrics from Accuracy to Precision, Recall, F1 Score. But even they are not actually that great. I would recommend going for:AUC Curves, Average Precision while dealing with imbalance data. Here is an amazing github repository which goes into very details of these metrics by talking about a particular imbalance dataset example: credit card frauds."
},
{
"code": null,
"e": 2405,
"s": 2139,
"text": "Let’s say, we have an imbalanced dataset and we do not have access to more data. So we should create our own data. The following chapter will present techniques on a high abstract level and I also added some great references for implementing each of them in Python."
},
{
"code": null,
"e": 2511,
"s": 2405,
"text": "You can balance your data by resampling them. The followings are two different techniques for resampling:"
},
{
"code": null,
"e": 2553,
"s": 2511,
"text": "Upsampling (increase your minority class)"
},
{
"code": null,
"e": 2595,
"s": 2553,
"text": "Downsample (decrease your majority class)"
},
{
"code": null,
"e": 2711,
"s": 2595,
"text": "For both of these, we will use the Sklearn Resample function. Let’s import the libraries and define our data as df:"
},
{
"code": null,
"e": 2872,
"s": 2711,
"text": "# Importing the librariesimport numpy as npimport pandas as pdfrom sklearn.utils import resample# Importing the dataset# Read datasetdf= pd.read_csv('data.csv')"
},
{
"code": null,
"e": 3033,
"s": 2872,
"text": "In this example, we have a binary classification problem where the majority is represented as 1 and the minority class is represented as 0. Let’s separate them:"
},
{
"code": null,
"e": 3146,
"s": 3033,
"text": "# Separate majority and minority classesdf_majority = df[df.iloc[:,4608]==1]df_minority = df[df.iloc[:,4608]==0]"
},
{
"code": null,
"e": 3405,
"s": 3146,
"text": "We can downsample the majority class, upsample the minority class or we can do both. You should try them to find which one is the most suitable for you. One other hyperparameter that you can tune is n_samples which is the number of samples that you resample."
},
{
"code": null,
"e": 3998,
"s": 3405,
"text": "# Separate majority and minority classesdf_majority = df[df.iloc[:,4608]==1]df_minority = df[df.iloc[:,4608]==0] # Downsample majority classdf_majority_downsampled = resample(df_majority, replace=False, n_samples=1000)#Upsample minority classdf_minority_upsampled = resample(df_minority, replace=True, n_samples=1000)# Combine minority class with downsampled majority classdf_up_down_sampled = pd.concat([df_majority_downsampled, df_minority_upsampled])"
},
{
"code": null,
"e": 4036,
"s": 3998,
"text": "Lastly display new class counts with:"
},
{
"code": null,
"e": 4077,
"s": 4036,
"text": "df_downsampled.prediction.value_counts()"
},
{
"code": null,
"e": 4130,
"s": 4077,
"text": "Congratulations, you brought balance to the power. 🎉"
},
{
"code": null,
"e": 4335,
"s": 4130,
"text": "Edit:An interview question which I got asked lately: How would you make sure that your upsampled & downsampled data comes from a good distribution/ how would you measure the performance of these methods ?"
},
{
"code": null,
"e": 4689,
"s": 4335,
"text": "One easy way to measure the performance of these methods are getting the test results for your new model which is trained with this additional data. Most of the time while upsampling you might first see an increase on the performance and then plateau or even decrease afterwards. I would pick the least number of upsampled data with the top performance."
},
{
"code": null,
"e": 4794,
"s": 4689,
"text": "But sometimes resampling doesn’t enough on its own. The article continues with more advanced techniques."
},
{
"code": null,
"e": 4951,
"s": 4794,
"text": "One other way to avoid having class imbalance is to weight the losses differently. To choose the weights, you first need to calculate the class frequencies."
},
{
"code": null,
"e": 5205,
"s": 4951,
"text": "# Count up the number of instances of each class (drop non-class columns from the counts)class_counts = df_classes.sum()#print the class frequenciesfor column in class_counts.keys(): print(f\"The class {column} has {df_classes[column].sum()} samples\")"
},
{
"code": null,
"e": 5476,
"s": 5205,
"text": "Changing the weights in the loss function allows data scientists to balance the contribution of each class. One way of doing this is by multiplying each example from each class by a class-specific weight factor so that the overall contribution of each class is the same."
},
{
"code": null,
"e": 5804,
"s": 5476,
"text": "Thanks to the Sklearn, there is a built-in parameter called class_weight in most of the ML algorithms which helps you to balance the contribution of each class. For example, in the Sklearn’s RandomForestClassifier you have options as balanced, balanced_subsample or you can give weights for each class manually as a dictionary."
},
{
"code": null,
"e": 5967,
"s": 5804,
"text": "#Fitting RandomForestClassifierfrom sklearn.ensemble import RandomForestClassifiermodel = RandomForestClassifier(n_estimators=1000, class_weight={0:0.10, 1:0.90})"
},
{
"code": null,
"e": 6133,
"s": 5967,
"text": "Amazing🥳, now you learned a very common technique that you can apply almost every kind of data with every ML algorithms. Let’s dive in even more advanced techniques."
},
{
"code": null,
"e": 6310,
"s": 6133,
"text": "From now onwards, the techniques that I’m going to mention are suitable mostly for Computer Vision and images. There are ways to generate data when you are working with images."
},
{
"code": null,
"e": 6653,
"s": 6310,
"text": "Data Augmentation is known as a very powerful technique used to artificially create variations in existing images to expand an existing image data set. This creates new and different images from the existing image data set that represents a comprehensive set of possible images. Here are several ways that you can do to increase your dataset."
},
{
"code": null,
"e": 6662,
"s": 6653,
"text": "Flipping"
},
{
"code": null,
"e": 6667,
"s": 6662,
"text": "Zoom"
},
{
"code": null,
"e": 6676,
"s": 6667,
"text": "Rotating"
},
{
"code": null,
"e": 6685,
"s": 6676,
"text": "Shearing"
},
{
"code": null,
"e": 6694,
"s": 6685,
"text": "Cropping"
},
{
"code": null,
"e": 6765,
"s": 6694,
"text": "And lastly generating new images with Generative Adversarial Networks."
},
{
"code": null,
"e": 7100,
"s": 6765,
"text": "Note: Sometimes using these techniques can harm your model more than helping it. Let’s assume the same Lung X-Ray dataset case where we have many different X-rays. If you flip the images you will have a heart in the right which can be seen as a cist. Again you killed people =( So be careful about using these augmentation techniques."
},
{
"code": null,
"e": 7135,
"s": 7100,
"text": "You can learn more about this here"
},
{
"code": null,
"e": 7502,
"s": 7135,
"text": "If you don’t have enough data to generalize your model you can use pre-trained models and tune them for your own task. This is called Transfer Learning and it is very common in the Computer Vision field. Since the training, huge models take so much time and resources, and people are getting pre-trained models like DenseNet and use them. The approach is as follows:"
},
{
"code": null,
"e": 7545,
"s": 7502,
"text": "Find a model which suits your requirements"
},
{
"code": null,
"e": 7807,
"s": 7545,
"text": "Re-use the model. This may involve using all or parts of the model or the first layers of the neural network. Since the complexity of features increases with the number of layers, the first layers always have more generic features that can be used successfully."
},
{
"code": null,
"e": 7982,
"s": 7807,
"text": "Fine-tuning: By going deeper, the neural network gets specialized on the task so you may want to tune the last couple of layers for your own task which is called Fine-tuning."
},
{
"code": null,
"e": 8011,
"s": 7982,
"text": "You can learn more from here"
},
{
"code": null,
"e": 8170,
"s": 8011,
"text": "We learned 4 different techniques that you can apply to your imbalanced data / small training set. Now you know how to increase your model’s performance with:"
},
{
"code": null,
"e": 8196,
"s": 8170,
"text": "Using Sampling Techniques"
},
{
"code": null,
"e": 8240,
"s": 8196,
"text": "changing the Class Weights of Loss Function"
},
{
"code": null,
"e": 8275,
"s": 8240,
"text": "Using Data Augmentation Techniques"
},
{
"code": null,
"e": 8303,
"s": 8275,
"text": "and using Transfer Learning"
}
] |
How to Install Flutter For Web? - GeeksforGeeks
|
13 Oct, 2021
Flutter is Google’s platform-independent technology for creating applications that can run on multiple platforms. This open-source UI software development kit allows you to reuse most of your code across platforms, which can significantly lower your budget costs.
Cross-Platform DevelopmentHot ReloadRich Widgets
Cross-Platform Development
Hot Reload
Rich Widgets
In this article, we will show you the installation process of Flutter.
The steps for installing Flutter are as follows:
Step1: Click on this link and select your operating system.
Select your operating system
Step 2: Get the latest stable version of Flutter SDK by downloading the following installation package
Click on the blue button
Unzip the zip file and place it in your desired installation location. (Eg: Documents folder)
Warning: Do not install Flutter in a directory like C:\Program Files\ that requires elevated privileges.
Step 3: Update your path
To run Flutter commands from the normal Windows console, follow these steps to add Flutter to the PATH environment variable:
From the start search bar, type env and select Edit environment variables for your account.
Click on Environment Variables
In User Variables, look for an entry named Path :
Double click on Path
On double-clicking on Path (or click on Path and then click on Edit button), another tab will pop- up:
Click on the ‘New’ button on the left side and add C:\flutter\bin. Click OK.
You must close and reopen any existing console windows for these changes to take effect.
Step 4: Set up an IDE
You can create applications with Flutter using any text editor combined with command-line tools. However, it is recommended to use Flutter editor plugins for an even better experience. These plugins give you code completion, syntax highlighting, widget editing aids, launch and debugging support, and more.
Step 5: Install Flutter plugin
Start VS Code.Invoke View > Command Palette....Type “install”, and select Extensions: Install Extensions.Type “flutter” in the extensions search field, select Flutter in the list and click Install. This also installs the required Dart plugin.
Start VS Code.
Invoke View > Command Palette....
Type “install”, and select Extensions: Install Extensions.
Type “flutter” in the extensions search field, select Flutter in the list and click Install. This also installs the required Dart plugin.
Install Flutter plugin
Now you can start building your application using Flutter.
how-to-install
Picked
TrueGeek-2021
How To
Installation Guide
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 24825,
"s": 24561,
"text": "Flutter is Google’s platform-independent technology for creating applications that can run on multiple platforms. This open-source UI software development kit allows you to reuse most of your code across platforms, which can significantly lower your budget costs."
},
{
"code": null,
"e": 24874,
"s": 24825,
"text": "Cross-Platform DevelopmentHot ReloadRich Widgets"
},
{
"code": null,
"e": 24901,
"s": 24874,
"text": "Cross-Platform Development"
},
{
"code": null,
"e": 24912,
"s": 24901,
"text": "Hot Reload"
},
{
"code": null,
"e": 24925,
"s": 24912,
"text": "Rich Widgets"
},
{
"code": null,
"e": 24998,
"s": 24925,
"text": "In this article, we will show you the installation process of Flutter. "
},
{
"code": null,
"e": 25047,
"s": 24998,
"text": "The steps for installing Flutter are as follows:"
},
{
"code": null,
"e": 25107,
"s": 25047,
"text": "Step1: Click on this link and select your operating system."
},
{
"code": null,
"e": 25136,
"s": 25107,
"text": "Select your operating system"
},
{
"code": null,
"e": 25240,
"s": 25136,
"text": "Step 2: Get the latest stable version of Flutter SDK by downloading the following installation package "
},
{
"code": null,
"e": 25265,
"s": 25240,
"text": "Click on the blue button"
},
{
"code": null,
"e": 25359,
"s": 25265,
"text": "Unzip the zip file and place it in your desired installation location. (Eg: Documents folder)"
},
{
"code": null,
"e": 25465,
"s": 25359,
"text": "Warning: Do not install Flutter in a directory like C:\\Program Files\\ that requires elevated privileges. "
},
{
"code": null,
"e": 25490,
"s": 25465,
"text": "Step 3: Update your path"
},
{
"code": null,
"e": 25617,
"s": 25490,
"text": "To run Flutter commands from the normal Windows console, follow these steps to add Flutter to the PATH environment variable: "
},
{
"code": null,
"e": 25711,
"s": 25617,
"text": "From the start search bar, type env and select Edit environment variables for your account. "
},
{
"code": null,
"e": 25742,
"s": 25711,
"text": "Click on Environment Variables"
},
{
"code": null,
"e": 25793,
"s": 25742,
"text": "In User Variables, look for an entry named Path : "
},
{
"code": null,
"e": 25815,
"s": 25793,
"text": "Double click on Path "
},
{
"code": null,
"e": 25918,
"s": 25815,
"text": "On double-clicking on Path (or click on Path and then click on Edit button), another tab will pop- up:"
},
{
"code": null,
"e": 25995,
"s": 25918,
"text": "Click on the ‘New’ button on the left side and add C:\\flutter\\bin. Click OK."
},
{
"code": null,
"e": 26084,
"s": 25995,
"text": "You must close and reopen any existing console windows for these changes to take effect."
},
{
"code": null,
"e": 26106,
"s": 26084,
"text": "Step 4: Set up an IDE"
},
{
"code": null,
"e": 26413,
"s": 26106,
"text": "You can create applications with Flutter using any text editor combined with command-line tools. However, it is recommended to use Flutter editor plugins for an even better experience. These plugins give you code completion, syntax highlighting, widget editing aids, launch and debugging support, and more."
},
{
"code": null,
"e": 26444,
"s": 26413,
"text": "Step 5: Install Flutter plugin"
},
{
"code": null,
"e": 26687,
"s": 26444,
"text": "Start VS Code.Invoke View > Command Palette....Type “install”, and select Extensions: Install Extensions.Type “flutter” in the extensions search field, select Flutter in the list and click Install. This also installs the required Dart plugin."
},
{
"code": null,
"e": 26702,
"s": 26687,
"text": "Start VS Code."
},
{
"code": null,
"e": 26736,
"s": 26702,
"text": "Invoke View > Command Palette...."
},
{
"code": null,
"e": 26795,
"s": 26736,
"text": "Type “install”, and select Extensions: Install Extensions."
},
{
"code": null,
"e": 26933,
"s": 26795,
"text": "Type “flutter” in the extensions search field, select Flutter in the list and click Install. This also installs the required Dart plugin."
},
{
"code": null,
"e": 26956,
"s": 26933,
"text": "Install Flutter plugin"
},
{
"code": null,
"e": 27015,
"s": 26956,
"text": "Now you can start building your application using Flutter."
},
{
"code": null,
"e": 27030,
"s": 27015,
"text": "how-to-install"
},
{
"code": null,
"e": 27037,
"s": 27030,
"text": "Picked"
},
{
"code": null,
"e": 27051,
"s": 27037,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 27058,
"s": 27051,
"text": "How To"
},
{
"code": null,
"e": 27077,
"s": 27058,
"text": "Installation Guide"
},
{
"code": null,
"e": 27086,
"s": 27077,
"text": "TrueGeek"
},
{
"code": null,
"e": 27184,
"s": 27086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27193,
"s": 27184,
"text": "Comments"
},
{
"code": null,
"e": 27206,
"s": 27193,
"text": "Old Comments"
},
{
"code": null,
"e": 27240,
"s": 27206,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27289,
"s": 27240,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27347,
"s": 27289,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27389,
"s": 27347,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27449,
"s": 27389,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27482,
"s": 27449,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27516,
"s": 27482,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27551,
"s": 27516,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 27609,
"s": 27551,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Check if a given array is sorted in Spiral manner or not - GeeksforGeeks
|
22 Apr, 2021
Given an array arr[] of size N, the task is to check if the array is spirally sorted or not. If found to be true, then print “YES”. Otherwise, print “NO”.
Note: An array is spirally sorted if arr[0] ≤ arr[N – 1] ≤ arr[1] ≤ arr[N – 2] ...
Examples:
Input: arr[] = { 1, 10, 14, 20, 18, 12, 5 } Output: YES Explanation: arr[0] < arr[6]arr[1] < arr[5]arr[2] < arr[4]Therefore, the required output is YES.
Input: arr[] = { 1, 2, 4, 3 } Output: NO
Approach: The idea is to traverse the array and for every array element, say arr[i], check if arr[i] is less than or equal to arr[N – i – 1] and arr[N – i – 1] less than or equal to arr[i + 1] or not. If found to be false, then print “NO”. Otherwise, if all array elements satisfy the condition, then print “YES”. Follow the steps below to solve the problem:
Initialize two variables, say start and end, to store the start and end indices of the given array.
Iterate a loop while start is less than end, and check if arr[start] less than or equal to arr[end] and arr[end] is less than or equal to arr[start + 1] or not. If found to be false, then print “NO”.
Otherwise, print “YES”.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <iostream>using namespace std; // Function to check if the array is// spirally sorted or notbool isSpiralSorted(int arr[], int n){ // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true;} // Driver Codeint main(){ int arr[] = { 1, 10, 14, 20, 18, 12, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call if (isSpiralSorted(arr, N)) cout << "YES" << endl; else cout << "NO" << endl; return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to check if the array is // spirally sorted or not static boolean isSpiralSorted(int[] arr, int n) { // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } // Driver code public static void main(String[] args) { int[] arr = { 1, 10, 14, 20, 18, 12, 5 }; int N = arr.length; // Function Call if (isSpiralSorted(arr, N) != false) System.out.print("YES"); else System.out.print("NO"); }} // This code is contributed by sanjoy_62
# Python3 program to implement# the above approach # Function to check if the array is# spirally sorted or notdef isSpiralSorted(arr, n) : # Stores start index # of the array start = 0; # Stores end index # of an array end = n - 1; while (start < end) : # If arr[start] # greater than arr[end] if (arr[start] > arr[end]) : return False; # Update start start += 1; # If arr[end] # greater than arr[start] if (arr[end] > arr[start]) : return False; # Update end end -= 1; return True; # Driver Codeif __name__ == "__main__" : arr = [ 1, 10, 14, 20, 18, 12, 5 ]; N = len(arr); # Function Call if (isSpiralSorted(arr, N)) : print("YES"); else : print("NO"); # This code is contributed by AnkThon
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if the array is // spirally sorted or not static bool isSpiralSorted(int[] arr, int n) { // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } // Driver code static void Main() { int[] arr = { 1, 10, 14, 20, 18, 12, 5 }; int N = arr.Length; // Function Call if (isSpiralSorted(arr, N)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed bydivyesh072019
<script> // Javascript program to implement // the above approach // Function to check if the array is // spirally sorted or not function isSpiralSorted(arr, n) { // Stores start index // of the array let start = 0; // Stores end index // of an array let end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } let arr = [ 1, 10, 14, 20, 18, 12, 5 ]; let N = arr.length; // Function Call if (isSpiralSorted(arr, N)) document.write("YES"); else document.write("NO"); </script>
YES
Time Complexity: O(N) Auxiliary Space: O(1)
divyesh072019
sanjoy_62
ankthon
suresh07
array-traversal-question
Arrays
Greedy
Mathematical
School Programming
Searching
Arrays
Searching
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25081,
"s": 25053,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25236,
"s": 25081,
"text": "Given an array arr[] of size N, the task is to check if the array is spirally sorted or not. If found to be true, then print “YES”. Otherwise, print “NO”."
},
{
"code": null,
"e": 25319,
"s": 25236,
"text": "Note: An array is spirally sorted if arr[0] ≤ arr[N – 1] ≤ arr[1] ≤ arr[N – 2] ..."
},
{
"code": null,
"e": 25329,
"s": 25319,
"text": "Examples:"
},
{
"code": null,
"e": 25482,
"s": 25329,
"text": "Input: arr[] = { 1, 10, 14, 20, 18, 12, 5 } Output: YES Explanation: arr[0] < arr[6]arr[1] < arr[5]arr[2] < arr[4]Therefore, the required output is YES."
},
{
"code": null,
"e": 25523,
"s": 25482,
"text": "Input: arr[] = { 1, 2, 4, 3 } Output: NO"
},
{
"code": null,
"e": 25882,
"s": 25523,
"text": "Approach: The idea is to traverse the array and for every array element, say arr[i], check if arr[i] is less than or equal to arr[N – i – 1] and arr[N – i – 1] less than or equal to arr[i + 1] or not. If found to be false, then print “NO”. Otherwise, if all array elements satisfy the condition, then print “YES”. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25982,
"s": 25882,
"text": "Initialize two variables, say start and end, to store the start and end indices of the given array."
},
{
"code": null,
"e": 26182,
"s": 25982,
"text": "Iterate a loop while start is less than end, and check if arr[start] less than or equal to arr[end] and arr[end] is less than or equal to arr[start + 1] or not. If found to be false, then print “NO”."
},
{
"code": null,
"e": 26206,
"s": 26182,
"text": "Otherwise, print “YES”."
},
{
"code": null,
"e": 26257,
"s": 26206,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26263,
"s": 26257,
"text": "C++14"
},
{
"code": null,
"e": 26268,
"s": 26263,
"text": "Java"
},
{
"code": null,
"e": 26276,
"s": 26268,
"text": "Python3"
},
{
"code": null,
"e": 26279,
"s": 26276,
"text": "C#"
},
{
"code": null,
"e": 26290,
"s": 26279,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>using namespace std; // Function to check if the array is// spirally sorted or notbool isSpiralSorted(int arr[], int n){ // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true;} // Driver Codeint main(){ int arr[] = { 1, 10, 14, 20, 18, 12, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call if (isSpiralSorted(arr, N)) cout << \"YES\" << endl; else cout << \"NO\" << endl; return 0;}",
"e": 27228,
"s": 26290,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to check if the array is // spirally sorted or not static boolean isSpiralSorted(int[] arr, int n) { // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } // Driver code public static void main(String[] args) { int[] arr = { 1, 10, 14, 20, 18, 12, 5 }; int N = arr.length; // Function Call if (isSpiralSorted(arr, N) != false) System.out.print(\"YES\"); else System.out.print(\"NO\"); }} // This code is contributed by sanjoy_62",
"e": 28222,
"s": 27228,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if the array is# spirally sorted or notdef isSpiralSorted(arr, n) : # Stores start index # of the array start = 0; # Stores end index # of an array end = n - 1; while (start < end) : # If arr[start] # greater than arr[end] if (arr[start] > arr[end]) : return False; # Update start start += 1; # If arr[end] # greater than arr[start] if (arr[end] > arr[start]) : return False; # Update end end -= 1; return True; # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 10, 14, 20, 18, 12, 5 ]; N = len(arr); # Function Call if (isSpiralSorted(arr, N)) : print(\"YES\"); else : print(\"NO\"); # This code is contributed by AnkThon",
"e": 29079,
"s": 28222,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if the array is // spirally sorted or not static bool isSpiralSorted(int[] arr, int n) { // Stores start index // of the array int start = 0; // Stores end index // of an array int end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } // Driver code static void Main() { int[] arr = { 1, 10, 14, 20, 18, 12, 5 }; int N = arr.Length; // Function Call if (isSpiralSorted(arr, N)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed bydivyesh072019",
"e": 30272,
"s": 29079,
"text": null
},
{
"code": "<script> // Javascript program to implement // the above approach // Function to check if the array is // spirally sorted or not function isSpiralSorted(arr, n) { // Stores start index // of the array let start = 0; // Stores end index // of an array let end = n - 1; while (start < end) { // If arr[start] // greater than arr[end] if (arr[start] > arr[end]) { return false; } // Update start start++; // If arr[end] // greater than arr[start] if (arr[end] > arr[start]) { return false; } // Update end end--; } return true; } let arr = [ 1, 10, 14, 20, 18, 12, 5 ]; let N = arr.length; // Function Call if (isSpiralSorted(arr, N)) document.write(\"YES\"); else document.write(\"NO\"); </script>",
"e": 31351,
"s": 30272,
"text": null
},
{
"code": null,
"e": 31355,
"s": 31351,
"text": "YES"
},
{
"code": null,
"e": 31401,
"s": 31357,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31415,
"s": 31401,
"text": "divyesh072019"
},
{
"code": null,
"e": 31425,
"s": 31415,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31433,
"s": 31425,
"text": "ankthon"
},
{
"code": null,
"e": 31442,
"s": 31433,
"text": "suresh07"
},
{
"code": null,
"e": 31467,
"s": 31442,
"text": "array-traversal-question"
},
{
"code": null,
"e": 31474,
"s": 31467,
"text": "Arrays"
},
{
"code": null,
"e": 31481,
"s": 31474,
"text": "Greedy"
},
{
"code": null,
"e": 31494,
"s": 31481,
"text": "Mathematical"
},
{
"code": null,
"e": 31513,
"s": 31494,
"text": "School Programming"
},
{
"code": null,
"e": 31523,
"s": 31513,
"text": "Searching"
},
{
"code": null,
"e": 31530,
"s": 31523,
"text": "Arrays"
},
{
"code": null,
"e": 31540,
"s": 31530,
"text": "Searching"
},
{
"code": null,
"e": 31547,
"s": 31540,
"text": "Greedy"
},
{
"code": null,
"e": 31560,
"s": 31547,
"text": "Mathematical"
},
{
"code": null,
"e": 31658,
"s": 31560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31667,
"s": 31658,
"text": "Comments"
},
{
"code": null,
"e": 31680,
"s": 31667,
"text": "Old Comments"
},
{
"code": null,
"e": 31728,
"s": 31680,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 31772,
"s": 31728,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31795,
"s": 31772,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31827,
"s": 31795,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31841,
"s": 31827,
"text": "Linear Search"
},
{
"code": null,
"e": 31892,
"s": 31841,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 31943,
"s": 31892,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 32001,
"s": 31943,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 32032,
"s": 32001,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Collections unmodifiableSet() method in Java with Examples - GeeksforGeeks
|
08 Oct, 2018
The unmodifiableSet() method of java.util.Collections class is used to return an unmodifiable view of the specified set. This method allows modules to provide users with “read-only” access to internal sets. Query operations on the returned set “read through” to the specified set, and attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned set will be serializable if the specified set is serializable.
Syntax:
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
Parameters: This method takes the set as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified set.
Below are the examples to illustrate the unmodifiableSet() method
Example 1:
// Java program to demonstrate// unmodifiableSet() method// for <Character> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of HashSet<Character> Set<Character> set = new HashSet<Character>(); // populate the table set.add('X'); set.add('Y'); // make the set unmodifiable Set<Character> immutableSet = Collections .unmodifiableSet(set); // printing unmodifiableSet System.out.println("unmodifiable Set: " + immutableSet); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
unmodifiable Set: [X, Y]
Example 2: For UnsupportedOperationException
// Java program to demonstrate// unmodifiableSet() method// for <Character> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of HashSet<Character> Set<Character> set = new HashSet<Character>(); // populate the table set.add('X'); set.add('Y'); // make the set unmodifiable Set<Character> immutableSet = Collections .unmodifiableSet(set); // printing unmodifiableSet System.out.println("unmodifiable Set: " + immutableSet); System.out.println("\nTrying to modify" + " the unmodifiable set"); immutableSet.add('Z'); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } }}
unmodifiable Set: [X, Y]
Trying to modify the unmodifiable set
Exception thrown : java.lang.UnsupportedOperationException
Java - util package
Java-Collections
Java-Functions
Java Programs
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Write Data into Excel Sheet using Java?
How to Replace a Element in Java ArrayList?
Comparing two ArrayList In Java
Removing last element from ArrayList in Java
Tic-Tac-Toe Game in Java
Java Servlet and JDBC Example | Insert data in MySQL
|
[
{
"code": null,
"e": 26107,
"s": 26079,
"text": "\n08 Oct, 2018"
},
{
"code": null,
"e": 26509,
"s": 26107,
"text": "The unmodifiableSet() method of java.util.Collections class is used to return an unmodifiable view of the specified set. This method allows modules to provide users with “read-only” access to internal sets. Query operations on the returned set “read through” to the specified set, and attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException."
},
{
"code": null,
"e": 26585,
"s": 26509,
"text": "The returned set will be serializable if the specified set is serializable."
},
{
"code": null,
"e": 26593,
"s": 26585,
"text": "Syntax:"
},
{
"code": null,
"e": 26654,
"s": 26593,
"text": "public static <T> Set<T> unmodifiableSet(Set<? extends T> s)"
},
{
"code": null,
"e": 26757,
"s": 26654,
"text": "Parameters: This method takes the set as a parameter for which an unmodifiable view is to be returned."
},
{
"code": null,
"e": 26834,
"s": 26757,
"text": "Return Value: This method returns an unmodifiable view of the specified set."
},
{
"code": null,
"e": 26900,
"s": 26834,
"text": "Below are the examples to illustrate the unmodifiableSet() method"
},
{
"code": null,
"e": 26911,
"s": 26900,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// unmodifiableSet() method// for <Character> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of HashSet<Character> Set<Character> set = new HashSet<Character>(); // populate the table set.add('X'); set.add('Y'); // make the set unmodifiable Set<Character> immutableSet = Collections .unmodifiableSet(set); // printing unmodifiableSet System.out.println(\"unmodifiable Set: \" + immutableSet); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27750,
"s": 26911,
"text": null
},
{
"code": null,
"e": 27776,
"s": 27750,
"text": "unmodifiable Set: [X, Y]\n"
},
{
"code": null,
"e": 27821,
"s": 27776,
"text": "Example 2: For UnsupportedOperationException"
},
{
"code": "// Java program to demonstrate// unmodifiableSet() method// for <Character> value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of HashSet<Character> Set<Character> set = new HashSet<Character>(); // populate the table set.add('X'); set.add('Y'); // make the set unmodifiable Set<Character> immutableSet = Collections .unmodifiableSet(set); // printing unmodifiableSet System.out.println(\"unmodifiable Set: \" + immutableSet); System.out.println(\"\\nTrying to modify\" + \" the unmodifiable set\"); immutableSet.add('Z'); } catch (UnsupportedOperationException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 28812,
"s": 27821,
"text": null
},
{
"code": null,
"e": 28936,
"s": 28812,
"text": "unmodifiable Set: [X, Y]\n\nTrying to modify the unmodifiable set\nException thrown : java.lang.UnsupportedOperationException\n"
},
{
"code": null,
"e": 28956,
"s": 28936,
"text": "Java - util package"
},
{
"code": null,
"e": 28973,
"s": 28956,
"text": "Java-Collections"
},
{
"code": null,
"e": 28988,
"s": 28973,
"text": "Java-Functions"
},
{
"code": null,
"e": 29002,
"s": 28988,
"text": "Java Programs"
},
{
"code": null,
"e": 29019,
"s": 29002,
"text": "Java-Collections"
},
{
"code": null,
"e": 29117,
"s": 29019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29165,
"s": 29117,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 29216,
"s": 29165,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 29250,
"s": 29216,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 29288,
"s": 29250,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 29335,
"s": 29288,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 29379,
"s": 29335,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 29411,
"s": 29379,
"text": "Comparing two ArrayList In Java"
},
{
"code": null,
"e": 29456,
"s": 29411,
"text": "Removing last element from ArrayList in Java"
},
{
"code": null,
"e": 29481,
"s": 29456,
"text": "Tic-Tac-Toe Game in Java"
}
] |
Number of horizontal or vertical line segments to connect 3 points - GeeksforGeeks
|
24 Nov, 2021
Given three points on the x-y coordinate plane. You need to find the no. of line segments formed by making a polyline passing through these points. (Line segment can be vertically or horizontally aligned to the coordinate axis) Examples :
Input : A = {-1, -1}, B = {-1, 3}, C = {4, 3}
Output : 2
Expantaion:
There are two segments in this polyline.
Input :A = {1, 1}, B = {2, 3} C = {3, 2}
Output : 3
The result is one if all points are on x axis or y axis. The result is 2 if points can form L shape. L shape is formed if any of the three points can be used as a joining point. Otherwise answer is 3.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find number of horizontal (or vertical// line segments needed to connect three points.#include <iostream>using namespace std; // Function to check if the third point forms a // rectangle with other two points at cornersbool isBetween(int a, int b, int c) { return min(a, b) <= c && c <= max(a, b);} // Returns true if point k can be used as a joining// point to connect using two line segmentsbool canJoin(int x[], int y[], int i, int j, int k) { // Check for the valid polyline with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} int countLineSegments(int x[], int y[]){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver codeint main(){ int x[3], y[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; cout << countLineSegments(x, y); return 0;}
// Java program to find number of horizontal// (or vertical line segments needed to// connect three points.import java.io.*; class GFG { // Function to check if the third// point forms a rectangle with // other two points at cornersstatic boolean isBetween(int a, int b, int c) { return (Math.min(a, b) <= c && c <= Math.max(a, b));} // Returns true if point k can be // used as a joining point to connect// using two line segmentsstatic boolean canJoin(int x[], int y[], int i, int j, int k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} static int countLineSegments(int x[], int y[]){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver codepublic static void main (String[] args) { int x[]=new int[3], y[]=new int[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; System.out.println(countLineSegments(x, y)); } } // This code is contributed by vt_m
# Python program to find number# of horizontal (or vertical# line segments needed to# connect three points. import math # Function to check if the# third point forms a # rectangle with other# two points at cornersdef isBetween(a, b, c) : return min(a, b) <= c and c <= max(a, b) # Returns true if point k# can be used as a joining# point to connect using# two line segmentsdef canJoin( x, y, i, j, k) : # Check for the valid polyline # with two segments return (x[k] == x[i] or x[k] == x[j]) and isBetween(y[i], y[j], y[k]) or (y[k] == y[i] or y[k] == y[j]) and isBetween(x[i], x[j], x[k]) def countLineSegments( x, y): # Check whether the X-coordinates or # Y-cocordinates are same. if ((x[0] == x[1] and x[1] == x[2]) or (y[0] == y[1] and y[1] == y[2])): return 1 # Iterate over all pairs to check for two # line segments elif (canJoin(x, y, 0, 1, 2) or canJoin(x, y, 0, 2, 1) or canJoin(x, y, 1, 2, 0)): return 2 # Otherwise answer is three. else: return 3#driver codex= [-1,-1, 4]y= [-1, 3, 3] print(countLineSegments(x, y)) # This code is contributed by Gitanjali.
// C# program to find number of horizontal// (or vertical) line segments needed to// connect three points.using System; class GFG { // Function to check if the third // point forms a rectangle with // other two points at corners static bool isBetween(int a, int b, int c) { return (Math.Min(a, b) <= c && c <= Math.Max(a, b)); } // Returns true if point k can be // used as a joining point to connect // using two line segments static bool canJoin(int[] x, int[] y, int i, int j, int k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]); } static int countLineSegments(int[] x, int[] y) { // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3; } // Driver code public static void Main() { int[] x = new int[3]; int[] y = new int[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; Console.WriteLine(countLineSegments(x, y)); }} // This code is contributed by vt_m.
<?php// PHP program to find number // of horizontal (or vertical// line segments needed to // connect three points. // Function to check if the // third point forms a // rectangle with other// two points at cornersfunction isBetween( $a, $b, $c) { return min($a, $b) <= $c and $c <= max($a, $b);} // Returns true if point k // can be used as a joining// point to connect using// two line segmentsfunction canJoin($x, $y, $i, $j, $k) { // Check for the valid // polyline with two segments return ($x[$k] == $x[$i] or $x[$k] == $x[$j]) and isBetween($y[$i], $y[$j], $y[$k]) or ($y[$k] == $y[$i] or $y[$k] == $y[$j]) and isBetween($x[$i], $x[$j], $x[$k]);} function countLineSegments( $x, $y){ // Check whether the X-coordinates // or Y-cocordinates are same. if (($x[0] == $x[1] and $x[1] == $x[2]) or ($y[0] == $y[1] and $y[1] == $y[2])) return 1; // Iterate over all pairs to // check for two line segments else if (canJoin($x, $y, 0, 1, 2) or canJoin($x, $y, 0, 2, 1) || canJoin($x, $y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver code$x = array(); $y = array();$x[0] = -1; $y[0] = -1;$x[1] = -1; $y[1] = 3;$x[2] = 4; $y[2] = 3;echo countLineSegments($x, $y); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find number of horizontal// (or vertical line segments needed to// connect three points. // Function to check if the third// point forms a rectangle with // other two points at cornersfunction isBetween(a, b, c) { return (Math.min(a, b) <= c && c <= Math.max(a, b));} // Returns true if point k can be // used as a joining point to connect// using two line segmentsfunction canJoin(x, y, i, j, k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} function countLineSegments(x, y){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;}// Driver code let x = [], y = []; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; document.write(countLineSegments(x, y)); </script>
Output :
2
vt_m
code_hunt
Competitive Programming
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Multistage Graph (Shortest Path)
7 Best Coding Challenge Websites in 2020
How to check if a given point lies inside or outside a polygon?
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Find if two rectangles overlap
|
[
{
"code": null,
"e": 26411,
"s": 26383,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26652,
"s": 26411,
"text": "Given three points on the x-y coordinate plane. You need to find the no. of line segments formed by making a polyline passing through these points. (Line segment can be vertically or horizontally aligned to the coordinate axis) Examples : "
},
{
"code": null,
"e": 26724,
"s": 26652,
"text": "Input : A = {-1, -1}, B = {-1, 3}, C = {4, 3}\nOutput : 2\nExpantaion:"
},
{
"code": null,
"e": 26824,
"s": 26724,
"text": "There are two segments in this polyline. \nInput :A = {1, 1}, B = {2, 3} C = {3, 2}\nOutput : 3"
},
{
"code": null,
"e": 27029,
"s": 26826,
"text": "The result is one if all points are on x axis or y axis. The result is 2 if points can form L shape. L shape is formed if any of the three points can be used as a joining point. Otherwise answer is 3. "
},
{
"code": null,
"e": 27033,
"s": 27029,
"text": "C++"
},
{
"code": null,
"e": 27038,
"s": 27033,
"text": "Java"
},
{
"code": null,
"e": 27046,
"s": 27038,
"text": "Python3"
},
{
"code": null,
"e": 27049,
"s": 27046,
"text": "C#"
},
{
"code": null,
"e": 27053,
"s": 27049,
"text": "PHP"
},
{
"code": null,
"e": 27064,
"s": 27053,
"text": "Javascript"
},
{
"code": "// CPP program to find number of horizontal (or vertical// line segments needed to connect three points.#include <iostream>using namespace std; // Function to check if the third point forms a // rectangle with other two points at cornersbool isBetween(int a, int b, int c) { return min(a, b) <= c && c <= max(a, b);} // Returns true if point k can be used as a joining// point to connect using two line segmentsbool canJoin(int x[], int y[], int i, int j, int k) { // Check for the valid polyline with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} int countLineSegments(int x[], int y[]){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver codeint main(){ int x[3], y[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; cout << countLineSegments(x, y); return 0;}",
"e": 28403,
"s": 27064,
"text": null
},
{
"code": "// Java program to find number of horizontal// (or vertical line segments needed to// connect three points.import java.io.*; class GFG { // Function to check if the third// point forms a rectangle with // other two points at cornersstatic boolean isBetween(int a, int b, int c) { return (Math.min(a, b) <= c && c <= Math.max(a, b));} // Returns true if point k can be // used as a joining point to connect// using two line segmentsstatic boolean canJoin(int x[], int y[], int i, int j, int k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} static int countLineSegments(int x[], int y[]){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver codepublic static void main (String[] args) { int x[]=new int[3], y[]=new int[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; System.out.println(countLineSegments(x, y)); } } // This code is contributed by vt_m",
"e": 29958,
"s": 28403,
"text": null
},
{
"code": "# Python program to find number# of horizontal (or vertical# line segments needed to# connect three points. import math # Function to check if the# third point forms a # rectangle with other# two points at cornersdef isBetween(a, b, c) : return min(a, b) <= c and c <= max(a, b) # Returns true if point k# can be used as a joining# point to connect using# two line segmentsdef canJoin( x, y, i, j, k) : # Check for the valid polyline # with two segments return (x[k] == x[i] or x[k] == x[j]) and isBetween(y[i], y[j], y[k]) or (y[k] == y[i] or y[k] == y[j]) and isBetween(x[i], x[j], x[k]) def countLineSegments( x, y): # Check whether the X-coordinates or # Y-cocordinates are same. if ((x[0] == x[1] and x[1] == x[2]) or (y[0] == y[1] and y[1] == y[2])): return 1 # Iterate over all pairs to check for two # line segments elif (canJoin(x, y, 0, 1, 2) or canJoin(x, y, 0, 2, 1) or canJoin(x, y, 1, 2, 0)): return 2 # Otherwise answer is three. else: return 3#driver codex= [-1,-1, 4]y= [-1, 3, 3] print(countLineSegments(x, y)) # This code is contributed by Gitanjali.",
"e": 31141,
"s": 29958,
"text": null
},
{
"code": "// C# program to find number of horizontal// (or vertical) line segments needed to// connect three points.using System; class GFG { // Function to check if the third // point forms a rectangle with // other two points at corners static bool isBetween(int a, int b, int c) { return (Math.Min(a, b) <= c && c <= Math.Max(a, b)); } // Returns true if point k can be // used as a joining point to connect // using two line segments static bool canJoin(int[] x, int[] y, int i, int j, int k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]); } static int countLineSegments(int[] x, int[] y) { // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3; } // Driver code public static void Main() { int[] x = new int[3]; int[] y = new int[3]; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; Console.WriteLine(countLineSegments(x, y)); }} // This code is contributed by vt_m.",
"e": 32883,
"s": 31141,
"text": null
},
{
"code": "<?php// PHP program to find number // of horizontal (or vertical// line segments needed to // connect three points. // Function to check if the // third point forms a // rectangle with other// two points at cornersfunction isBetween( $a, $b, $c) { return min($a, $b) <= $c and $c <= max($a, $b);} // Returns true if point k // can be used as a joining// point to connect using// two line segmentsfunction canJoin($x, $y, $i, $j, $k) { // Check for the valid // polyline with two segments return ($x[$k] == $x[$i] or $x[$k] == $x[$j]) and isBetween($y[$i], $y[$j], $y[$k]) or ($y[$k] == $y[$i] or $y[$k] == $y[$j]) and isBetween($x[$i], $x[$j], $x[$k]);} function countLineSegments( $x, $y){ // Check whether the X-coordinates // or Y-cocordinates are same. if (($x[0] == $x[1] and $x[1] == $x[2]) or ($y[0] == $y[1] and $y[1] == $y[2])) return 1; // Iterate over all pairs to // check for two line segments else if (canJoin($x, $y, 0, 1, 2) or canJoin($x, $y, 0, 2, 1) || canJoin($x, $y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;} // Driver code$x = array(); $y = array();$x[0] = -1; $y[0] = -1;$x[1] = -1; $y[1] = 3;$x[2] = 4; $y[2] = 3;echo countLineSegments($x, $y); // This code is contributed by anuj_67.?>",
"e": 34344,
"s": 32883,
"text": null
},
{
"code": "<script> // JavaScript program to find number of horizontal// (or vertical line segments needed to// connect three points. // Function to check if the third// point forms a rectangle with // other two points at cornersfunction isBetween(a, b, c) { return (Math.min(a, b) <= c && c <= Math.max(a, b));} // Returns true if point k can be // used as a joining point to connect// using two line segmentsfunction canJoin(x, y, i, j, k) { // Check for the valid polyline // with two segments return (x[k] == x[i] || x[k] == x[j]) && isBetween(y[i], y[j], y[k]) || (y[k] == y[i] || y[k] == y[j]) && isBetween(x[i], x[j], x[k]);} function countLineSegments(x, y){ // Check whether the X-coordinates or // Y-cocordinates are same. if ((x[0] == x[1] && x[1] == x[2]) || (y[0] == y[1] && y[1] == y[2])) return 1; // Iterate over all pairs to check for two // line segments else if (canJoin(x, y, 0, 1, 2) || canJoin(x, y, 0, 2, 1) || canJoin(x, y, 1, 2, 0)) return 2; // Otherwise answer is three. else return 3;}// Driver code let x = [], y = []; x[0] = -1; y[0] = -1; x[1] = -1; y[1] = 3; x[2] = 4; y[2] = 3; document.write(countLineSegments(x, y)); </script>",
"e": 35736,
"s": 34344,
"text": null
},
{
"code": null,
"e": 35747,
"s": 35736,
"text": "Output : "
},
{
"code": null,
"e": 35751,
"s": 35747,
"text": " 2"
},
{
"code": null,
"e": 35758,
"s": 35753,
"text": "vt_m"
},
{
"code": null,
"e": 35768,
"s": 35758,
"text": "code_hunt"
},
{
"code": null,
"e": 35792,
"s": 35768,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35802,
"s": 35792,
"text": "Geometric"
},
{
"code": null,
"e": 35815,
"s": 35802,
"text": "Mathematical"
},
{
"code": null,
"e": 35828,
"s": 35815,
"text": "Mathematical"
},
{
"code": null,
"e": 35838,
"s": 35828,
"text": "Geometric"
},
{
"code": null,
"e": 35936,
"s": 35838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36014,
"s": 35936,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 36043,
"s": 36014,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 36070,
"s": 36043,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 36103,
"s": 36070,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 36144,
"s": 36103,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 36208,
"s": 36144,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 36266,
"s": 36208,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 36317,
"s": 36266,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 36370,
"s": 36317,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
}
] |
Amazon Interview Experience for SDE-1 - GeeksforGeeks
|
20 Aug, 2021
Hi All, Initially, I have found the Amazon SDE job requirement on Linked In then I applied on the Amazon job portal for the same. I got an email for round one after two weeks.
Round 1: It was conducted online and needs to implement the coding on the HackerRank platform. There are 3 sections of the assessment.
Coding challenge (2 scenarios) and Coding approach (elaborate why you code the way you do) – 105 minutesWorkstyle survey – 15 minutesFeedback survey – 5 minutes
Coding challenge (2 scenarios) and Coding approach (elaborate why you code the way you do) – 105 minutes
Workstyle survey – 15 minutes
Feedback survey – 5 minutes
Questions asked were:
Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern.
Sample Input:
n = 6, size = {2, 3, 4, 5, 6, 7}
Sample Output :
68
Approach: This can be solved by using minimum heap.
Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1. The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix.
Sample Input :
[1, 0, 0],
[1, 0, 0],
[1, 9, 1]]
Sample Output :
3
Approach : This can be solved by using BFS or DFS.
Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern.
Sample Input:
n = 6, size = {2, 3, 4, 5, 6, 7}
Sample Output :
68
Approach: This can be solved by using minimum heap.
Sample Input:
n = 6, size = {2, 3, 4, 5, 6, 7}
Sample Output :
68
Approach: This can be solved by using minimum heap.
Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1. The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix.
Sample Input :
[1, 0, 0],
[1, 0, 0],
[1, 9, 1]]
Sample Output :
3
Approach : This can be solved by using BFS or DFS.
Sample Input :
[1, 0, 0],
[1, 0, 0],
[1, 9, 1]]
Sample Output :
3
Approach : This can be solved by using BFS or DFS.
All test cases passed for both so that I expected for the second round. After 15-20 days I got a mail from HR for an Amazon Chime Interview. There will be 2 rounds on that day only.
Round 2:
Question 1: Search a Word in a 2D Grid of characters it can be possible in 8 directions
Here I took more time to solve this problem and approached the brute force approach. The interviewer didn’t ask for an efficient approach since I have crossed the time limit.
Round 3:
In this round questions asked all about arrays and string
Question 1: Reverse words in a given String
Question 2: Print all pairs with given sum
Question 3: Count pairs in an array whose sum is divisible by K
Here The Interviewer expects an efficient solution for all the questions but I gave the efficient solution for question 1 alone.
Next week I got a call from HR, badly I am not shortlisted for the upcoming rounds anyway I got an experience. I could suggest everyone should try to work on problems for efficient approach.
All the best!
Amazon
Marketing
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Zoho Interview | Set 3 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1
Infosys Interview Experience for DSE 2022
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1 (On-Campus)
|
[
{
"code": null,
"e": 27006,
"s": 26978,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 27182,
"s": 27006,
"text": "Hi All, Initially, I have found the Amazon SDE job requirement on Linked In then I applied on the Amazon job portal for the same. I got an email for round one after two weeks."
},
{
"code": null,
"e": 27317,
"s": 27182,
"text": "Round 1: It was conducted online and needs to implement the coding on the HackerRank platform. There are 3 sections of the assessment."
},
{
"code": null,
"e": 27478,
"s": 27317,
"text": "Coding challenge (2 scenarios) and Coding approach (elaborate why you code the way you do) – 105 minutesWorkstyle survey – 15 minutesFeedback survey – 5 minutes"
},
{
"code": null,
"e": 27583,
"s": 27478,
"text": "Coding challenge (2 scenarios) and Coding approach (elaborate why you code the way you do) – 105 minutes"
},
{
"code": null,
"e": 27613,
"s": 27583,
"text": "Workstyle survey – 15 minutes"
},
{
"code": null,
"e": 27641,
"s": 27613,
"text": "Feedback survey – 5 minutes"
},
{
"code": null,
"e": 27663,
"s": 27641,
"text": "Questions asked were:"
},
{
"code": null,
"e": 28404,
"s": 27663,
"text": "Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern.\nSample Input:\n\nn = 6, size = {2, 3, 4, 5, 6, 7}\n\nSample Output :\n\n68\n\nApproach: This can be solved by using minimum heap.\n\nGiven a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1. The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix.\nSample Input :\n\n[1, 0, 0],\n\n[1, 0, 0],\n\n[1, 9, 1]]\n\nSample Output :\n\n3\n\nApproach : This can be solved by using BFS or DFS.\n\n"
},
{
"code": null,
"e": 28646,
"s": 28404,
"text": "Given n number of sorted files, the task is to find the minimum computations done to reach the Optimal Merge Pattern.\nSample Input:\n\nn = 6, size = {2, 3, 4, 5, 6, 7}\n\nSample Output :\n\n68\n\nApproach: This can be solved by using minimum heap.\n\n"
},
{
"code": null,
"e": 28771,
"s": 28646,
"text": "\nSample Input:\n\nn = 6, size = {2, 3, 4, 5, 6, 7}\n\nSample Output :\n\n68\n\nApproach: This can be solved by using minimum heap.\n\n"
},
{
"code": null,
"e": 29271,
"s": 28771,
"text": "Given a matrix with values 0 (trenches), 1 (flat), and 9 (obstacle) you have to find the minimum distance to reach 9 (obstacle). If not possible then return -1. The demolition robot must start at the top left corner of the matrix, which is always flat and can move on the block up, down, right, left. The demolition robot cannot enter 0 trenches and cannot leave the matrix.\nSample Input :\n\n[1, 0, 0],\n\n[1, 0, 0],\n\n[1, 9, 1]]\n\nSample Output :\n\n3\n\nApproach : This can be solved by using BFS or DFS.\n\n"
},
{
"code": null,
"e": 29397,
"s": 29271,
"text": "\nSample Input :\n\n[1, 0, 0],\n\n[1, 0, 0],\n\n[1, 9, 1]]\n\nSample Output :\n\n3\n\nApproach : This can be solved by using BFS or DFS.\n\n"
},
{
"code": null,
"e": 29579,
"s": 29397,
"text": "All test cases passed for both so that I expected for the second round. After 15-20 days I got a mail from HR for an Amazon Chime Interview. There will be 2 rounds on that day only."
},
{
"code": null,
"e": 29588,
"s": 29579,
"text": "Round 2:"
},
{
"code": null,
"e": 29676,
"s": 29588,
"text": "Question 1: Search a Word in a 2D Grid of characters it can be possible in 8 directions"
},
{
"code": null,
"e": 29851,
"s": 29676,
"text": "Here I took more time to solve this problem and approached the brute force approach. The interviewer didn’t ask for an efficient approach since I have crossed the time limit."
},
{
"code": null,
"e": 29860,
"s": 29851,
"text": "Round 3:"
},
{
"code": null,
"e": 29919,
"s": 29860,
"text": "In this round questions asked all about arrays and string "
},
{
"code": null,
"e": 29963,
"s": 29919,
"text": "Question 1: Reverse words in a given String"
},
{
"code": null,
"e": 30006,
"s": 29963,
"text": "Question 2: Print all pairs with given sum"
},
{
"code": null,
"e": 30070,
"s": 30006,
"text": "Question 3: Count pairs in an array whose sum is divisible by K"
},
{
"code": null,
"e": 30199,
"s": 30070,
"text": "Here The Interviewer expects an efficient solution for all the questions but I gave the efficient solution for question 1 alone."
},
{
"code": null,
"e": 30391,
"s": 30199,
"text": "Next week I got a call from HR, badly I am not shortlisted for the upcoming rounds anyway I got an experience. I could suggest everyone should try to work on problems for efficient approach."
},
{
"code": null,
"e": 30405,
"s": 30391,
"text": "All the best!"
},
{
"code": null,
"e": 30412,
"s": 30405,
"text": "Amazon"
},
{
"code": null,
"e": 30422,
"s": 30412,
"text": "Marketing"
},
{
"code": null,
"e": 30444,
"s": 30422,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30451,
"s": 30444,
"text": "Amazon"
},
{
"code": null,
"e": 30549,
"s": 30451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30600,
"s": 30549,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 30642,
"s": 30600,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30678,
"s": 30642,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 30714,
"s": 30678,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30742,
"s": 30714,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30814,
"s": 30742,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 30852,
"s": 30814,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30894,
"s": 30852,
"text": "Infosys Interview Experience for DSE 2022"
},
{
"code": null,
"e": 30940,
"s": 30894,
"text": "Amazon Interview Experience (Off-Campus) 2022"
}
] |
Find n'th number in a number system with only 3 and 4 - GeeksforGeeks
|
16 Apr, 2021
Given a number system with only 3 and 4. Find the nth number in the number system. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, ...Source: Zoho Interview
We can generate all numbers with i digits using the numbers with (i-1) digits. The idea is to first add a ‘3’ as prefix in all numbers with (i-1) digit, then add a ‘4’. For example, the numbers with 2 digits are 33, 34, 43 and 44. The numbers with 3 digits are 333, 334, 343, 344, 433, 434, 443 and 444 which can be generated by first adding a 3 as prefix, then 4. Following are detailed steps.
1) Create an array 'arr[]' of strings size n+1.
2) Initialize arr[0] as empty string. (Number with 0 digits)
3) Do following while array size is smaller than or equal to n
.....a) Generate numbers by adding a 3 as prefix to the numbers generated
in previous iteration. Add these numbers to arr[]
.....a) Generate numbers by adding a 4 as prefix to the numbers generated
in previous iteration. Add these numbers to arr[]
Thanks to kaushik Lele for suggesting this idea in a comment here. Following is C++ implementation for the same.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find n'th number// in a number system with// only 3 and 4#include <iostream>using namespace std; // Function to find n'th number// in a number system with only// 3 and 4void find(int n){ // An array of strings to // store first n numbers. arr[i] // stores i'th number string arr[n + 1]; // arr[0] stores the empty string (String // with 0 digits) arr[0] = ""; // size indicates number of // current elements in arr[]. m // indicates number of elements // added to arr[] in // previous iteration. int size = 1, m = 1; // Every iteration of following // loop generates and adds // 2*m numbers to arr[] using // the m numbers generated in // previous iteration. while (size <= n) { // Consider all numbers added // in previous iteration, // add a prefix "3" to them and // add new numbers to // arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = "3" + arr[size - m + i]; // Add prefix "4" to numbers // of previous iteration // and add new numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = "4" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } cout << arr[n] << endl;} // Driver program to test above functionsint main(){ for (int i = 1; i < 16; i++) find(i); return 0;}
// Java program to find n'th number in a number system with// only 3 and 4import java.io.*; class GFG { // Function to find n'th number in a number system with // only 3 and 4 static void find(int n) { // An array of strings to store first n numbers. // arr[i] stores i'th number String[] arr = new String[n + 1]; // arr[0] stores the empty string (String with 0 // digits) arr[0] = ""; // size indicates number of current elements in // arr[], m indicates number of elements added to // arr[] in previous iteration int size = 1, m = 1; // Every iteration of following loop generates and // adds 2*m numbers to arr[] using the m numbers // generated in previous iteration while (size <= n) { // Consider all numbers added in previous // iteration, add a prefix "3" to them and add // new numbers to arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = "3" + arr[size - m + i]; // Add prefix "4" to numbers of previous // iteration and add new numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = "4" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } System.out.println(arr[n]); } // Driver program public static void main(String[] args) { for (int i = 0; i < 16; i++) find(i); }} // Contributed by Pramod Kumar
# Python3 program to find n'th# number in a number system# with only 3 and 4 # Function to find n'th number in a# number system with only 3 and 4def find(n): # An array of strings to store # first n numbers. arr[i] stores # i'th number arr = [''] * (n + 1); # arr[0] = ""; # arr[0] stores # the empty string (String with 0 digits) # size indicates number of current # elements in arr[]. m indicates # number of elements added to arr[] # in previous iteration. size = 1; m = 1; # Every iteration of following # loop generates and adds 2*m # numbers to arr[] using the m # numbers generated in previous # iteration. while (size <= n): # Consider all numbers added # in previous iteration, add # a prefix "3" to them and # add new numbers to arr[] i = 0; while(i < m and (size + i) <= n): arr[size + i] = "3" + arr[size - m + i]; i += 1; # Add prefix "4" to numbers of # previous iteration and add # new numbers to arr[] i = 0; while(i < m and (size + m + i) <= n): arr[size + m + i] = "4" + arr[size - m + i]; i += 1; # Update no. of elements added # in previous iteration m = m << 1; # Or m = m*2; # Update size size = size + m; print(arr[n]); # Driver Codefor i in range(1, 16): find(i); # This code is contributed by mits
// C# program to find n'th number in a// number system with only 3 and 4using System; class GFG { // Function to find n'th number in a // number system with only 3 and 4 static void find(int n) { // An array of strings to store first // n numbers. arr[i] stores i'th number String[] arr = new String[n + 1]; // arr[0] stores the empty string // (String with 0 digits) arr[0] = ""; // size indicates number of current // elements in arr[], m indicates // number of elements added to arr[] // in previous iteration int size = 1, m = 1; // Every iteration of following loop // generates and adds 2*m numbers to // arr[] using the m numbers generated // in previous iteration while (size <= n) { // Consider all numbers added in // previous iteration, add a prefix // "3" to them and add new numbers // to arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = "3" + arr[size - m + i]; // Add prefix "4" to numbers of // previous iteration and add new // numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = "4" + arr[size - m + i]; // Update no. of elements added // in previous iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } Console.WriteLine(arr[n]); } // Driver program public static void Main () { for (int i = 0; i < 16; i++) find(i); }} // This code is contributed by Sam007.
<?php// PHP program to find n'th// number in a number system// with only 3 and 4 // Function to find n'th number in a// number system with only 3 and 4function find($n){ // An array of strings to store // first n numbers. arr[i] stores // i'th number $arr = array_fill(0, $n + 1, ""); // $arr[0] = ""; // arr[0] stores // the empty string (String with 0 digits) // size indicates number of current // elements in arr[]. m indicates // number of elements added to arr[] // in previous iteration. $size = 1; $m = 1; // Every iteration of following // loop generates and adds 2*m // numbers to arr[] using the m // numbers generated in previous // iteration. while ($size <= $n) { // Consider all numbers added // in previous iteration, add // a prefix "3" to them and // add new numbers to arr[] for ($i = 0; $i < $m && ($size + $i) <= $n; $i++) $arr[$size + $i] = "3" . $arr[$size - $m + $i]; // Add prefix "4" to numbers of // previous iteration and add // new numbers to arr[] for ($i = 0; $i < $m && ($size + $m + $i) <= $n; $i++) $arr[$size + $m + $i] = "4" . $arr[$size - $m + $i]; // Update no. of elements added // in previous iteration $m = $m << 1; // Or m = m*2; // Update size $size = $size + $m; } echo $arr[$n] . "\n";} // Driver Codefor ($i = 1; $i < 16; $i++) find($i); // This code is contributed by mits?>
<script>// javascript program to find n'th number in a number system with// only 3 and 4 // Function to find n'th number in a number system with // only 3 and 4function find(n){ // An array of strings to store first n numbers. // arr[i] stores i'th number var arr = Array.from({length: n + 1}, (_, i) => " "); // arr[0] stores the empty string (String with 0 // digits) arr[0] = ""; // size indicates number of current elements in // arr, m indicates number of elements added to // arr in previous iteration var size = 1, m = 1; // Every iteration of following loop generates and // adds 2*m numbers to arr using the m numbers // generated in previous iteration while (size <= n) { // Consider all numbers added in previous // iteration, add a prefix "3" to them and add // new numbers to arr for (var i = 0; i < m && (size + i) <= n; i++) arr[size + i] = "3" + arr[size - m + i]; // Add prefix "4" to numbers of previous // iteration and add new numbers to arr for (var i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = "4" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } document.write(arr[n]+"<br>");} // Driver programfor (i = 0; i < 16; i++) find(i); // This code is contributed by Amit Katiyar</script>
Output:
3
4
33
34
43
44
333
334
343
344
433
434
443
444
3333
This idea was suggested by Arjun J (https://auth.geeksforgeeks.org/user/camsboyfriend/profile).
The idea here is, as we are going to deal with only two numbers, i.e., 3 and 4, so we can just compare them with binary numbers.
Explanation :
1) 3 - 0 (0)
2) 4 - 1 (1)
3) 33 - 00 (0)
4) 34 - 01 (1)
5) 43 - 10 (2)
6) 44 - 11 (3)
7) 333 - 000 (0)
8) 334 - 001 (1)
9) 343 - 010 (2)
10) 344 - 011 (3)
11) 433 - 100 (4)
12) 434 - 101 (5)
13) 443 - 110 (6)
14) 444 - 111 (7)
15) 3333 - 1000 (8)
Here we can note that
Every (n – 1)’th number gets a new digit where n is a power of 2Whenever a new digit is added we start the counting binary numbers from 0.0 in binary form corresponds to 3 in our number system and similarly 1 corresponds to 4.
Every (n – 1)’th number gets a new digit where n is a power of 2
Whenever a new digit is added we start the counting binary numbers from 0.
0 in binary form corresponds to 3 in our number system and similarly 1 corresponds to 4.
Below is the C++ implementation for the same :
C++
// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // function to find highest power of 2// less than or equal to nint highestPowerof2(unsigned int n){ if (n < 1) return 0; int res = 1; for (int i = 0; i < 8 * sizeof(unsigned int); i++) { int curr = 1 << i; if (curr > n) break; res = curr; } return res;} // function to convert decimal to binary formvector<int> decToBinary(int n, int size){ vector<int> binaryNum(size + 1); int i = 0; while (n > 0) { binaryNum[i] = n % 2; n = (n >> 1); i++; } return binaryNum;} // Driver Codesigned main(){ for (int n = 1; n < 16; n++) { int hp2 = highestPowerof2(n + 1); int howMany = n - hp2 + 1; vector<int> arr = decToBinary(howMany, log2(hp2 - 1)); for (int i = log2(hp2 - 1); i >= 0; i--) { if (arr[i]) cout << 4; else cout << 3; } cout << '\n'; }}
Output:
3
4
33
34
43
44
333
334
343
344
433
434
443
444
3333
This article is contributed by Raman. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
Mithun Kumar
camsboyfriend
amit143katiyar
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
|
[
{
"code": null,
"e": 26371,
"s": 26343,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 26634,
"s": 26371,
"text": "Given a number system with only 3 and 4. Find the nth number in the number system. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, ...Source: Zoho Interview"
},
{
"code": null,
"e": 27030,
"s": 26634,
"text": "We can generate all numbers with i digits using the numbers with (i-1) digits. The idea is to first add a ‘3’ as prefix in all numbers with (i-1) digit, then add a ‘4’. For example, the numbers with 2 digits are 33, 34, 43 and 44. The numbers with 3 digits are 333, 334, 343, 344, 433, 434, 443 and 444 which can be generated by first adding a 3 as prefix, then 4. Following are detailed steps. "
},
{
"code": null,
"e": 27470,
"s": 27030,
"text": "1) Create an array 'arr[]' of strings size n+1. \n2) Initialize arr[0] as empty string. (Number with 0 digits)\n3) Do following while array size is smaller than or equal to n\n.....a) Generate numbers by adding a 3 as prefix to the numbers generated \n in previous iteration. Add these numbers to arr[]\n.....a) Generate numbers by adding a 4 as prefix to the numbers generated \n in previous iteration. Add these numbers to arr[]"
},
{
"code": null,
"e": 27585,
"s": 27470,
"text": "Thanks to kaushik Lele for suggesting this idea in a comment here. Following is C++ implementation for the same. "
},
{
"code": null,
"e": 27589,
"s": 27585,
"text": "C++"
},
{
"code": null,
"e": 27594,
"s": 27589,
"text": "Java"
},
{
"code": null,
"e": 27602,
"s": 27594,
"text": "Python3"
},
{
"code": null,
"e": 27605,
"s": 27602,
"text": "C#"
},
{
"code": null,
"e": 27609,
"s": 27605,
"text": "PHP"
},
{
"code": null,
"e": 27620,
"s": 27609,
"text": "Javascript"
},
{
"code": "// C++ program to find n'th number// in a number system with// only 3 and 4#include <iostream>using namespace std; // Function to find n'th number// in a number system with only// 3 and 4void find(int n){ // An array of strings to // store first n numbers. arr[i] // stores i'th number string arr[n + 1]; // arr[0] stores the empty string (String // with 0 digits) arr[0] = \"\"; // size indicates number of // current elements in arr[]. m // indicates number of elements // added to arr[] in // previous iteration. int size = 1, m = 1; // Every iteration of following // loop generates and adds // 2*m numbers to arr[] using // the m numbers generated in // previous iteration. while (size <= n) { // Consider all numbers added // in previous iteration, // add a prefix \"3\" to them and // add new numbers to // arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = \"3\" + arr[size - m + i]; // Add prefix \"4\" to numbers // of previous iteration // and add new numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = \"4\" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } cout << arr[n] << endl;} // Driver program to test above functionsint main(){ for (int i = 1; i < 16; i++) find(i); return 0;}",
"e": 29173,
"s": 27620,
"text": null
},
{
"code": "// Java program to find n'th number in a number system with// only 3 and 4import java.io.*; class GFG { // Function to find n'th number in a number system with // only 3 and 4 static void find(int n) { // An array of strings to store first n numbers. // arr[i] stores i'th number String[] arr = new String[n + 1]; // arr[0] stores the empty string (String with 0 // digits) arr[0] = \"\"; // size indicates number of current elements in // arr[], m indicates number of elements added to // arr[] in previous iteration int size = 1, m = 1; // Every iteration of following loop generates and // adds 2*m numbers to arr[] using the m numbers // generated in previous iteration while (size <= n) { // Consider all numbers added in previous // iteration, add a prefix \"3\" to them and add // new numbers to arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = \"3\" + arr[size - m + i]; // Add prefix \"4\" to numbers of previous // iteration and add new numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = \"4\" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } System.out.println(arr[n]); } // Driver program public static void main(String[] args) { for (int i = 0; i < 16; i++) find(i); }} // Contributed by Pramod Kumar",
"e": 30866,
"s": 29173,
"text": null
},
{
"code": "# Python3 program to find n'th# number in a number system# with only 3 and 4 # Function to find n'th number in a# number system with only 3 and 4def find(n): # An array of strings to store # first n numbers. arr[i] stores # i'th number arr = [''] * (n + 1); # arr[0] = \"\"; # arr[0] stores # the empty string (String with 0 digits) # size indicates number of current # elements in arr[]. m indicates # number of elements added to arr[] # in previous iteration. size = 1; m = 1; # Every iteration of following # loop generates and adds 2*m # numbers to arr[] using the m # numbers generated in previous # iteration. while (size <= n): # Consider all numbers added # in previous iteration, add # a prefix \"3\" to them and # add new numbers to arr[] i = 0; while(i < m and (size + i) <= n): arr[size + i] = \"3\" + arr[size - m + i]; i += 1; # Add prefix \"4\" to numbers of # previous iteration and add # new numbers to arr[] i = 0; while(i < m and (size + m + i) <= n): arr[size + m + i] = \"4\" + arr[size - m + i]; i += 1; # Update no. of elements added # in previous iteration m = m << 1; # Or m = m*2; # Update size size = size + m; print(arr[n]); # Driver Codefor i in range(1, 16): find(i); # This code is contributed by mits",
"e": 32329,
"s": 30866,
"text": null
},
{
"code": "// C# program to find n'th number in a// number system with only 3 and 4using System; class GFG { // Function to find n'th number in a // number system with only 3 and 4 static void find(int n) { // An array of strings to store first // n numbers. arr[i] stores i'th number String[] arr = new String[n + 1]; // arr[0] stores the empty string // (String with 0 digits) arr[0] = \"\"; // size indicates number of current // elements in arr[], m indicates // number of elements added to arr[] // in previous iteration int size = 1, m = 1; // Every iteration of following loop // generates and adds 2*m numbers to // arr[] using the m numbers generated // in previous iteration while (size <= n) { // Consider all numbers added in // previous iteration, add a prefix // \"3\" to them and add new numbers // to arr[] for (int i = 0; i < m && (size + i) <= n; i++) arr[size + i] = \"3\" + arr[size - m + i]; // Add prefix \"4\" to numbers of // previous iteration and add new // numbers to arr[] for (int i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = \"4\" + arr[size - m + i]; // Update no. of elements added // in previous iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } Console.WriteLine(arr[n]); } // Driver program public static void Main () { for (int i = 0; i < 16; i++) find(i); }} // This code is contributed by Sam007.",
"e": 34258,
"s": 32329,
"text": null
},
{
"code": "<?php// PHP program to find n'th// number in a number system// with only 3 and 4 // Function to find n'th number in a// number system with only 3 and 4function find($n){ // An array of strings to store // first n numbers. arr[i] stores // i'th number $arr = array_fill(0, $n + 1, \"\"); // $arr[0] = \"\"; // arr[0] stores // the empty string (String with 0 digits) // size indicates number of current // elements in arr[]. m indicates // number of elements added to arr[] // in previous iteration. $size = 1; $m = 1; // Every iteration of following // loop generates and adds 2*m // numbers to arr[] using the m // numbers generated in previous // iteration. while ($size <= $n) { // Consider all numbers added // in previous iteration, add // a prefix \"3\" to them and // add new numbers to arr[] for ($i = 0; $i < $m && ($size + $i) <= $n; $i++) $arr[$size + $i] = \"3\" . $arr[$size - $m + $i]; // Add prefix \"4\" to numbers of // previous iteration and add // new numbers to arr[] for ($i = 0; $i < $m && ($size + $m + $i) <= $n; $i++) $arr[$size + $m + $i] = \"4\" . $arr[$size - $m + $i]; // Update no. of elements added // in previous iteration $m = $m << 1; // Or m = m*2; // Update size $size = $size + $m; } echo $arr[$n] . \"\\n\";} // Driver Codefor ($i = 1; $i < 16; $i++) find($i); // This code is contributed by mits?>",
"e": 35820,
"s": 34258,
"text": null
},
{
"code": "<script>// javascript program to find n'th number in a number system with// only 3 and 4 // Function to find n'th number in a number system with // only 3 and 4function find(n){ // An array of strings to store first n numbers. // arr[i] stores i'th number var arr = Array.from({length: n + 1}, (_, i) => \" \"); // arr[0] stores the empty string (String with 0 // digits) arr[0] = \"\"; // size indicates number of current elements in // arr, m indicates number of elements added to // arr in previous iteration var size = 1, m = 1; // Every iteration of following loop generates and // adds 2*m numbers to arr using the m numbers // generated in previous iteration while (size <= n) { // Consider all numbers added in previous // iteration, add a prefix \"3\" to them and add // new numbers to arr for (var i = 0; i < m && (size + i) <= n; i++) arr[size + i] = \"3\" + arr[size - m + i]; // Add prefix \"4\" to numbers of previous // iteration and add new numbers to arr for (var i = 0; i < m && (size + m + i) <= n; i++) arr[size + m + i] = \"4\" + arr[size - m + i]; // Update no. of elements added in previous // iteration m = m << 1; // Or m = m*2; // Update size size = size + m; } document.write(arr[n]+\"<br>\");} // Driver programfor (i = 0; i < 16; i++) find(i); // This code is contributed by Amit Katiyar</script>",
"e": 37322,
"s": 35820,
"text": null
},
{
"code": null,
"e": 37332,
"s": 37322,
"text": "Output: "
},
{
"code": null,
"e": 37385,
"s": 37332,
"text": "3\n4\n33\n34\n43\n44\n333\n334\n343\n344\n433\n434\n443\n444\n3333"
},
{
"code": null,
"e": 37481,
"s": 37385,
"text": "This idea was suggested by Arjun J (https://auth.geeksforgeeks.org/user/camsboyfriend/profile)."
},
{
"code": null,
"e": 37610,
"s": 37481,
"text": "The idea here is, as we are going to deal with only two numbers, i.e., 3 and 4, so we can just compare them with binary numbers."
},
{
"code": null,
"e": 37624,
"s": 37610,
"text": "Explanation :"
},
{
"code": null,
"e": 37944,
"s": 37624,
"text": "1) 3 - 0 (0)\n2) 4 - 1 (1)\n\n3) 33 - 00 (0)\n4) 34 - 01 (1)\n5) 43 - 10 (2) \n6) 44 - 11 (3)\n\n7) 333 - 000 (0)\n8) 334 - 001 (1)\n9) 343 - 010 (2) \n10) 344 - 011 (3)\n11) 433 - 100 (4)\n12) 434 - 101 (5)\n13) 443 - 110 (6)\n14) 444 - 111 (7)\n15) 3333 - 1000 (8)"
},
{
"code": null,
"e": 37967,
"s": 37944,
"text": "Here we can note that "
},
{
"code": null,
"e": 38195,
"s": 37967,
"text": "Every (n – 1)’th number gets a new digit where n is a power of 2Whenever a new digit is added we start the counting binary numbers from 0.0 in binary form corresponds to 3 in our number system and similarly 1 corresponds to 4."
},
{
"code": null,
"e": 38260,
"s": 38195,
"text": "Every (n – 1)’th number gets a new digit where n is a power of 2"
},
{
"code": null,
"e": 38335,
"s": 38260,
"text": "Whenever a new digit is added we start the counting binary numbers from 0."
},
{
"code": null,
"e": 38425,
"s": 38335,
"text": "0 in binary form corresponds to 3 in our number system and similarly 1 corresponds to 4."
},
{
"code": null,
"e": 38472,
"s": 38425,
"text": "Below is the C++ implementation for the same :"
},
{
"code": null,
"e": 38476,
"s": 38472,
"text": "C++"
},
{
"code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // function to find highest power of 2// less than or equal to nint highestPowerof2(unsigned int n){ if (n < 1) return 0; int res = 1; for (int i = 0; i < 8 * sizeof(unsigned int); i++) { int curr = 1 << i; if (curr > n) break; res = curr; } return res;} // function to convert decimal to binary formvector<int> decToBinary(int n, int size){ vector<int> binaryNum(size + 1); int i = 0; while (n > 0) { binaryNum[i] = n % 2; n = (n >> 1); i++; } return binaryNum;} // Driver Codesigned main(){ for (int n = 1; n < 16; n++) { int hp2 = highestPowerof2(n + 1); int howMany = n - hp2 + 1; vector<int> arr = decToBinary(howMany, log2(hp2 - 1)); for (int i = log2(hp2 - 1); i >= 0; i--) { if (arr[i]) cout << 4; else cout << 3; } cout << '\\n'; }}",
"e": 39510,
"s": 38476,
"text": null
},
{
"code": null,
"e": 39519,
"s": 39510,
"text": "Output: "
},
{
"code": null,
"e": 39572,
"s": 39519,
"text": "3\n4\n33\n34\n43\n44\n333\n334\n343\n344\n433\n434\n443\n444\n3333"
},
{
"code": null,
"e": 39735,
"s": 39572,
"text": "This article is contributed by Raman. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 39742,
"s": 39735,
"text": "Sam007"
},
{
"code": null,
"e": 39755,
"s": 39742,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 39769,
"s": 39755,
"text": "camsboyfriend"
},
{
"code": null,
"e": 39784,
"s": 39769,
"text": "amit143katiyar"
},
{
"code": null,
"e": 39797,
"s": 39784,
"text": "Mathematical"
},
{
"code": null,
"e": 39810,
"s": 39797,
"text": "Mathematical"
},
{
"code": null,
"e": 39908,
"s": 39810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39932,
"s": 39908,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 39975,
"s": 39932,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 39989,
"s": 39975,
"text": "Prime Numbers"
},
{
"code": null,
"e": 40031,
"s": 39989,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 40053,
"s": 40031,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 40126,
"s": 40053,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40167,
"s": 40126,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 40210,
"s": 40167,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 40231,
"s": 40210,
"text": "Operators in C / C++"
}
] |
How to delete only one row in CSV with Python? - GeeksforGeeks
|
24 Jan, 2021
Prerequisites: pandas
One can open and edit CSV files in Python via Pandas library. While editing the file one might want to remove the entire row in the file. Following are some different approaches to do the same:
Data set in use: iris.csv dataset
This method is only good for removing the first or the last row from the dataset. And the following two lines of code which although means same represent the use of the .iloc[] method in pandas.
Syntax:
df.iloc[<row_number>, <column_number>]
or
df.iloc[<row_number>]
Approach: To remove first row
Import the library
Load the dataset in python
To remove the first-row using slicing. Since the index column by default is numeric, hence the index label will also be integers.
(0 indexes will be removed as in python indexing starts from 0):
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) df = df.iloc[1:] print(df)
Output
removing first row
Approach: To remove the last row
import the library
load the dataset in python
to remove the last-row using slicing. As the index column by default is numeric, hence the index label will also be integers.
(here -1 represents the last row of the data)
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) df = df.iloc[:-1] print(df)
Output
removing last row
Removing using Label means the name of the row is specified in the code whereas using indexing means the index(position/ row number starting from 0) of the row is specified in the code.
Data set in use:
subset – top 5 items
Approach: Using row label
Import pandas library
Load dataset
Select required data
With the use of row label (here 5.1) dropping the row corresponding to the same label. Label can be of any data type (string or integer or float etc).
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) # 2.df_s = df[:5] # 3.df_s.set_index('sepal_length', inplace=True) # 4.1.df_s = df_s.drop(5.1) print(df_s)
Output
using row label
Approach: Using row index
Import pandas library
Load dataset
Select required data
With the use of row index one needs to pass the index of the row to be removed.
df.index[ ] takes index numbers as a parameter starting from 1 and onwards whereas in python indexing starts from 0.
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) df_s = df[:5] df_s.set_index('sepal_length', inplace=True) df_s = df_s.drop(df_s.index[1])#df_s.drop(df_s.index[1],inplace = True) print(df_s)
Output
using row index
Dataset in use:
subset – top 5 items
Approach 1:
Import module
Load data
Select required data
Find the row that specifies the specified condition
Use drop() method and pass the index of the fetched row as a parameter in the drop method.
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) df_s1 = df[:5] df_s1 = df_s1.drop(df_s1[(df_s1.sepal_length == 4.7) & (df_s1.petal_length == 1.3)].index) print(df_s1)
Output
first method – conditional removal
Approach 2:
Import module
Load data
Select required data
Find the row that specifies the specified condition using query() method
Use drop() method and pass the index of the fetched row as a parameter in the drop method.
Program:
Python3
import pandas as pd url = "https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv"df = pd.read_csv(url) df_s1 = df[:5] df_s1 = df_s1.drop(df_s1.query('sepal_length==5.0').index) print(df_s1)
Output:
second method – conditional removal
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
loops in python
|
[
{
"code": null,
"e": 24413,
"s": 24385,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24435,
"s": 24413,
"text": "Prerequisites: pandas"
},
{
"code": null,
"e": 24629,
"s": 24435,
"text": "One can open and edit CSV files in Python via Pandas library. While editing the file one might want to remove the entire row in the file. Following are some different approaches to do the same:"
},
{
"code": null,
"e": 24664,
"s": 24629,
"text": "Data set in use: iris.csv dataset "
},
{
"code": null,
"e": 24860,
"s": 24664,
"text": "This method is only good for removing the first or the last row from the dataset. And the following two lines of code which although means same represent the use of the .iloc[] method in pandas."
},
{
"code": null,
"e": 24868,
"s": 24860,
"text": "Syntax:"
},
{
"code": null,
"e": 24907,
"s": 24868,
"text": "df.iloc[<row_number>, <column_number>]"
},
{
"code": null,
"e": 24910,
"s": 24907,
"text": "or"
},
{
"code": null,
"e": 24932,
"s": 24910,
"text": "df.iloc[<row_number>]"
},
{
"code": null,
"e": 24962,
"s": 24932,
"text": "Approach: To remove first row"
},
{
"code": null,
"e": 24981,
"s": 24962,
"text": "Import the library"
},
{
"code": null,
"e": 25008,
"s": 24981,
"text": "Load the dataset in python"
},
{
"code": null,
"e": 25138,
"s": 25008,
"text": "To remove the first-row using slicing. Since the index column by default is numeric, hence the index label will also be integers."
},
{
"code": null,
"e": 25203,
"s": 25138,
"text": "(0 indexes will be removed as in python indexing starts from 0):"
},
{
"code": null,
"e": 25212,
"s": 25203,
"text": "Program:"
},
{
"code": null,
"e": 25220,
"s": 25212,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) df = df.iloc[1:] print(df)",
"e": 25416,
"s": 25220,
"text": null
},
{
"code": null,
"e": 25423,
"s": 25416,
"text": "Output"
},
{
"code": null,
"e": 25442,
"s": 25423,
"text": "removing first row"
},
{
"code": null,
"e": 25476,
"s": 25442,
"text": "Approach: To remove the last row "
},
{
"code": null,
"e": 25495,
"s": 25476,
"text": "import the library"
},
{
"code": null,
"e": 25522,
"s": 25495,
"text": "load the dataset in python"
},
{
"code": null,
"e": 25648,
"s": 25522,
"text": "to remove the last-row using slicing. As the index column by default is numeric, hence the index label will also be integers."
},
{
"code": null,
"e": 25694,
"s": 25648,
"text": "(here -1 represents the last row of the data)"
},
{
"code": null,
"e": 25703,
"s": 25694,
"text": "Program:"
},
{
"code": null,
"e": 25711,
"s": 25703,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) df = df.iloc[:-1] print(df)",
"e": 25908,
"s": 25711,
"text": null
},
{
"code": null,
"e": 25915,
"s": 25908,
"text": "Output"
},
{
"code": null,
"e": 25933,
"s": 25915,
"text": "removing last row"
},
{
"code": null,
"e": 26119,
"s": 25933,
"text": "Removing using Label means the name of the row is specified in the code whereas using indexing means the index(position/ row number starting from 0) of the row is specified in the code."
},
{
"code": null,
"e": 26136,
"s": 26119,
"text": "Data set in use:"
},
{
"code": null,
"e": 26157,
"s": 26136,
"text": "subset – top 5 items"
},
{
"code": null,
"e": 26183,
"s": 26157,
"text": "Approach: Using row label"
},
{
"code": null,
"e": 26205,
"s": 26183,
"text": "Import pandas library"
},
{
"code": null,
"e": 26218,
"s": 26205,
"text": "Load dataset"
},
{
"code": null,
"e": 26239,
"s": 26218,
"text": "Select required data"
},
{
"code": null,
"e": 26390,
"s": 26239,
"text": "With the use of row label (here 5.1) dropping the row corresponding to the same label. Label can be of any data type (string or integer or float etc)."
},
{
"code": null,
"e": 26399,
"s": 26390,
"text": "Program:"
},
{
"code": null,
"e": 26407,
"s": 26399,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) # 2.df_s = df[:5] # 3.df_s.set_index('sepal_length', inplace=True) # 4.1.df_s = df_s.drop(5.1) print(df_s)",
"e": 26685,
"s": 26407,
"text": null
},
{
"code": null,
"e": 26692,
"s": 26685,
"text": "Output"
},
{
"code": null,
"e": 26709,
"s": 26692,
"text": "using row label "
},
{
"code": null,
"e": 26735,
"s": 26709,
"text": "Approach: Using row index"
},
{
"code": null,
"e": 26757,
"s": 26735,
"text": "Import pandas library"
},
{
"code": null,
"e": 26770,
"s": 26757,
"text": "Load dataset"
},
{
"code": null,
"e": 26791,
"s": 26770,
"text": "Select required data"
},
{
"code": null,
"e": 26871,
"s": 26791,
"text": "With the use of row index one needs to pass the index of the row to be removed."
},
{
"code": null,
"e": 26988,
"s": 26871,
"text": "df.index[ ] takes index numbers as a parameter starting from 1 and onwards whereas in python indexing starts from 0."
},
{
"code": null,
"e": 26997,
"s": 26988,
"text": "Program:"
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) df_s = df[:5] df_s.set_index('sepal_length', inplace=True) df_s = df_s.drop(df_s.index[1])#df_s.drop(df_s.index[1],inplace = True) print(df_s)",
"e": 27319,
"s": 27005,
"text": null
},
{
"code": null,
"e": 27326,
"s": 27319,
"text": "Output"
},
{
"code": null,
"e": 27342,
"s": 27326,
"text": "using row index"
},
{
"code": null,
"e": 27358,
"s": 27342,
"text": "Dataset in use:"
},
{
"code": null,
"e": 27379,
"s": 27358,
"text": "subset – top 5 items"
},
{
"code": null,
"e": 27391,
"s": 27379,
"text": "Approach 1:"
},
{
"code": null,
"e": 27405,
"s": 27391,
"text": "Import module"
},
{
"code": null,
"e": 27415,
"s": 27405,
"text": "Load data"
},
{
"code": null,
"e": 27436,
"s": 27415,
"text": "Select required data"
},
{
"code": null,
"e": 27488,
"s": 27436,
"text": "Find the row that specifies the specified condition"
},
{
"code": null,
"e": 27579,
"s": 27488,
"text": "Use drop() method and pass the index of the fetched row as a parameter in the drop method."
},
{
"code": null,
"e": 27588,
"s": 27579,
"text": "Program:"
},
{
"code": null,
"e": 27596,
"s": 27588,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) df_s1 = df[:5] df_s1 = df_s1.drop(df_s1[(df_s1.sepal_length == 4.7) & (df_s1.petal_length == 1.3)].index) print(df_s1)",
"e": 27913,
"s": 27596,
"text": null
},
{
"code": null,
"e": 27920,
"s": 27913,
"text": "Output"
},
{
"code": null,
"e": 27955,
"s": 27920,
"text": "first method – conditional removal"
},
{
"code": null,
"e": 28002,
"s": 27990,
"text": "Approach 2:"
},
{
"code": null,
"e": 28016,
"s": 28002,
"text": "Import module"
},
{
"code": null,
"e": 28026,
"s": 28016,
"text": "Load data"
},
{
"code": null,
"e": 28047,
"s": 28026,
"text": "Select required data"
},
{
"code": null,
"e": 28120,
"s": 28047,
"text": "Find the row that specifies the specified condition using query() method"
},
{
"code": null,
"e": 28211,
"s": 28120,
"text": "Use drop() method and pass the index of the fetched row as a parameter in the drop method."
},
{
"code": null,
"e": 28220,
"s": 28211,
"text": "Program:"
},
{
"code": null,
"e": 28228,
"s": 28220,
"text": "Python3"
},
{
"code": "import pandas as pd url = \"https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv\"df = pd.read_csv(url) df_s1 = df[:5] df_s1 = df_s1.drop(df_s1.query('sepal_length==5.0').index) print(df_s1)",
"e": 28485,
"s": 28228,
"text": null
},
{
"code": null,
"e": 28493,
"s": 28485,
"text": "Output:"
},
{
"code": null,
"e": 28529,
"s": 28493,
"text": "second method – conditional removal"
},
{
"code": null,
"e": 28540,
"s": 28529,
"text": "python-csv"
},
{
"code": null,
"e": 28547,
"s": 28540,
"text": "Python"
},
{
"code": null,
"e": 28645,
"s": 28547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28654,
"s": 28645,
"text": "Comments"
},
{
"code": null,
"e": 28667,
"s": 28654,
"text": "Old Comments"
},
{
"code": null,
"e": 28703,
"s": 28667,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 28721,
"s": 28703,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28744,
"s": 28721,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 28766,
"s": 28744,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28805,
"s": 28766,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28838,
"s": 28805,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 28887,
"s": 28838,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 28920,
"s": 28887,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 28961,
"s": 28920,
"text": "Python - Call function from another file"
}
] |
Javascript | JSON PHP - GeeksforGeeks
|
20 Oct, 2021
JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object into the JSON format is done by the given function:
JSON.stringify(object)
Converting the JSON format into the JavaScript object is done by the given function:
JSON.parse(string_format)
Exchanging the data from server, PHP as server language used. The JSON.parse() function is used to get the data from php or from the any other server. For the receiving the data from the server few AJAX statements to check whether the server is ready to respond the data from the server or not. If those conditions are fulfilled then the data from the php file can be received. The protocols used to sending and receiving the data from server is given by:
XMLHttpRequest()
PHP Files and its client JavaScript: Consider a php file in which the object of the person are given with his personal data like name, gender, age are given into it. The data form the object of the php are to be encoded into JSON format. The given file is saved by geeks.php
php
<?php$myObj = new stdClass();$myObj->name = "Geeks";$myObj->college="NIT";$myObj->gender = "Male";$myObj->age = 30; $myJSON = json_encode($myObj); echo $myJSON;?>
From the php file the data is being sent to the JSON via the “echo” and the data will be responded in the JavaScript of the client. In the php file json_encode() is used to convert the objects in the php file to json format. Accessing the data from php file via client JavaScript use the following script:
html
<!DOCTYPE html><html><body><h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1><p style="font-size:25px">JSON get data from a PHP file on the server.</p> <h4>Author Name:</h4><p id="name"></p> <h4>College:</h4><p id="college"></p> <h4>Gender:</h4><p id="gender"></p> <h4>Age:</h4><p id="age"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("name").innerHTML = myObj.name; document.getElementById("college").innerHTML = myObj.college; document.getElementById("gender").innerHTML = myObj.gender; document.getElementById("age").innerHTML = myObj.age; }};xmlhttp.open("GET", "geeks.php", true);xmlhttp.send(); </script> </body></html>
Output:
In the Script JSON.parse(this.responseText) function is used to parse the data into variable so that it can call the values from that object. The this.response is used to take the data from the php that is being print as a string. In the given code the php object data is being taken extracted by script of the JSON. By the AJAX function in the script are checking the data whether it is responding are not when the it has responded the data will be sent and print in the web page. The xmlhttp.open(“GET”, “geeks.php”, true) function is used to get the value from the php file geeks.php. The xmlhttp.send() function is used to send the values in to the XMLHttpRequest().PHP Array and its client JavaScript: Consider a php file which consists an array of the name. The data is encoded into the JSON and will be printed using the “echo”.
php
<?php$arrDay = array( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); $arrJSON = json_encode($arrDay); echo $arrJSON;?>
Lets access the data from php file’s array using client JavaScript. To do so let us consider the following HTML file.
html
<!DOCTYPE html><html><body><h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1><p style="font-size:25px">JSON get data from PHP file, and converting into JavaScript array.</p> <p style = "font-size:25px;">Second Date of week: </p> <p id="day"></p> <script>var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("day").innerHTML = myObj[2]; }};xmlhttp.open("GET", "daylist.php", true);xmlhttp.send(); </script> </body></html>
Output:
In the array is parsed to the variable in the JavaScript that value is being called by the array of js that is been initialised on the above line.PHP Database: Retrieving the data from the database is just similar to getting the data from the normal php file. But the few additional queries to be added. In this process first data from the database has to be extracted to the php file and then that data has to be taken by the JavaScript to project it into client server. First create the MySQL database using the php. The following program is used to create a table and inserted few data into it.
php
<?php $conn = new mysqli("localhost", "root", "", "geeksforgeeks"); $createTable = "create table geeks(names varchar(255))"; $tableadd = $conn->query($createTable); $conn->query("insert into geeks values('Geeks')"); $conn->query("insert into geeks values('gfg')"); $conn->query("insert into geeks values('g4g')"); $conn->close();?>
Now, extracting the data from other php script.
php
<?php $conn = new mysqli("localhost", "root", "", "geeksforgeeks"); $result = $conn->query("select names from geeks"); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); $sresult = json_encode($output); echo $sresult; $conn->close(); ?>
Now let us gather data in the client JavaScript and print the result.
html
<!DOCTYPE html><html> <body> <h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1> <p style="font-size:25px"> JSON received the data from the PHP file </p> <p id="arrayContent"></p> <script> var obj, xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("arrayContent").innerHTML = this.responseText; } }; xmlhttp.open("GET", "data.php", true); xmlhttp.send(); </script> </body></html>
In the following that is sent to client and printed the result in JSON structure since it is not filtered values into each different values. output:
PHP Loop: This is the combination of the array and the above two topics (PHP Array and Its client JavaScript & PHP Database) with the integrating them with the loops in it. In this JavaScript parses the values into a variable those values are are called by arrays and after printing the each myObj it’s values will be incremented to the next value.
html
<!DOCTYPE html><html> <body> <h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1> <p style="font-size:25px"> JSON received the data from the PHP file </p> <p id="arrayContent"></p> <script> var obj, xmlhttp, myObj, x, txt = ""; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].names + "<br>"; } document.getElementById("arrayContent").innerHTML = txt; } }; xmlhttp.open("GET", "data.php", true); xmlhttp.send(); </script> </body></html>
Output:
PHP Method = POST: It quiet simple if above topics had understood completely. In the following syntax changes will occur. In the POST method the arguments have to be passed via send method but in the GET method the arguments can passed when the request of the php file sent.GET method:
open("GET", file_name?x=argument, asyn, username, password)
POST method:
open("POST", file_name, asyn, username, password)
The arguments are passed by the send(argument) method and send a request from the php to access data from server. So use function to get request are given below:
setRequestHeader("Content-type", "application/x-www-form-urlencoded")
In the php file a header has to be added:
header("Content-Type: application/json; charset=UTF-8")
. The php file given below can be saved using post.php
php
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_POST["x"], false); $conn = new mysqli("localhost", "root", "", "geeksforgeeks"); $result = $conn->query("select names from ".$obj->table); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); $sresult = json_encode($output); echo $sresult;?>
After doing all this in php and the html file this will be appear as follows:
html
<!DOCTYPE html><html> <body> <h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1> <p style="font-size:25px">geeks table values:</p> <p id="arrayContent"></p> <script> var obj, xmlhttp, myObj, x, txt = ""; obj = JSON.stringify({"table":"geeks"}); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].names + "<br>"; } document.getElementById("arrayContent").innerHTML = txt; } }; xmlhttp.open("POST", "post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + obj ); </script> </body></html>
Output:
Akanksha_Rai
singghakshay
kashishsoda
JSON
Picked
JavaScript
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
|
[
{
"code": null,
"e": 25454,
"s": 25426,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25809,
"s": 25454,
"text": "JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object into the JSON format is done by the given function: "
},
{
"code": null,
"e": 25832,
"s": 25809,
"text": "JSON.stringify(object)"
},
{
"code": null,
"e": 25919,
"s": 25832,
"text": "Converting the JSON format into the JavaScript object is done by the given function: "
},
{
"code": null,
"e": 25945,
"s": 25919,
"text": "JSON.parse(string_format)"
},
{
"code": null,
"e": 26403,
"s": 25945,
"text": "Exchanging the data from server, PHP as server language used. The JSON.parse() function is used to get the data from php or from the any other server. For the receiving the data from the server few AJAX statements to check whether the server is ready to respond the data from the server or not. If those conditions are fulfilled then the data from the php file can be received. The protocols used to sending and receiving the data from server is given by: "
},
{
"code": null,
"e": 26420,
"s": 26403,
"text": "XMLHttpRequest()"
},
{
"code": null,
"e": 26696,
"s": 26420,
"text": "PHP Files and its client JavaScript: Consider a php file in which the object of the person are given with his personal data like name, gender, age are given into it. The data form the object of the php are to be encoded into JSON format. The given file is saved by geeks.php "
},
{
"code": null,
"e": 26700,
"s": 26696,
"text": "php"
},
{
"code": "<?php$myObj = new stdClass();$myObj->name = \"Geeks\";$myObj->college=\"NIT\";$myObj->gender = \"Male\";$myObj->age = 30; $myJSON = json_encode($myObj); echo $myJSON;?>",
"e": 26865,
"s": 26700,
"text": null
},
{
"code": null,
"e": 27172,
"s": 26865,
"text": "From the php file the data is being sent to the JSON via the “echo” and the data will be responded in the JavaScript of the client. In the php file json_encode() is used to convert the objects in the php file to json format. Accessing the data from php file via client JavaScript use the following script: "
},
{
"code": null,
"e": 27177,
"s": 27172,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><body><h1 style = \"color:#090; text-align:center;\">GeeksforGeeks</h1><p style=\"font-size:25px\">JSON get data from a PHP file on the server.</p> <h4>Author Name:</h4><p id=\"name\"></p> <h4>College:</h4><p id=\"college\"></p> <h4>Gender:</h4><p id=\"gender\"></p> <h4>Age:</h4><p id=\"age\"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById(\"name\").innerHTML = myObj.name; document.getElementById(\"college\").innerHTML = myObj.college; document.getElementById(\"gender\").innerHTML = myObj.gender; document.getElementById(\"age\").innerHTML = myObj.age; }};xmlhttp.open(\"GET\", \"geeks.php\", true);xmlhttp.send(); </script> </body></html>",
"e": 28035,
"s": 27177,
"text": null
},
{
"code": null,
"e": 28045,
"s": 28035,
"text": "Output: "
},
{
"code": null,
"e": 28882,
"s": 28045,
"text": "In the Script JSON.parse(this.responseText) function is used to parse the data into variable so that it can call the values from that object. The this.response is used to take the data from the php that is being print as a string. In the given code the php object data is being taken extracted by script of the JSON. By the AJAX function in the script are checking the data whether it is responding are not when the it has responded the data will be sent and print in the web page. The xmlhttp.open(“GET”, “geeks.php”, true) function is used to get the value from the php file geeks.php. The xmlhttp.send() function is used to send the values in to the XMLHttpRequest().PHP Array and its client JavaScript: Consider a php file which consists an array of the name. The data is encoded into the JSON and will be printed using the “echo”. "
},
{
"code": null,
"e": 28886,
"s": 28882,
"text": "php"
},
{
"code": "<?php$arrDay = array( \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"); $arrJSON = json_encode($arrDay); echo $arrJSON;?>",
"e": 29058,
"s": 28886,
"text": null
},
{
"code": null,
"e": 29177,
"s": 29058,
"text": "Lets access the data from php file’s array using client JavaScript. To do so let us consider the following HTML file. "
},
{
"code": null,
"e": 29182,
"s": 29177,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><body><h1 style = \"color:#090; text-align:center;\">GeeksforGeeks</h1><p style=\"font-size:25px\">JSON get data from PHP file, and converting into JavaScript array.</p> <p style = \"font-size:25px;\">Second Date of week: </p> <p id=\"day\"></p> <script>var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById(\"day\").innerHTML = myObj[2]; }};xmlhttp.open(\"GET\", \"daylist.php\", true);xmlhttp.send(); </script> </body></html> ",
"e": 29802,
"s": 29182,
"text": null
},
{
"code": null,
"e": 29812,
"s": 29802,
"text": "Output: "
},
{
"code": null,
"e": 30412,
"s": 29812,
"text": "In the array is parsed to the variable in the JavaScript that value is being called by the array of js that is been initialised on the above line.PHP Database: Retrieving the data from the database is just similar to getting the data from the normal php file. But the few additional queries to be added. In this process first data from the database has to be extracted to the php file and then that data has to be taken by the JavaScript to project it into client server. First create the MySQL database using the php. The following program is used to create a table and inserted few data into it. "
},
{
"code": null,
"e": 30416,
"s": 30412,
"text": "php"
},
{
"code": "<?php $conn = new mysqli(\"localhost\", \"root\", \"\", \"geeksforgeeks\"); $createTable = \"create table geeks(names varchar(255))\"; $tableadd = $conn->query($createTable); $conn->query(\"insert into geeks values('Geeks')\"); $conn->query(\"insert into geeks values('gfg')\"); $conn->query(\"insert into geeks values('g4g')\"); $conn->close();?>",
"e": 30784,
"s": 30416,
"text": null
},
{
"code": null,
"e": 30834,
"s": 30784,
"text": "Now, extracting the data from other php script. "
},
{
"code": null,
"e": 30838,
"s": 30834,
"text": "php"
},
{
"code": "<?php $conn = new mysqli(\"localhost\", \"root\", \"\", \"geeksforgeeks\"); $result = $conn->query(\"select names from geeks\"); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); $sresult = json_encode($output); echo $sresult; $conn->close(); ?>",
"e": 31125,
"s": 30838,
"text": null
},
{
"code": null,
"e": 31197,
"s": 31125,
"text": "Now let us gather data in the client JavaScript and print the result. "
},
{
"code": null,
"e": 31202,
"s": 31197,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style = \"color:#090; text-align:center;\">GeeksforGeeks</h1> <p style=\"font-size:25px\"> JSON received the data from the PHP file </p> <p id=\"arrayContent\"></p> <script> var obj, xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById(\"arrayContent\").innerHTML = this.responseText; } }; xmlhttp.open(\"GET\", \"data.php\", true); xmlhttp.send(); </script> </body></html> ",
"e": 31902,
"s": 31202,
"text": null
},
{
"code": null,
"e": 32053,
"s": 31902,
"text": "In the following that is sent to client and printed the result in JSON structure since it is not filtered values into each different values. output: "
},
{
"code": null,
"e": 32404,
"s": 32053,
"text": "PHP Loop: This is the combination of the array and the above two topics (PHP Array and Its client JavaScript & PHP Database) with the integrating them with the loops in it. In this JavaScript parses the values into a variable those values are are called by arrays and after printing the each myObj it’s values will be incremented to the next value. "
},
{
"code": null,
"e": 32409,
"s": 32404,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style = \"color:#090; text-align:center;\">GeeksforGeeks</h1> <p style=\"font-size:25px\"> JSON received the data from the PHP file </p> <p id=\"arrayContent\"></p> <script> var obj, xmlhttp, myObj, x, txt = \"\"; xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].names + \"<br>\"; } document.getElementById(\"arrayContent\").innerHTML = txt; } }; xmlhttp.open(\"GET\", \"data.php\", true); xmlhttp.send(); </script> </body></html> ",
"e": 33234,
"s": 32409,
"text": null
},
{
"code": null,
"e": 33244,
"s": 33234,
"text": "Output: "
},
{
"code": null,
"e": 33532,
"s": 33244,
"text": "PHP Method = POST: It quiet simple if above topics had understood completely. In the following syntax changes will occur. In the POST method the arguments have to be passed via send method but in the GET method the arguments can passed when the request of the php file sent.GET method: "
},
{
"code": null,
"e": 33592,
"s": 33532,
"text": "open(\"GET\", file_name?x=argument, asyn, username, password)"
},
{
"code": null,
"e": 33607,
"s": 33592,
"text": "POST method: "
},
{
"code": null,
"e": 33657,
"s": 33607,
"text": "open(\"POST\", file_name, asyn, username, password)"
},
{
"code": null,
"e": 33821,
"s": 33657,
"text": "The arguments are passed by the send(argument) method and send a request from the php to access data from server. So use function to get request are given below: "
},
{
"code": null,
"e": 33891,
"s": 33821,
"text": "setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\")"
},
{
"code": null,
"e": 33935,
"s": 33891,
"text": "In the php file a header has to be added: "
},
{
"code": null,
"e": 33991,
"s": 33935,
"text": "header(\"Content-Type: application/json; charset=UTF-8\")"
},
{
"code": null,
"e": 34048,
"s": 33991,
"text": ". The php file given below can be saved using post.php "
},
{
"code": null,
"e": 34052,
"s": 34048,
"text": "php"
},
{
"code": "<?php header(\"Content-Type: application/json; charset=UTF-8\"); $obj = json_decode($_POST[\"x\"], false); $conn = new mysqli(\"localhost\", \"root\", \"\", \"geeksforgeeks\"); $result = $conn->query(\"select names from \".$obj->table); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); $sresult = json_encode($output); echo $sresult;?>",
"e": 34423,
"s": 34052,
"text": null
},
{
"code": null,
"e": 34503,
"s": 34423,
"text": "After doing all this in php and the html file this will be appear as follows: "
},
{
"code": null,
"e": 34508,
"s": 34503,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1 style = \"color:#090; text-align:center;\">GeeksforGeeks</h1> <p style=\"font-size:25px\">geeks table values:</p> <p id=\"arrayContent\"></p> <script> var obj, xmlhttp, myObj, x, txt = \"\"; obj = JSON.stringify({\"table\":\"geeks\"}); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].names + \"<br>\"; } document.getElementById(\"arrayContent\").innerHTML = txt; } }; xmlhttp.open(\"POST\", \"post.php\", true); xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\"); xmlhttp.send(\"x=\" + obj ); </script> </body></html> ",
"e": 35491,
"s": 34508,
"text": null
},
{
"code": null,
"e": 35501,
"s": 35491,
"text": "Output: "
},
{
"code": null,
"e": 35516,
"s": 35503,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35529,
"s": 35516,
"text": "singghakshay"
},
{
"code": null,
"e": 35541,
"s": 35529,
"text": "kashishsoda"
},
{
"code": null,
"e": 35546,
"s": 35541,
"text": "JSON"
},
{
"code": null,
"e": 35553,
"s": 35546,
"text": "Picked"
},
{
"code": null,
"e": 35564,
"s": 35553,
"text": "JavaScript"
},
{
"code": null,
"e": 35568,
"s": 35564,
"text": "PHP"
},
{
"code": null,
"e": 35585,
"s": 35568,
"text": "Web Technologies"
},
{
"code": null,
"e": 35589,
"s": 35585,
"text": "PHP"
},
{
"code": null,
"e": 35687,
"s": 35589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35696,
"s": 35687,
"text": "Comments"
},
{
"code": null,
"e": 35709,
"s": 35696,
"text": "Old Comments"
},
{
"code": null,
"e": 35770,
"s": 35709,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35811,
"s": 35770,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 35864,
"s": 35811,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 35918,
"s": 35864,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 35966,
"s": 35918,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 36016,
"s": 35966,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 36061,
"s": 36016,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 36085,
"s": 36061,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 36129,
"s": 36085,
"text": "How to pop an alert message box using PHP ?"
}
] |
Fade In Up Animation Effect with CSS
|
To implement Fade In Up Animation Effect on an image with CSS, you can try to run the following code −
Live Demo
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
.fadeIn {
-webkit-animation-name: fadeIn;
animation-name: fadeIn;
}
</style>
</head>
<body>
<div id="animated-example" class="animated fadeIn"></div>
<button onclick="myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "To implement Fade In Up Animation Effect on an image with CSS, you can try to run the following code −"
},
{
"code": null,
"e": 1175,
"s": 1165,
"text": "Live Demo"
},
{
"code": null,
"e": 2217,
"s": 1175,
"text": "<html>\n <head>\n <style>\n\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n\n @-webkit-keyframes fadeIn {\n 0% {opacity: 0;}\n 100% {opacity: 1;}\n }\n\n @keyframes fadeIn {\n 0% {opacity: 0;}\n 100% {opacity: 1;}\n }\n\n .fadeIn {\n -webkit-animation-name: fadeIn;\n animation-name: fadeIn;\n }\n </style>\n </head>\n <body>\n\n <div id=\"animated-example\" class=\"animated fadeIn\"></div>\n <button onclick=\"myFunction()\">Reload page</button>\n\n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</html>"
}
] |
How to create three-dimensional arrays of different sizes in R?
|
A three-dimensional array can have matrices of different size and they are not necessarily to be square or rectangular. Also, all the elements in an array are of same data type. To create a three-dimensional array of different size we would need to use the proper number of rows and columns within the array function.
Live Demo
A1<-array(c(1:4,5:8,9:12),c(2,2,3))
A1
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
, , 3
[,1] [,2]
[1,] 9 11
[2,] 10 12
Live Demo
A2<-array(c(rpois(4,1),rpois(4,5),rpois(4,8)),c(2,2,3))
A2
, , 1
[,1] [,2]
[1,] 1 2
[2,] 1 0
, , 2
[,1] [,2]
[1,] 2 4
[2,] 4 6
, , 3
[,1] [,2]
[1,] 8 2
[2,] 5 9
Live Demo
A3<-array(c(rpois(10,1),rpois(10,5),rpois(10,8)),c(2,5,3))
A3
, , 1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 0
[2,] 2 0 1 1 1
, , 2
[,1] [,2] [,3] [,4] [,5]
[1,] 7 4 8 5 4
[2,] 4 4 6 4 6
, , 3
[,1] [,2] [,3] [,4] [,5]
[1,] 5 4 11 9 7
[2,] 3 9 10 11 4
Live Demo
A4<-array(c(rnorm(25,1,0.25),rnorm(25,5,3.2),rnorm(25,125,8)),c(5,5,3))
A4
, , 1
[,1] [,2] [,3] [,4] [,5]
[1,] 0.9965280 1.2496879 1.0314247 0.708599 0.8077254
[2,] 0.7922626 1.0025704 0.7009782 1.142506 0.7445184
[3,] 1.0053649 0.5531278 1.4328092 1.385334 1.0892912
[4,] 0.9793857 1.3234864 0.5553419 1.215801 1.1023305
[5,] 1.3995579 1.0262346 1.2721514 1.394952 0.6184446
, , 2
[,1] [,2] [,3] [,4] [,5]
[1,] 6.174299 6.038592 12.470821 1.722607 1.069005
[2,] 3.789770 8.430932 8.747260 7.552801 3.886604
[3,] 1.730295 2.493142 3.465323 3.507519 3.834119
[4,] 6.075908 7.348407 4.118381 6.081857 4.167369
[5,] 4.130724 6.829041 7.469443 3.409544 5.808045
, , 3
[,1] [,2] [,3] [,4] [,5]
[1,] 110.6113 119.8429 121.6303 122.9954 140.5715
[2,] 125.5317 122.1797 135.2451 119.5165 122.9406
[3,] 124.0559 119.0249 135.1922 114.0559 112.1363
[4,] 118.1446 119.0530 134.6688 118.8334 124.4825
[5,] 120.2941 109.3362 119.8095 129.1414 127.6529
Live Demo
A5<-array(c(rexp(25,1.25),rexp(25,3.2),rexp(25,1.37)),c(5,5,3))
A5
, , 1
[,1] [,2] [,3] [,4] [,5]
[1,] 1.3964752 0.14365375 0.1244120 0.006844883 0.1649243
[2,] 0.4146687 0.74798876 1.3172895 0.273072680 1.9675031
[3,] 0.5640029 0.05317204 0.1365023 1.139974748 0.4691554
[4,] 3.4377135 0.40737835 0.1296337 3.827344957 0.3062992
[5,] 0.5489296 0.68912311 0.9960337 1.891826684 0.6505368
, , 2
[,1] [,2] [,3] [,4] [,5]
[1,] 0.461391444 0.14704248 1.7219179 0.26808968 0.01277777
[2,] 0.002633461 0.02843441 0.5924807 0.59324483 1.34762650
[3,] 0.296192070 0.38350989 0.3453407 0.14514950 0.21145723
[4,] 0.137173681 0.34683067 0.9046680 0.05949873 0.42690397
[5,] 0.171683422 0.12761626 0.3183557 0.01596812 0.04222600
, , 3
[,1] [,2] [,3] [,4] [,5]
[1,] 0.7641526 0.78719016 0.96282362 0.02212902 0.3261842
[2,] 1.1584192 1.20147453 0.03766346 0.30549609 1.1452613
[3,] 0.5849248 1.97291039 0.52678525 0.78435948 0.0107882
[4,] 2.1916248 0.09176414 1.40056593 1.11841176 0.7624021
[5,] 0.1565796 1.35400081 0.26728881 0.36045571 0.3076494
|
[
{
"code": null,
"e": 1380,
"s": 1062,
"text": "A three-dimensional array can have matrices of different size and they are not necessarily to be square or rectangular. Also, all the elements in an array are of same data type. To create a three-dimensional array of different size we would need to use the proper number of rows and columns within the array function."
},
{
"code": null,
"e": 1391,
"s": 1380,
"text": " Live Demo"
},
{
"code": null,
"e": 1430,
"s": 1391,
"text": "A1<-array(c(1:4,5:8,9:12),c(2,2,3))\nA1"
},
{
"code": null,
"e": 1535,
"s": 1430,
"text": ", , 1\n[,1] [,2]\n[1,] 1 3\n[2,] 2 4\n, , 2\n[,1] [,2]\n[1,] 5 7\n[2,] 6 8\n, , 3\n[,1] [,2]\n[1,] 9 11\n[2,] 10 12"
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": " Live Demo"
},
{
"code": null,
"e": 1605,
"s": 1546,
"text": "A2<-array(c(rpois(4,1),rpois(4,5),rpois(4,8)),c(2,2,3))\nA2"
},
{
"code": null,
"e": 1707,
"s": 1605,
"text": ", , 1\n[,1] [,2]\n[1,] 1 2\n[2,] 1 0\n, , 2\n[,1] [,2]\n[1,] 2 4\n[2,] 4 6\n, , 3\n[,1] [,2]\n[1,] 8 2\n[2,] 5 9"
},
{
"code": null,
"e": 1718,
"s": 1707,
"text": " Live Demo"
},
{
"code": null,
"e": 1780,
"s": 1718,
"text": "A3<-array(c(rpois(10,1),rpois(10,5),rpois(10,8)),c(2,5,3))\nA3"
},
{
"code": null,
"e": 1966,
"s": 1780,
"text": ", , 1\n[,1] [,2] [,3] [,4] [,5]\n[1,] 1 0 1 1 0\n[2,] 2 0 1 1 1\n, , 2\n[,1] [,2] [,3] [,4] [,5]\n[1,] 7 4 8 5 4\n[2,] 4 4 6 4 6\n, , 3\n[,1] [,2] [,3] [,4] [,5]\n[1,] 5 4 11 9 7\n[2,] 3 9 10 11 4"
},
{
"code": null,
"e": 1977,
"s": 1966,
"text": " Live Demo"
},
{
"code": null,
"e": 2052,
"s": 1977,
"text": "A4<-array(c(rnorm(25,1,0.25),rnorm(25,5,3.2),rnorm(25,125,8)),c(5,5,3))\nA4"
},
{
"code": null,
"e": 2987,
"s": 2052,
"text": ", , 1\n [,1] [,2] [,3] [,4] [,5]\n[1,] 0.9965280 1.2496879 1.0314247 0.708599 0.8077254\n[2,] 0.7922626 1.0025704 0.7009782 1.142506 0.7445184\n[3,] 1.0053649 0.5531278 1.4328092 1.385334 1.0892912\n[4,] 0.9793857 1.3234864 0.5553419 1.215801 1.1023305\n[5,] 1.3995579 1.0262346 1.2721514 1.394952 0.6184446\n, , 2\n [,1] [,2] [,3] [,4] [,5]\n[1,] 6.174299 6.038592 12.470821 1.722607 1.069005\n[2,] 3.789770 8.430932 8.747260 7.552801 3.886604\n[3,] 1.730295 2.493142 3.465323 3.507519 3.834119\n[4,] 6.075908 7.348407 4.118381 6.081857 4.167369\n[5,] 4.130724 6.829041 7.469443 3.409544 5.808045\n, , 3\n [,1] [,2] [,3] [,4] [,5]\n[1,] 110.6113 119.8429 121.6303 122.9954 140.5715\n[2,] 125.5317 122.1797 135.2451 119.5165 122.9406\n[3,] 124.0559 119.0249 135.1922 114.0559 112.1363\n[4,] 118.1446 119.0530 134.6688 118.8334 124.4825\n[5,] 120.2941 109.3362 119.8095 129.1414 127.6529"
},
{
"code": null,
"e": 2998,
"s": 2987,
"text": " Live Demo"
},
{
"code": null,
"e": 3065,
"s": 2998,
"text": "A5<-array(c(rexp(25,1.25),rexp(25,3.2),rexp(25,1.37)),c(5,5,3))\nA5"
},
{
"code": null,
"e": 4129,
"s": 3065,
"text": ", , 1\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1.3964752 0.14365375 0.1244120 0.006844883 0.1649243\n[2,] 0.4146687 0.74798876 1.3172895 0.273072680 1.9675031\n[3,] 0.5640029 0.05317204 0.1365023 1.139974748 0.4691554\n[4,] 3.4377135 0.40737835 0.1296337 3.827344957 0.3062992\n[5,] 0.5489296 0.68912311 0.9960337 1.891826684 0.6505368\n, , 2\n [,1] [,2] [,3] [,4] [,5]\n[1,] 0.461391444 0.14704248 1.7219179 0.26808968 0.01277777\n[2,] 0.002633461 0.02843441 0.5924807 0.59324483 1.34762650\n[3,] 0.296192070 0.38350989 0.3453407 0.14514950 0.21145723\n[4,] 0.137173681 0.34683067 0.9046680 0.05949873 0.42690397\n[5,] 0.171683422 0.12761626 0.3183557 0.01596812 0.04222600\n, , 3\n [,1] [,2] [,3] [,4] [,5]\n[1,] 0.7641526 0.78719016 0.96282362 0.02212902 0.3261842\n[2,] 1.1584192 1.20147453 0.03766346 0.30549609 1.1452613\n[3,] 0.5849248 1.97291039 0.52678525 0.78435948 0.0107882\n[4,] 2.1916248 0.09176414 1.40056593 1.11841176 0.7624021\n[5,] 0.1565796 1.35400081 0.26728881 0.36045571 0.3076494"
}
] |
Python - Pretty Print Numbers
|
The python module pprint is used for giving proper printing formats to various data objects in python. Those data objects can represent a dictionary data type or even a data object containing the JSON data. In the below example we see how that data looks before applying the pprint module and after applying it.
import pprint
student_dict = {'Name': 'Tusar', 'Class': 'XII',
'Address': {'FLAT ':1308, 'BLOCK ':'A', 'LANE ':2, 'CITY ': 'HYD'}}
print student_dict
print "\n"
print "***With Pretty Print***"
print "-----------------------"
pprint.pprint(student_dict,width=-1)
When we run the above program, we get the following output −
{'Address': {'FLAT ': 1308, 'LANE ': 2, 'CITY ': 'HYD', 'BLOCK ': 'A'}, 'Name': 'Tusar', 'Class': 'XII'}
***With Pretty Print***
-----------------------
{'Address': {'BLOCK ': 'A',
'CITY ': 'HYD',
'FLAT ': 1308,
'LANE ': 2},
'Class': 'XII',
'Name': 'Tusar'}
Pprint can also handle JSON data by formatting them to a more readable format.
import pprint
emp = {"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
"7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"] }
x= pprint.pformat(emp, indent=2)
print x
When we run the above program, we get the following output −
{ 'Dept': [ 'IT',
'Operations',
'IT',
'HR',
'Finance',
'IT',
'Operations',
'Finance'],
'Name': ['Rick', 'Dan', 'Michelle', 'Ryan', 'Gary', 'Nina', 'Simon', 'Guru'],
'Salary': [ '623.3',
'515.2',
'611',
'729',
'843.25',
'578',
'632.8',
'722.5'],
'StartDate': [ '1/1/2012',
'9/23/2013',
'11/15/2014',
'5/11/2014',
'3/27/2015',
'5/21/2013',
'7/30/2013',
'6/17/2014']}
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": 2900,
"s": 2587,
"text": "The python module pprint is used for giving proper printing formats to various data objects in python. Those data objects can represent a dictionary data type or even a data object containing the JSON data. In the below example we see how that data looks before applying the pprint module and after applying it."
},
{
"code": null,
"e": 3171,
"s": 2900,
"text": "import pprint\n\nstudent_dict = {'Name': 'Tusar', 'Class': 'XII', \n 'Address': {'FLAT ':1308, 'BLOCK ':'A', 'LANE ':2, 'CITY ': 'HYD'}}\n\nprint student_dict\nprint \"\\n\"\nprint \"***With Pretty Print***\"\nprint \"-----------------------\"\npprint.pprint(student_dict,width=-1)\n"
},
{
"code": null,
"e": 3232,
"s": 3171,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 3534,
"s": 3232,
"text": "{'Address': {'FLAT ': 1308, 'LANE ': 2, 'CITY ': 'HYD', 'BLOCK ': 'A'}, 'Name': 'Tusar', 'Class': 'XII'}\n\n\n***With Pretty Print***\n-----------------------\n{'Address': {'BLOCK ': 'A',\n 'CITY ': 'HYD',\n 'FLAT ': 1308,\n 'LANE ': 2},\n 'Class': 'XII',\n 'Name': 'Tusar'}\n"
},
{
"code": null,
"e": 3614,
"s": 3534,
"text": " Pprint can also handle JSON data by formatting them to a more readable format."
},
{
"code": null,
"e": 4034,
"s": 3614,
"text": "import pprint\n\nemp = {\"Name\":[\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\",\"Nina\",\"Simon\",\"Guru\" ],\n \"Salary\":[\"623.3\",\"515.2\",\"611\",\"729\",\"843.25\",\"578\",\"632.8\",\"722.5\" ], \n \"StartDate\":[ \"1/1/2012\",\"9/23/2013\",\"11/15/2014\",\"5/11/2014\",\"3/27/2015\",\"5/21/2013\",\n \"7/30/2013\",\"6/17/2014\"],\n \"Dept\":[ \"IT\",\"Operations\",\"IT\",\"HR\",\"Finance\",\"IT\",\"Operations\",\"Finance\"] }\n\nx= pprint.pformat(emp, indent=2)\nprint x\n "
},
{
"code": null,
"e": 4095,
"s": 4034,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4768,
"s": 4095,
"text": "{ 'Dept': [ 'IT',\n 'Operations',\n 'IT',\n 'HR',\n 'Finance',\n 'IT',\n 'Operations',\n 'Finance'],\n 'Name': ['Rick', 'Dan', 'Michelle', 'Ryan', 'Gary', 'Nina', 'Simon', 'Guru'],\n 'Salary': [ '623.3',\n '515.2',\n '611',\n '729',\n '843.25',\n '578',\n '632.8',\n '722.5'],\n 'StartDate': [ '1/1/2012',\n '9/23/2013',\n '11/15/2014',\n '5/11/2014',\n '3/27/2015',\n '5/21/2013',\n '7/30/2013',\n '6/17/2014']}\n"
},
{
"code": null,
"e": 4805,
"s": 4768,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4821,
"s": 4805,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4854,
"s": 4821,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4873,
"s": 4854,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4908,
"s": 4873,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4930,
"s": 4908,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4964,
"s": 4930,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4992,
"s": 4964,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5027,
"s": 4992,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5041,
"s": 5027,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5074,
"s": 5041,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5091,
"s": 5074,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5098,
"s": 5091,
"text": " Print"
},
{
"code": null,
"e": 5109,
"s": 5098,
"text": " Add Notes"
}
] |
What are table rowspan and colspan in HTML?
|
The rowspan and colspan are <td> tag attributes. These are used to specify the number of rows or columns a cell should span. The rowspan attribute is for rows as well as the colspan attribute is for columns.
These attributes have numeric values, for example, colspan=3 will span three columns.You can try to run the following code to work with the rowspan and colspan attribute in HTML
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<h1>Heading</h1>
<table>
<tr>
<th colspan="2"></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td rowspan="3"></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
|
[
{
"code": null,
"e": 1270,
"s": 1062,
"text": "The rowspan and colspan are <td> tag attributes. These are used to specify the number of rows or columns a cell should span. The rowspan attribute is for rows as well as the colspan attribute is for columns."
},
{
"code": null,
"e": 1448,
"s": 1270,
"text": "These attributes have numeric values, for example, colspan=3 will span three columns.You can try to run the following code to work with the rowspan and colspan attribute in HTML"
},
{
"code": null,
"e": 2050,
"s": 1448,
"text": "<html>\n <head>\n <style>\n table, th, td {\n border: 1px solid black;\n width: 100px;\n height: 50px;\n }\n </style>\n </head>\n\n <body>\n <h1>Heading</h1>\n <table>\n <tr>\n <th colspan=\"2\"></th>\n <th></th>\n </tr>\n <tr>\n <td></td>\n <td></td>\n <td rowspan=\"3\"></td>\n </tr>\n <tr>\n <td></td>\n <td></td>\n </tr>\n <tr>\n <td></td>\n <td></td>\n </tr>\n </table>\n </body>\n</html>"
}
] |
MongoDB - Regex - GeeksforGeeks
|
05 Feb, 2021
MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support. In MongoDB, we can do pattern matching in two different ways:
With $regex Operator
Without $regex Operator
This operator provides regular expression capabilities for pattern matching stings in the queries. Or in other words, this operator is used to search for the given string in the specified collection. It is helpful when we don’t know the exact field value that we are looking in the document. For example, a collection containing 3 documents i.e.,
{
name: "Tony",
position: "Backend developer"
}
{
name: "Bruce",
position: "frontend developer"
}
{
name: "Nick",
position: "HR Manager"
}
and we are looking for developer information. So, with the help of the $regex operator, we create a pattern(i.e., {position: {$regex: “developer”}}) that will return only those documents that contain developer string.
Important Points:
You are not allowed to use $regex operator inside $in operator.
If you want to add a regular expression inside a comma-separated list of a query condition, then you have to use the $regex operator.
If you want to use x and s options then you have to use $regex operator expression with $options.
Starting from the latest version of MongoDB(i.e., 4.0.7) you are allowed to use $not operator with $regex operator expression.
For case-sensitive regular expression queries, if the index of the specified field is available, then MongoDB matches the regular expression to the values in the index. It is the easiest way to match rather than scanning all the collections For case-insensitive regular expression queries, they do not utilize index effectively.
If you want to use Perl compatible regular expressions support regular expressions that are not supported in JavaScript, then you must use $regex operator.
Syntax:
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
$options:
In MongoDB, the following <options> are available for use with regular expression:
i: To match both lower case and upper case pattern in the string.
m: To include ^ and $ in the pattern in the match i.e. to specifically search for ^ and $ inside the string. Without this option, these anchors match at the beginning or end of the string.
x: To ignore all white space characters in the $regex pattern.
s: To allow the dot character “.” to match all characters including newline characters.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Documents: Six documents that contain the details of the employees in the form of field-value pairs.
Displaying details of employee who are having the word developer in their position field:
db.employee.find({position : {$regex : "developer"}}).pretty()
Here, we are displaying the documents of those employees whose position field contain developer string. So we pass a regular expression using $regex operator(i.e. {$regex : “developer”}) for the position field in the find() method.
Displaying details of employee who are a software engineer with case insensitive by using i <options>:
db.employee.find({position:{$regex:"software",$options:"$i"}}).pretty()
Here, we are displaying the documents of those employees whose position field contain case-insensitive “software” string. So, we pass a regular expression with option(i.e., {$regex : “software”, $options: “$i”}) for the position field in the find() method. In the regular expression, $options:”$i” is used to match both lower case and upper case pattern in the given string(i.e., “software”).
Displaying details of the employee whose name starts with B:
db.employee.find({Name:{$regex:"^B"}}).pretty()
Here, we are displaying the documents of those employees whose name starts with ‘B’ letter. So, we pass a regular expression using $regex operator(i.e. {$regex : “^B”}) for the Name field in the find() method.
Displaying details of the employee whose name ends with e:
db.employee.find({Name:{$regex:"e$"}}).pretty()
Here, we are displaying the documents of those employees whose names end with the ‘e’ letter. So, we pass a regular expression using $regex operator(i.e. {$regex : “e$”}) for the Name field in the find() method.
In MongoDB, we can do pattern matching without using the $regex operator. Simply, by using a regular expression object to specify a regular expression. Also, by using regular expression object you are allowed to use regular expression inside $ in operator.
Syntax:
{ <field>: /pattern/<options> }
Here, // means to specify your search criteria in between these delimiters.
Example:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Documents: Six documents that contain the details of the employees in the form of field-value pairs.
Displaying details of employee who are having the word “te” in their name by using regular expression object:
db.employee.find({Name: /te/}).pretty()
Here, we are displaying the documents of those employees whose names contain the “te” string. So, we pass a regular expression(i.e., {Name: /te/}) for the Name field in the find() method. In this regular expression, // means to specify your search criteria in between these delimiters, i.e., /te/.
MongoDB-operators
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
MongoDB - Distinct() Method
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Update() Method
Create user and add role in MongoDB
MongoDB - sort() Method
|
[
{
"code": null,
"e": 23873,
"s": 23845,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 24234,
"s": 23873,
"text": "MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support. In MongoDB, we can do pattern matching in two different ways:"
},
{
"code": null,
"e": 24255,
"s": 24234,
"text": "With $regex Operator"
},
{
"code": null,
"e": 24279,
"s": 24255,
"text": "Without $regex Operator"
},
{
"code": null,
"e": 24626,
"s": 24279,
"text": "This operator provides regular expression capabilities for pattern matching stings in the queries. Or in other words, this operator is used to search for the given string in the specified collection. It is helpful when we don’t know the exact field value that we are looking in the document. For example, a collection containing 3 documents i.e.,"
},
{
"code": null,
"e": 24770,
"s": 24626,
"text": "{\nname: \"Tony\",\nposition: \"Backend developer\"\n} \n{\nname: \"Bruce\",\nposition: \"frontend developer\"\n} \n{\nname: \"Nick\",\nposition: \"HR Manager\"\n} "
},
{
"code": null,
"e": 24989,
"s": 24770,
"text": "and we are looking for developer information. So, with the help of the $regex operator, we create a pattern(i.e., {position: {$regex: “developer”}}) that will return only those documents that contain developer string. "
},
{
"code": null,
"e": 25007,
"s": 24989,
"text": "Important Points:"
},
{
"code": null,
"e": 25071,
"s": 25007,
"text": "You are not allowed to use $regex operator inside $in operator."
},
{
"code": null,
"e": 25205,
"s": 25071,
"text": "If you want to add a regular expression inside a comma-separated list of a query condition, then you have to use the $regex operator."
},
{
"code": null,
"e": 25303,
"s": 25205,
"text": "If you want to use x and s options then you have to use $regex operator expression with $options."
},
{
"code": null,
"e": 25430,
"s": 25303,
"text": "Starting from the latest version of MongoDB(i.e., 4.0.7) you are allowed to use $not operator with $regex operator expression."
},
{
"code": null,
"e": 25759,
"s": 25430,
"text": "For case-sensitive regular expression queries, if the index of the specified field is available, then MongoDB matches the regular expression to the values in the index. It is the easiest way to match rather than scanning all the collections For case-insensitive regular expression queries, they do not utilize index effectively."
},
{
"code": null,
"e": 25915,
"s": 25759,
"text": "If you want to use Perl compatible regular expressions support regular expressions that are not supported in JavaScript, then you must use $regex operator."
},
{
"code": null,
"e": 25923,
"s": 25915,
"text": "Syntax:"
},
{
"code": null,
"e": 26039,
"s": 25923,
"text": "{ <field>: { $regex: /pattern/, $options: '<options>' } }\n{ <field>: { $regex: 'pattern', $options: '<options>' } }"
},
{
"code": null,
"e": 26049,
"s": 26039,
"text": "$options:"
},
{
"code": null,
"e": 26132,
"s": 26049,
"text": "In MongoDB, the following <options> are available for use with regular expression:"
},
{
"code": null,
"e": 26198,
"s": 26132,
"text": "i: To match both lower case and upper case pattern in the string."
},
{
"code": null,
"e": 26387,
"s": 26198,
"text": "m: To include ^ and $ in the pattern in the match i.e. to specifically search for ^ and $ inside the string. Without this option, these anchors match at the beginning or end of the string."
},
{
"code": null,
"e": 26450,
"s": 26387,
"text": "x: To ignore all white space characters in the $regex pattern."
},
{
"code": null,
"e": 26538,
"s": 26450,
"text": "s: To allow the dot character “.” to match all characters including newline characters."
},
{
"code": null,
"e": 26548,
"s": 26538,
"text": "Examples:"
},
{
"code": null,
"e": 26596,
"s": 26548,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 26620,
"s": 26596,
"text": "Database: GeeksforGeeks"
},
{
"code": null,
"e": 26641,
"s": 26620,
"text": "Collection: employee"
},
{
"code": null,
"e": 26742,
"s": 26641,
"text": "Documents: Six documents that contain the details of the employees in the form of field-value pairs."
},
{
"code": null,
"e": 26832,
"s": 26742,
"text": "Displaying details of employee who are having the word developer in their position field:"
},
{
"code": null,
"e": 26895,
"s": 26832,
"text": "db.employee.find({position : {$regex : \"developer\"}}).pretty()"
},
{
"code": null,
"e": 27127,
"s": 26895,
"text": "Here, we are displaying the documents of those employees whose position field contain developer string. So we pass a regular expression using $regex operator(i.e. {$regex : “developer”}) for the position field in the find() method."
},
{
"code": null,
"e": 27230,
"s": 27127,
"text": "Displaying details of employee who are a software engineer with case insensitive by using i <options>:"
},
{
"code": null,
"e": 27302,
"s": 27230,
"text": "db.employee.find({position:{$regex:\"software\",$options:\"$i\"}}).pretty()"
},
{
"code": null,
"e": 27695,
"s": 27302,
"text": "Here, we are displaying the documents of those employees whose position field contain case-insensitive “software” string. So, we pass a regular expression with option(i.e., {$regex : “software”, $options: “$i”}) for the position field in the find() method. In the regular expression, $options:”$i” is used to match both lower case and upper case pattern in the given string(i.e., “software”)."
},
{
"code": null,
"e": 27756,
"s": 27695,
"text": "Displaying details of the employee whose name starts with B:"
},
{
"code": null,
"e": 27804,
"s": 27756,
"text": "db.employee.find({Name:{$regex:\"^B\"}}).pretty()"
},
{
"code": null,
"e": 28014,
"s": 27804,
"text": "Here, we are displaying the documents of those employees whose name starts with ‘B’ letter. So, we pass a regular expression using $regex operator(i.e. {$regex : “^B”}) for the Name field in the find() method."
},
{
"code": null,
"e": 28073,
"s": 28014,
"text": "Displaying details of the employee whose name ends with e:"
},
{
"code": null,
"e": 28121,
"s": 28073,
"text": "db.employee.find({Name:{$regex:\"e$\"}}).pretty()"
},
{
"code": null,
"e": 28333,
"s": 28121,
"text": "Here, we are displaying the documents of those employees whose names end with the ‘e’ letter. So, we pass a regular expression using $regex operator(i.e. {$regex : “e$”}) for the Name field in the find() method."
},
{
"code": null,
"e": 28590,
"s": 28333,
"text": "In MongoDB, we can do pattern matching without using the $regex operator. Simply, by using a regular expression object to specify a regular expression. Also, by using regular expression object you are allowed to use regular expression inside $ in operator."
},
{
"code": null,
"e": 28599,
"s": 28590,
"text": "Syntax: "
},
{
"code": null,
"e": 28631,
"s": 28599,
"text": "{ <field>: /pattern/<options> }"
},
{
"code": null,
"e": 28707,
"s": 28631,
"text": "Here, // means to specify your search criteria in between these delimiters."
},
{
"code": null,
"e": 28716,
"s": 28707,
"text": "Example:"
},
{
"code": null,
"e": 28764,
"s": 28716,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 28788,
"s": 28764,
"text": "Database: GeeksforGeeks"
},
{
"code": null,
"e": 28809,
"s": 28788,
"text": "Collection: employee"
},
{
"code": null,
"e": 28910,
"s": 28809,
"text": "Documents: Six documents that contain the details of the employees in the form of field-value pairs."
},
{
"code": null,
"e": 29020,
"s": 28910,
"text": "Displaying details of employee who are having the word “te” in their name by using regular expression object:"
},
{
"code": null,
"e": 29060,
"s": 29020,
"text": "db.employee.find({Name: /te/}).pretty()"
},
{
"code": null,
"e": 29358,
"s": 29060,
"text": "Here, we are displaying the documents of those employees whose names contain the “te” string. So, we pass a regular expression(i.e., {Name: /te/}) for the Name field in the find() method. In this regular expression, // means to specify your search criteria in between these delimiters, i.e., /te/."
},
{
"code": null,
"e": 29376,
"s": 29358,
"text": "MongoDB-operators"
},
{
"code": null,
"e": 29383,
"s": 29376,
"text": "Picked"
},
{
"code": null,
"e": 29391,
"s": 29383,
"text": "MongoDB"
},
{
"code": null,
"e": 29489,
"s": 29391,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29498,
"s": 29489,
"text": "Comments"
},
{
"code": null,
"e": 29511,
"s": 29498,
"text": "Old Comments"
},
{
"code": null,
"e": 29539,
"s": 29511,
"text": "MongoDB - Distinct() Method"
},
{
"code": null,
"e": 29577,
"s": 29539,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 29602,
"s": 29577,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 29629,
"s": 29602,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 29686,
"s": 29629,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
},
{
"code": null,
"e": 29741,
"s": 29686,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 29767,
"s": 29741,
"text": "MongoDB - Update() Method"
},
{
"code": null,
"e": 29803,
"s": 29767,
"text": "Create user and add role in MongoDB"
}
] |
Print the given pattern recursively
|
Here, as per the given problem pattern needs to be displayed using recursive approach.
Recursive function is the one that calls itself n number of times. There can be ‘n’ number of recursive function in a program. The problem working with recursive function is their complexity.
START
Step 1 -> function int printpattern(int n)
If n>0
Printpattern(n-1)
Print *
End IF
End
Step 2 -> function int pattern(int n)
If n>0
pattern(n-1)
End IF
Printpattern(n)
Print \n
End
STOP
#include <stdio.h>
int printpattern(int n) {
if(n>0) {
printpattern(n-1);
printf("*");
}
}
int pattern(int n) {
if(n>0) {
pattern(n-1); //will recursively print the pattern
}
printpattern(n); //will reduce the n recursively.
printf("\n"); //for new line
}
int main(int argc, char const *argv[]) {
int n = 7;
pattern(n);
return 0;
}
if we run above program then it will generate following output.
*
**
***
****
*****
******
*******
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Here, as per the given problem pattern needs to be displayed using recursive approach."
},
{
"code": null,
"e": 1341,
"s": 1149,
"text": "Recursive function is the one that calls itself n number of times. There can be ‘n’ number of recursive function in a program. The problem working with recursive function is their complexity."
},
{
"code": null,
"e": 1569,
"s": 1341,
"text": "START\nStep 1 -> function int printpattern(int n)\n If n>0\n Printpattern(n-1)\n Print *\n End IF\nEnd\nStep 2 -> function int pattern(int n)\n If n>0\n pattern(n-1)\n End IF\n Printpattern(n)\n Print \\n\nEnd\nSTOP"
},
{
"code": null,
"e": 1946,
"s": 1569,
"text": "#include <stdio.h>\nint printpattern(int n) {\n if(n>0) {\n printpattern(n-1);\n printf(\"*\");\n }\n}\nint pattern(int n) {\n if(n>0) {\n pattern(n-1); //will recursively print the pattern\n }\n printpattern(n); //will reduce the n recursively.\n printf(\"\\n\"); //for new line\n}\nint main(int argc, char const *argv[]) {\n int n = 7;\n pattern(n);\n return 0;\n}"
},
{
"code": null,
"e": 2010,
"s": 1946,
"text": "if we run above program then it will generate following output."
},
{
"code": null,
"e": 2045,
"s": 2010,
"text": "*\n**\n***\n****\n*****\n******\n*******"
}
] |
Entity Framework - Nested Entity Types
|
Prior to Entity Framework 6, Entity Framework didn't recognize entities or complex types that were nested within other entities or complex types. When Entity Framework generated the model, the nested types just disappeared.
Let’s take a look at a simple example in which we have our basic model with three entities Student, Course and Enrollment.
Let’s add a property Identity, which is a Person type. Person is another entity, contains BirthDate and FatherName properties.
Let’s add a property Identity, which is a Person type. Person is another entity, contains BirthDate and FatherName properties.
In Entity Framework terms, because it has no identity and is part of an entity, it's an Entity Framework complex type, and we've actually had support for complex types since the first version of Entity Framework.
In Entity Framework terms, because it has no identity and is part of an entity, it's an Entity Framework complex type, and we've actually had support for complex types since the first version of Entity Framework.
The Person type isn't nested as shown in the following code.
The Person type isn't nested as shown in the following code.
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public Person Identity { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
public class Person {
public Person(string fatherName, DateTime birthDate) {
FatherName = fatherName;
BirthDate = birthDate;
}
public string FatherName { get; set; }
public DateTime BirthDate { get; set; }
}
Entity Framework will know how to persist Person types when it is used in previous versions as well.
By using Entity Framework Power Tool we will see how Entity Framework interprets the model. Right click on Program.cs file and select Entity Framework → View Entity Data Model (Read only)
Now you will see that Identity property is defined in Student class.
If this Person class won't be used by any other entity, then we can nest it inside the Student class, but this earlier version of Entity Framework doesn't acknowledge nested types.
In older version, you generate the model again, not only is the type not recognized, but because it's not there, the property isn't there either, so Entity Framework won't persist the Person type at all.
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public Person Identity { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public class Person {
public Person(string fatherName, DateTime birthDate) {
FatherName = fatherName;
BirthDate = birthDate;
}
public string FatherName { get; set; }
public DateTime BirthDate { get; set; }
}
}
With Entity Framework 6, nested entities and complex types are recognized. In the above code, you can see that Person is nested within the Student class.
When you use the Entity Framework Power Tool to show how Entity Framework interprets the model this time, there's true Identity property, and Person complex type. So Entity Framework will persist that data.
Now you can see that Identity is a nested entity type, which was not supported before Entity Framework 6.
We recommend that you execute the above example in a step-by-step manner for better understanding.
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3256,
"s": 3032,
"text": "Prior to Entity Framework 6, Entity Framework didn't recognize entities or complex types that were nested within other entities or complex types. When Entity Framework generated the model, the nested types just disappeared."
},
{
"code": null,
"e": 3379,
"s": 3256,
"text": "Let’s take a look at a simple example in which we have our basic model with three entities Student, Course and Enrollment."
},
{
"code": null,
"e": 3506,
"s": 3379,
"text": "Let’s add a property Identity, which is a Person type. Person is another entity, contains BirthDate and FatherName properties."
},
{
"code": null,
"e": 3633,
"s": 3506,
"text": "Let’s add a property Identity, which is a Person type. Person is another entity, contains BirthDate and FatherName properties."
},
{
"code": null,
"e": 3846,
"s": 3633,
"text": "In Entity Framework terms, because it has no identity and is part of an entity, it's an Entity Framework complex type, and we've actually had support for complex types since the first version of Entity Framework."
},
{
"code": null,
"e": 4059,
"s": 3846,
"text": "In Entity Framework terms, because it has no identity and is part of an entity, it's an Entity Framework complex type, and we've actually had support for complex types since the first version of Entity Framework."
},
{
"code": null,
"e": 4120,
"s": 4059,
"text": "The Person type isn't nested as shown in the following code."
},
{
"code": null,
"e": 4181,
"s": 4120,
"text": "The Person type isn't nested as shown in the following code."
},
{
"code": null,
"e": 4715,
"s": 4181,
"text": "public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n public Person Identity { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n}\n\npublic class Person {\n\n public Person(string fatherName, DateTime birthDate) {\n FatherName = fatherName;\n BirthDate = birthDate;\n }\n\t\n public string FatherName { get; set; }\n public DateTime BirthDate { get; set; }\n}"
},
{
"code": null,
"e": 4816,
"s": 4715,
"text": "Entity Framework will know how to persist Person types when it is used in previous versions as well."
},
{
"code": null,
"e": 5004,
"s": 4816,
"text": "By using Entity Framework Power Tool we will see how Entity Framework interprets the model. Right click on Program.cs file and select Entity Framework → View Entity Data Model (Read only)"
},
{
"code": null,
"e": 5073,
"s": 5004,
"text": "Now you will see that Identity property is defined in Student class."
},
{
"code": null,
"e": 5254,
"s": 5073,
"text": "If this Person class won't be used by any other entity, then we can nest it inside the Student class, but this earlier version of Entity Framework doesn't acknowledge nested types."
},
{
"code": null,
"e": 5458,
"s": 5254,
"text": "In older version, you generate the model again, not only is the type not recognized, but because it's not there, the property isn't there either, so Entity Framework won't persist the Person type at all."
},
{
"code": null,
"e": 6017,
"s": 5458,
"text": "public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n\t\n public DateTime EnrollmentDate { get; set; }\n public Person Identity { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n public class Person {\n\n public Person(string fatherName, DateTime birthDate) {\n FatherName = fatherName;\n BirthDate = birthDate;\n }\n\n public string FatherName { get; set; }\n public DateTime BirthDate { get; set; }\n }\n}"
},
{
"code": null,
"e": 6171,
"s": 6017,
"text": "With Entity Framework 6, nested entities and complex types are recognized. In the above code, you can see that Person is nested within the Student class."
},
{
"code": null,
"e": 6378,
"s": 6171,
"text": "When you use the Entity Framework Power Tool to show how Entity Framework interprets the model this time, there's true Identity property, and Person complex type. So Entity Framework will persist that data."
},
{
"code": null,
"e": 6484,
"s": 6378,
"text": "Now you can see that Identity is a nested entity type, which was not supported before Entity Framework 6."
},
{
"code": null,
"e": 6583,
"s": 6484,
"text": "We recommend that you execute the above example in a step-by-step manner for better understanding."
},
{
"code": null,
"e": 6616,
"s": 6583,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6634,
"s": 6616,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6669,
"s": 6634,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6682,
"s": 6669,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6717,
"s": 6682,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6733,
"s": 6717,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6768,
"s": 6733,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6786,
"s": 6768,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 6793,
"s": 6786,
"text": " Print"
},
{
"code": null,
"e": 6804,
"s": 6793,
"text": " Add Notes"
}
] |
C Program for Two Pointers Technique - GeeksforGeeks
|
13 Jan, 2022
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X.
Let’s see the naive solution.
C
// Naive solution to find if there is a// pair in A[0..N-1] with given sum.#include <stdio.h> int isPairSum(int A[],int N,int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} // Driver Codeint main(){ int arr[]={3,5,9,2,8,10,11}; int val=17; int arrSize = sizeof(arr)/sizeof(arr[0]); // Function call printf("%d",isPairSum(arr,arrSize,val)); return 0;}
1
Time Complexity: O(n2).
Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X.
C
#include <stdio.h> // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Driver codeint main(){ // array declaration int arr[] = { 3, 5, 9, 2, 8, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf("%d", isPairSum(arr, arrSize, val)); return 0;}
1
Illustration :
Time Complexity: O(n)
How does this work? The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer i when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j.
More problems based on two pointer technique.
Find the closest pair from two sorted arrays
Find the pair in array whose sum is closest to x
Find all triplets with zero sum
Find a triplet that sum to a given value
Find a triplet such that sum of two equals to third element
Find four elements that sum to a given value
Please refer complete article on Two Pointers Technique for more details!
two-pointer-algorithm
Arrays
C Language
C Programs
Searching
Technical Scripter
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Building Heap from Array
Window Sliding Technique
1's and 2's complement of a Binary Number
Reversal algorithm for array rotation
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Multidimensional Arrays in C / C++
std::sort() in C++ STL
Command line arguments in C/C++
rand() and srand() in C/C++
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 24683,
"s": 24405,
"text": "Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X."
},
{
"code": null,
"e": 24715,
"s": 24683,
"text": "Let’s see the naive solution. "
},
{
"code": null,
"e": 24717,
"s": 24715,
"text": "C"
},
{
"code": "// Naive solution to find if there is a// pair in A[0..N-1] with given sum.#include <stdio.h> int isPairSum(int A[],int N,int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} // Driver Codeint main(){ int arr[]={3,5,9,2,8,10,11}; int val=17; int arrSize = sizeof(arr)/sizeof(arr[0]); // Function call printf(\"%d\",isPairSum(arr,arrSize,val)); return 0;}",
"e": 25489,
"s": 24717,
"text": null
},
{
"code": null,
"e": 25491,
"s": 25489,
"text": "1"
},
{
"code": null,
"e": 25516,
"s": 25491,
"text": "Time Complexity: O(n2)."
},
{
"code": null,
"e": 25969,
"s": 25516,
"text": "Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X. "
},
{
"code": null,
"e": 25971,
"s": 25969,
"text": "C"
},
{
"code": "#include <stdio.h> // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Driver codeint main(){ // array declaration int arr[] = { 3, 5, 9, 2, 8, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf(\"%d\", isPairSum(arr, arrSize, val)); return 0;}",
"e": 26970,
"s": 25971,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26970,
"text": "1"
},
{
"code": null,
"e": 26989,
"s": 26972,
"text": "Illustration : "
},
{
"code": null,
"e": 27012,
"s": 26989,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 27374,
"s": 27012,
"text": "How does this work? The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer i when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j."
},
{
"code": null,
"e": 27421,
"s": 27374,
"text": "More problems based on two pointer technique. "
},
{
"code": null,
"e": 27466,
"s": 27421,
"text": "Find the closest pair from two sorted arrays"
},
{
"code": null,
"e": 27515,
"s": 27466,
"text": "Find the pair in array whose sum is closest to x"
},
{
"code": null,
"e": 27547,
"s": 27515,
"text": "Find all triplets with zero sum"
},
{
"code": null,
"e": 27588,
"s": 27547,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 27648,
"s": 27588,
"text": "Find a triplet such that sum of two equals to third element"
},
{
"code": null,
"e": 27693,
"s": 27648,
"text": "Find four elements that sum to a given value"
},
{
"code": null,
"e": 27767,
"s": 27693,
"text": "Please refer complete article on Two Pointers Technique for more details!"
},
{
"code": null,
"e": 27789,
"s": 27767,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Arrays"
},
{
"code": null,
"e": 27807,
"s": 27796,
"text": "C Language"
},
{
"code": null,
"e": 27818,
"s": 27807,
"text": "C Programs"
},
{
"code": null,
"e": 27828,
"s": 27818,
"text": "Searching"
},
{
"code": null,
"e": 27847,
"s": 27828,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27869,
"s": 27847,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 27876,
"s": 27869,
"text": "Arrays"
},
{
"code": null,
"e": 27886,
"s": 27876,
"text": "Searching"
},
{
"code": null,
"e": 27984,
"s": 27886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27993,
"s": 27984,
"text": "Comments"
},
{
"code": null,
"e": 28006,
"s": 27993,
"text": "Old Comments"
},
{
"code": null,
"e": 28055,
"s": 28006,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28080,
"s": 28055,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 28105,
"s": 28080,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28147,
"s": 28105,
"text": "1's and 2's complement of a Binary Number"
},
{
"code": null,
"e": 28185,
"s": 28147,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28263,
"s": 28185,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 28298,
"s": 28263,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28321,
"s": 28298,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 28353,
"s": 28321,
"text": "Command line arguments in C/C++"
}
] |
Manipulating machine learning results with random state | by Ler Wei Han | Towards Data Science
|
Tuning hyperparameters, performing the right kind of feature engineering, feature selection etc are all part of the data science flow for building your machine learning model. Hours are spent tweaking and modifying each part of the process to improve the outcome of our model.
However, there is one argument nested within the most popular functions in data science that can be altered to change your machine learning results.
.....and it has nothing to do with domain knowledge or any of the engineering you have done on your data.
ML_model(n_estimators=100,max_depth=5,gamma=0,random_state=0..)
A seemingly harmless argument that could change your results, yet barely any article teaches you how to optimise it. With some manipulation to the random permutation of the training data and the model seed, anyone can artificially improve their results.
In this article, I would like to gently highlight an often overlooked component of most data science projects — random state and how it affects our model outputs in machine learning.
To show how this affects the prediction result, I will be using Kaggle’s famous Titanic dataset to predict the survival of the passengers.
Using the train dataset, I have applied some bare minimum data cleaning and feature engineering just to get the data good enough for training. I will be using a typical grid search cross validation with the xgboost classifier model for this example.
Training data that I will be using:
X_train.head()
Using grid search to find the optimal xgboost hyperparameters, I got the best parameters for the model.
#performing grid search to find best hyperparameter
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
from xgboost import XGBClassifier
XGB = XGBClassifier(random_state=0)
parameter_grid = {'min_child_weight': [1, 5, 10],
'gamma': [0.5, 1, 1.5, 2, 5],
'subsample': [0.6, 0.8, 1.0],
'colsample_bytree': [0.6, 0.8, 1.0],
'max_depth': [3, 4, 5]}
cross_validation = StratifiedKFold(n_splits=3,random_state=0,shuffle=True)
grid_search_XGB = GridSearchCV(XGB,
param_grid=parameter_grid,
cv=cross_validation,
n_jobs=-1,
verbose=0)
grid_search_XGB.fit(X_train, Y_train)
print('Best score: {}'.format(grid_search_XGB.best_score_))
print('Best parameters: {}'.format(grid_search_XGB.best_params_))
Best score: 0.8249158249158249
Best parameters: {'colsample_bytree': 1.0, 'gamma': 0.5, 'max_depth': 4, 'min_child_weight': 1, 'subsample': 0.8}
Based on the cross validation result, my best performance achieved is 82.49% and the best parameters are:
'colsample_bytree': 1.0, 'gamma': 0.5, 'max_depth': 4, 'min_child_weight': 1, 'subsample': 0.8
This process is a staple to many machine learning projects: search through a range of hyperparameters to get the best averaged cross validation result. At this time, the work is considered done.
After all, cross validation should be robust to randomness.... right?
For data science tutorials or showcases of results in Kaggle kernels, the notebook would have ended right there. However I would like pull back the previous workflow to show how the result differs with different random states.
This time lets run the code with 5 different random states on the classifier:
for i in np.arange(0,5):
XGB = XGBClassifier(random_state=i)
parameter_grid = {'min_child_weight': [1, 5, 10],
'gamma': [0.5, 1, 1.5, 2, 5],
'subsample': [0.6, 0.8, 1.0],
'colsample_bytree': [0.6, 0.8, 1.0],
'max_depth': [3, 4, 5]}
cross_validation = StratifiedKFold(n_splits=5,random_state=0,shuffle=True)
grid_search_XGB = GridSearchCV(XGB,
param_grid=parameter_grid,
cv=cross_validation,
n_jobs=-1,
verbose=0)
grid_search_XGB.fit(X_train, Y_train)
print('Xgboost Random state:{}'.format(i),'Best score: {}'.format(grid_search_XGB.best_score_))
Xgboost Random state:0 Best score: 0.835016835016835
Xgboost Random state:1 Best score: 0.8361391694725028
Xgboost Random state:2 Best score: 0.8383838383838383
Xgboost Random state:3 Best score: 0.8361391694725028
Xgboost Random state:4 Best score: 0.8372615039281706
Lets change the cross validation random state as well:
parameter_grid = {'min_child_weight': [1, 5, 10],
'gamma': [0.5, 1, 1.5, 2, 5],
'subsample': [0.6, 0.8, 1.0],
'colsample_bytree': [0.6, 0.8, 1.0],
'max_depth': [3, 4, 5]}
for i in np.arange(0,5):
for j in np.arange(0,5):
XGB = XGBClassifier(random_state=i)
cross_validation = StratifiedKFold(n_splits=3,random_state=j,shuffle=True)
grid_search_XGB = GridSearchCV(XGB,
param_grid=parameter_grid,
cv=cross_validation,
n_jobs=-1,
verbose=0)
grid_search_XGB.fit(X_train, Y_train)
print('Xgboost Random state:{}'.format(i),'CV Random state:{}'.format(j),'Best score: {}'.format(grid_search_XGB.best_score_))
Xgboost Random state:0 CV Random state:0 Best score: 0.8249158249158249
Xgboost Random state:0 CV Random state:1 Best score: 0.8305274971941639
Xgboost Random state:0 CV Random state:2 Best score: 0.8395061728395061
Xgboost Random state:0 CV Random state:3 Best score: 0.8417508417508418
Xgboost Random state:0 CV Random state:4 Best score: 0.8439955106621774
Xgboost Random state:1 CV Random state:0 Best score: 0.8271604938271605
Xgboost Random state:1 CV Random state:1 Best score: 0.8249158249158249
Xgboost Random state:1 CV Random state:2 Best score: 0.8406285072951739
Xgboost Random state:1 CV Random state:3 Best score: 0.8395061728395061
Xgboost Random state:1 CV Random state:4 Best score: 0.8428731762065096
Xgboost Random state:2 CV Random state:0 Best score: 0.8271604938271605
Xgboost Random state:2 CV Random state:1 Best score: 0.8226711560044894
Xgboost Random state:2 CV Random state:2 Best score: 0.8395061728395061
Xgboost Random state:2 CV Random state:3 Best score: 0.8383838383838383
Xgboost Random state:2 CV Random state:4 Best score: 0.8428731762065096
Xgboost Random state:3 CV Random state:0 Best score: 0.8260381593714927
Xgboost Random state:3 CV Random state:1 Best score: 0.8237934904601572
Xgboost Random state:3 CV Random state:2 Best score: 0.8406285072951739
Xgboost Random state:3 CV Random state:3 Best score: 0.8417508417508418
Xgboost Random state:3 CV Random state:4 Best score: 0.8417508417508418
Xgboost Random state:4 CV Random state:0 Best score: 0.8305274971941639
Xgboost Random state:4 CV Random state:1 Best score: 0.8271604938271605
Xgboost Random state:4 CV Random state:2 Best score: 0.8484848484848485
Xgboost Random state:4 CV Random state:3 Best score: 0.8406285072951739
Xgboost Random state:4 CV Random state:4 Best score: 0.8428731762065096
All the results returned are different. With 5 different random states for the xgboost classifier and the cross validation split, the grid search run produces 25 different best performance results.
Having multiple results stems from the fact that the data and the algorithm we use have a random component that can affect the output.
However this creates a huge doubt in the data science process as we make changes to our model all the time.
For each of the changes that I make, I would compare the results across different runs to validate the improvements. E.g Changing ‘a’ improves model by 2%, adding ‘b’ to the features improves it by a further 3%.
With the variation of results as shown above, it makes me wonder if my feature engineering actually contributed to a better result or the improvement was all down to chance.
Maybe a different random state would make my results worse than before.
Notice that with classifier random state 4 and stratified shuffle random state 2, my results are substantially higher at 84.84% compared to my initial run.
Which result do I present then?
It is tantalizing to present the best of the model results, since the random seed is fixed and the results are reproducible.
It seems absurd that an improvement of 2% to the result can be attributed to just a different random state. It seems like on a good day with the correct seed, we get a better result.
There are many ways to tackle this issue in a data science pipeline. This is by no means a complete list, but just some of the practices I carry out on my work.
1) Fix the random state from the start
Commit to a fixed random state for everything or better yet, fix a global random seed so that randomness does not come into play. Treat it as an immutable variable in your process and not something to be tinkered with.
Alternatively,
2) Use the prediction results as an interval
Since the results vary across a range, you can opt to report the cross validation results as a range. Repeat the run with different seeds in order to produce a confidence interval that you can report with. Its the range that one can comfortably say the performance band of the model really lies within.
3) Reduce imbalance/randomness in data split
One of the ways to reduce the effect of a random split on your data is to make sure the split does not affect the composition of the data too much.
Stratify your data to reduce randomness. Stratifying your data ensures that the data for your train test split/oob error/cross validation has the same ratio of survivors/non-survivors in the train and test set respectively. The splits are made by preserving the percentage of each class will then reduce the magnitude of how a random shuffle affects the outcome. Stratification can even be done on multiple columns.
It is certainly important to note that variation in performance should not be drastic despite randomization in the data.
If the accuracy results vary wildly with the seed, it probably means that the model is not robust and you should consider improving your methods to better fit the data. Most of the time it does not matter, but when margins are very close, it would be tempting to consider all variables that can be used to improve model performance, including random state.
Hopefully this article has managed to highlight how randomness affects our models and a couple of ways to mitigate its effect.
Here is the github repo of the code I have used, all of which can be reproduced. Thanks for reading!
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "Tuning hyperparameters, performing the right kind of feature engineering, feature selection etc are all part of the data science flow for building your machine learning model. Hours are spent tweaking and modifying each part of the process to improve the outcome of our model."
},
{
"code": null,
"e": 597,
"s": 448,
"text": "However, there is one argument nested within the most popular functions in data science that can be altered to change your machine learning results."
},
{
"code": null,
"e": 703,
"s": 597,
"text": ".....and it has nothing to do with domain knowledge or any of the engineering you have done on your data."
},
{
"code": null,
"e": 767,
"s": 703,
"text": "ML_model(n_estimators=100,max_depth=5,gamma=0,random_state=0..)"
},
{
"code": null,
"e": 1021,
"s": 767,
"text": "A seemingly harmless argument that could change your results, yet barely any article teaches you how to optimise it. With some manipulation to the random permutation of the training data and the model seed, anyone can artificially improve their results."
},
{
"code": null,
"e": 1204,
"s": 1021,
"text": "In this article, I would like to gently highlight an often overlooked component of most data science projects — random state and how it affects our model outputs in machine learning."
},
{
"code": null,
"e": 1343,
"s": 1204,
"text": "To show how this affects the prediction result, I will be using Kaggle’s famous Titanic dataset to predict the survival of the passengers."
},
{
"code": null,
"e": 1593,
"s": 1343,
"text": "Using the train dataset, I have applied some bare minimum data cleaning and feature engineering just to get the data good enough for training. I will be using a typical grid search cross validation with the xgboost classifier model for this example."
},
{
"code": null,
"e": 1629,
"s": 1593,
"text": "Training data that I will be using:"
},
{
"code": null,
"e": 1645,
"s": 1629,
"text": "X_train.head()\n"
},
{
"code": null,
"e": 1749,
"s": 1645,
"text": "Using grid search to find the optimal xgboost hyperparameters, I got the best parameters for the model."
},
{
"code": null,
"e": 2636,
"s": 1749,
"text": "#performing grid search to find best hyperparameter\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import StratifiedKFold\nfrom xgboost import XGBClassifier\nXGB = XGBClassifier(random_state=0)\nparameter_grid = {'min_child_weight': [1, 5, 10],\n 'gamma': [0.5, 1, 1.5, 2, 5],\n 'subsample': [0.6, 0.8, 1.0],\n 'colsample_bytree': [0.6, 0.8, 1.0],\n 'max_depth': [3, 4, 5]}\n\ncross_validation = StratifiedKFold(n_splits=3,random_state=0,shuffle=True)\n\ngrid_search_XGB = GridSearchCV(XGB,\n param_grid=parameter_grid,\n cv=cross_validation,\n n_jobs=-1,\n verbose=0)\n\ngrid_search_XGB.fit(X_train, Y_train)\nprint('Best score: {}'.format(grid_search_XGB.best_score_))\nprint('Best parameters: {}'.format(grid_search_XGB.best_params_))\n \n"
},
{
"code": null,
"e": 2782,
"s": 2636,
"text": "Best score: 0.8249158249158249\nBest parameters: {'colsample_bytree': 1.0, 'gamma': 0.5, 'max_depth': 4, 'min_child_weight': 1, 'subsample': 0.8}\n"
},
{
"code": null,
"e": 2888,
"s": 2782,
"text": "Based on the cross validation result, my best performance achieved is 82.49% and the best parameters are:"
},
{
"code": null,
"e": 2983,
"s": 2888,
"text": "'colsample_bytree': 1.0, 'gamma': 0.5, 'max_depth': 4, 'min_child_weight': 1, 'subsample': 0.8"
},
{
"code": null,
"e": 3178,
"s": 2983,
"text": "This process is a staple to many machine learning projects: search through a range of hyperparameters to get the best averaged cross validation result. At this time, the work is considered done."
},
{
"code": null,
"e": 3248,
"s": 3178,
"text": "After all, cross validation should be robust to randomness.... right?"
},
{
"code": null,
"e": 3475,
"s": 3248,
"text": "For data science tutorials or showcases of results in Kaggle kernels, the notebook would have ended right there. However I would like pull back the previous workflow to show how the result differs with different random states."
},
{
"code": null,
"e": 3553,
"s": 3475,
"text": "This time lets run the code with 5 different random states on the classifier:"
},
{
"code": null,
"e": 4274,
"s": 3553,
"text": "for i in np.arange(0,5):\n XGB = XGBClassifier(random_state=i)\n parameter_grid = {'min_child_weight': [1, 5, 10],\n 'gamma': [0.5, 1, 1.5, 2, 5],\n 'subsample': [0.6, 0.8, 1.0],\n 'colsample_bytree': [0.6, 0.8, 1.0],\n 'max_depth': [3, 4, 5]}\n\n cross_validation = StratifiedKFold(n_splits=5,random_state=0,shuffle=True)\n\n grid_search_XGB = GridSearchCV(XGB,\n param_grid=parameter_grid,\n cv=cross_validation,\n n_jobs=-1,\n verbose=0)\n\n grid_search_XGB.fit(X_train, Y_train)\n print('Xgboost Random state:{}'.format(i),'Best score: {}'.format(grid_search_XGB.best_score_))\n \n"
},
{
"code": null,
"e": 4544,
"s": 4274,
"text": "Xgboost Random state:0 Best score: 0.835016835016835\nXgboost Random state:1 Best score: 0.8361391694725028\nXgboost Random state:2 Best score: 0.8383838383838383\nXgboost Random state:3 Best score: 0.8361391694725028\nXgboost Random state:4 Best score: 0.8372615039281706\n"
},
{
"code": null,
"e": 4599,
"s": 4544,
"text": "Lets change the cross validation random state as well:"
},
{
"code": null,
"e": 5392,
"s": 4599,
"text": " parameter_grid = {'min_child_weight': [1, 5, 10],\n 'gamma': [0.5, 1, 1.5, 2, 5],\n 'subsample': [0.6, 0.8, 1.0],\n 'colsample_bytree': [0.6, 0.8, 1.0],\n 'max_depth': [3, 4, 5]}\n\nfor i in np.arange(0,5):\n for j in np.arange(0,5):\n XGB = XGBClassifier(random_state=i)\n cross_validation = StratifiedKFold(n_splits=3,random_state=j,shuffle=True)\n grid_search_XGB = GridSearchCV(XGB,\n param_grid=parameter_grid,\n cv=cross_validation,\n n_jobs=-1,\n verbose=0)\n\n grid_search_XGB.fit(X_train, Y_train)\n print('Xgboost Random state:{}'.format(i),'CV Random state:{}'.format(j),'Best score: {}'.format(grid_search_XGB.best_score_))\n"
},
{
"code": null,
"e": 7193,
"s": 5392,
"text": "Xgboost Random state:0 CV Random state:0 Best score: 0.8249158249158249\nXgboost Random state:0 CV Random state:1 Best score: 0.8305274971941639\nXgboost Random state:0 CV Random state:2 Best score: 0.8395061728395061\nXgboost Random state:0 CV Random state:3 Best score: 0.8417508417508418\nXgboost Random state:0 CV Random state:4 Best score: 0.8439955106621774\nXgboost Random state:1 CV Random state:0 Best score: 0.8271604938271605\nXgboost Random state:1 CV Random state:1 Best score: 0.8249158249158249\nXgboost Random state:1 CV Random state:2 Best score: 0.8406285072951739\nXgboost Random state:1 CV Random state:3 Best score: 0.8395061728395061\nXgboost Random state:1 CV Random state:4 Best score: 0.8428731762065096\nXgboost Random state:2 CV Random state:0 Best score: 0.8271604938271605\nXgboost Random state:2 CV Random state:1 Best score: 0.8226711560044894\nXgboost Random state:2 CV Random state:2 Best score: 0.8395061728395061\nXgboost Random state:2 CV Random state:3 Best score: 0.8383838383838383\nXgboost Random state:2 CV Random state:4 Best score: 0.8428731762065096\nXgboost Random state:3 CV Random state:0 Best score: 0.8260381593714927\nXgboost Random state:3 CV Random state:1 Best score: 0.8237934904601572\nXgboost Random state:3 CV Random state:2 Best score: 0.8406285072951739\nXgboost Random state:3 CV Random state:3 Best score: 0.8417508417508418\nXgboost Random state:3 CV Random state:4 Best score: 0.8417508417508418\nXgboost Random state:4 CV Random state:0 Best score: 0.8305274971941639\nXgboost Random state:4 CV Random state:1 Best score: 0.8271604938271605\nXgboost Random state:4 CV Random state:2 Best score: 0.8484848484848485\nXgboost Random state:4 CV Random state:3 Best score: 0.8406285072951739\nXgboost Random state:4 CV Random state:4 Best score: 0.8428731762065096\n"
},
{
"code": null,
"e": 7391,
"s": 7193,
"text": "All the results returned are different. With 5 different random states for the xgboost classifier and the cross validation split, the grid search run produces 25 different best performance results."
},
{
"code": null,
"e": 7526,
"s": 7391,
"text": "Having multiple results stems from the fact that the data and the algorithm we use have a random component that can affect the output."
},
{
"code": null,
"e": 7634,
"s": 7526,
"text": "However this creates a huge doubt in the data science process as we make changes to our model all the time."
},
{
"code": null,
"e": 7846,
"s": 7634,
"text": "For each of the changes that I make, I would compare the results across different runs to validate the improvements. E.g Changing ‘a’ improves model by 2%, adding ‘b’ to the features improves it by a further 3%."
},
{
"code": null,
"e": 8020,
"s": 7846,
"text": "With the variation of results as shown above, it makes me wonder if my feature engineering actually contributed to a better result or the improvement was all down to chance."
},
{
"code": null,
"e": 8092,
"s": 8020,
"text": "Maybe a different random state would make my results worse than before."
},
{
"code": null,
"e": 8248,
"s": 8092,
"text": "Notice that with classifier random state 4 and stratified shuffle random state 2, my results are substantially higher at 84.84% compared to my initial run."
},
{
"code": null,
"e": 8280,
"s": 8248,
"text": "Which result do I present then?"
},
{
"code": null,
"e": 8405,
"s": 8280,
"text": "It is tantalizing to present the best of the model results, since the random seed is fixed and the results are reproducible."
},
{
"code": null,
"e": 8588,
"s": 8405,
"text": "It seems absurd that an improvement of 2% to the result can be attributed to just a different random state. It seems like on a good day with the correct seed, we get a better result."
},
{
"code": null,
"e": 8749,
"s": 8588,
"text": "There are many ways to tackle this issue in a data science pipeline. This is by no means a complete list, but just some of the practices I carry out on my work."
},
{
"code": null,
"e": 8788,
"s": 8749,
"text": "1) Fix the random state from the start"
},
{
"code": null,
"e": 9007,
"s": 8788,
"text": "Commit to a fixed random state for everything or better yet, fix a global random seed so that randomness does not come into play. Treat it as an immutable variable in your process and not something to be tinkered with."
},
{
"code": null,
"e": 9022,
"s": 9007,
"text": "Alternatively,"
},
{
"code": null,
"e": 9067,
"s": 9022,
"text": "2) Use the prediction results as an interval"
},
{
"code": null,
"e": 9370,
"s": 9067,
"text": "Since the results vary across a range, you can opt to report the cross validation results as a range. Repeat the run with different seeds in order to produce a confidence interval that you can report with. Its the range that one can comfortably say the performance band of the model really lies within."
},
{
"code": null,
"e": 9415,
"s": 9370,
"text": "3) Reduce imbalance/randomness in data split"
},
{
"code": null,
"e": 9563,
"s": 9415,
"text": "One of the ways to reduce the effect of a random split on your data is to make sure the split does not affect the composition of the data too much."
},
{
"code": null,
"e": 9979,
"s": 9563,
"text": "Stratify your data to reduce randomness. Stratifying your data ensures that the data for your train test split/oob error/cross validation has the same ratio of survivors/non-survivors in the train and test set respectively. The splits are made by preserving the percentage of each class will then reduce the magnitude of how a random shuffle affects the outcome. Stratification can even be done on multiple columns."
},
{
"code": null,
"e": 10100,
"s": 9979,
"text": "It is certainly important to note that variation in performance should not be drastic despite randomization in the data."
},
{
"code": null,
"e": 10457,
"s": 10100,
"text": "If the accuracy results vary wildly with the seed, it probably means that the model is not robust and you should consider improving your methods to better fit the data. Most of the time it does not matter, but when margins are very close, it would be tempting to consider all variables that can be used to improve model performance, including random state."
},
{
"code": null,
"e": 10584,
"s": 10457,
"text": "Hopefully this article has managed to highlight how randomness affects our models and a couple of ways to mitigate its effect."
}
] |
CSS | @page rule - GeeksforGeeks
|
24 Jan, 2022
The CSS @page rule defines the dimension of the page which is gonna be print. There are few important things should be under control when you want to print a web page those are listed below:
The page size, orientation, margins, border, and padding.
Page breaks.
Headers and footers.
Page counters.
Orphans.
All the above things are controllable when you follow the @page rule.Syntax:
@page [:left | :right | :first] {
/* print-specific rules */
}
Page Descriptor: There are three Descriptor in @page rule those are:
size: Specify the size of page box’s containing block.
html
@page { size: A4; }
marks: It helps to trim the page that you want to print.
html
@page { marks: crop cross; }
bleed: It extend the bleed area of the box
html
@page { bleed: 7pt; }
Example:
html
<!DOCTYPE html><html lang="en"><head><title>CSS @page rule</title><style type="text/css"> /* default for all pages */ @page { margin: 2in; } /* margin on left page */ @page :left { margin: 1in; } /* margin on right page */ @page :right { margin: 3in; } /* top margin on first page */ @page :first { margin-top: 5in; } h1{ color:green; }</style></head><body> <center> <h1>GeeksforGeeks</h1> <h2>CSS Page At-rule</h2> <p> If you open output in a new window and print the page the margin around the text content appears differently than it appears on the screen. </p> </center> </body></html>
Output: When you choose to print the output screen of the above code.
Supported Browsers: The browsers supported by CSS @page rule are listed below:
Google Chrome 2.0
Internet Explorer 8.0
Safari 5.1
Opera 6.0
sumitgumber28
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to Upload Image into Database and Display it using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24916,
"s": 24888,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25109,
"s": 24916,
"text": "The CSS @page rule defines the dimension of the page which is gonna be print. There are few important things should be under control when you want to print a web page those are listed below: "
},
{
"code": null,
"e": 25167,
"s": 25109,
"text": "The page size, orientation, margins, border, and padding."
},
{
"code": null,
"e": 25180,
"s": 25167,
"text": "Page breaks."
},
{
"code": null,
"e": 25201,
"s": 25180,
"text": "Headers and footers."
},
{
"code": null,
"e": 25216,
"s": 25201,
"text": "Page counters."
},
{
"code": null,
"e": 25225,
"s": 25216,
"text": "Orphans."
},
{
"code": null,
"e": 25304,
"s": 25225,
"text": "All the above things are controllable when you follow the @page rule.Syntax: "
},
{
"code": null,
"e": 25372,
"s": 25304,
"text": "@page [:left | :right | :first] {\n /* print-specific rules */\n} "
},
{
"code": null,
"e": 25442,
"s": 25372,
"text": "Page Descriptor: There are three Descriptor in @page rule those are: "
},
{
"code": null,
"e": 25498,
"s": 25442,
"text": "size: Specify the size of page box’s containing block. "
},
{
"code": null,
"e": 25503,
"s": 25498,
"text": "html"
},
{
"code": "@page { size: A4; }",
"e": 25528,
"s": 25503,
"text": null
},
{
"code": null,
"e": 25586,
"s": 25528,
"text": "marks: It helps to trim the page that you want to print. "
},
{
"code": null,
"e": 25591,
"s": 25586,
"text": "html"
},
{
"code": "@page { marks: crop cross; }",
"e": 25625,
"s": 25591,
"text": null
},
{
"code": null,
"e": 25669,
"s": 25625,
"text": "bleed: It extend the bleed area of the box "
},
{
"code": null,
"e": 25674,
"s": 25669,
"text": "html"
},
{
"code": "@page { bleed: 7pt; }",
"e": 25701,
"s": 25674,
"text": null
},
{
"code": null,
"e": 25711,
"s": 25701,
"text": "Example: "
},
{
"code": null,
"e": 25716,
"s": 25711,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head><title>CSS @page rule</title><style type=\"text/css\"> /* default for all pages */ @page { margin: 2in; } /* margin on left page */ @page :left { margin: 1in; } /* margin on right page */ @page :right { margin: 3in; } /* top margin on first page */ @page :first { margin-top: 5in; } h1{ color:green; }</style></head><body> <center> <h1>GeeksforGeeks</h1> <h2>CSS Page At-rule</h2> <p> If you open output in a new window and print the page the margin around the text content appears differently than it appears on the screen. </p> </center> </body></html>",
"e": 26441,
"s": 25716,
"text": null
},
{
"code": null,
"e": 26512,
"s": 26441,
"text": "Output: When you choose to print the output screen of the above code. "
},
{
"code": null,
"e": 26592,
"s": 26512,
"text": "Supported Browsers: The browsers supported by CSS @page rule are listed below: "
},
{
"code": null,
"e": 26610,
"s": 26592,
"text": "Google Chrome 2.0"
},
{
"code": null,
"e": 26632,
"s": 26610,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 26643,
"s": 26632,
"text": "Safari 5.1"
},
{
"code": null,
"e": 26653,
"s": 26643,
"text": "Opera 6.0"
},
{
"code": null,
"e": 26667,
"s": 26653,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26682,
"s": 26667,
"text": "CSS-Properties"
},
{
"code": null,
"e": 26686,
"s": 26682,
"text": "CSS"
},
{
"code": null,
"e": 26703,
"s": 26686,
"text": "Web Technologies"
},
{
"code": null,
"e": 26801,
"s": 26703,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26810,
"s": 26801,
"text": "Comments"
},
{
"code": null,
"e": 26823,
"s": 26810,
"text": "Old Comments"
},
{
"code": null,
"e": 26881,
"s": 26823,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26918,
"s": 26881,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26955,
"s": 26918,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26996,
"s": 26955,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27057,
"s": 26996,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27099,
"s": 27057,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27132,
"s": 27099,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27175,
"s": 27132,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27219,
"s": 27175,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
Python OpenCV - namedWindow() Function - GeeksforGeeks
|
25 Apr, 2022
Python OpenCV namedWindow() method is used to create a window with a suitable name and size to display images and videos on the screen. The image by default is displayed in its original size, so we may need to resize the image for it to fit our screen.
Created windows are referred by their names and can also be used as a placeholder. The function does nothing If a window exists with the same name.
Syntax: cv2.namedWindow(window_name, flag)
Parameters:
window_name: Name of the window that will display image/video
flag: Represents if window size is automatically set or adjustable.
Some of the flag values are:
WINDOW_NORMAL – Allows to manually change window size
WINDOW_AUTOSIZE(Default) – Automatically sets the window size
WINDOW_FULLSCREEN – Changes the window size to fullscreen
Return Value: It doesn’t return anything
Python3
# Python program to explain cv2.namedWindow() method # Importing OpenCVimport cv2 # Path to image in local directorypath = 'C:/Users/art/OneDrive/Desktop/geeks.png' # Using cv2.imread() to read an image in default modeimage = cv2.imread(path) # Using namedWindow()# A window with 'Display' name is created# with WINDOW_AUTOSIZE, window size is set automaticallycv2.namedWindow("Display", cv2.WINDOW_AUTOSIZE) # using cv2.imshow() to display the imagecv2.imshow('Display', image) # Waiting 0ms for user to press any keycv2.waitKey(0) # Using cv2.destroyAllWindows() to destroy# all created windows open on screencv2.destroyAllWindows()
Output:
Explanation:
In this code, in order to use namedWindow function OpenCV python library is imported.
Then by using cv2.imread, a file from a particular location(path) is loaded into ‘image’ variable in default mode.
Now to create a window with ‘Display’ name and automatic size for image namedWindow is used.
By using cv2.imshow, the custom window is displayed on the screen. After waiting for 0ms user can destroy all windows by pressing any key from the keyboard.
Python3
# Python Program to explain namedWindow() method # Importing OpenCVimport cv2 # Path to image in local directorypath = 'C:/Users/art/OneDrive/Desktop/geeks.png' # Using cv2.imread() to read an image in grayscale modeimage = cv2.imread(path, 0) # Using namedWindow()# A window with 'Display_Image' name is created# with WINDOW_NORMAL allowing us to have random sizecv2.namedWindow("Display_Image", cv2.WINDOW_NORMAL) # Using cv2.imshow() to display the imagecv2.imshow('Display_Image', image) # Waiting 0ms for user to press any keycv2.waitKey(0) # Using cv2.destroyAllWindows() to destroy# all created windows open on screencv2.destroyAllWindows()
Output:
Note: When a user randomly changes size, the window size is changed dimensions of the image remain unchanged.
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 24465,
"s": 24212,
"text": "Python OpenCV namedWindow() method is used to create a window with a suitable name and size to display images and videos on the screen. The image by default is displayed in its original size, so we may need to resize the image for it to fit our screen."
},
{
"code": null,
"e": 24614,
"s": 24465,
"text": "Created windows are referred by their names and can also be used as a placeholder. The function does nothing If a window exists with the same name. "
},
{
"code": null,
"e": 24657,
"s": 24614,
"text": "Syntax: cv2.namedWindow(window_name, flag)"
},
{
"code": null,
"e": 24669,
"s": 24657,
"text": "Parameters:"
},
{
"code": null,
"e": 24731,
"s": 24669,
"text": "window_name: Name of the window that will display image/video"
},
{
"code": null,
"e": 24800,
"s": 24731,
"text": "flag: Represents if window size is automatically set or adjustable."
},
{
"code": null,
"e": 24829,
"s": 24800,
"text": "Some of the flag values are:"
},
{
"code": null,
"e": 24883,
"s": 24829,
"text": "WINDOW_NORMAL – Allows to manually change window size"
},
{
"code": null,
"e": 24945,
"s": 24883,
"text": "WINDOW_AUTOSIZE(Default) – Automatically sets the window size"
},
{
"code": null,
"e": 25003,
"s": 24945,
"text": "WINDOW_FULLSCREEN – Changes the window size to fullscreen"
},
{
"code": null,
"e": 25044,
"s": 25003,
"text": "Return Value: It doesn’t return anything"
},
{
"code": null,
"e": 25052,
"s": 25044,
"text": "Python3"
},
{
"code": "# Python program to explain cv2.namedWindow() method # Importing OpenCVimport cv2 # Path to image in local directorypath = 'C:/Users/art/OneDrive/Desktop/geeks.png' # Using cv2.imread() to read an image in default modeimage = cv2.imread(path) # Using namedWindow()# A window with 'Display' name is created# with WINDOW_AUTOSIZE, window size is set automaticallycv2.namedWindow(\"Display\", cv2.WINDOW_AUTOSIZE) # using cv2.imshow() to display the imagecv2.imshow('Display', image) # Waiting 0ms for user to press any keycv2.waitKey(0) # Using cv2.destroyAllWindows() to destroy# all created windows open on screencv2.destroyAllWindows()",
"e": 25687,
"s": 25052,
"text": null
},
{
"code": null,
"e": 25695,
"s": 25687,
"text": "Output:"
},
{
"code": null,
"e": 25709,
"s": 25695,
"text": "Explanation: "
},
{
"code": null,
"e": 25796,
"s": 25709,
"text": "In this code, in order to use namedWindow function OpenCV python library is imported. "
},
{
"code": null,
"e": 25912,
"s": 25796,
"text": "Then by using cv2.imread, a file from a particular location(path) is loaded into ‘image’ variable in default mode. "
},
{
"code": null,
"e": 26006,
"s": 25912,
"text": "Now to create a window with ‘Display’ name and automatic size for image namedWindow is used. "
},
{
"code": null,
"e": 26164,
"s": 26006,
"text": "By using cv2.imshow, the custom window is displayed on the screen. After waiting for 0ms user can destroy all windows by pressing any key from the keyboard. "
},
{
"code": null,
"e": 26172,
"s": 26164,
"text": "Python3"
},
{
"code": "# Python Program to explain namedWindow() method # Importing OpenCVimport cv2 # Path to image in local directorypath = 'C:/Users/art/OneDrive/Desktop/geeks.png' # Using cv2.imread() to read an image in grayscale modeimage = cv2.imread(path, 0) # Using namedWindow()# A window with 'Display_Image' name is created# with WINDOW_NORMAL allowing us to have random sizecv2.namedWindow(\"Display_Image\", cv2.WINDOW_NORMAL) # Using cv2.imshow() to display the imagecv2.imshow('Display_Image', image) # Waiting 0ms for user to press any keycv2.waitKey(0) # Using cv2.destroyAllWindows() to destroy# all created windows open on screencv2.destroyAllWindows()",
"e": 26820,
"s": 26172,
"text": null
},
{
"code": null,
"e": 26828,
"s": 26820,
"text": "Output:"
},
{
"code": null,
"e": 26938,
"s": 26828,
"text": "Note: When a user randomly changes size, the window size is changed dimensions of the image remain unchanged."
},
{
"code": null,
"e": 26945,
"s": 26938,
"text": "Picked"
},
{
"code": null,
"e": 26959,
"s": 26945,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 26966,
"s": 26959,
"text": "Python"
},
{
"code": null,
"e": 27064,
"s": 26966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27073,
"s": 27064,
"text": "Comments"
},
{
"code": null,
"e": 27086,
"s": 27073,
"text": "Old Comments"
},
{
"code": null,
"e": 27107,
"s": 27086,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27139,
"s": 27107,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27162,
"s": 27139,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27184,
"s": 27162,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27211,
"s": 27184,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27227,
"s": 27211,
"text": "Deque in Python"
},
{
"code": null,
"e": 27269,
"s": 27227,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27325,
"s": 27269,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27370,
"s": 27325,
"text": "Python - Ways to remove duplicates from list"
}
] |
Building a Simple Text Recognizer in Python | by Behic Guven | Towards Data Science
|
In this post, I will show you how to extract text from an image using Python. This process is simply called “Text Recognition” or “Text Detection”. So basically as you can understand from the title, we will build a simple python program that will extract text for us. After the extraction, the program will also export the result into a text document. This way, we can keep a record of our results.
If you haven’t heard of Computer Vision before, this is the best time to learn about it. Most of the machine learning and artificial intelligence fields are strongly related to Computer Vision. As we are growing and exploring, seeing the outside world has a big impact on our development. This goes the same for machines, they see the outside world using images, and those images are basically turned into data that computers can understand. Computer Vision is a very deep ocean, I just tried to give some idea of it. If you want to learn more about Computer Vision, here is a nice video by Google Cloud Platform:
There are many nice projects that I want to show you in the following weeks to get started with computer vision. You will be amazed at how powerful things you can do using computer vision. Text Recognition is just one drop from the big ocean. If you are ready, let get started!
First, let’s install the module packages that we will be using in this program. We will install PIL, pytesseract packages. PIL stands for Python Imaging Library, it adds image processing capabilities to your program. The module supports many image formats. And PyTesseract is another module we will be using, which basically does the text recognition part. It will help us to recognize the text and read it.
Here is the code to pip install multiple modules at the same time:
pip install Pillow pytesseract
If you want to learn more about these packages:
PIL
PyTesseract
Now let’s import the libraries into our program:
# adds image processing capabilitiesfrom PIL import Image# will convert the image to text stringimport pytesseract
In this step, we will choose an image that we want to work on. You can download an image from Google or take a picture using your phone. Both ways should work fine. After choosing your image, create a new folder in the same directory, you can call it “image_test” and copy the image file into that folder.
I’ve downloaded an image that has a quote by Virginia Woolf. Fun Fact: I really enjoy reading her books :)
Anyway, after pasting the image in our image_test folder, let’s get back to coding. In the following code, we are creating an image variable to store the image file and then recognizing text using image_to_string method.
# assigning an image from the source pathimg = Image.open(‘image_test/virginia-quote.jpg’)# converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img)
In this step, we will export our results from the previous code into a text document. This way we will have both the original image file and the text we recognized from that image.
with open(‘text_result.txt’, mode =’w’) as file: file.write(result) print(“ready!”)
Well done! You just created your own Text Recognizer using Python. If you want to make it better, check the next extra step. Also here is another project you may be interested.
towardsdatascience.com
PIL is a great and huge package that has many capabilities. In this extra step, we would do some little touches to the image so that our text recognizer can recognize or in other words “read” the text easier. Making little touches on images is taking a big role in Computer Vision. The computer needs our help to process the image in a better way.
Without image processing, it is like putting the recipe ingredients in front of a child and ask him/her to eat. With the right image processing, it is like putting the cooked food in front of the child. The difference is huge, I highly recommend going through image processing documentation to learn more.
Here is the whole code with some little touches added, in other words, a freshly cooked code :)
# adds more image processing capabilitiesfrom PIL import Image, ImageEnhance# assigning an image from the source pathimg = Image.open(‘image_test/virginia-quote.jpg’)# adding some sharpness and contrast to the image enhancer1 = ImageEnhance.Sharpness(img)enhancer2 = ImageEnhance.Contrast(img)img_edit = enhancer1.enhance(20.0)img_edit = enhancer2.enhance(1.5)# save the new imageimg_edit.save("edited_image.png")# converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img_edit)with open(‘text_result2.txt’, mode =’w’) as file: file.write(result) print(“ready!”)
Personally, I am using the one we just created to convert my book pages into text documents, it makes note-taking process much easier and faster. Instead of writing down my favorite lines each time, now I am just taking a picture of that page and converting it with the Text Recognizer. Isn’t that the cool part about coding? Create something that will solve a problem in your life.
I am Behic Guven, and I love sharing stories on creativity, programming, motivation, and life. Follow me Medium to stay inspired.
|
[
{
"code": null,
"e": 571,
"s": 172,
"text": "In this post, I will show you how to extract text from an image using Python. This process is simply called “Text Recognition” or “Text Detection”. So basically as you can understand from the title, we will build a simple python program that will extract text for us. After the extraction, the program will also export the result into a text document. This way, we can keep a record of our results."
},
{
"code": null,
"e": 1185,
"s": 571,
"text": "If you haven’t heard of Computer Vision before, this is the best time to learn about it. Most of the machine learning and artificial intelligence fields are strongly related to Computer Vision. As we are growing and exploring, seeing the outside world has a big impact on our development. This goes the same for machines, they see the outside world using images, and those images are basically turned into data that computers can understand. Computer Vision is a very deep ocean, I just tried to give some idea of it. If you want to learn more about Computer Vision, here is a nice video by Google Cloud Platform:"
},
{
"code": null,
"e": 1463,
"s": 1185,
"text": "There are many nice projects that I want to show you in the following weeks to get started with computer vision. You will be amazed at how powerful things you can do using computer vision. Text Recognition is just one drop from the big ocean. If you are ready, let get started!"
},
{
"code": null,
"e": 1871,
"s": 1463,
"text": "First, let’s install the module packages that we will be using in this program. We will install PIL, pytesseract packages. PIL stands for Python Imaging Library, it adds image processing capabilities to your program. The module supports many image formats. And PyTesseract is another module we will be using, which basically does the text recognition part. It will help us to recognize the text and read it."
},
{
"code": null,
"e": 1938,
"s": 1871,
"text": "Here is the code to pip install multiple modules at the same time:"
},
{
"code": null,
"e": 1969,
"s": 1938,
"text": "pip install Pillow pytesseract"
},
{
"code": null,
"e": 2017,
"s": 1969,
"text": "If you want to learn more about these packages:"
},
{
"code": null,
"e": 2021,
"s": 2017,
"text": "PIL"
},
{
"code": null,
"e": 2033,
"s": 2021,
"text": "PyTesseract"
},
{
"code": null,
"e": 2082,
"s": 2033,
"text": "Now let’s import the libraries into our program:"
},
{
"code": null,
"e": 2197,
"s": 2082,
"text": "# adds image processing capabilitiesfrom PIL import Image# will convert the image to text stringimport pytesseract"
},
{
"code": null,
"e": 2503,
"s": 2197,
"text": "In this step, we will choose an image that we want to work on. You can download an image from Google or take a picture using your phone. Both ways should work fine. After choosing your image, create a new folder in the same directory, you can call it “image_test” and copy the image file into that folder."
},
{
"code": null,
"e": 2610,
"s": 2503,
"text": "I’ve downloaded an image that has a quote by Virginia Woolf. Fun Fact: I really enjoy reading her books :)"
},
{
"code": null,
"e": 2831,
"s": 2610,
"text": "Anyway, after pasting the image in our image_test folder, let’s get back to coding. In the following code, we are creating an image variable to store the image file and then recognizing text using image_to_string method."
},
{
"code": null,
"e": 3027,
"s": 2831,
"text": "# assigning an image from the source pathimg = Image.open(‘image_test/virginia-quote.jpg’)# converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img)"
},
{
"code": null,
"e": 3208,
"s": 3027,
"text": "In this step, we will export our results from the previous code into a text document. This way we will have both the original image file and the text we recognized from that image."
},
{
"code": null,
"e": 3292,
"s": 3208,
"text": "with open(‘text_result.txt’, mode =’w’) as file: file.write(result) print(“ready!”)"
},
{
"code": null,
"e": 3469,
"s": 3292,
"text": "Well done! You just created your own Text Recognizer using Python. If you want to make it better, check the next extra step. Also here is another project you may be interested."
},
{
"code": null,
"e": 3492,
"s": 3469,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3840,
"s": 3492,
"text": "PIL is a great and huge package that has many capabilities. In this extra step, we would do some little touches to the image so that our text recognizer can recognize or in other words “read” the text easier. Making little touches on images is taking a big role in Computer Vision. The computer needs our help to process the image in a better way."
},
{
"code": null,
"e": 4146,
"s": 3840,
"text": "Without image processing, it is like putting the recipe ingredients in front of a child and ask him/her to eat. With the right image processing, it is like putting the cooked food in front of the child. The difference is huge, I highly recommend going through image processing documentation to learn more."
},
{
"code": null,
"e": 4242,
"s": 4146,
"text": "Here is the whole code with some little touches added, in other words, a freshly cooked code :)"
},
{
"code": null,
"e": 4850,
"s": 4242,
"text": "# adds more image processing capabilitiesfrom PIL import Image, ImageEnhance# assigning an image from the source pathimg = Image.open(‘image_test/virginia-quote.jpg’)# adding some sharpness and contrast to the image enhancer1 = ImageEnhance.Sharpness(img)enhancer2 = ImageEnhance.Contrast(img)img_edit = enhancer1.enhance(20.0)img_edit = enhancer2.enhance(1.5)# save the new imageimg_edit.save(\"edited_image.png\")# converts the image to result and saves it into result variableresult = pytesseract.image_to_string(img_edit)with open(‘text_result2.txt’, mode =’w’) as file: file.write(result) print(“ready!”)"
},
{
"code": null,
"e": 5233,
"s": 4850,
"text": "Personally, I am using the one we just created to convert my book pages into text documents, it makes note-taking process much easier and faster. Instead of writing down my favorite lines each time, now I am just taking a picture of that page and converting it with the Text Recognizer. Isn’t that the cool part about coding? Create something that will solve a problem in your life."
}
] |
float() in Python
|
17 Sep, 2021
Python float() function is used to return a floating-point number from a number or a string.
Syntax: float(x)
The method only accepts one parameter and that is also optional to use. Let us look at the various types of argument, the method accepts:
A number: Can be an integer or a floating-point number.
A String :
Must contain numbers of any type.
Any left or right whitespaces or a new line is ignored by the method.
Mathematical Operators can be used.
Can contain NaN, Infinity or inf (any cases)
Values that the float() method can return depending upon the argument passed
If an argument is passed, then the equivalent floating-point number is returned.
If no argument is passed then the method returns 0.0.
If any string is passed that is not a decimal point number or does not match any cases mentioned above then an error will be raised.
If a number is passed outside the range of Python float then OverflowError is generated.
Python3
# Python program to illustrate# Various examples and working of float()# for integersprint(float(21.89)) # for floating point numbersprint(float(8)) # for integer type stringsprint(float("23")) # for floating type stringsprint(float("-16.54")) # for string floats with whitespacesprint(float(" -24.45 \n")) # for inf/infinityprint(float("InF"))print(float("InFiNiTy")) # for NaNprint(float("nan"))print(float("NaN")) # Error is generated at lastprint(float("Geeks"))
Output:
21.89
8.0
23.0
-16.54
-24.45
inf
inf
nan
nan
All lines are executed properly but the last one will return an error:
Traceback (most recent call last):
File "/home/21499f1e9ca207f0052f13d64cb6be31.py", line 25, in
print(float("Geeks"))
ValueError: could not convert string to float: 'Geeks'
Python3
# Python program to illustrate# Various examples and working of float() # for inf/infinityprint(float("InF"))print(float("InFiNiTy")) # for NaNprint(float("nan"))print(float("NaN"))
Output:
inf
inf
nan
nan
Python3
# python code to convert int# floatnumber = 90result = float(number) print(result)
Output:
90.0
Python3
# python code to convert string# to floatstring = "90"result = float(string) print(result)
Output:
90.0
Python3
number = "geeks"try: print(float(number))except ValueError as e: print(e)
Output:
could not convert string to float: 'geeks'
kumar_satyam
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 147,
"s": 53,
"text": "Python float() function is used to return a floating-point number from a number or a string. "
},
{
"code": null,
"e": 165,
"s": 147,
"text": "Syntax: float(x)"
},
{
"code": null,
"e": 304,
"s": 165,
"text": "The method only accepts one parameter and that is also optional to use. Let us look at the various types of argument, the method accepts: "
},
{
"code": null,
"e": 360,
"s": 304,
"text": "A number: Can be an integer or a floating-point number."
},
{
"code": null,
"e": 371,
"s": 360,
"text": "A String :"
},
{
"code": null,
"e": 405,
"s": 371,
"text": "Must contain numbers of any type."
},
{
"code": null,
"e": 475,
"s": 405,
"text": "Any left or right whitespaces or a new line is ignored by the method."
},
{
"code": null,
"e": 511,
"s": 475,
"text": "Mathematical Operators can be used."
},
{
"code": null,
"e": 556,
"s": 511,
"text": "Can contain NaN, Infinity or inf (any cases)"
},
{
"code": null,
"e": 633,
"s": 556,
"text": "Values that the float() method can return depending upon the argument passed"
},
{
"code": null,
"e": 714,
"s": 633,
"text": "If an argument is passed, then the equivalent floating-point number is returned."
},
{
"code": null,
"e": 768,
"s": 714,
"text": "If no argument is passed then the method returns 0.0."
},
{
"code": null,
"e": 901,
"s": 768,
"text": "If any string is passed that is not a decimal point number or does not match any cases mentioned above then an error will be raised."
},
{
"code": null,
"e": 990,
"s": 901,
"text": "If a number is passed outside the range of Python float then OverflowError is generated."
},
{
"code": null,
"e": 998,
"s": 990,
"text": "Python3"
},
{
"code": "# Python program to illustrate# Various examples and working of float()# for integersprint(float(21.89)) # for floating point numbersprint(float(8)) # for integer type stringsprint(float(\"23\")) # for floating type stringsprint(float(\"-16.54\")) # for string floats with whitespacesprint(float(\" -24.45 \\n\")) # for inf/infinityprint(float(\"InF\"))print(float(\"InFiNiTy\")) # for NaNprint(float(\"nan\"))print(float(\"NaN\")) # Error is generated at lastprint(float(\"Geeks\"))",
"e": 1471,
"s": 998,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1471,
"text": "Output: "
},
{
"code": null,
"e": 1525,
"s": 1480,
"text": "21.89\n8.0\n23.0\n-16.54\n-24.45\ninf\ninf\nnan\nnan"
},
{
"code": null,
"e": 1597,
"s": 1525,
"text": "All lines are executed properly but the last one will return an error: "
},
{
"code": null,
"e": 1778,
"s": 1597,
"text": "Traceback (most recent call last):\n File \"/home/21499f1e9ca207f0052f13d64cb6be31.py\", line 25, in \n print(float(\"Geeks\"))\nValueError: could not convert string to float: 'Geeks'"
},
{
"code": null,
"e": 1786,
"s": 1778,
"text": "Python3"
},
{
"code": "# Python program to illustrate# Various examples and working of float() # for inf/infinityprint(float(\"InF\"))print(float(\"InFiNiTy\")) # for NaNprint(float(\"nan\"))print(float(\"NaN\"))",
"e": 1968,
"s": 1786,
"text": null
},
{
"code": null,
"e": 1976,
"s": 1968,
"text": "Output:"
},
{
"code": null,
"e": 1992,
"s": 1976,
"text": "inf\ninf\nnan\nnan"
},
{
"code": null,
"e": 2000,
"s": 1992,
"text": "Python3"
},
{
"code": "# python code to convert int# floatnumber = 90result = float(number) print(result)",
"e": 2083,
"s": 2000,
"text": null
},
{
"code": null,
"e": 2091,
"s": 2083,
"text": "Output:"
},
{
"code": null,
"e": 2096,
"s": 2091,
"text": "90.0"
},
{
"code": null,
"e": 2104,
"s": 2096,
"text": "Python3"
},
{
"code": "# python code to convert string# to floatstring = \"90\"result = float(string) print(result)",
"e": 2195,
"s": 2104,
"text": null
},
{
"code": null,
"e": 2203,
"s": 2195,
"text": "Output:"
},
{
"code": null,
"e": 2208,
"s": 2203,
"text": "90.0"
},
{
"code": null,
"e": 2216,
"s": 2208,
"text": "Python3"
},
{
"code": "number = \"geeks\"try: print(float(number))except ValueError as e: print(e)",
"e": 2296,
"s": 2216,
"text": null
},
{
"code": null,
"e": 2304,
"s": 2296,
"text": "Output:"
},
{
"code": null,
"e": 2347,
"s": 2304,
"text": "could not convert string to float: 'geeks'"
},
{
"code": null,
"e": 2360,
"s": 2347,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2386,
"s": 2360,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2393,
"s": 2386,
"text": "Python"
}
] |
Visitor Method – Python Design Patterns
|
04 Jan, 2022
Visitor Method is a Behavioral Design Pattern which allows us to separate the algorithm from an object structure on which it operates. It helps us to add new features to an existing class hierarchy dynamically without changing it. All the behavioral patterns proved as the best methods to handle the communication between the objects. Similarly, it is used when we have to perform an operation on a group of similar kinds of objects.A Visitor Method consists of two parts:
method named as Visit() implemented by the visitor and used and called for every element of the data structure.
Visitable classes providing Accept() methods that accept a visitor
Client: The Client class acts as the consumer of the classes of the visitor design pattern. It can access the data structure objects and can instruct them to accept a visitor for the future processing.
Visitor: An Abstract class which is used to declare visit operations for all visitable classes.
Concrete Visitor: Each Visitor will be responsible for different operations. For each type of visitor all the visit methods, declared in abstract visitor, must be implemented.
Visitable: Accept operations is declared by this class. It also act as the entry point which enables an object to be visited by visitor.
Concrete Visitable: These classes implement the Visitable class and defines the accept operation. The visitor object is passed to this object using the accept operation.
Imagine you are handling the Software management of GeeksforGeeks and they have started certain courses such as DSA, SDE, and STL which are definitely useful for students who are preparing for the product based companies. But how will you handle all the data of Courses, Instructors, students, classes, IDs in your database? If you go with a simple direct approach to handle such a situation, you will definitely end up with a mess only.
Visitor-problem-diagram
Let’s look at the solution to the above-described problem. The Visitor method suggests adding a new behavior in a separate class called Visitor class instead of mixing it with the already existing classes. We will pass the original object to the visitor’s method as parameters such that the method will access all the necessary information.
Python3
""" The Courses hierarchy cannot be changed to add new functionality dynamically. Abstract Crop class for Concrete Courses_At_GFG classes: methods defined in this class will be inherited by all Concrete Courses_At_GFG classes.""" class Courses_At_GFG: def accept(self, visitor): visitor.visit(self) def teaching(self, visitor): print(self, "Taught by ", visitor) def studying(self, visitor): print(self, "studied by ", visitor) def __str__(self): return self.__class__.__name__ """Concrete Courses_At_GFG class: Classes being visited."""class SDE(Courses_At_GFG): pass class STL(Courses_At_GFG): pass class DSA(Courses_At_GFG): pass """ Abstract Visitor class for Concrete Visitor classes: method defined in this class will be inherited by all Concrete Visitor classes."""class Visitor: def __str__(self): return self.__class__.__name__ """ Concrete Visitors: Classes visiting Concrete Course objects. These classes have a visit() method which is called by the accept() method of the Concrete Course_At_GFG classes."""class Instructor(Visitor): def visit(self, crop): crop.teaching(self) class Student(Visitor): def visit(self, crop): crop.studying(self) """creating objects for concrete classes"""sde = SDE()stl = STL()dsa = DSA() """Creating Visitors"""instructor = Instructor()student = Student() """Visitors visiting courses"""sde.accept(instructor)sde.accept(student) stl.accept(instructor)stl.accept(student) dsa.accept(instructor)dsa.accept(student)
SDE Taught by Instructor
SDE studied by Student
STL Taught by Instructor
STL studied by Student
DSA Taught by Instructor
DSA studied by Student
Following is the UML diagram for Visitor Method
UML-diagram-visitor-method
Open/Closed principle: Introducing new behavior in class is easy which can work with objects of different classes without making changes in these classes.
Single Responsibility Principle: Multiple versions of same behavior can be operated into the same class.
Addition of entities: Adding an entity in Visitor Method is easy as we have to make changes in visitor class only and it will not affect the existing item.
Updating Logic: If the logic of operation is updated, then we need to make change only in the visitor implementation rather than doing it in all the item classes.
Lots of Updates: We have to update each and every visitor whenever a class get added or removed form the primary hierarchy
Hard to Extend: If there are too many visitor classes then it becomes really hard to extend the whole interface of the class.
Lack of Access: Sometimes visitors might not have the access to private field of certain classes that they are supposed to work with.
Recursive structures: Visitor Method works really well with recursive structures like directory trees or XML structures. The Visitor object can visit each node in the recursive structure
Performing Operations: We cam use the visitor method when we have to perform operations on all the elements of the complex object like Tree.
Further Read – Visitor Method in C++
anikaseth98
varshagumber28
sumitgumber28
python-design-pattern
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 502,
"s": 28,
"text": "Visitor Method is a Behavioral Design Pattern which allows us to separate the algorithm from an object structure on which it operates. It helps us to add new features to an existing class hierarchy dynamically without changing it. All the behavioral patterns proved as the best methods to handle the communication between the objects. Similarly, it is used when we have to perform an operation on a group of similar kinds of objects.A Visitor Method consists of two parts: "
},
{
"code": null,
"e": 614,
"s": 502,
"text": "method named as Visit() implemented by the visitor and used and called for every element of the data structure."
},
{
"code": null,
"e": 681,
"s": 614,
"text": "Visitable classes providing Accept() methods that accept a visitor"
},
{
"code": null,
"e": 885,
"s": 683,
"text": "Client: The Client class acts as the consumer of the classes of the visitor design pattern. It can access the data structure objects and can instruct them to accept a visitor for the future processing."
},
{
"code": null,
"e": 981,
"s": 885,
"text": "Visitor: An Abstract class which is used to declare visit operations for all visitable classes."
},
{
"code": null,
"e": 1157,
"s": 981,
"text": "Concrete Visitor: Each Visitor will be responsible for different operations. For each type of visitor all the visit methods, declared in abstract visitor, must be implemented."
},
{
"code": null,
"e": 1294,
"s": 1157,
"text": "Visitable: Accept operations is declared by this class. It also act as the entry point which enables an object to be visited by visitor."
},
{
"code": null,
"e": 1464,
"s": 1294,
"text": "Concrete Visitable: These classes implement the Visitable class and defines the accept operation. The visitor object is passed to this object using the accept operation."
},
{
"code": null,
"e": 1905,
"s": 1466,
"text": "Imagine you are handling the Software management of GeeksforGeeks and they have started certain courses such as DSA, SDE, and STL which are definitely useful for students who are preparing for the product based companies. But how will you handle all the data of Courses, Instructors, students, classes, IDs in your database? If you go with a simple direct approach to handle such a situation, you will definitely end up with a mess only. "
},
{
"code": null,
"e": 1929,
"s": 1905,
"text": "Visitor-problem-diagram"
},
{
"code": null,
"e": 2273,
"s": 1931,
"text": "Let’s look at the solution to the above-described problem. The Visitor method suggests adding a new behavior in a separate class called Visitor class instead of mixing it with the already existing classes. We will pass the original object to the visitor’s method as parameters such that the method will access all the necessary information. "
},
{
"code": null,
"e": 2281,
"s": 2273,
"text": "Python3"
},
{
"code": "\"\"\" The Courses hierarchy cannot be changed to add new functionality dynamically. Abstract Crop class for Concrete Courses_At_GFG classes: methods defined in this class will be inherited by all Concrete Courses_At_GFG classes.\"\"\" class Courses_At_GFG: def accept(self, visitor): visitor.visit(self) def teaching(self, visitor): print(self, \"Taught by \", visitor) def studying(self, visitor): print(self, \"studied by \", visitor) def __str__(self): return self.__class__.__name__ \"\"\"Concrete Courses_At_GFG class: Classes being visited.\"\"\"class SDE(Courses_At_GFG): pass class STL(Courses_At_GFG): pass class DSA(Courses_At_GFG): pass \"\"\" Abstract Visitor class for Concrete Visitor classes: method defined in this class will be inherited by all Concrete Visitor classes.\"\"\"class Visitor: def __str__(self): return self.__class__.__name__ \"\"\" Concrete Visitors: Classes visiting Concrete Course objects. These classes have a visit() method which is called by the accept() method of the Concrete Course_At_GFG classes.\"\"\"class Instructor(Visitor): def visit(self, crop): crop.teaching(self) class Student(Visitor): def visit(self, crop): crop.studying(self) \"\"\"creating objects for concrete classes\"\"\"sde = SDE()stl = STL()dsa = DSA() \"\"\"Creating Visitors\"\"\"instructor = Instructor()student = Student() \"\"\"Visitors visiting courses\"\"\"sde.accept(instructor)sde.accept(student) stl.accept(instructor)stl.accept(student) dsa.accept(instructor)dsa.accept(student)",
"e": 3821,
"s": 2281,
"text": null
},
{
"code": null,
"e": 3971,
"s": 3821,
"text": "SDE Taught by Instructor\nSDE studied by Student\nSTL Taught by Instructor\nSTL studied by Student\nDSA Taught by Instructor\nDSA studied by Student"
},
{
"code": null,
"e": 4019,
"s": 3971,
"text": "Following is the UML diagram for Visitor Method"
},
{
"code": null,
"e": 4046,
"s": 4019,
"text": "UML-diagram-visitor-method"
},
{
"code": null,
"e": 4201,
"s": 4046,
"text": "Open/Closed principle: Introducing new behavior in class is easy which can work with objects of different classes without making changes in these classes."
},
{
"code": null,
"e": 4306,
"s": 4201,
"text": "Single Responsibility Principle: Multiple versions of same behavior can be operated into the same class."
},
{
"code": null,
"e": 4462,
"s": 4306,
"text": "Addition of entities: Adding an entity in Visitor Method is easy as we have to make changes in visitor class only and it will not affect the existing item."
},
{
"code": null,
"e": 4625,
"s": 4462,
"text": "Updating Logic: If the logic of operation is updated, then we need to make change only in the visitor implementation rather than doing it in all the item classes."
},
{
"code": null,
"e": 4748,
"s": 4625,
"text": "Lots of Updates: We have to update each and every visitor whenever a class get added or removed form the primary hierarchy"
},
{
"code": null,
"e": 4874,
"s": 4748,
"text": "Hard to Extend: If there are too many visitor classes then it becomes really hard to extend the whole interface of the class."
},
{
"code": null,
"e": 5008,
"s": 4874,
"text": "Lack of Access: Sometimes visitors might not have the access to private field of certain classes that they are supposed to work with."
},
{
"code": null,
"e": 5195,
"s": 5008,
"text": "Recursive structures: Visitor Method works really well with recursive structures like directory trees or XML structures. The Visitor object can visit each node in the recursive structure"
},
{
"code": null,
"e": 5336,
"s": 5195,
"text": "Performing Operations: We cam use the visitor method when we have to perform operations on all the elements of the complex object like Tree."
},
{
"code": null,
"e": 5373,
"s": 5336,
"text": "Further Read – Visitor Method in C++"
},
{
"code": null,
"e": 5385,
"s": 5373,
"text": "anikaseth98"
},
{
"code": null,
"e": 5400,
"s": 5385,
"text": "varshagumber28"
},
{
"code": null,
"e": 5414,
"s": 5400,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5436,
"s": 5414,
"text": "python-design-pattern"
},
{
"code": null,
"e": 5443,
"s": 5436,
"text": "Python"
}
] |
Find the largest multiple of 3 from array of digits | Set 2 (In O(n) time and O(1) space)
|
01 Dec, 2021
Given an array of digits (contain elements from 0 to 9). Find the largest number that can be made from some or all digits of array and is divisible by 3. The same element may appear multiple times in the array, but each element in the array may only be used once. Examples:
Input : arr[] = {5, 4, 3, 1, 1}
Output : 4311
Input : Arr[] = {5, 5, 5, 7}
Output : 555
Asked In : Google Interview
We have discussed a queue based solution. Both solutions (discussed in previous and this posts) are based on the fact that a number is divisible by 3 if and only if sum of digits of the number is divisible by 3. For example, let us consider 555, it is divisible by 3 because sum of digits is 5 + 5 + 5 = 15, which is divisible by 3. If a sum of digits is not divisible by 3 then the remainder should be either 1 or 2. If we get remainder either ‘1’ or ‘2’, we have to remove maximum two digits to make a number that is divisible by 3:
If remainder is ‘1’ : We have to remove single digit that have remainder ‘1’ or we have to remove two digit that have remainder ‘2’ ( 2 + 2 => 4 % 3 => ‘1’)If remainder is ‘2’ : .We have to remove single digit that have remainder ‘2’ or we have to remove two digit that have remainder ‘1’ ( 1 + 1 => 2 % 3 => 2 ).
If remainder is ‘1’ : We have to remove single digit that have remainder ‘1’ or we have to remove two digit that have remainder ‘2’ ( 2 + 2 => 4 % 3 => ‘1’)
If remainder is ‘2’ : .We have to remove single digit that have remainder ‘2’ or we have to remove two digit that have remainder ‘1’ ( 1 + 1 => 2 % 3 => 2 ).
Examples :
Input : arr[] = 5, 5, 5, 7
Sum of digits = 5 + 5 + 5 + 7 = 22
Remainder = 22 % 3 = 1
We remove smallest single digit that
has remainder '1'. We remove 7 % 3 = 1
So largest number divisible by 3 is : 555
Let's take an another example :
Input : arr[] = 4 , 4 , 1 , 1 , 1 , 3
Sum of digits = 4 + 4 + 1 + 1 + 1 + 3 = 14
Reminder = 14 % 3 = 2
We have to remove the smallest digit that
has remainder ' 2 ' or two digits that have
remainder '1'. Here there is no digit with
reminder '2', so we have to remove two smallest
digits that have remainder '1'. The digits are :
1, 1. So largest number divisible by 3 is 4 4 3 1
Below are implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to find the largest number// that can be mode from elements of the// array and is divisible by 3#include<bits/stdc++.h>using namespace std; // Number of digits#define MAX_SIZE 10 // function to sort array of digits using// countsvoid sortArrayUsingCounts(int arr[], int n){ // Store count of all elements int count[MAX_SIZE] = {0}; for (int i = 0; i < n; i++) count[arr[i]]++; // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) while (count[i] > 0) arr[index++] = i, count[i]--;} // Remove elements from arr[] at indexes ind1 and ind2bool removeAndPrintResult(int arr[], int n, int ind1, int ind2 = -1){ for (int i = n-1; i >=0; i--) if (i != ind1 && i != ind2) cout << arr[i] ;} // Returns largest multiple of 3 that can be formed// using arr[] elements.bool largest3Multiple(int arr[], int n){ // Sum of all array element int sum = accumulate(arr, arr+n, 0); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // Sum is divisible by 3 , no need to // delete an element if (sum%3 == 0) { removeAndPrintResult(arr,n,-1,-1); return true ; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to delete either // one element of remainder '1' or two elements // of remainder '2' if (remainder == 1) { int rem_2[2]; rem_2[0] = -1, rem_2[1] = -1; // Traverse array elements for (int i = 0 ; i < n ; i++) { // Store first element of remainder '1' if (arr[i]%3 == 1) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 2) { // If this is first occurrence of remainder 2 if (rem_2[0] == -1) rem_2[0] = i; // If second occurrence else if (rem_2[1] == -1) rem_2[1] = i; } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to delete either // one element of remainder '2' or two elements // of remainder '1' else if (remainder == 2) { int rem_1[2]; rem_1[0] = -1, rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i]%3 == 2) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 1) { // If this is first occurrence of remainder 1 if (rem_1[0] == -1) rem_1[0] = i; // If second occurrence else if (rem_1[1] == -1) rem_1[1] = i; } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } cout << "Not possible"; return false;} // Driver codeint main(){ int arr[] = {4, 4, 1, 1, 1, 3 } ; int n = sizeof(arr)/sizeof(arr[0]); largest3Multiple(arr, n); return 0;}
// Java program to find the largest number// that can be mode from elements of the// array and is divisible by 3import java.util.*; class GFG { // Number of digits static int MAX_SIZE = 10; // function to sort array of digits using // counts static void sortArrayUsingCounts(int arr[], int n) { // Store count of all elements int[] count = new int[MAX_SIZE]; for (int i = 0; i < n; i++) { count[arr[i]]++; } // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } // Remove elements from arr[] // at indexes ind1 and ind2 static void removeAndPrintResult(int arr[], int n, int ind1, int ind2) { for (int i = n - 1; i >= 0; i--) { if (i != ind1 && i != ind2) { System.out.print(arr[i]); } } } // Returns largest multiple of 3 // that can be formed using // arr[] elements. static boolean largest3Multiple(int arr[], int n) { // Sum of all array element int sum = accumulate(arr, 0, n); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // If sum is divisible by 3, // no need to delete an element if (sum % 3 == 0) { removeAndPrintResult(arr, n, -1, -1); return true; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to // delete either one element of // remainder '1' or two elements of // remainder '2' if (remainder == 1) { int[] rem_2 = new int[2]; rem_2[0] = -1; rem_2[1] = -1; // Traverse array elements for (int i = 0; i < n; i++) { // Store first element of remainder '1' if (arr[i] % 3 == 1) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 2) { // If this is first occurrence // of remainder 2 if (rem_2[0] == -1) { rem_2[0] = i; } // If second occurrence else if (rem_2[1] == -1) { rem_2[1] = i; } } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to // delete either one element of // remainder '2' or two elements of // remainder '1' else if (remainder == 2) { int[] rem_1 = new int[2]; rem_1[0] = -1; rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i] % 3 == 2) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 1) { // If this is first occurrence // of remainder 1 if (rem_1[0] == -1) { rem_1[0] = i; } // If second occurrence else if (rem_1[1] == -1) { rem_1[1] = i; } } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } System.out.print("Not possible"); return false; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // Driver code public static void main(String[] args) { int arr[] = {4, 4, 1, 1, 1, 3}; int n = arr.length; largest3Multiple(arr, n); }}
# Python3 program to find the largest number# that can be mode from elements of the# array and is divisible by 3 # Number of digitsMAX_SIZE = 10 # function to sort array of digits using# countsdef sortArrayUsingCounts(arr, n): # Store count of all elements count = [0]*MAX_SIZE for i in range(n): count[arr[i]] += 1 # Store index = 0 for i in range(MAX_SIZE): while count[i] > 0: arr[index] = i index += 1 count[i] -= 1 # Remove elements from arr[] at indexes ind1 and ind2def removeAndPrintResult(arr, n, ind1, ind2=-1): for i in range(n-1, -1, -1): if i != ind1 and i != ind2: print(arr[i], end="") # Returns largest multiple of 3 that can be formed# using arr[] elements.def largest3Multiple(arr, n): # Sum of all array element s = sum(arr) # Sort array element in increasing order sortArrayUsingCounts(arr, n) # Sum is divisible by 3, no need to # delete an element if s % 3 == 0: removeAndPrintResult(arr, n, -1) return True # Find reminder remainder = s % 3 # If remainder is '1', we have to delete either # one element of remainder '1' or two elements # of remainder '2' if remainder == 1: rem_2 = [0]*2 rem_2[0] = -1; rem_2[1] = -1 # Traverse array elements for i in range(n): # Store first element of remainder '1' if arr[i] % 3 == 1: removeAndPrintResult(arr, n, i) return True if arr[i] % 3 == 2: # If this is first occurrence of remainder 2 if rem_2[0] == -1: rem_2[0] = i # If second occurrence elif rem_2[1] == -1: rem_2[1] = i if rem_2[0] != -1 and rem_2[1] != -1: removeAndPrintResult(arr, n, rem_2[0], rem_2[1]) return True # If remainder is '2', we have to delete either # one element of remainder '2' or two elements # of remainder '1' elif remainder == 2: rem_1 = [0]*2 rem_1[0] = -1; rem_1[1] = -1 # traverse array elements for i in range(n): # store first element of remainder '2' if arr[i] % 3 == 2: removeAndPrintResult(arr, n, i) return True if arr[i] % 3 == 1: # If this is first occurrence of remainder 1 if rem_1[0] == -1: rem_1[0] = i # If second occurrence elif rem_1[1] == -1: rem_1[1] = i if rem_1[0] != -1 and rem_1[1] != -1: removeAndPrintResult(arr, n, rem_1[0], rem_1[1]) return True print("Not possible") return False # Driver codeif __name__ == "__main__": arr = [4, 4, 1, 1, 1, 3] n = len(arr) largest3Multiple(arr, n) # This code is contributed by# sanjeev2552
// C# program to find the largest number// that can be mode from elements of the// array and is divisible by 3using System; class GFG { // Number of digits static int MAX_SIZE = 10; // function to sort array of digits using // counts static void sortArrayUsingCounts(int []arr, int n) { // Store count of all elements int[] count = new int[MAX_SIZE]; for (int i = 0; i < n; i++) { count[arr[i]]++; } // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } // Remove elements from arr[] // at indexes ind1 and ind2 static void removeAndPrintResult(int []arr, int n, int ind1, int ind2) { for (int i = n - 1; i >= 0; i--) { if (i != ind1 && i != ind2) { Console.Write(arr[i]); } } } // Returns largest multiple of 3 // that can be formed using // arr[] elements. static Boolean largest3Multiple(int []arr, int n) { // Sum of all array element int sum = accumulate(arr, 0, n); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // If sum is divisible by 3, // no need to delete an element if (sum % 3 == 0) { removeAndPrintResult(arr, n, -1, -1); return true; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to // delete either one element of // remainder '1' or two elements of // remainder '2' if (remainder == 1) { int[] rem_2 = new int[2]; rem_2[0] = -1; rem_2[1] = -1; // Traverse array elements for (int i = 0; i < n; i++) { // Store first element of remainder '1' if (arr[i] % 3 == 1) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 2) { // If this is first occurrence // of remainder 2 if (rem_2[0] == -1) { rem_2[0] = i; } // If second occurrence else if (rem_2[1] == -1) { rem_2[1] = i; } } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to // delete either one element of // remainder '2' or two elements of // remainder '1' else if (remainder == 2) { int[] rem_1 = new int[2]; rem_1[0] = -1; rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i] % 3 == 2) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 1) { // If this is first occurrence // of remainder 1 if (rem_1[0] == -1) { rem_1[0] = i; } // If second occurrence else if (rem_1[1] == -1) { rem_1[1] = i; } } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } Console.Write("Not possible"); return false; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = {4, 4, 1, 1, 1, 3}; int n = arr.Length; largest3Multiple(arr, n); }} // This code is contributed by 29AjayKumar
<script>// JavaScript program to find the largest number// that can be mode from elements of the// array and is divisible by 3 // Number of digitsconst MAX_SIZE = 10; // function to sort array of digits using// countsfunction sortArrayUsingCounts(arr, n){ // Store count of all elements let count = new Uint8Array(MAX_SIZE); for (let i = 0; i < n; i++) count[arr[i]]++; // Store let index = 0; for (let i = 0; i < MAX_SIZE; i++) while (count[i] > 0) arr[index++] = i, count[i]--;} // Remove elements from arr[] at indexes ind1 and ind2function removeAndPrintResult(arr, n, ind1, ind2 = -1){ for (let i = n-1; i >=0; i--) if (i != ind1 && i != ind2) document.write(arr[i]) ;} // Returns largest multiple of 3 that can be formed// using arr[] elements.function largest3Multiple(arr, n){ // Sum of all array element let sum = arr.reduce((a, b) => a + b, 0); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // Sum is divisible by 3 , no need to // delete an element if (sum%3 == 0) { removeAndPrintResult(arr, n, -1); return true ; } // Find reminder let remainder = sum % 3; // If remainder is '1', we have to delete either // one element of remainder '1' or two elements // of remainder '2' if (remainder == 1) { let rem_2 = new Array(2); rem_2[0] = -1, rem_2[1] = -1; // Traverse array elements for (let i = 0 ; i < n ; i++) { // Store first element of remainder '1' if (arr[i]%3 == 1) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 2) { // If this is first occurrence of remainder 2 if (rem_2[0] == -1) rem_2[0] = i; // If second occurrence else if (rem_2[1] == -1) rem_2[1] = i; } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to delete either // one element of remainder '2' or two elements // of remainder '1' else if (remainder == 2) { let rem_1 = new Array(2); rem_1[0] = -1, rem_1[1] = -1; // traverse array elements for (let i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i]%3 == 2) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 1) { // If this is first occurrence of remainder 1 if (rem_1[0] == -1) rem_1[0] = i; // If second occurrence else if (rem_1[1] == -1) rem_1[1] = i; } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } document.write("Not possible"); return false;} // Driver code let arr = [4 , 4 , 1 , 1 , 1 , 3]; let n = arr.length; largest3Multiple(arr, n); // This code is contributed by Surbhi Tyagi.</script>
Output:
4431
Time Complexity : O(n) This article is contributed by Nishant Singh. 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.
sanjeev2552
princi singh
29AjayKumar
2435shivkant
surbhityagi15
divisibility
Mathematical
Sorting
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 328,
"s": 52,
"text": "Given an array of digits (contain elements from 0 to 9). Find the largest number that can be made from some or all digits of array and is divisible by 3. The same element may appear multiple times in the array, but each element in the array may only be used once. Examples: "
},
{
"code": null,
"e": 420,
"s": 328,
"text": "Input : arr[] = {5, 4, 3, 1, 1} \nOutput : 4311\n\nInput : Arr[] = {5, 5, 5, 7} \nOutput : 555 "
},
{
"code": null,
"e": 449,
"s": 420,
"text": "Asked In : Google Interview "
},
{
"code": null,
"e": 986,
"s": 449,
"text": "We have discussed a queue based solution. Both solutions (discussed in previous and this posts) are based on the fact that a number is divisible by 3 if and only if sum of digits of the number is divisible by 3. For example, let us consider 555, it is divisible by 3 because sum of digits is 5 + 5 + 5 = 15, which is divisible by 3. If a sum of digits is not divisible by 3 then the remainder should be either 1 or 2. If we get remainder either ‘1’ or ‘2’, we have to remove maximum two digits to make a number that is divisible by 3: "
},
{
"code": null,
"e": 1300,
"s": 986,
"text": "If remainder is ‘1’ : We have to remove single digit that have remainder ‘1’ or we have to remove two digit that have remainder ‘2’ ( 2 + 2 => 4 % 3 => ‘1’)If remainder is ‘2’ : .We have to remove single digit that have remainder ‘2’ or we have to remove two digit that have remainder ‘1’ ( 1 + 1 => 2 % 3 => 2 )."
},
{
"code": null,
"e": 1457,
"s": 1300,
"text": "If remainder is ‘1’ : We have to remove single digit that have remainder ‘1’ or we have to remove two digit that have remainder ‘2’ ( 2 + 2 => 4 % 3 => ‘1’)"
},
{
"code": null,
"e": 1615,
"s": 1457,
"text": "If remainder is ‘2’ : .We have to remove single digit that have remainder ‘2’ or we have to remove two digit that have remainder ‘1’ ( 1 + 1 => 2 % 3 => 2 )."
},
{
"code": null,
"e": 1628,
"s": 1615,
"text": "Examples : "
},
{
"code": null,
"e": 2255,
"s": 1628,
"text": "Input : arr[] = 5, 5, 5, 7 \nSum of digits = 5 + 5 + 5 + 7 = 22\nRemainder = 22 % 3 = 1 \nWe remove smallest single digit that \nhas remainder '1'. We remove 7 % 3 = 1 \nSo largest number divisible by 3 is : 555\n\nLet's take an another example :\nInput : arr[] = 4 , 4 , 1 , 1 , 1 , 3\nSum of digits = 4 + 4 + 1 + 1 + 1 + 3 = 14\nReminder = 14 % 3 = 2 \nWe have to remove the smallest digit that \nhas remainder ' 2 ' or two digits that have\nremainder '1'. Here there is no digit with \nreminder '2', so we have to remove two smallest \ndigits that have remainder '1'. The digits are : \n1, 1. So largest number divisible by 3 is 4 4 3 1 "
},
{
"code": null,
"e": 2296,
"s": 2255,
"text": "Below are implementation of above idea. "
},
{
"code": null,
"e": 2300,
"s": 2296,
"text": "C++"
},
{
"code": null,
"e": 2305,
"s": 2300,
"text": "Java"
},
{
"code": null,
"e": 2313,
"s": 2305,
"text": "Python3"
},
{
"code": null,
"e": 2316,
"s": 2313,
"text": "C#"
},
{
"code": null,
"e": 2327,
"s": 2316,
"text": "Javascript"
},
{
"code": "// C++ program to find the largest number// that can be mode from elements of the// array and is divisible by 3#include<bits/stdc++.h>using namespace std; // Number of digits#define MAX_SIZE 10 // function to sort array of digits using// countsvoid sortArrayUsingCounts(int arr[], int n){ // Store count of all elements int count[MAX_SIZE] = {0}; for (int i = 0; i < n; i++) count[arr[i]]++; // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) while (count[i] > 0) arr[index++] = i, count[i]--;} // Remove elements from arr[] at indexes ind1 and ind2bool removeAndPrintResult(int arr[], int n, int ind1, int ind2 = -1){ for (int i = n-1; i >=0; i--) if (i != ind1 && i != ind2) cout << arr[i] ;} // Returns largest multiple of 3 that can be formed// using arr[] elements.bool largest3Multiple(int arr[], int n){ // Sum of all array element int sum = accumulate(arr, arr+n, 0); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // Sum is divisible by 3 , no need to // delete an element if (sum%3 == 0) { removeAndPrintResult(arr,n,-1,-1); return true ; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to delete either // one element of remainder '1' or two elements // of remainder '2' if (remainder == 1) { int rem_2[2]; rem_2[0] = -1, rem_2[1] = -1; // Traverse array elements for (int i = 0 ; i < n ; i++) { // Store first element of remainder '1' if (arr[i]%3 == 1) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 2) { // If this is first occurrence of remainder 2 if (rem_2[0] == -1) rem_2[0] = i; // If second occurrence else if (rem_2[1] == -1) rem_2[1] = i; } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to delete either // one element of remainder '2' or two elements // of remainder '1' else if (remainder == 2) { int rem_1[2]; rem_1[0] = -1, rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i]%3 == 2) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 1) { // If this is first occurrence of remainder 1 if (rem_1[0] == -1) rem_1[0] = i; // If second occurrence else if (rem_1[1] == -1) rem_1[1] = i; } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } cout << \"Not possible\"; return false;} // Driver codeint main(){ int arr[] = {4, 4, 1, 1, 1, 3 } ; int n = sizeof(arr)/sizeof(arr[0]); largest3Multiple(arr, n); return 0;}",
"e": 5713,
"s": 2327,
"text": null
},
{
"code": "// Java program to find the largest number// that can be mode from elements of the// array and is divisible by 3import java.util.*; class GFG { // Number of digits static int MAX_SIZE = 10; // function to sort array of digits using // counts static void sortArrayUsingCounts(int arr[], int n) { // Store count of all elements int[] count = new int[MAX_SIZE]; for (int i = 0; i < n; i++) { count[arr[i]]++; } // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } // Remove elements from arr[] // at indexes ind1 and ind2 static void removeAndPrintResult(int arr[], int n, int ind1, int ind2) { for (int i = n - 1; i >= 0; i--) { if (i != ind1 && i != ind2) { System.out.print(arr[i]); } } } // Returns largest multiple of 3 // that can be formed using // arr[] elements. static boolean largest3Multiple(int arr[], int n) { // Sum of all array element int sum = accumulate(arr, 0, n); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // If sum is divisible by 3, // no need to delete an element if (sum % 3 == 0) { removeAndPrintResult(arr, n, -1, -1); return true; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to // delete either one element of // remainder '1' or two elements of // remainder '2' if (remainder == 1) { int[] rem_2 = new int[2]; rem_2[0] = -1; rem_2[1] = -1; // Traverse array elements for (int i = 0; i < n; i++) { // Store first element of remainder '1' if (arr[i] % 3 == 1) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 2) { // If this is first occurrence // of remainder 2 if (rem_2[0] == -1) { rem_2[0] = i; } // If second occurrence else if (rem_2[1] == -1) { rem_2[1] = i; } } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to // delete either one element of // remainder '2' or two elements of // remainder '1' else if (remainder == 2) { int[] rem_1 = new int[2]; rem_1[0] = -1; rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i] % 3 == 2) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 1) { // If this is first occurrence // of remainder 1 if (rem_1[0] == -1) { rem_1[0] = i; } // If second occurrence else if (rem_1[1] == -1) { rem_1[1] = i; } } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } System.out.print(\"Not possible\"); return false; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // Driver code public static void main(String[] args) { int arr[] = {4, 4, 1, 1, 1, 3}; int n = arr.length; largest3Multiple(arr, n); }}",
"e": 10619,
"s": 5713,
"text": null
},
{
"code": "# Python3 program to find the largest number# that can be mode from elements of the# array and is divisible by 3 # Number of digitsMAX_SIZE = 10 # function to sort array of digits using# countsdef sortArrayUsingCounts(arr, n): # Store count of all elements count = [0]*MAX_SIZE for i in range(n): count[arr[i]] += 1 # Store index = 0 for i in range(MAX_SIZE): while count[i] > 0: arr[index] = i index += 1 count[i] -= 1 # Remove elements from arr[] at indexes ind1 and ind2def removeAndPrintResult(arr, n, ind1, ind2=-1): for i in range(n-1, -1, -1): if i != ind1 and i != ind2: print(arr[i], end=\"\") # Returns largest multiple of 3 that can be formed# using arr[] elements.def largest3Multiple(arr, n): # Sum of all array element s = sum(arr) # Sort array element in increasing order sortArrayUsingCounts(arr, n) # Sum is divisible by 3, no need to # delete an element if s % 3 == 0: removeAndPrintResult(arr, n, -1) return True # Find reminder remainder = s % 3 # If remainder is '1', we have to delete either # one element of remainder '1' or two elements # of remainder '2' if remainder == 1: rem_2 = [0]*2 rem_2[0] = -1; rem_2[1] = -1 # Traverse array elements for i in range(n): # Store first element of remainder '1' if arr[i] % 3 == 1: removeAndPrintResult(arr, n, i) return True if arr[i] % 3 == 2: # If this is first occurrence of remainder 2 if rem_2[0] == -1: rem_2[0] = i # If second occurrence elif rem_2[1] == -1: rem_2[1] = i if rem_2[0] != -1 and rem_2[1] != -1: removeAndPrintResult(arr, n, rem_2[0], rem_2[1]) return True # If remainder is '2', we have to delete either # one element of remainder '2' or two elements # of remainder '1' elif remainder == 2: rem_1 = [0]*2 rem_1[0] = -1; rem_1[1] = -1 # traverse array elements for i in range(n): # store first element of remainder '2' if arr[i] % 3 == 2: removeAndPrintResult(arr, n, i) return True if arr[i] % 3 == 1: # If this is first occurrence of remainder 1 if rem_1[0] == -1: rem_1[0] = i # If second occurrence elif rem_1[1] == -1: rem_1[1] = i if rem_1[0] != -1 and rem_1[1] != -1: removeAndPrintResult(arr, n, rem_1[0], rem_1[1]) return True print(\"Not possible\") return False # Driver codeif __name__ == \"__main__\": arr = [4, 4, 1, 1, 1, 3] n = len(arr) largest3Multiple(arr, n) # This code is contributed by# sanjeev2552",
"e": 13618,
"s": 10619,
"text": null
},
{
"code": "// C# program to find the largest number// that can be mode from elements of the// array and is divisible by 3using System; class GFG { // Number of digits static int MAX_SIZE = 10; // function to sort array of digits using // counts static void sortArrayUsingCounts(int []arr, int n) { // Store count of all elements int[] count = new int[MAX_SIZE]; for (int i = 0; i < n; i++) { count[arr[i]]++; } // Store int index = 0; for (int i = 0; i < MAX_SIZE; i++) { while (count[i] > 0) { arr[index++] = i; count[i]--; } } } // Remove elements from arr[] // at indexes ind1 and ind2 static void removeAndPrintResult(int []arr, int n, int ind1, int ind2) { for (int i = n - 1; i >= 0; i--) { if (i != ind1 && i != ind2) { Console.Write(arr[i]); } } } // Returns largest multiple of 3 // that can be formed using // arr[] elements. static Boolean largest3Multiple(int []arr, int n) { // Sum of all array element int sum = accumulate(arr, 0, n); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // If sum is divisible by 3, // no need to delete an element if (sum % 3 == 0) { removeAndPrintResult(arr, n, -1, -1); return true; } // Find reminder int remainder = sum % 3; // If remainder is '1', we have to // delete either one element of // remainder '1' or two elements of // remainder '2' if (remainder == 1) { int[] rem_2 = new int[2]; rem_2[0] = -1; rem_2[1] = -1; // Traverse array elements for (int i = 0; i < n; i++) { // Store first element of remainder '1' if (arr[i] % 3 == 1) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 2) { // If this is first occurrence // of remainder 2 if (rem_2[0] == -1) { rem_2[0] = i; } // If second occurrence else if (rem_2[1] == -1) { rem_2[1] = i; } } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to // delete either one element of // remainder '2' or two elements of // remainder '1' else if (remainder == 2) { int[] rem_1 = new int[2]; rem_1[0] = -1; rem_1[1] = -1; // traverse array elements for (int i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i] % 3 == 2) { removeAndPrintResult(arr, n, i, -1); return true; } if (arr[i] % 3 == 1) { // If this is first occurrence // of remainder 1 if (rem_1[0] == -1) { rem_1[0] = i; } // If second occurrence else if (rem_1[1] == -1) { rem_1[1] = i; } } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } Console.Write(\"Not possible\"); return false; } static int accumulate(int[] arr, int start, int end) { int sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = {4, 4, 1, 1, 1, 3}; int n = arr.Length; largest3Multiple(arr, n); }} // This code is contributed by 29AjayKumar",
"e": 18547,
"s": 13618,
"text": null
},
{
"code": "<script>// JavaScript program to find the largest number// that can be mode from elements of the// array and is divisible by 3 // Number of digitsconst MAX_SIZE = 10; // function to sort array of digits using// countsfunction sortArrayUsingCounts(arr, n){ // Store count of all elements let count = new Uint8Array(MAX_SIZE); for (let i = 0; i < n; i++) count[arr[i]]++; // Store let index = 0; for (let i = 0; i < MAX_SIZE; i++) while (count[i] > 0) arr[index++] = i, count[i]--;} // Remove elements from arr[] at indexes ind1 and ind2function removeAndPrintResult(arr, n, ind1, ind2 = -1){ for (let i = n-1; i >=0; i--) if (i != ind1 && i != ind2) document.write(arr[i]) ;} // Returns largest multiple of 3 that can be formed// using arr[] elements.function largest3Multiple(arr, n){ // Sum of all array element let sum = arr.reduce((a, b) => a + b, 0); // Sort array element in increasing order sortArrayUsingCounts(arr, n); // Sum is divisible by 3 , no need to // delete an element if (sum%3 == 0) { removeAndPrintResult(arr, n, -1); return true ; } // Find reminder let remainder = sum % 3; // If remainder is '1', we have to delete either // one element of remainder '1' or two elements // of remainder '2' if (remainder == 1) { let rem_2 = new Array(2); rem_2[0] = -1, rem_2[1] = -1; // Traverse array elements for (let i = 0 ; i < n ; i++) { // Store first element of remainder '1' if (arr[i]%3 == 1) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 2) { // If this is first occurrence of remainder 2 if (rem_2[0] == -1) rem_2[0] = i; // If second occurrence else if (rem_2[1] == -1) rem_2[1] = i; } } if (rem_2[0] != -1 && rem_2[1] != -1) { removeAndPrintResult(arr, n, rem_2[0], rem_2[1]); return true; } } // If remainder is '2', we have to delete either // one element of remainder '2' or two elements // of remainder '1' else if (remainder == 2) { let rem_1 = new Array(2); rem_1[0] = -1, rem_1[1] = -1; // traverse array elements for (let i = 0; i < n; i++) { // store first element of remainder '2' if (arr[i]%3 == 2) { removeAndPrintResult(arr, n, i); return true; } if (arr[i]%3 == 1) { // If this is first occurrence of remainder 1 if (rem_1[0] == -1) rem_1[0] = i; // If second occurrence else if (rem_1[1] == -1) rem_1[1] = i; } } if (rem_1[0] != -1 && rem_1[1] != -1) { removeAndPrintResult(arr, n, rem_1[0], rem_1[1]); return true; } } document.write(\"Not possible\"); return false;} // Driver code let arr = [4 , 4 , 1 , 1 , 1 , 3]; let n = arr.length; largest3Multiple(arr, n); // This code is contributed by Surbhi Tyagi.</script>",
"e": 21908,
"s": 18547,
"text": null
},
{
"code": null,
"e": 21918,
"s": 21908,
"text": "Output: "
},
{
"code": null,
"e": 21923,
"s": 21918,
"text": "4431"
},
{
"code": null,
"e": 22368,
"s": 21923,
"text": "Time Complexity : O(n) This article is contributed by Nishant Singh. 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": 22380,
"s": 22368,
"text": "sanjeev2552"
},
{
"code": null,
"e": 22393,
"s": 22380,
"text": "princi singh"
},
{
"code": null,
"e": 22405,
"s": 22393,
"text": "29AjayKumar"
},
{
"code": null,
"e": 22418,
"s": 22405,
"text": "2435shivkant"
},
{
"code": null,
"e": 22432,
"s": 22418,
"text": "surbhityagi15"
},
{
"code": null,
"e": 22445,
"s": 22432,
"text": "divisibility"
},
{
"code": null,
"e": 22458,
"s": 22445,
"text": "Mathematical"
},
{
"code": null,
"e": 22466,
"s": 22458,
"text": "Sorting"
},
{
"code": null,
"e": 22479,
"s": 22466,
"text": "Mathematical"
},
{
"code": null,
"e": 22487,
"s": 22479,
"text": "Sorting"
}
] |
How to Create Section Counter using HTML and CSS ?
|
09 Feb, 2022
Section counter is like a card and is useful for webpage footer. It contains details about the company. In this article, we will introduce some predicted data about some companies. We divide this article into two sections, in the first section we will create the normal structure then we will work on the design.Creating the Structure: In this section, we will use simple HTML code to create three section to display few details about the company. We will use fontawesome icon to represent the functions more specifically for the user.
CDN link for the Icons from the Font Awesome:
<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>
HTML Code:
html
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <h1>GeeksforGeeks</h1> <strong>Section Counter</strong> <br><br> <div class="row"> <div class="column"> <div class="card"> <p><i class="fa fa-user"></i></p> <h3>759+</h3> <p>Contributor</p> </div> </div> <div class="column"> <div class="card"> <p><i class="fa fa-book"></i></p> <h3>60k+</h3> <p>Article</p> </div> </div> <div class="column"> <div class="card"> <p><i class="fa fa-smile-o"></i></p> <h3>70+</h3> <p>Employees</p> </div> </div> </div></body> </html>
Designing the Structure: We have already created the structure and here we will design the structure by using simple CSS. Also, we will add some animation to it.
CSS Code:
CSS
<style> h1 { color: green; } * { box-sizing: border-box; } body { text-align: center; } /* Float columns */ .column { float: left; width: 33%; padding: 0 5px; } .row { margin: 0 -5px; } .row:after { content: ""; display: table; } /* Style the cards */ .card { padding: 10px; text-align: center; background-color: gray; color: white; } .card:hover { transform: scale(1.1); background-color: black; transition-duration: 2s; color: white; } .fa { font-size: 50px; } </style>
Final Solution: In this section, we will combine the above two sections in a single file then we will get the complete solution.
Program:
html
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> h1 { color: green; } * { box-sizing: border-box; } body { text-align: center; } /* Float three columns */ .column { float: left; width: 33%; padding: 0 5px; } .row { margin: 0 -5px; } /* Clear floats after the columns */ .row:after { content: ""; display: table; } /* Style the cards */ .card { padding: 10px; text-align: center; background-color: gray; color: white; } .card:hover { transform: scale(1.1); background-color: black; transition-duration: 2s; color: white; } .fa { font-size: 50px; } </style></head> <body> <h1>GeeksforGeeks</h1> <strong>Section Counter</strong> <br><br> <div class="row"> <div class="column"> <div class="card"> <p><i class="fa fa-user"></i></p> <h3>759+</h3> <p>Contributor</p> </div> </div> <div class="column"> <div class="card"> <p><i class="fa fa-book"></i></p> <h3>60k+</h3> <p>Article</p> </div> </div> <div class="column"> <div class="card"> <p><i class="fa fa-smile-o"></i></p> <h3>70+</h3> <p>Employees</p> </div> </div> </div></body> </html>
Output:
surindertarika1234
simranarora5sos
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, 2022"
},
{
"code": null,
"e": 566,
"s": 28,
"text": "Section counter is like a card and is useful for webpage footer. It contains details about the company. In this article, we will introduce some predicted data about some companies. We divide this article into two sections, in the first section we will create the normal structure then we will work on the design.Creating the Structure: In this section, we will use simple HTML code to create three section to display few details about the company. We will use fontawesome icon to represent the functions more specifically for the user. "
},
{
"code": null,
"e": 614,
"s": 566,
"text": "CDN link for the Icons from the Font Awesome: "
},
{
"code": null,
"e": 730,
"s": 614,
"text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> "
},
{
"code": null,
"e": 743,
"s": 730,
"text": "HTML Code: "
},
{
"code": null,
"e": 748,
"s": 743,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> </head> <body> <h1>GeeksforGeeks</h1> <strong>Section Counter</strong> <br><br> <div class=\"row\"> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-user\"></i></p> <h3>759+</h3> <p>Contributor</p> </div> </div> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-book\"></i></p> <h3>60k+</h3> <p>Article</p> </div> </div> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-smile-o\"></i></p> <h3>70+</h3> <p>Employees</p> </div> </div> </div></body> </html> ",
"e": 1757,
"s": 748,
"text": null
},
{
"code": null,
"e": 1920,
"s": 1757,
"text": "Designing the Structure: We have already created the structure and here we will design the structure by using simple CSS. Also, we will add some animation to it. "
},
{
"code": null,
"e": 1932,
"s": 1920,
"text": "CSS Code: "
},
{
"code": null,
"e": 1936,
"s": 1932,
"text": "CSS"
},
{
"code": "<style> h1 { color: green; } * { box-sizing: border-box; } body { text-align: center; } /* Float columns */ .column { float: left; width: 33%; padding: 0 5px; } .row { margin: 0 -5px; } .row:after { content: \"\"; display: table; } /* Style the cards */ .card { padding: 10px; text-align: center; background-color: gray; color: white; } .card:hover { transform: scale(1.1); background-color: black; transition-duration: 2s; color: white; } .fa { font-size: 50px; } </style>",
"e": 2661,
"s": 1936,
"text": null
},
{
"code": null,
"e": 2791,
"s": 2661,
"text": "Final Solution: In this section, we will combine the above two sections in a single file then we will get the complete solution. "
},
{
"code": null,
"e": 2802,
"s": 2791,
"text": "Program: "
},
{
"code": null,
"e": 2807,
"s": 2802,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> h1 { color: green; } * { box-sizing: border-box; } body { text-align: center; } /* Float three columns */ .column { float: left; width: 33%; padding: 0 5px; } .row { margin: 0 -5px; } /* Clear floats after the columns */ .row:after { content: \"\"; display: table; } /* Style the cards */ .card { padding: 10px; text-align: center; background-color: gray; color: white; } .card:hover { transform: scale(1.1); background-color: black; transition-duration: 2s; color: white; } .fa { font-size: 50px; } </style></head> <body> <h1>GeeksforGeeks</h1> <strong>Section Counter</strong> <br><br> <div class=\"row\"> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-user\"></i></p> <h3>759+</h3> <p>Contributor</p> </div> </div> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-book\"></i></p> <h3>60k+</h3> <p>Article</p> </div> </div> <div class=\"column\"> <div class=\"card\"> <p><i class=\"fa fa-smile-o\"></i></p> <h3>70+</h3> <p>Employees</p> </div> </div> </div></body> </html>",
"e": 4733,
"s": 2807,
"text": null
},
{
"code": null,
"e": 4743,
"s": 4733,
"text": "Output: "
},
{
"code": null,
"e": 4764,
"s": 4745,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4780,
"s": 4764,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4789,
"s": 4780,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4799,
"s": 4789,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4803,
"s": 4799,
"text": "CSS"
},
{
"code": null,
"e": 4808,
"s": 4803,
"text": "HTML"
},
{
"code": null,
"e": 4825,
"s": 4808,
"text": "Web Technologies"
},
{
"code": null,
"e": 4852,
"s": 4825,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4857,
"s": 4852,
"text": "HTML"
}
] |
Zoho Interview | Set 1 (On-Campus)
|
11 Aug, 2014
First Round: (Aptitude written round)This round consisted of two sections “Reasoning Aptitude” and “Technical Aptitude”. Reasoning section was more like puzzles so do concentrate on logical puzzles. Technical Aptitude dealt more with “operator precedence”, “pointers”, “iterations”, “dynamic memory allocations”.
Second Round: (Normal Programming round)1. Print the word with odd letters as
P M
R A
O R
G
O R
R A
P M
2. Given a set of numbers like <10, 36, 54,89,12> we want to find sum of weights based on the following conditions 1. 5 if a perfect square 2. 4 if multiple of 4 and divisible by 6 3. 3 if even number
And sort the numbers based on the weight and print it as follows
<10,its_weight>,<36,its weight><89,its weight>
Should display the numbers based on increasing order.
3. Save the string “WELCOMETOZOHOCORPORATION” in a two dimensional array and search for substring like “too” in the two dimensional string both from left to right and from top to bottom.
w e L C O
M E T O Z
O H O C O
R P O R A
T I O n
And print the start and ending index as
Start index : <1,2>
End index: <3, 2>
4. Given a 9×9 sudoku we have to evaluate it for its correctness. We have to check both the sub matrix correctness and the whole sudoku correctness.
5. Given a two dimensional array of string like
<”luke”, “shaw”>
<”wayne”, “rooney”>
<”rooney”, “ronaldo”>
<”shaw”, “rooney”>
Where the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren Here “ronaldo” has 2 grandchildren. So our output should be 2.
Third Round: (Advanced Programming Round)Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were: 1. Booking 2. Availability checking 3. Cancellation 4. Prepare chartWe were asked to create the modules for representing each data first and to continue with the implementation phase.
Fourth Round: (Technical Round)Technical question which revolved around “data structures” and “OOPS”
Fifth Round: (HR round)Some general hr questions asked mainly about our projects and about certifications if we had one.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Zoho
Interview Experiences
Strings
Zoho
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Aug, 2014"
},
{
"code": null,
"e": 367,
"s": 54,
"text": "First Round: (Aptitude written round)This round consisted of two sections “Reasoning Aptitude” and “Technical Aptitude”. Reasoning section was more like puzzles so do concentrate on logical puzzles. Technical Aptitude dealt more with “operator precedence”, “pointers”, “iterations”, “dynamic memory allocations”."
},
{
"code": null,
"e": 445,
"s": 367,
"text": "Second Round: (Normal Programming round)1. Print the word with odd letters as"
},
{
"code": null,
"e": 516,
"s": 445,
"text": "P M\n R A\n O R\n G\n O R\n R A\nP M "
},
{
"code": null,
"e": 726,
"s": 516,
"text": "2. Given a set of numbers like <10, 36, 54,89,12> we want to find sum of weights based on the following conditions 1. 5 if a perfect square 2. 4 if multiple of 4 and divisible by 6 3. 3 if even number"
},
{
"code": null,
"e": 791,
"s": 726,
"text": "And sort the numbers based on the weight and print it as follows"
},
{
"code": null,
"e": 838,
"s": 791,
"text": "<10,its_weight>,<36,its weight><89,its weight>"
},
{
"code": null,
"e": 892,
"s": 838,
"text": "Should display the numbers based on increasing order."
},
{
"code": null,
"e": 1079,
"s": 892,
"text": "3. Save the string “WELCOMETOZOHOCORPORATION” in a two dimensional array and search for substring like “too” in the two dimensional string both from left to right and from top to bottom."
},
{
"code": null,
"e": 1130,
"s": 1079,
"text": "w\te\tL\tC\tO\nM\tE\tT\tO\tZ\nO\tH\tO\tC\tO\nR\tP\tO\tR\tA\nT\tI\tO\tn\t "
},
{
"code": null,
"e": 1170,
"s": 1130,
"text": "And print the start and ending index as"
},
{
"code": null,
"e": 1190,
"s": 1170,
"text": "Start index : <1,2>"
},
{
"code": null,
"e": 1208,
"s": 1190,
"text": "End index: <3, 2>"
},
{
"code": null,
"e": 1357,
"s": 1208,
"text": "4. Given a 9×9 sudoku we have to evaluate it for its correctness. We have to check both the sub matrix correctness and the whole sudoku correctness."
},
{
"code": null,
"e": 1405,
"s": 1357,
"text": "5. Given a two dimensional array of string like"
},
{
"code": null,
"e": 1492,
"s": 1405,
"text": " <”luke”, “shaw”>\n <”wayne”, “rooney”>\n <”rooney”, “ronaldo”>\n <”shaw”, “rooney”> "
},
{
"code": null,
"e": 1677,
"s": 1492,
"text": "Where the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren Here “ronaldo” has 2 grandchildren. So our output should be 2."
},
{
"code": null,
"e": 2015,
"s": 1677,
"text": "Third Round: (Advanced Programming Round)Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were: 1. Booking 2. Availability checking 3. Cancellation 4. Prepare chartWe were asked to create the modules for representing each data first and to continue with the implementation phase."
},
{
"code": null,
"e": 2116,
"s": 2015,
"text": "Fourth Round: (Technical Round)Technical question which revolved around “data structures” and “OOPS”"
},
{
"code": null,
"e": 2237,
"s": 2116,
"text": "Fifth Round: (HR round)Some general hr questions asked mainly about our projects and about certifications if we had one."
},
{
"code": null,
"e": 2458,
"s": 2237,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2463,
"s": 2458,
"text": "Zoho"
},
{
"code": null,
"e": 2485,
"s": 2463,
"text": "Interview Experiences"
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Strings"
},
{
"code": null,
"e": 2498,
"s": 2493,
"text": "Zoho"
},
{
"code": null,
"e": 2506,
"s": 2498,
"text": "Strings"
}
] |
Java Object Creation of Inherited Class
|
18 Apr, 2022
In Java, being an object-oriented language, objects inside a class is created with help of constructors. When it comes down to inheritance in Java we are basically dealing with deriving a class from another class. Now let us understand inheritance a step deeper so when a particular class inherits a class we do have a keyword that we use in order to refer to parent constructor via super keyword.
It is used as a suffix followed by the “.” operator in constructor/s in a class. This property of parent class(super class) also gets initiated well before child class(sub class) inherits and uses them.
Note: It is mandatory that when an object is created, the constructor is for sure called but it is not mandatory when a constructor is called object creation is mandatory.
We already have seen above when we created an object of a subclass, the constructor of the same class is called, if not made the default constructor is called while we called superclass constructor without creating an object of class inside subclass via keyword.
In inheritance, subclass acquires super class properties. An important point to note is, when a subclass object is created, a separate object of a superclass object will not be created. Only a subclass object is created that has superclass variables. This situation is different from a normal assumption that a constructor call means an object of the class is created, so we can’t blindly say that whenever a class constructor is executed, the object of that class is created or not.
Example:
Java
// Java program to demonstrate that Both Super Class// and Subclass Constructors Refer to Same Object // Importing required classesimport java.util.*; // Class 1// Super Classclass Fruit { // Method inside super class public Fruit() { // Print statement System.out.println("Super class constructor"); // Displaying object hashcode of super class System.out.println("Super class object hashcode :" + this.hashCode()); System.out.println(this.getClass().getName()); }} // Class 2// Sub class extending above super classclass Apple extends Fruit { // Method inside sub class public Apple() { // Print statement System.out.println("Subclass constructor invoked"); // Displaying object hashcode of sub class System.out.println("Sub class object hashcode :" + this.hashCode()); System.out.println(this.hashCode() + " " + super.hashCode()); System.out.println(this.getClass().getName() + " " + super.getClass().getName()); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an instance of above class // inside main() method Apple myApple = new Apple(); }}
Super class constructor
Super class object hashcode :1149319664
Apple
Subclass constructor invoked
Sub class object hashcode :1149319664
1149319664 1149319664
Apple Apple
Output Explanation: As we can see that both superclass(Fruit) object hashcode and subclass(Apple) object hashcode are same, so only one object is created. This object is of class Apple(subclass) as when we try to print the name of the class in which object is created, it is printing Apple which is a subclass.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
surinderdawra388
java-inheritance
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 450,
"s": 52,
"text": "In Java, being an object-oriented language, objects inside a class is created with help of constructors. When it comes down to inheritance in Java we are basically dealing with deriving a class from another class. Now let us understand inheritance a step deeper so when a particular class inherits a class we do have a keyword that we use in order to refer to parent constructor via super keyword."
},
{
"code": null,
"e": 654,
"s": 450,
"text": "It is used as a suffix followed by the “.” operator in constructor/s in a class. This property of parent class(super class) also gets initiated well before child class(sub class) inherits and uses them. "
},
{
"code": null,
"e": 827,
"s": 654,
"text": "Note: It is mandatory that when an object is created, the constructor is for sure called but it is not mandatory when a constructor is called object creation is mandatory. "
},
{
"code": null,
"e": 1095,
"s": 827,
"text": "We already have seen above when we created an object of a subclass, the constructor of the same class is called, if not made the default constructor is called while we called superclass constructor without creating an object of class inside subclass via keyword. "
},
{
"code": null,
"e": 1579,
"s": 1095,
"text": "In inheritance, subclass acquires super class properties. An important point to note is, when a subclass object is created, a separate object of a superclass object will not be created. Only a subclass object is created that has superclass variables. This situation is different from a normal assumption that a constructor call means an object of the class is created, so we can’t blindly say that whenever a class constructor is executed, the object of that class is created or not."
},
{
"code": null,
"e": 1588,
"s": 1579,
"text": "Example:"
},
{
"code": null,
"e": 1593,
"s": 1588,
"text": "Java"
},
{
"code": "// Java program to demonstrate that Both Super Class// and Subclass Constructors Refer to Same Object // Importing required classesimport java.util.*; // Class 1// Super Classclass Fruit { // Method inside super class public Fruit() { // Print statement System.out.println(\"Super class constructor\"); // Displaying object hashcode of super class System.out.println(\"Super class object hashcode :\" + this.hashCode()); System.out.println(this.getClass().getName()); }} // Class 2// Sub class extending above super classclass Apple extends Fruit { // Method inside sub class public Apple() { // Print statement System.out.println(\"Subclass constructor invoked\"); // Displaying object hashcode of sub class System.out.println(\"Sub class object hashcode :\" + this.hashCode()); System.out.println(this.hashCode() + \" \" + super.hashCode()); System.out.println(this.getClass().getName() + \" \" + super.getClass().getName()); }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an instance of above class // inside main() method Apple myApple = new Apple(); }}",
"e": 2952,
"s": 1593,
"text": null
},
{
"code": null,
"e": 3123,
"s": 2952,
"text": "Super class constructor\nSuper class object hashcode :1149319664\nApple\nSubclass constructor invoked\nSub class object hashcode :1149319664\n1149319664 1149319664\nApple Apple"
},
{
"code": null,
"e": 3435,
"s": 3123,
"text": "Output Explanation: As we can see that both superclass(Fruit) object hashcode and subclass(Apple) object hashcode are same, so only one object is created. This object is of class Apple(subclass) as when we try to print the name of the class in which object is created, it is printing Apple which is a subclass."
},
{
"code": null,
"e": 3859,
"s": 3435,
"text": "This article is contributed by Gaurav Miglani. 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": 3873,
"s": 3859,
"text": "solankimayank"
},
{
"code": null,
"e": 3890,
"s": 3873,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3907,
"s": 3890,
"text": "java-inheritance"
},
{
"code": null,
"e": 3912,
"s": 3907,
"text": "Java"
},
{
"code": null,
"e": 3917,
"s": 3912,
"text": "Java"
}
] |
Validation Based Protocol in DBMS
|
25 Nov, 2020
Validation Based Protocol is also called Optimistic Concurrency Control Technique. This protocol is used in DBMS (Database Management System) for avoiding concurrency in transactions. It is called optimistic because of the assumption it makes, i.e. very less interference occurs, therefore, there is no need for checking while the transaction is executed.
In this technique, no checking is done while the transaction is been executed. Until the transaction end is reached updates in the transaction are not applied directly to the database. All updates are applied to local copies of data items kept for the transaction. At the end of transaction execution, while execution of the transaction, a validation phase checks whether any of transaction updates violate serializability. If there is no violation of serializability the transaction is committed and the database is updated; or else, the transaction is updated and then restarted.
Optimistic Concurrency Control is a three-phase protocol. The three phases for validation based protocol:
Read Phase: Values of committed data items from the database can be read by a transaction. Updates are only applied to local data versions. Validation Phase: Checking is performed to make sure that there is no violation of serializability when the transaction updates are applied to the database. Write Phase: On the success of the validation phase, the transaction updates are applied to the database, otherwise, the updates are discarded and the transaction is slowed down.
Read Phase: Values of committed data items from the database can be read by a transaction. Updates are only applied to local data versions.
Validation Phase: Checking is performed to make sure that there is no violation of serializability when the transaction updates are applied to the database.
Write Phase: On the success of the validation phase, the transaction updates are applied to the database, otherwise, the updates are discarded and the transaction is slowed down.
The idea behind optimistic concurrency is to do all the checks at once; hence transaction execution proceeds with a minimum of overhead until the validation phase is reached. If there is not much interference among transactions most of them will have successful validation, otherwise, results will be discarded and restarted later. These circumstances are not much favourable for optimization techniques, since, the assumption of less interference is not satisfied.
Validation based protocol is useful for rare conflicts. Since only local copies of data are included in rollbacks, cascading rollbacks are avoided. This method is not favourable for longer transactions because they are more likely to have conflicts and might be repeatedly rolled back due to conflicts with short transactions.
In order to perform the Validation test, each transaction should go through the various phases as described above. Then, we must know about the following three time-stamps that we assigned to transaction Ti, to check its validity:
1. Start(Ti): It is the time when Ti started its execution.
2. Validation(Ti): It is the time when Ti just finished its read phase and begin its validation phase.
3. Finish(Ti): the time when Ti end it’s all writing operations in the database under write-phase.
Two more terms that we need to know are:
1. Write_set: of a transaction contains all the write operations that Ti performs.
2. Read_set: of a transaction contains all the read operations that Ti performs.
In the Validation phase for transaction Ti the protocol inspect that Ti doesn’t overlap or intervene with any other transactions currently in their validation phase or in committed. The validation phase for Ti checks that for all transaction Tj one of the following below conditions must hold to being validated or pass validation phase:
1. Finish(Tj)<Starts(Ti), since Tj finishes its execution means completes its write-phase before Ti started its execution(read-phase). Then the serializability indeed maintained.
2. Ti begins its write phase after Tj completes its write phase, and the read_set of Ti should be disjoint with write_set of Tj.
3. Tj completes its read phase before Ti completes its read phase and both read_set and write_set of Ti are disjoint with the write_set of Tj.
Ex: Here two Transactions Ti and Tj are given, since TS(Tj)<TS(Ti) so the validation phase succeeds in the Schedule-A. It’s noteworthy that the final write operations to the database are performed only after the validation of both Ti and Tj. Since Ti reads the old values of x(12) and y(15) while print(x+y) operation unless final write operation take place.
Schedule-A
x=x-10
r(y) //y=15
y=y+10
r(x)
<validate>
print(x+y)
w(x)
w(y)
Schedule-A is a validated schedule
Advantages:
1. Avoid Cascading-rollbacks: This validation based scheme avoid cascading rollbacks since the final write operations to the database are performed only after the transaction passes the validation phase. If the transaction fails then no updation operation is performed in the database. So no dirty read will happen hence possibilities cascading-rollback would be null.
2. Avoid deadlock: Since a strict time-stamping based technique is used to maintain the specific order of transactions. Hence deadlock isn’t possible in this scheme.
Disadvantages:
1. Starvation: There might be a possibility of starvation for long-term transactions, due to a sequence of conflicting short-term transactions that cause the repeated sequence of restarts of the long-term transactions so on and so forth. To avoid starvation, conflicting transactions must be temporarily blocked for some time, to let the long-term transactions to finish.
_as
madhav_mohan
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Difference between OLAP and OLTP in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
SQL | DDL, DML, TCL and DCL
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 409,
"s": 52,
"text": "Validation Based Protocol is also called Optimistic Concurrency Control Technique. This protocol is used in DBMS (Database Management System) for avoiding concurrency in transactions. It is called optimistic because of the assumption it makes, i.e. very less interference occurs, therefore, there is no need for checking while the transaction is executed. "
},
{
"code": null,
"e": 992,
"s": 409,
"text": "In this technique, no checking is done while the transaction is been executed. Until the transaction end is reached updates in the transaction are not applied directly to the database. All updates are applied to local copies of data items kept for the transaction. At the end of transaction execution, while execution of the transaction, a validation phase checks whether any of transaction updates violate serializability. If there is no violation of serializability the transaction is committed and the database is updated; or else, the transaction is updated and then restarted. "
},
{
"code": null,
"e": 1100,
"s": 992,
"text": "Optimistic Concurrency Control is a three-phase protocol. The three phases for validation based protocol: "
},
{
"code": null,
"e": 1580,
"s": 1100,
"text": "Read Phase: Values of committed data items from the database can be read by a transaction. Updates are only applied to local data versions. Validation Phase: Checking is performed to make sure that there is no violation of serializability when the transaction updates are applied to the database. Write Phase: On the success of the validation phase, the transaction updates are applied to the database, otherwise, the updates are discarded and the transaction is slowed down. "
},
{
"code": null,
"e": 1722,
"s": 1580,
"text": "Read Phase: Values of committed data items from the database can be read by a transaction. Updates are only applied to local data versions. "
},
{
"code": null,
"e": 1881,
"s": 1722,
"text": "Validation Phase: Checking is performed to make sure that there is no violation of serializability when the transaction updates are applied to the database. "
},
{
"code": null,
"e": 2062,
"s": 1881,
"text": "Write Phase: On the success of the validation phase, the transaction updates are applied to the database, otherwise, the updates are discarded and the transaction is slowed down. "
},
{
"code": null,
"e": 2529,
"s": 2062,
"text": "The idea behind optimistic concurrency is to do all the checks at once; hence transaction execution proceeds with a minimum of overhead until the validation phase is reached. If there is not much interference among transactions most of them will have successful validation, otherwise, results will be discarded and restarted later. These circumstances are not much favourable for optimization techniques, since, the assumption of less interference is not satisfied. "
},
{
"code": null,
"e": 2856,
"s": 2529,
"text": "Validation based protocol is useful for rare conflicts. Since only local copies of data are included in rollbacks, cascading rollbacks are avoided. This method is not favourable for longer transactions because they are more likely to have conflicts and might be repeatedly rolled back due to conflicts with short transactions."
},
{
"code": null,
"e": 3087,
"s": 2856,
"text": "In order to perform the Validation test, each transaction should go through the various phases as described above. Then, we must know about the following three time-stamps that we assigned to transaction Ti, to check its validity:"
},
{
"code": null,
"e": 3148,
"s": 3087,
"text": "1. Start(Ti): It is the time when Ti started its execution. "
},
{
"code": null,
"e": 3252,
"s": 3148,
"text": "2. Validation(Ti): It is the time when Ti just finished its read phase and begin its validation phase. "
},
{
"code": null,
"e": 3351,
"s": 3252,
"text": "3. Finish(Ti): the time when Ti end it’s all writing operations in the database under write-phase."
},
{
"code": null,
"e": 3392,
"s": 3351,
"text": "Two more terms that we need to know are:"
},
{
"code": null,
"e": 3475,
"s": 3392,
"text": "1. Write_set: of a transaction contains all the write operations that Ti performs."
},
{
"code": null,
"e": 3556,
"s": 3475,
"text": "2. Read_set: of a transaction contains all the read operations that Ti performs."
},
{
"code": null,
"e": 3894,
"s": 3556,
"text": "In the Validation phase for transaction Ti the protocol inspect that Ti doesn’t overlap or intervene with any other transactions currently in their validation phase or in committed. The validation phase for Ti checks that for all transaction Tj one of the following below conditions must hold to being validated or pass validation phase:"
},
{
"code": null,
"e": 4074,
"s": 3894,
"text": "1. Finish(Tj)<Starts(Ti), since Tj finishes its execution means completes its write-phase before Ti started its execution(read-phase). Then the serializability indeed maintained. "
},
{
"code": null,
"e": 4203,
"s": 4074,
"text": "2. Ti begins its write phase after Tj completes its write phase, and the read_set of Ti should be disjoint with write_set of Tj."
},
{
"code": null,
"e": 4346,
"s": 4203,
"text": "3. Tj completes its read phase before Ti completes its read phase and both read_set and write_set of Ti are disjoint with the write_set of Tj."
},
{
"code": null,
"e": 4706,
"s": 4346,
"text": "Ex: Here two Transactions Ti and Tj are given, since TS(Tj)<TS(Ti) so the validation phase succeeds in the Schedule-A. It’s noteworthy that the final write operations to the database are performed only after the validation of both Ti and Tj. Since Ti reads the old values of x(12) and y(15) while print(x+y) operation unless final write operation take place. "
},
{
"code": null,
"e": 4797,
"s": 4706,
"text": " Schedule-A"
},
{
"code": null,
"e": 4804,
"s": 4797,
"text": "x=x-10"
},
{
"code": null,
"e": 4816,
"s": 4804,
"text": "r(y) //y=15"
},
{
"code": null,
"e": 4823,
"s": 4816,
"text": "y=y+10"
},
{
"code": null,
"e": 4828,
"s": 4823,
"text": "r(x)"
},
{
"code": null,
"e": 4839,
"s": 4828,
"text": "<validate>"
},
{
"code": null,
"e": 4850,
"s": 4839,
"text": "print(x+y)"
},
{
"code": null,
"e": 4855,
"s": 4850,
"text": "w(x)"
},
{
"code": null,
"e": 4860,
"s": 4855,
"text": "w(y)"
},
{
"code": null,
"e": 4923,
"s": 4860,
"text": " Schedule-A is a validated schedule"
},
{
"code": null,
"e": 4935,
"s": 4923,
"text": "Advantages:"
},
{
"code": null,
"e": 5304,
"s": 4935,
"text": "1. Avoid Cascading-rollbacks: This validation based scheme avoid cascading rollbacks since the final write operations to the database are performed only after the transaction passes the validation phase. If the transaction fails then no updation operation is performed in the database. So no dirty read will happen hence possibilities cascading-rollback would be null."
},
{
"code": null,
"e": 5470,
"s": 5304,
"text": "2. Avoid deadlock: Since a strict time-stamping based technique is used to maintain the specific order of transactions. Hence deadlock isn’t possible in this scheme."
},
{
"code": null,
"e": 5485,
"s": 5470,
"text": "Disadvantages:"
},
{
"code": null,
"e": 5858,
"s": 5485,
"text": "1. Starvation: There might be a possibility of starvation for long-term transactions, due to a sequence of conflicting short-term transactions that cause the repeated sequence of restarts of the long-term transactions so on and so forth. To avoid starvation, conflicting transactions must be temporarily blocked for some time, to let the long-term transactions to finish. "
},
{
"code": null,
"e": 5864,
"s": 5860,
"text": "_as"
},
{
"code": null,
"e": 5877,
"s": 5864,
"text": "madhav_mohan"
},
{
"code": null,
"e": 5882,
"s": 5877,
"text": "DBMS"
},
{
"code": null,
"e": 5890,
"s": 5882,
"text": "GATE CS"
},
{
"code": null,
"e": 5895,
"s": 5890,
"text": "DBMS"
},
{
"code": null,
"e": 5993,
"s": 5895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6034,
"s": 5993,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 6075,
"s": 6034,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 6112,
"s": 6075,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 6144,
"s": 6112,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 6172,
"s": 6144,
"text": "SQL | DDL, DML, TCL and DCL"
},
{
"code": null,
"e": 6192,
"s": 6172,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 6219,
"s": 6192,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 6232,
"s": 6219,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 6281,
"s": 6232,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
How to Solve Histogram Equalization Numerical Problem in MATLAB?
|
22 Nov, 2021
Histogram Equalization is a mathematical technique to widen the dynamic range of the histogram. Sometimes the histogram is spanned over a short range, by equalization the span of the histogram is widened. In digital image processing, the contrast of an image is enhanced using this very technique.
It is used to increase the spread of the histogram. If the histogram represents the digital image, then by spreading the intensity values over a large dynamic range we can improve the contrast of the image.
Find the frequency of each value represented on the horizontal axis of the histogram i.e. intensity in the case of an image.
Calculate the probability density function for each intensity value.
After finding the PDF, calculate the cumulative density function for each intensity’s frequency.
The CDF value is in the range 0-1, so we multiply all CDF values by the largest value of intensity i.e. 255.
Round off the final values to integer values.
Example:
Matlab
% MATLAB code for Histogram equalisation% function to return resultant% matrix and summaryfunction [f,r]=HistEq(k,max)Freq=zeros(1,max);[x,y]=size(k); % Calculate frequency of each% intensity value.for i=1:x for j=1:y Freq(k(i,j)+1)=Freq(k(i,j)+1)+1; endend % Calculate PDF for each intensity value.PDF=zeros(1,max);Total=x*y;for i=1:max PDF(i)=Freq(i)/Total;end % Calculate the CDF for each intensity value.CDF=zeros(1,max);CDF(1)=PDF(1);for i=2:max CDF(i)=CDF(i-1)+PDF(i);end % Multiply by Maximum intensity value% and round off the result.Result=zeros(1,max);for i=1:max Result(i)=uint8(CDF(i)*(max-1));end % Compute the Equalized image/matrix.mat=zeros(size(k));for i=1:x for j=1:y mat(i,j)=Result(k(i,j)+1); endend f=mat;r=Result;end % Utility code here.k=[0, 1, 1, 3, 4; 7, 2, 5, 5, 7; 6, 3, 2, 1, 1; 1, 4, 4, 2, 1]; [new_matrix, summary]=HistEq(k,8);
Output:
A 3-bit image of size 4×5 is shown below. Compute the histogram equalized image.
Steps:
Find the range of intensity values.
Find the frequency of each intensity value.
Calculate the probability density function for each frequency.
Calculate the cumulative density function for each frequency.
Multiply CDF with the highest intensity value possible.
Round off the values obtained in step-5.
Overview of calculation:
Range of intensity values = [0, 1, 2, 3, 4, 5, 6, 7]
Frequency of values = [1, 6, 3, 2, 3, 2, 1, 2]
total = 20 = 4*5
Calculate PDF = frequency of each intensity/Total sum of
all frequencies, for each i value of intensity
Calculate CDF =cumulative frequency of each intensity
value = sum of all PDF value (<=i)
Multiply CDF with 7.
Round off the final value of intensity.
The tabular form of the calculation is given here:
Interpretation:
The pixel intensity in the image has modified.
0 intensity is replaced by 0.
1 intensity is replaced by 2.
2 intensity is replaced by 4.
3 intensity is replaced by 4.
4 intensity is replaced by 5.
5 intensity is replaced by 6.
6 intensity is replaced by 6.
7 intensity is replaced by 7.
Output: The new image is as follow:
MATLAB-Maths
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
MRI Image Segmentation in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
How to remove space in a string in MATLAB?
How to Convert RGB Image to Binary Image Using MATLAB?
Implementation of Cayley-Hamilton’s Theorem in MATLAB
Double Integral in MATLAB
Classes and Object in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 353,
"s": 54,
"text": "Histogram Equalization is a mathematical technique to widen the dynamic range of the histogram. Sometimes the histogram is spanned over a short range, by equalization the span of the histogram is widened. In digital image processing, the contrast of an image is enhanced using this very technique. "
},
{
"code": null,
"e": 561,
"s": 353,
"text": "It is used to increase the spread of the histogram. If the histogram represents the digital image, then by spreading the intensity values over a large dynamic range we can improve the contrast of the image. "
},
{
"code": null,
"e": 686,
"s": 561,
"text": "Find the frequency of each value represented on the horizontal axis of the histogram i.e. intensity in the case of an image."
},
{
"code": null,
"e": 755,
"s": 686,
"text": "Calculate the probability density function for each intensity value."
},
{
"code": null,
"e": 852,
"s": 755,
"text": "After finding the PDF, calculate the cumulative density function for each intensity’s frequency."
},
{
"code": null,
"e": 961,
"s": 852,
"text": "The CDF value is in the range 0-1, so we multiply all CDF values by the largest value of intensity i.e. 255."
},
{
"code": null,
"e": 1007,
"s": 961,
"text": "Round off the final values to integer values."
},
{
"code": null,
"e": 1016,
"s": 1007,
"text": "Example:"
},
{
"code": null,
"e": 1023,
"s": 1016,
"text": "Matlab"
},
{
"code": "% MATLAB code for Histogram equalisation% function to return resultant% matrix and summaryfunction [f,r]=HistEq(k,max)Freq=zeros(1,max);[x,y]=size(k); % Calculate frequency of each% intensity value.for i=1:x for j=1:y Freq(k(i,j)+1)=Freq(k(i,j)+1)+1; endend % Calculate PDF for each intensity value.PDF=zeros(1,max);Total=x*y;for i=1:max PDF(i)=Freq(i)/Total;end % Calculate the CDF for each intensity value.CDF=zeros(1,max);CDF(1)=PDF(1);for i=2:max CDF(i)=CDF(i-1)+PDF(i);end % Multiply by Maximum intensity value% and round off the result.Result=zeros(1,max);for i=1:max Result(i)=uint8(CDF(i)*(max-1));end % Compute the Equalized image/matrix.mat=zeros(size(k));for i=1:x for j=1:y mat(i,j)=Result(k(i,j)+1); endend f=mat;r=Result;end % Utility code here.k=[0, 1, 1, 3, 4; 7, 2, 5, 5, 7; 6, 3, 2, 1, 1; 1, 4, 4, 2, 1]; [new_matrix, summary]=HistEq(k,8);",
"e": 1938,
"s": 1023,
"text": null
},
{
"code": null,
"e": 1946,
"s": 1938,
"text": "Output:"
},
{
"code": null,
"e": 2028,
"s": 1946,
"text": "A 3-bit image of size 4×5 is shown below. Compute the histogram equalized image. "
},
{
"code": null,
"e": 2035,
"s": 2028,
"text": "Steps:"
},
{
"code": null,
"e": 2071,
"s": 2035,
"text": "Find the range of intensity values."
},
{
"code": null,
"e": 2115,
"s": 2071,
"text": "Find the frequency of each intensity value."
},
{
"code": null,
"e": 2178,
"s": 2115,
"text": "Calculate the probability density function for each frequency."
},
{
"code": null,
"e": 2240,
"s": 2178,
"text": "Calculate the cumulative density function for each frequency."
},
{
"code": null,
"e": 2296,
"s": 2240,
"text": "Multiply CDF with the highest intensity value possible."
},
{
"code": null,
"e": 2337,
"s": 2296,
"text": "Round off the values obtained in step-5."
},
{
"code": null,
"e": 2736,
"s": 2337,
"text": "Overview of calculation:\nRange of intensity values = [0, 1, 2, 3, 4, 5, 6, 7]\nFrequency of values = [1, 6, 3, 2, 3, 2, 1, 2] \ntotal = 20 = 4*5\nCalculate PDF = frequency of each intensity/Total sum of\nall frequencies, for each i value of intensity\nCalculate CDF =cumulative frequency of each intensity \nvalue = sum of all PDF value (<=i)\nMultiply CDF with 7.\nRound off the final value of intensity."
},
{
"code": null,
"e": 2787,
"s": 2736,
"text": "The tabular form of the calculation is given here:"
},
{
"code": null,
"e": 3091,
"s": 2787,
"text": "Interpretation: \nThe pixel intensity in the image has modified.\n0 intensity is replaced by 0.\n1 intensity is replaced by 2.\n2 intensity is replaced by 4.\n3 intensity is replaced by 4.\n4 intensity is replaced by 5.\n5 intensity is replaced by 6.\n6 intensity is replaced by 6.\n7 intensity is replaced by 7."
},
{
"code": null,
"e": 3127,
"s": 3091,
"text": "Output: The new image is as follow:"
},
{
"code": null,
"e": 3144,
"s": 3131,
"text": "MATLAB-Maths"
},
{
"code": null,
"e": 3151,
"s": 3144,
"text": "MATLAB"
},
{
"code": null,
"e": 3249,
"s": 3151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3328,
"s": 3249,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 3361,
"s": 3328,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 3426,
"s": 3361,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 3500,
"s": 3426,
"text": "How to detect duplicate values and its indices within an array in MATLAB?"
},
{
"code": null,
"e": 3543,
"s": 3500,
"text": "How to remove space in a string in MATLAB?"
},
{
"code": null,
"e": 3598,
"s": 3543,
"text": "How to Convert RGB Image to Binary Image Using MATLAB?"
},
{
"code": null,
"e": 3652,
"s": 3598,
"text": "Implementation of Cayley-Hamilton’s Theorem in MATLAB"
},
{
"code": null,
"e": 3678,
"s": 3652,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 3707,
"s": 3678,
"text": "Classes and Object in MATLAB"
}
] |
FastText Working and Implementation
|
26 Nov, 2020
What is FastText?
FastText is an open-source, free library from Facebook AI Research(FAIR) for learning word embeddings and word classifications. This model allows creating unsupervised learning or supervised learning algorithm for obtaining vector representations for words. It also evaluates these models. FastText supports both CBOW and Skip-gram models.
Uses of FastText:
It is used for finding semantic similaritiesIt can also be used for text classification(ex: spam filtering).It can train large datasets in minutes.
It is used for finding semantic similarities
It can also be used for text classification(ex: spam filtering).
It can train large datasets in minutes.
Working of FastText:
FastText is very fast in training word vector models. You can train about 1 billion words in less than 10 minutes. The models built through deep neural networks can be slow to train and test. These methods use a linear classifier to train the model.
Linear classifier: In this text and labels are represented as vectors. We find vector representations such that text and it’s associated labels have similar vectors. In simple words, the vector corresponding to the text is closer to its corresponding label.
To find the probability score of a correct label given it’s associated text we use the softmax function:
Here travel is the label and car is the text associated to it.
To maximize this probability of the correct label we can use the Gradient Descent algorithm.
This is quite computationally expensive because for every piece of text not only we have to get the score associated with its correct label but we need to get the score for every other label in the training set. This limits the use of these models on very large datasets.
FastText solves this problem by using a hierarchical classifier to train the model.
Hierarchical Classifier used by FastText:
In this method, it represents the labels in a binary tree. Every node in the binary tree represents a probability. A label is represented by the probability along the path to that given label. This means that the leaf nodes of the binary tree represent the labels.
FastText uses the Huffman algorithm to build these trees to make full use of the fact that classes can be imbalanced. Depth of the frequently occurring labels is smaller than the infrequent ones.
Using a binary tree speed up the time of search as instead of having to go through all the different elements you just search for the nodes. So now we won’t have to compute the score for every single possible label, and we will only be calculating just the probability on each node in the path to the one correct label. Hence this method vastly reduces the time complexity of training the model.
Increasing the speed does not sacrifice the accuracy of the model.
When we have unlabeled dataset FastText uses the N-Gram Technique to train the model. Let us understand more in detail how this technique works-
Let us consider a word from our dataset, for example: “kingdom”. Now it will take a look at the word “kingdom” and will break it into its n-gram components as-
kingdom = ['k','in','kin','king','kingd','kingdo','kingdom',...]
These are some n-gram components for the given words. There will be many more components for this word but only a few are stated here just to get an idea. The size of the n-gram components can be chosen as per your choice. The length of n-grams can be between the minimum and the maximum number of characters selected. You can do so by using the -minn and -maxn flags respectively.
Note: When your text is not words from a particular language then using n-grams won’t make sense. for example: when the corpus contains ids it will not be storing words but numbers and special characters. In this case, you can turn off the -gram embeddings by selecting the -minn and -maxn parameters as 0.
When the model updates, fastText learns the weights for every n-gram along with the entire word token.
In this manner, each token/word will be expressed as the sum and an average of its n-gram components.
Word vectors generated through fastText hold extra information about their sub-words. As in the above example, we can see that one of the components for the word “kingdom” is the word “king”. This information helps the model build semantic similarity between the two words.
It also allows for capturing the meaning of suffixes/prefixes for the given words in the corpus.
It allows for generating better word embeddings for different or rare words as well.
It can also generate word embeddings for out of vocabulary(OOV) words.
While using fastText even if you don’t remove the stopwords still the accuracy is not compromised. You can perform simple pre-processing steps on your corpus if you fell like.
As fastText has the feature of providing sub-word information, it can also be used on morphologically rich languages like Spanish, French, German, etc.
We do get better word embeddings through fastText but it uses more memory as compared to word2vec or GloVe as it generates a lot of sub-words for each word.
Implementation of FastText
Firstly we will have to build fastText. For doing so follow the steps given below –
In your terminal run the below commands-
$ wget https://github.com/facebookresearch/fastText/archive/v0.9.2.zip
$ unzip v0.9.2.zip
$ cd fastText-0.9.2
$ make
Note: If your make command gives an error like – ‘make’ is not recognized as an internal or external command, operable program or batch file. You can download the MinGW by clicking on the link.
After this you need to add the path of its bin folder to system variables then you can use it instead of the make command as-
$ mingw32-make
We have successfully built fastText.
The commands supported by fastText are –
supervised train a supervised classifier
quantize quantize a model to reduce the memory usage
test evaluate a supervised classifier
test-label print labels with precision and recall scores
predict predict most likely labels
predict-prob predict most likely labels with probabilities
skipgram train a skipgram model
cbow train a cbow model
print-word-vectors print word vectors given a trained model
print-sentence-vectors print sentence vectors given a trained model
print-ngrams print ngrams given a trained model and word
nn query for nearest neighbors
analogies query for analogies
dump dump arguments,dictionary,input/output vectors
Now I have taken the amazon reviews dataset and saved it as amazon_reviews.txt. You can also perform some pre-processing on your data to get better results.
We will be training a skipgram model. After you are in the fastText-0.9.2 directory, run the below-mentioned command-
$ fasttext skipgram -input amazon_reviews.txt -output model_trained
Here the input file is amazon_reviews.txt. Make sure to give the full path to your file if it is not in the dame directory. model_trained is the name given for the output file.
You can also add other parameters to it explicitly as per your requirement like epos etc. Here we have used the defaults.
It first starts reading the words present in the input document. The document consisted of 32M words and had an ETA of around 15 mins.
It gives detailed statistics of the learning rate of the neural network, how many words are being processed every second on every thread. It also shows the loss value which goes on decreasing as the model is being trained.
After the model is trained we get two files generated i.e. model_trained.bin and model_trained.vec. The .bin file contains the parameters of the model along with the dictionary. This is the file which fasttext uses. The .vec file is a text file which contains the word vectors. This is the file which you will be using in your applications.
We are now going to use our word vectors and perform some operations on it-
1) Finding Nearest Neighbors for a given word
To initialize the nearest neighbor interface execute the following command:
$ fasttext nn model_trained.bin
The interface asks for a query word to which you want to find the nearest neighbors. The output for the query word “brutality” is-
2) Performing Word Analogies
To perform word analogies of the form ( A – B + C ) on words you can execute the below-mentioned command:
$ fasttext analogies model_trained.bin
The word analogies for A = king, B = man, C = woman are:
The first output for the query is “queen” which is the most correct answer possible for this query. Hence, our model trained is quite accurate.
You can also perform other operations like testing your model with a file of test data, making predictions of the correct labels, getting the n-grams for the given words,etc. You can do these by using the above-mentioned commands available in fasttext.
Machine Learning
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": "\n26 Nov, 2020"
},
{
"code": null,
"e": 46,
"s": 28,
"text": "What is FastText?"
},
{
"code": null,
"e": 386,
"s": 46,
"text": "FastText is an open-source, free library from Facebook AI Research(FAIR) for learning word embeddings and word classifications. This model allows creating unsupervised learning or supervised learning algorithm for obtaining vector representations for words. It also evaluates these models. FastText supports both CBOW and Skip-gram models."
},
{
"code": null,
"e": 404,
"s": 386,
"text": "Uses of FastText:"
},
{
"code": null,
"e": 552,
"s": 404,
"text": "It is used for finding semantic similaritiesIt can also be used for text classification(ex: spam filtering).It can train large datasets in minutes."
},
{
"code": null,
"e": 597,
"s": 552,
"text": "It is used for finding semantic similarities"
},
{
"code": null,
"e": 662,
"s": 597,
"text": "It can also be used for text classification(ex: spam filtering)."
},
{
"code": null,
"e": 702,
"s": 662,
"text": "It can train large datasets in minutes."
},
{
"code": null,
"e": 723,
"s": 702,
"text": "Working of FastText:"
},
{
"code": null,
"e": 974,
"s": 723,
"text": "FastText is very fast in training word vector models. You can train about 1 billion words in less than 10 minutes. The models built through deep neural networks can be slow to train and test. These methods use a linear classifier to train the model. "
},
{
"code": null,
"e": 1232,
"s": 974,
"text": "Linear classifier: In this text and labels are represented as vectors. We find vector representations such that text and it’s associated labels have similar vectors. In simple words, the vector corresponding to the text is closer to its corresponding label."
},
{
"code": null,
"e": 1337,
"s": 1232,
"text": "To find the probability score of a correct label given it’s associated text we use the softmax function:"
},
{
"code": null,
"e": 1400,
"s": 1337,
"text": "Here travel is the label and car is the text associated to it."
},
{
"code": null,
"e": 1493,
"s": 1400,
"text": "To maximize this probability of the correct label we can use the Gradient Descent algorithm."
},
{
"code": null,
"e": 1766,
"s": 1493,
"text": "This is quite computationally expensive because for every piece of text not only we have to get the score associated with its correct label but we need to get the score for every other label in the training set. This limits the use of these models on very large datasets. "
},
{
"code": null,
"e": 1851,
"s": 1766,
"text": "FastText solves this problem by using a hierarchical classifier to train the model. "
},
{
"code": null,
"e": 1894,
"s": 1851,
"text": "Hierarchical Classifier used by FastText: "
},
{
"code": null,
"e": 2159,
"s": 1894,
"text": "In this method, it represents the labels in a binary tree. Every node in the binary tree represents a probability. A label is represented by the probability along the path to that given label. This means that the leaf nodes of the binary tree represent the labels."
},
{
"code": null,
"e": 2355,
"s": 2159,
"text": "FastText uses the Huffman algorithm to build these trees to make full use of the fact that classes can be imbalanced. Depth of the frequently occurring labels is smaller than the infrequent ones."
},
{
"code": null,
"e": 2751,
"s": 2355,
"text": "Using a binary tree speed up the time of search as instead of having to go through all the different elements you just search for the nodes. So now we won’t have to compute the score for every single possible label, and we will only be calculating just the probability on each node in the path to the one correct label. Hence this method vastly reduces the time complexity of training the model."
},
{
"code": null,
"e": 2818,
"s": 2751,
"text": "Increasing the speed does not sacrifice the accuracy of the model."
},
{
"code": null,
"e": 2963,
"s": 2818,
"text": "When we have unlabeled dataset FastText uses the N-Gram Technique to train the model. Let us understand more in detail how this technique works-"
},
{
"code": null,
"e": 3123,
"s": 2963,
"text": "Let us consider a word from our dataset, for example: “kingdom”. Now it will take a look at the word “kingdom” and will break it into its n-gram components as-"
},
{
"code": null,
"e": 3189,
"s": 3123,
"text": "kingdom = ['k','in','kin','king','kingd','kingdo','kingdom',...]\n"
},
{
"code": null,
"e": 3571,
"s": 3189,
"text": "These are some n-gram components for the given words. There will be many more components for this word but only a few are stated here just to get an idea. The size of the n-gram components can be chosen as per your choice. The length of n-grams can be between the minimum and the maximum number of characters selected. You can do so by using the -minn and -maxn flags respectively."
},
{
"code": null,
"e": 3878,
"s": 3571,
"text": "Note: When your text is not words from a particular language then using n-grams won’t make sense. for example: when the corpus contains ids it will not be storing words but numbers and special characters. In this case, you can turn off the -gram embeddings by selecting the -minn and -maxn parameters as 0."
},
{
"code": null,
"e": 3981,
"s": 3878,
"text": "When the model updates, fastText learns the weights for every n-gram along with the entire word token."
},
{
"code": null,
"e": 4083,
"s": 3981,
"text": "In this manner, each token/word will be expressed as the sum and an average of its n-gram components."
},
{
"code": null,
"e": 4357,
"s": 4083,
"text": "Word vectors generated through fastText hold extra information about their sub-words. As in the above example, we can see that one of the components for the word “kingdom” is the word “king”. This information helps the model build semantic similarity between the two words."
},
{
"code": null,
"e": 4454,
"s": 4357,
"text": "It also allows for capturing the meaning of suffixes/prefixes for the given words in the corpus."
},
{
"code": null,
"e": 4539,
"s": 4454,
"text": "It allows for generating better word embeddings for different or rare words as well."
},
{
"code": null,
"e": 4610,
"s": 4539,
"text": "It can also generate word embeddings for out of vocabulary(OOV) words."
},
{
"code": null,
"e": 4786,
"s": 4610,
"text": "While using fastText even if you don’t remove the stopwords still the accuracy is not compromised. You can perform simple pre-processing steps on your corpus if you fell like."
},
{
"code": null,
"e": 4938,
"s": 4786,
"text": "As fastText has the feature of providing sub-word information, it can also be used on morphologically rich languages like Spanish, French, German, etc."
},
{
"code": null,
"e": 5095,
"s": 4938,
"text": "We do get better word embeddings through fastText but it uses more memory as compared to word2vec or GloVe as it generates a lot of sub-words for each word."
},
{
"code": null,
"e": 5122,
"s": 5095,
"text": "Implementation of FastText"
},
{
"code": null,
"e": 5206,
"s": 5122,
"text": "Firstly we will have to build fastText. For doing so follow the steps given below –"
},
{
"code": null,
"e": 5366,
"s": 5206,
"text": "In your terminal run the below commands-\n\n$ wget https://github.com/facebookresearch/fastText/archive/v0.9.2.zip\n$ unzip v0.9.2.zip\n$ cd fastText-0.9.2\n$ make\n"
},
{
"code": null,
"e": 5560,
"s": 5366,
"text": "Note: If your make command gives an error like – ‘make’ is not recognized as an internal or external command, operable program or batch file. You can download the MinGW by clicking on the link."
},
{
"code": null,
"e": 5686,
"s": 5560,
"text": "After this you need to add the path of its bin folder to system variables then you can use it instead of the make command as-"
},
{
"code": null,
"e": 5702,
"s": 5686,
"text": "$ mingw32-make\n"
},
{
"code": null,
"e": 5739,
"s": 5702,
"text": "We have successfully built fastText."
},
{
"code": null,
"e": 5780,
"s": 5739,
"text": "The commands supported by fastText are –"
},
{
"code": null,
"e": 6626,
"s": 5780,
"text": " supervised train a supervised classifier\n quantize quantize a model to reduce the memory usage\n test evaluate a supervised classifier\n test-label print labels with precision and recall scores\n predict predict most likely labels\n predict-prob predict most likely labels with probabilities\n skipgram train a skipgram model\n cbow train a cbow model\n print-word-vectors print word vectors given a trained model\n print-sentence-vectors print sentence vectors given a trained model\n print-ngrams print ngrams given a trained model and word\n nn query for nearest neighbors\n analogies query for analogies\n dump dump arguments,dictionary,input/output vectors\n\n\n"
},
{
"code": null,
"e": 6783,
"s": 6626,
"text": "Now I have taken the amazon reviews dataset and saved it as amazon_reviews.txt. You can also perform some pre-processing on your data to get better results."
},
{
"code": null,
"e": 6901,
"s": 6783,
"text": "We will be training a skipgram model. After you are in the fastText-0.9.2 directory, run the below-mentioned command-"
},
{
"code": null,
"e": 6970,
"s": 6901,
"text": "$ fasttext skipgram -input amazon_reviews.txt -output model_trained\n"
},
{
"code": null,
"e": 7147,
"s": 6970,
"text": "Here the input file is amazon_reviews.txt. Make sure to give the full path to your file if it is not in the dame directory. model_trained is the name given for the output file."
},
{
"code": null,
"e": 7269,
"s": 7147,
"text": "You can also add other parameters to it explicitly as per your requirement like epos etc. Here we have used the defaults."
},
{
"code": null,
"e": 7404,
"s": 7269,
"text": "It first starts reading the words present in the input document. The document consisted of 32M words and had an ETA of around 15 mins."
},
{
"code": null,
"e": 7627,
"s": 7404,
"text": "It gives detailed statistics of the learning rate of the neural network, how many words are being processed every second on every thread. It also shows the loss value which goes on decreasing as the model is being trained."
},
{
"code": null,
"e": 7968,
"s": 7627,
"text": "After the model is trained we get two files generated i.e. model_trained.bin and model_trained.vec. The .bin file contains the parameters of the model along with the dictionary. This is the file which fasttext uses. The .vec file is a text file which contains the word vectors. This is the file which you will be using in your applications."
},
{
"code": null,
"e": 8044,
"s": 7968,
"text": "We are now going to use our word vectors and perform some operations on it-"
},
{
"code": null,
"e": 8090,
"s": 8044,
"text": "1) Finding Nearest Neighbors for a given word"
},
{
"code": null,
"e": 8166,
"s": 8090,
"text": "To initialize the nearest neighbor interface execute the following command:"
},
{
"code": null,
"e": 8199,
"s": 8166,
"text": "$ fasttext nn model_trained.bin\n"
},
{
"code": null,
"e": 8330,
"s": 8199,
"text": "The interface asks for a query word to which you want to find the nearest neighbors. The output for the query word “brutality” is-"
},
{
"code": null,
"e": 8359,
"s": 8330,
"text": "2) Performing Word Analogies"
},
{
"code": null,
"e": 8465,
"s": 8359,
"text": "To perform word analogies of the form ( A – B + C ) on words you can execute the below-mentioned command:"
},
{
"code": null,
"e": 8505,
"s": 8465,
"text": "$ fasttext analogies model_trained.bin\n"
},
{
"code": null,
"e": 8562,
"s": 8505,
"text": "The word analogies for A = king, B = man, C = woman are:"
},
{
"code": null,
"e": 8706,
"s": 8562,
"text": "The first output for the query is “queen” which is the most correct answer possible for this query. Hence, our model trained is quite accurate."
},
{
"code": null,
"e": 8959,
"s": 8706,
"text": "You can also perform other operations like testing your model with a file of test data, making predictions of the correct labels, getting the n-grams for the given words,etc. You can do these by using the above-mentioned commands available in fasttext."
},
{
"code": null,
"e": 8976,
"s": 8959,
"text": "Machine Learning"
},
{
"code": null,
"e": 8993,
"s": 8976,
"text": "Machine Learning"
}
] |
Tensorflow.js tf.data.zip() Function
|
09 Mar, 2022
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.
The tf.data.zip() function is used for creating a dataset by zipping together a dict, array, or nested structure of Dataset.
Syntax:
tf.data.zip(datasets)
Parameters:
dataset: It is the set of data.
Return Value: It returns the tf.data.Dataset.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing Array dataset.let geek1 = tf.data.array([1, 2, 3, 4]);let geek2 = tf.data.array([5, 6, 7, 8]); // Zipping dataset of objects.let geek3 = tf.data.zip([geek1, geek2]); // Printing the returned promise. await geek3.forEachAsync(function(geek){ console.log(JSON.stringify(geek))});
Output:
[1,5]
[2,6]
[3,7]
[4,8]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Zipping two array dataset.let geek = tf.data.zip({ geek1: tf.data.array([1, 2, 3, 4]), geek2: tf.data.array([5, 6, 7, 8])}); // Printing the result.await geek.forEachAsync(function(e){ console.log(JSON.stringify(e))});
Output:
{"geek1":1,"geek2":5}
{"geek1":2,"geek2":6}
{"geek1":3,"geek2":7}
{"geek1":4,"geek2":8}
Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.zip
sagartomar9927
Picked
Tensorflow.js
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": "\n09 Mar, 2022"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js."
},
{
"code": null,
"e": 446,
"s": 321,
"text": "The tf.data.zip() function is used for creating a dataset by zipping together a dict, array, or nested structure of Dataset."
},
{
"code": null,
"e": 455,
"s": 446,
"text": "Syntax: "
},
{
"code": null,
"e": 477,
"s": 455,
"text": "tf.data.zip(datasets)"
},
{
"code": null,
"e": 489,
"s": 477,
"text": "Parameters:"
},
{
"code": null,
"e": 521,
"s": 489,
"text": "dataset: It is the set of data."
},
{
"code": null,
"e": 567,
"s": 521,
"text": "Return Value: It returns the tf.data.Dataset."
},
{
"code": null,
"e": 578,
"s": 567,
"text": "Example 1:"
},
{
"code": null,
"e": 589,
"s": 578,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing Array dataset.let geek1 = tf.data.array([1, 2, 3, 4]);let geek2 = tf.data.array([5, 6, 7, 8]); // Zipping dataset of objects.let geek3 = tf.data.zip([geek1, geek2]); // Printing the returned promise. await geek3.forEachAsync(function(geek){ console.log(JSON.stringify(geek))});",
"e": 961,
"s": 589,
"text": null
},
{
"code": null,
"e": 969,
"s": 961,
"text": "Output:"
},
{
"code": null,
"e": 993,
"s": 969,
"text": "[1,5]\n[2,6]\n[3,7]\n[4,8]"
},
{
"code": null,
"e": 1004,
"s": 993,
"text": "Example 2:"
},
{
"code": null,
"e": 1015,
"s": 1004,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Zipping two array dataset.let geek = tf.data.zip({ geek1: tf.data.array([1, 2, 3, 4]), geek2: tf.data.array([5, 6, 7, 8])}); // Printing the result.await geek.forEachAsync(function(e){ console.log(JSON.stringify(e))});",
"e": 1321,
"s": 1015,
"text": null
},
{
"code": null,
"e": 1329,
"s": 1321,
"text": "Output:"
},
{
"code": null,
"e": 1417,
"s": 1329,
"text": "{\"geek1\":1,\"geek2\":5}\n{\"geek1\":2,\"geek2\":6}\n{\"geek1\":3,\"geek2\":7}\n{\"geek1\":4,\"geek2\":8}"
},
{
"code": null,
"e": 1479,
"s": 1417,
"text": "Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.zip"
},
{
"code": null,
"e": 1494,
"s": 1479,
"text": "sagartomar9927"
},
{
"code": null,
"e": 1501,
"s": 1494,
"text": "Picked"
},
{
"code": null,
"e": 1515,
"s": 1501,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 1526,
"s": 1515,
"text": "JavaScript"
},
{
"code": null,
"e": 1543,
"s": 1526,
"text": "Web Technologies"
}
] |
How to Install PIP on Windows ?
|
07 Jul, 2022
Prerequisite: Python Language Introduction
Before we start with how to install pip for Python on Windows, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently.
PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “online repository” termed as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. So whenever you type:
pip install package_name
pip will look for that package on PyPI and if found, it will download and install the package on your local system.
Run the following command to test if python is installed or not. If not click here.
python --version
If it is installed, You will see something like this:
Python 3.10.0
The PIP can be downloaded and installed using the command line by going through the following steps:
Curl is a UNIX command that is used to send the PUT, GET, and POST requests to a URL. This tool is utilized for downloading files, testing REST APIs, etc.
Step 1: Open the cmd terminal
Step 2: In python, a curl is a tool for transferring data requests to and from a server. Use the following command to request:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
Pip must be manually installed on Windows. You might need to use the correct version of the file from pypa.org if you’re using an earlier version of Python or pip. Get the file and save it to a folder on your PC.
Step 1: Download the get-pip.py (https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as python is installed.
Step 2: Change the current path of the directory in the command line to the path of the directory where the above file exists.
Step 3: get-pip.py is a bootstrapping script that enables users to install pip in Python environments. Run the command given below:
python get-pip.py
Step 4: Now wait through the installation process. Voila! pip is now installed on your system.
One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:
pip -V
or
pip --version
If you are facing any path error then you can follow the following steps to add the pip to your PATH. You can follow the following steps to set the Path:
Go to System and Security > System in the Control Panel once it has been opened.
On the left side, click the Advanced system settings link.
Then select Environment Variables.
Double-click the PATH variable under System Variables.
Click New, and add the directory where pip is installed, e.g. C:Python33Scripts, and select OK.
pip can be upgraded using the following command.
python -m pip install -U pip
It may happen sometimes that your pip current pip version is not supporting your current version of python or machine for that you can downgrade your pip version with the following command. Note: You can mention the version you want to install
python -m pip install pip==17.0
surajkumarguptaintern
how-to-install
python-basics
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 97,
"s": 54,
"text": "Prerequisite: Python Language Introduction"
},
{
"code": null,
"e": 392,
"s": 97,
"text": "Before we start with how to install pip for Python on Windows, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. "
},
{
"code": null,
"e": 689,
"s": 392,
"text": "PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “online repository” termed as Python Package Index (PyPI). pip uses PyPI as the default source for packages and their dependencies. So whenever you type:"
},
{
"code": null,
"e": 714,
"s": 689,
"text": "pip install package_name"
},
{
"code": null,
"e": 830,
"s": 714,
"text": "pip will look for that package on PyPI and if found, it will download and install the package on your local system."
},
{
"code": null,
"e": 914,
"s": 830,
"text": "Run the following command to test if python is installed or not. If not click here."
},
{
"code": null,
"e": 931,
"s": 914,
"text": "python --version"
},
{
"code": null,
"e": 985,
"s": 931,
"text": "If it is installed, You will see something like this:"
},
{
"code": null,
"e": 999,
"s": 985,
"text": "Python 3.10.0"
},
{
"code": null,
"e": 1100,
"s": 999,
"text": "The PIP can be downloaded and installed using the command line by going through the following steps:"
},
{
"code": null,
"e": 1255,
"s": 1100,
"text": "Curl is a UNIX command that is used to send the PUT, GET, and POST requests to a URL. This tool is utilized for downloading files, testing REST APIs, etc."
},
{
"code": null,
"e": 1286,
"s": 1255,
"text": "Step 1: Open the cmd terminal "
},
{
"code": null,
"e": 1413,
"s": 1286,
"text": "Step 2: In python, a curl is a tool for transferring data requests to and from a server. Use the following command to request:"
},
{
"code": null,
"e": 1469,
"s": 1413,
"text": "curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py"
},
{
"code": null,
"e": 1487,
"s": 1469,
"text": "python get-pip.py"
},
{
"code": null,
"e": 1702,
"s": 1489,
"text": "Pip must be manually installed on Windows. You might need to use the correct version of the file from pypa.org if you’re using an earlier version of Python or pip. Get the file and save it to a folder on your PC."
},
{
"code": null,
"e": 1837,
"s": 1702,
"text": "Step 1: Download the get-pip.py (https://bootstrap.pypa.io/get-pip.py) file and store it in the same directory as python is installed."
},
{
"code": null,
"e": 1967,
"s": 1839,
"text": "Step 2: Change the current path of the directory in the command line to the path of the directory where the above file exists. "
},
{
"code": null,
"e": 2101,
"s": 1969,
"text": "Step 3: get-pip.py is a bootstrapping script that enables users to install pip in Python environments. Run the command given below:"
},
{
"code": null,
"e": 2119,
"s": 2101,
"text": "python get-pip.py"
},
{
"code": null,
"e": 2214,
"s": 2119,
"text": "Step 4: Now wait through the installation process. Voila! pip is now installed on your system."
},
{
"code": null,
"e": 2384,
"s": 2216,
"text": "One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:"
},
{
"code": null,
"e": 2408,
"s": 2384,
"text": "pip -V\nor\npip --version"
},
{
"code": null,
"e": 2564,
"s": 2410,
"text": "If you are facing any path error then you can follow the following steps to add the pip to your PATH. You can follow the following steps to set the Path:"
},
{
"code": null,
"e": 2645,
"s": 2564,
"text": "Go to System and Security > System in the Control Panel once it has been opened."
},
{
"code": null,
"e": 2704,
"s": 2645,
"text": "On the left side, click the Advanced system settings link."
},
{
"code": null,
"e": 2739,
"s": 2704,
"text": "Then select Environment Variables."
},
{
"code": null,
"e": 2794,
"s": 2739,
"text": "Double-click the PATH variable under System Variables."
},
{
"code": null,
"e": 2890,
"s": 2794,
"text": "Click New, and add the directory where pip is installed, e.g. C:Python33Scripts, and select OK."
},
{
"code": null,
"e": 2939,
"s": 2890,
"text": "pip can be upgraded using the following command."
},
{
"code": null,
"e": 2968,
"s": 2939,
"text": "python -m pip install -U pip"
},
{
"code": null,
"e": 3213,
"s": 2968,
"text": "It may happen sometimes that your pip current pip version is not supporting your current version of python or machine for that you can downgrade your pip version with the following command. Note: You can mention the version you want to install "
},
{
"code": null,
"e": 3245,
"s": 3213,
"text": "python -m pip install pip==17.0"
},
{
"code": null,
"e": 3267,
"s": 3245,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 3282,
"s": 3267,
"text": "how-to-install"
},
{
"code": null,
"e": 3296,
"s": 3282,
"text": "python-basics"
},
{
"code": null,
"e": 3303,
"s": 3296,
"text": "How To"
},
{
"code": null,
"e": 3322,
"s": 3303,
"text": "Installation Guide"
},
{
"code": null,
"e": 3329,
"s": 3322,
"text": "Python"
}
] |
Fizz Buzz Implementation | Set 2
|
01 Jul, 2021
Given an integer N, the task is to print all the numbers from 1 to N replacing the multiples of 3, 5 and both 3 and 5 by “Fizz”, “Buzz” and “Fizz Buzz” respectively.
Examples:
Input: N = 5Output: 1, 2, Fizz, 4, Buzz
Input: N = 15Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14Fizz Buzz
Approach using modulo operator: The simplest approach to solve this problem is to use modulo operator. Refer to the previous post of this article for this approach.
Approach without using modulo operator: The above problem can be solved without using the modulo operator because:
Modulo operator is a very expensive operation. In the lowest level, modulo is a division.
The DIV instruction of the compiler gives the division and modulo results. However, modern CPUs use specialized division circuits with lookup tables and so, there won’t be any significant change in speed by using bit-shifting.
But for large integers, it is observed that the runtime is much slower in the modulo operation program than the other, with O(N2) computational complexity.
Follow the below steps to solve the problem:
Initialize two count variables, say count3 and count5, to store the count of numbers divisible by 3 and 5 respectively.
Iterate over the range [1, N] using a variable, say i, and perform the following steps:Increment count3 and count5 by 1.If the value of count3 is equal to 3, print “Fizz” and set count3 = 0.Similarly, if the value of count5 is equal to 5, print “Buzz” and set count5 = 0.If none of the above conditions match, then print i.
Increment count3 and count5 by 1.
If the value of count3 is equal to 3, print “Fizz” and set count3 = 0.
Similarly, if the value of count5 is equal to 5, print “Buzz” and set count5 = 0.
If none of the above conditions match, then print i.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate FizzBuzz sequencevoid fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for (int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches bool flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { cout << "Fizz"; // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { cout << "Buzz"; // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { cout << i; } cout << " "; }} // Driver Codeint main(){ int N = 15; fizzBuzz(N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to generate FizzBuzz sequencestatic void fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for (int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches boolean flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { System.out.print("Fizz"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { System.out.print("Buzz"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { System.out.print(i); } System.out.print(" "); }} // Driver Codepublic static void main(String[] args){ int N = 15; fizzBuzz(N);}} // This code is contributed by susmitakundugoaldanga.
# Python3 program for the above approach # Function to generate FizzBuzz sequencedef fizzBuzz(N): # Stores count of multiples # of 3 and 5 respectively count3 = 0 count5 = 0 # Iterate from 1 to N for i in range(1, N + 1): # Increment count3 by 1 count3 += 1 # Increment count5 by 1 count5 += 1 # Initialize a boolean variable # to check if none of the # condition matches flag = False # Check if the value of count3 # is equal to 3 if (count3 == 3): print ("Fizz", end = "") # Reset count3 to 0, and # set flag as True count3 = 0 flag = True # Check if the value of count5 # is equal to 5 if (count5 == 5): print ("Buzz", end = "") # Reset count5 to 0, and # set flag as True count5 = 0 flag = True # If none of the condition matches if (not flag): print (i, end = "") print(end = " ") # Driver Codeif __name__ == '__main__': N = 15 fizzBuzz(N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System; class GFG{ // Function to generate FizzBuzz sequencestatic void fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for(int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a bool variable // to check if none of the // condition matches bool flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { Console.Write("Fizz"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { Console.Write("Buzz"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { Console.Write(i); } Console.Write(" "); }} // Driver Codepublic static void Main(String[] args){ int N = 15; fizzBuzz(N);}} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Function to generate FizzBuzz sequencefunction fizzBuzz(N){ // Stores count of multiples // of 3 and 5 respectively let count3 = 0; let count5 = 0; // Iterate from 1 to N for (let i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches let flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { document.write("Fizz"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { document.write("Buzz"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { document.write(i); } document.write(" "); }} // Driver Codelet N = 15;fizzBuzz(N); // This code is contributed by unknown2108 </script>
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
susmitakundugoaldanga
shikhasingrajput
unknown2108
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Median of two sorted arrays of same size
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "Given an integer N, the task is to print all the numbers from 1 to N replacing the multiples of 3, 5 and both 3 and 5 by “Fizz”, “Buzz” and “Fizz Buzz” respectively."
},
{
"code": null,
"e": 228,
"s": 218,
"text": "Examples:"
},
{
"code": null,
"e": 268,
"s": 228,
"text": "Input: N = 5Output: 1, 2, Fizz, 4, Buzz"
},
{
"code": null,
"e": 360,
"s": 268,
"text": "Input: N = 15Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14Fizz Buzz"
},
{
"code": null,
"e": 525,
"s": 360,
"text": "Approach using modulo operator: The simplest approach to solve this problem is to use modulo operator. Refer to the previous post of this article for this approach."
},
{
"code": null,
"e": 640,
"s": 525,
"text": "Approach without using modulo operator: The above problem can be solved without using the modulo operator because:"
},
{
"code": null,
"e": 730,
"s": 640,
"text": "Modulo operator is a very expensive operation. In the lowest level, modulo is a division."
},
{
"code": null,
"e": 957,
"s": 730,
"text": "The DIV instruction of the compiler gives the division and modulo results. However, modern CPUs use specialized division circuits with lookup tables and so, there won’t be any significant change in speed by using bit-shifting."
},
{
"code": null,
"e": 1113,
"s": 957,
"text": "But for large integers, it is observed that the runtime is much slower in the modulo operation program than the other, with O(N2) computational complexity."
},
{
"code": null,
"e": 1158,
"s": 1113,
"text": "Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 1278,
"s": 1158,
"text": "Initialize two count variables, say count3 and count5, to store the count of numbers divisible by 3 and 5 respectively."
},
{
"code": null,
"e": 1602,
"s": 1278,
"text": "Iterate over the range [1, N] using a variable, say i, and perform the following steps:Increment count3 and count5 by 1.If the value of count3 is equal to 3, print “Fizz” and set count3 = 0.Similarly, if the value of count5 is equal to 5, print “Buzz” and set count5 = 0.If none of the above conditions match, then print i."
},
{
"code": null,
"e": 1636,
"s": 1602,
"text": "Increment count3 and count5 by 1."
},
{
"code": null,
"e": 1707,
"s": 1636,
"text": "If the value of count3 is equal to 3, print “Fizz” and set count3 = 0."
},
{
"code": null,
"e": 1789,
"s": 1707,
"text": "Similarly, if the value of count5 is equal to 5, print “Buzz” and set count5 = 0."
},
{
"code": null,
"e": 1842,
"s": 1789,
"text": "If none of the above conditions match, then print i."
},
{
"code": null,
"e": 1893,
"s": 1842,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1897,
"s": 1893,
"text": "C++"
},
{
"code": null,
"e": 1902,
"s": 1897,
"text": "Java"
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Python3"
},
{
"code": null,
"e": 1913,
"s": 1910,
"text": "C#"
},
{
"code": null,
"e": 1924,
"s": 1913,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to generate FizzBuzz sequencevoid fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for (int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches bool flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { cout << \"Fizz\"; // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { cout << \"Buzz\"; // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { cout << i; } cout << \" \"; }} // Driver Codeint main(){ int N = 15; fizzBuzz(N); return 0;}",
"e": 3138,
"s": 1924,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to generate FizzBuzz sequencestatic void fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for (int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches boolean flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { System.out.print(\"Fizz\"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { System.out.print(\"Buzz\"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { System.out.print(i); } System.out.print(\" \"); }} // Driver Codepublic static void main(String[] args){ int N = 15; fizzBuzz(N);}} // This code is contributed by susmitakundugoaldanga.",
"e": 4462,
"s": 3138,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to generate FizzBuzz sequencedef fizzBuzz(N): # Stores count of multiples # of 3 and 5 respectively count3 = 0 count5 = 0 # Iterate from 1 to N for i in range(1, N + 1): # Increment count3 by 1 count3 += 1 # Increment count5 by 1 count5 += 1 # Initialize a boolean variable # to check if none of the # condition matches flag = False # Check if the value of count3 # is equal to 3 if (count3 == 3): print (\"Fizz\", end = \"\") # Reset count3 to 0, and # set flag as True count3 = 0 flag = True # Check if the value of count5 # is equal to 5 if (count5 == 5): print (\"Buzz\", end = \"\") # Reset count5 to 0, and # set flag as True count5 = 0 flag = True # If none of the condition matches if (not flag): print (i, end = \"\") print(end = \" \") # Driver Codeif __name__ == '__main__': N = 15 fizzBuzz(N) # This code is contributed by mohit kumar 29.",
"e": 5637,
"s": 4462,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to generate FizzBuzz sequencestatic void fizzBuzz(int N){ // Stores count of multiples // of 3 and 5 respectively int count3 = 0; int count5 = 0; // Iterate from 1 to N for(int i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a bool variable // to check if none of the // condition matches bool flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { Console.Write(\"Fizz\"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { Console.Write(\"Buzz\"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { Console.Write(i); } Console.Write(\" \"); }} // Driver Codepublic static void Main(String[] args){ int N = 15; fizzBuzz(N);}} // This code is contributed by shikhasingrajput",
"e": 6967,
"s": 5637,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to generate FizzBuzz sequencefunction fizzBuzz(N){ // Stores count of multiples // of 3 and 5 respectively let count3 = 0; let count5 = 0; // Iterate from 1 to N for (let i = 1; i <= N; i++) { // Increment count3 by 1 count3++; // Increment count5 by 1 count5++; // Initialize a boolean variable // to check if none of the // condition matches let flag = false; // Check if the value of count3 // is equal to 3 if (count3 == 3) { document.write(\"Fizz\"); // Reset count3 to 0, and // set flag as True count3 = 0; flag = true; } // Check if the value of count5 // is equal to 5 if (count5 == 5) { document.write(\"Buzz\"); // Reset count5 to 0, and // set flag as True count5 = 0; flag = true; } // If none of the condition matches if (!flag) { document.write(i); } document.write(\" \"); }} // Driver Codelet N = 15;fizzBuzz(N); // This code is contributed by unknown2108 </script>",
"e": 8214,
"s": 6967,
"text": null
},
{
"code": null,
"e": 8272,
"s": 8214,
"text": "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz"
},
{
"code": null,
"e": 8317,
"s": 8274,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8332,
"s": 8317,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8354,
"s": 8332,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8371,
"s": 8354,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 8383,
"s": 8371,
"text": "unknown2108"
},
{
"code": null,
"e": 8396,
"s": 8383,
"text": "Mathematical"
},
{
"code": null,
"e": 8409,
"s": 8396,
"text": "Mathematical"
},
{
"code": null,
"e": 8507,
"s": 8409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8539,
"s": 8507,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 8601,
"s": 8539,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
},
{
"code": null,
"e": 8647,
"s": 8601,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 8691,
"s": 8647,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 8726,
"s": 8691,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 8768,
"s": 8726,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 8800,
"s": 8768,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 8841,
"s": 8800,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 8866,
"s": 8841,
"text": "Fizz Buzz Implementation"
}
] |
SGML Full Form - GeeksforGeeks
|
16 Dec, 2021
SGML stands for Standard Generalized Markup Language. It can be defined as the standard for defining generalized markup language for documents.
It was developed and designed by the International Organization for Standards i.e ISO. HTML was theoretically an example of an SGML-based language until HTML 5, which browsers cannot parse as SGML for compatibility reasons. The SGML is extended from GML and later on it is extended to HTML and XML.
The extension of SGML files is:
.sgml
Syntax:
<NAME TYPE="user">
Geeks for Geeks
</NAME>
SGML code typically looks like:
HTML
<EMAIL> <SENDER> <PERSON> <FIRSTNAME>GEEKSFOR GEEKS</LASTNAME> </PERSON> </SENDER> <BODY> <p>Hello, Welcome to GEEKF FOR GEEKS</p> </BODY></EMAIL>
The SGML Declarations.
The Prologue, containing a DOCTYPE declaration with the various markup declarations that together make a DTD i.e Document Type Definition.
The instance itself, containing one top-most element and its contents
Components of an SGML Document :
There are mainly three components of SGML document. They are –
SGML DeclarationPrologDocument instance.
SGML Declaration
Prolog
Document instance.
It has the capability to encode the full structure of the document and can support any media type.
It is of much more use than HTML which provides capabilities to code visual representation and not to structure the real piece of information.
Separates content from appearance.
SGML files encoding is allowed for more complex formatting as compared to HTML.
The Stylesheets present in SGML make the content to use for different purposes.
Extremely flexible.
Well supported with many tools available because of ISO standard.
It may be typical to code software in SGML.
Tools that are used in SGML are expensive.
It may not be used widely.
Special software is required to run or to allow the document to display.
Creating DTD’s requires exacting software engineering.
jyoti369
gabaa406
ManasChhabra2
Picked
Full Form
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RFID Full Form
BLOB Full Form
JPEG Full Form
CIDR Full Form
ODBC Full Form
FCFS Scheduling Full Form
DML Full Form
ASP Full Form
LRU Full Form
DBSCAN Full Form
|
[
{
"code": null,
"e": 24828,
"s": 24800,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 24973,
"s": 24828,
"text": "SGML stands for Standard Generalized Markup Language. It can be defined as the standard for defining generalized markup language for documents. "
},
{
"code": null,
"e": 25272,
"s": 24973,
"text": "It was developed and designed by the International Organization for Standards i.e ISO. HTML was theoretically an example of an SGML-based language until HTML 5, which browsers cannot parse as SGML for compatibility reasons. The SGML is extended from GML and later on it is extended to HTML and XML."
},
{
"code": null,
"e": 25306,
"s": 25272,
"text": "The extension of SGML files is: "
},
{
"code": null,
"e": 25312,
"s": 25306,
"text": ".sgml"
},
{
"code": null,
"e": 25322,
"s": 25312,
"text": "Syntax: "
},
{
"code": null,
"e": 25369,
"s": 25322,
"text": "<NAME TYPE=\"user\">\n Geeks for Geeks\n</NAME>"
},
{
"code": null,
"e": 25403,
"s": 25369,
"text": "SGML code typically looks like: "
},
{
"code": null,
"e": 25408,
"s": 25403,
"text": "HTML"
},
{
"code": "<EMAIL> <SENDER> <PERSON> <FIRSTNAME>GEEKSFOR GEEKS</LASTNAME> </PERSON> </SENDER> <BODY> <p>Hello, Welcome to GEEKF FOR GEEKS</p> </BODY></EMAIL>",
"e": 25603,
"s": 25408,
"text": null
},
{
"code": null,
"e": 25626,
"s": 25603,
"text": "The SGML Declarations."
},
{
"code": null,
"e": 25766,
"s": 25626,
"text": "The Prologue, containing a DOCTYPE declaration with the various markup declarations that together make a DTD i.e Document Type Definition. "
},
{
"code": null,
"e": 25836,
"s": 25766,
"text": "The instance itself, containing one top-most element and its contents"
},
{
"code": null,
"e": 25869,
"s": 25836,
"text": "Components of an SGML Document :"
},
{
"code": null,
"e": 25933,
"s": 25869,
"text": "There are mainly three components of SGML document. They are – "
},
{
"code": null,
"e": 25974,
"s": 25933,
"text": "SGML DeclarationPrologDocument instance."
},
{
"code": null,
"e": 25991,
"s": 25974,
"text": "SGML Declaration"
},
{
"code": null,
"e": 25998,
"s": 25991,
"text": "Prolog"
},
{
"code": null,
"e": 26017,
"s": 25998,
"text": "Document instance."
},
{
"code": null,
"e": 26116,
"s": 26017,
"text": "It has the capability to encode the full structure of the document and can support any media type."
},
{
"code": null,
"e": 26259,
"s": 26116,
"text": "It is of much more use than HTML which provides capabilities to code visual representation and not to structure the real piece of information."
},
{
"code": null,
"e": 26294,
"s": 26259,
"text": "Separates content from appearance."
},
{
"code": null,
"e": 26374,
"s": 26294,
"text": "SGML files encoding is allowed for more complex formatting as compared to HTML."
},
{
"code": null,
"e": 26454,
"s": 26374,
"text": "The Stylesheets present in SGML make the content to use for different purposes."
},
{
"code": null,
"e": 26474,
"s": 26454,
"text": "Extremely flexible."
},
{
"code": null,
"e": 26540,
"s": 26474,
"text": "Well supported with many tools available because of ISO standard."
},
{
"code": null,
"e": 26584,
"s": 26540,
"text": "It may be typical to code software in SGML."
},
{
"code": null,
"e": 26627,
"s": 26584,
"text": "Tools that are used in SGML are expensive."
},
{
"code": null,
"e": 26654,
"s": 26627,
"text": "It may not be used widely."
},
{
"code": null,
"e": 26727,
"s": 26654,
"text": "Special software is required to run or to allow the document to display."
},
{
"code": null,
"e": 26782,
"s": 26727,
"text": "Creating DTD’s requires exacting software engineering."
},
{
"code": null,
"e": 26791,
"s": 26782,
"text": "jyoti369"
},
{
"code": null,
"e": 26800,
"s": 26791,
"text": "gabaa406"
},
{
"code": null,
"e": 26814,
"s": 26800,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26821,
"s": 26814,
"text": "Picked"
},
{
"code": null,
"e": 26831,
"s": 26821,
"text": "Full Form"
},
{
"code": null,
"e": 26929,
"s": 26831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26944,
"s": 26929,
"text": "RFID Full Form"
},
{
"code": null,
"e": 26959,
"s": 26944,
"text": "BLOB Full Form"
},
{
"code": null,
"e": 26974,
"s": 26959,
"text": "JPEG Full Form"
},
{
"code": null,
"e": 26989,
"s": 26974,
"text": "CIDR Full Form"
},
{
"code": null,
"e": 27004,
"s": 26989,
"text": "ODBC Full Form"
},
{
"code": null,
"e": 27030,
"s": 27004,
"text": "FCFS Scheduling Full Form"
},
{
"code": null,
"e": 27044,
"s": 27030,
"text": "DML Full Form"
},
{
"code": null,
"e": 27058,
"s": 27044,
"text": "ASP Full Form"
},
{
"code": null,
"e": 27072,
"s": 27058,
"text": "LRU Full Form"
}
] |
How to create a client-side image-map in HTML5 ? - GeeksforGeeks
|
20 Oct, 2020
In this article, we will create a client-side image map by using an <img> tag. The <img> tag is used to add images on a webpage. This tag is an empty tag which means it can contain only a list of attributes and it has no closing tag.
Syntax:
<img src="url" alt="some_text" usemap="#mapname">
Example:
<!DOCTYPE html><html> <head> <title> Define a client-side image-map </title></head> <body> <h2> HTML5: How to define a client-side image-map? </h2> <h4> Inserted image using <img> tag: </h4> <img src="https://www.geeksforgeeks.org/wp-content/uploads/gfgLogo.png" alt="GeeksforGeeks logo"></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
arorakashish0911
HTML-Misc
HTML5
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24992,
"s": 24964,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 25226,
"s": 24992,
"text": "In this article, we will create a client-side image map by using an <img> tag. The <img> tag is used to add images on a webpage. This tag is an empty tag which means it can contain only a list of attributes and it has no closing tag."
},
{
"code": null,
"e": 25234,
"s": 25226,
"text": "Syntax:"
},
{
"code": null,
"e": 25284,
"s": 25234,
"text": "<img src=\"url\" alt=\"some_text\" usemap=\"#mapname\">"
},
{
"code": null,
"e": 25293,
"s": 25284,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Define a client-side image-map </title></head> <body> <h2> HTML5: How to define a client-side image-map? </h2> <h4> Inserted image using <img> tag: </h4> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/gfgLogo.png\" alt=\"GeeksforGeeks logo\"></body> </html>",
"e": 25668,
"s": 25293,
"text": null
},
{
"code": null,
"e": 25676,
"s": 25668,
"text": "Output:"
},
{
"code": null,
"e": 25696,
"s": 25676,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 25710,
"s": 25696,
"text": "Google Chrome"
},
{
"code": null,
"e": 25728,
"s": 25710,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25736,
"s": 25728,
"text": "Firefox"
},
{
"code": null,
"e": 25742,
"s": 25736,
"text": "Opera"
},
{
"code": null,
"e": 25749,
"s": 25742,
"text": "Safari"
},
{
"code": null,
"e": 25886,
"s": 25749,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25903,
"s": 25886,
"text": "arorakashish0911"
},
{
"code": null,
"e": 25913,
"s": 25903,
"text": "HTML-Misc"
},
{
"code": null,
"e": 25919,
"s": 25913,
"text": "HTML5"
},
{
"code": null,
"e": 25924,
"s": 25919,
"text": "HTML"
},
{
"code": null,
"e": 25941,
"s": 25924,
"text": "Web Technologies"
},
{
"code": null,
"e": 25968,
"s": 25941,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 25973,
"s": 25968,
"text": "HTML"
},
{
"code": null,
"e": 26071,
"s": 25973,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26112,
"s": 26071,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 26136,
"s": 26112,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26173,
"s": 26136,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26202,
"s": 26173,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26222,
"s": 26202,
"text": "Angular File Upload"
},
{
"code": null,
"e": 26262,
"s": 26222,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26295,
"s": 26262,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26340,
"s": 26295,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26383,
"s": 26340,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to change the PyGame icon? - GeeksforGeeks
|
30 Apr, 2021
While building a video game, do you wish to set your image or company’s logo as the icon for a game? If yes, then you can do it easily by using set_icon() function after declaring the image you wish to set as an icon. Read the article given below to know more in detail.
Syntax:
pygame_icon = pygame.image.load('#Enter the image')
pygame.display.set_icon(pygame_icon)
Step 1: First, import the library Pygame.
import pygame
Step 2: Now, construct the GUI game.
pygame.init()
Step 3: Further, set the dimensions of your GUI game.
screen = pygame.display.set_mode([#width of game, #height of game])
Step 4: Next, take the image as input that we wish to set as an icon.
img = pygame.image.load('#Enter the image')
Step 5: Then, set the image as an icon. The icon set will appear in the top-left corner when the game is in running state.
pygame.display.set_icon(img)
Step 6: Later on, set the running value for running the game.
running = True
Step 7: Set the things which you want your game to do when it is in a running state
while running:
for event in pygame.event.get():
Step 7.1: Once the app is in a running state, make it quit if the user wants to quit.
if event.type == pygame.QUIT:
running = False
Step 7.2: Moreover, set the background color which you wish to see in your app.
screen.fill(# RGB Value of Color)
Step 7.3: Then, make your app do whatever you want it do while being in a running state.
Step 7.4: After doing everything you wish to do, update the changes done.
pygame.display.update()
Step 8: Finally, quit the GUI game
pygame.quit()
Below is the implementation.
Python
# Python program to change # the Pygame icon # Import the library Pygameimport pygame # Construct the GUI gamepygame.init() # Set dimensions of game GUIscreen = pygame.display.set_mode([600, 400]) # Take image as inputimg = pygame.image.load('gfg_image.jpg') # Set image as iconpygame.display.set_icon(img) # Set running valuerunning = True # Setting what happens when game # is in running statewhile running: for event in pygame.event.get(): # Close if the user quits the game if event.type == pygame.QUIT: running = False # Set the background color screen.fill((255, 255, 0)) # Draw a circle on the screen pygame.draw.circle(screen, (0, 0, 0), (300, 200), 75) # Update the GUI game pygame.display.update() # Quit the GUI gamepygame.quit()
Output:
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 24484,
"s": 24212,
"text": "While building a video game, do you wish to set your image or company’s logo as the icon for a game? If yes, then you can do it easily by using set_icon() function after declaring the image you wish to set as an icon. Read the article given below to know more in detail. "
},
{
"code": null,
"e": 24492,
"s": 24484,
"text": "Syntax:"
},
{
"code": null,
"e": 24581,
"s": 24492,
"text": "pygame_icon = pygame.image.load('#Enter the image')\npygame.display.set_icon(pygame_icon)"
},
{
"code": null,
"e": 24623,
"s": 24581,
"text": "Step 1: First, import the library Pygame."
},
{
"code": null,
"e": 24637,
"s": 24623,
"text": "import pygame"
},
{
"code": null,
"e": 24674,
"s": 24637,
"text": "Step 2: Now, construct the GUI game."
},
{
"code": null,
"e": 24688,
"s": 24674,
"text": "pygame.init()"
},
{
"code": null,
"e": 24742,
"s": 24688,
"text": "Step 3: Further, set the dimensions of your GUI game."
},
{
"code": null,
"e": 24810,
"s": 24742,
"text": "screen = pygame.display.set_mode([#width of game, #height of game])"
},
{
"code": null,
"e": 24880,
"s": 24810,
"text": "Step 4: Next, take the image as input that we wish to set as an icon."
},
{
"code": null,
"e": 24924,
"s": 24880,
"text": "img = pygame.image.load('#Enter the image')"
},
{
"code": null,
"e": 25047,
"s": 24924,
"text": "Step 5: Then, set the image as an icon. The icon set will appear in the top-left corner when the game is in running state."
},
{
"code": null,
"e": 25076,
"s": 25047,
"text": "pygame.display.set_icon(img)"
},
{
"code": null,
"e": 25138,
"s": 25076,
"text": "Step 6: Later on, set the running value for running the game."
},
{
"code": null,
"e": 25153,
"s": 25138,
"text": "running = True"
},
{
"code": null,
"e": 25237,
"s": 25153,
"text": "Step 7: Set the things which you want your game to do when it is in a running state"
},
{
"code": null,
"e": 25288,
"s": 25237,
"text": "while running:\n for event in pygame.event.get():"
},
{
"code": null,
"e": 25374,
"s": 25288,
"text": "Step 7.1: Once the app is in a running state, make it quit if the user wants to quit."
},
{
"code": null,
"e": 25438,
"s": 25374,
"text": " if event.type == pygame.QUIT:\n running = False"
},
{
"code": null,
"e": 25518,
"s": 25438,
"text": "Step 7.2: Moreover, set the background color which you wish to see in your app."
},
{
"code": null,
"e": 25555,
"s": 25518,
"text": " screen.fill(# RGB Value of Color)"
},
{
"code": null,
"e": 25644,
"s": 25555,
"text": "Step 7.3: Then, make your app do whatever you want it do while being in a running state."
},
{
"code": null,
"e": 25718,
"s": 25644,
"text": "Step 7.4: After doing everything you wish to do, update the changes done."
},
{
"code": null,
"e": 25745,
"s": 25718,
"text": " pygame.display.update()"
},
{
"code": null,
"e": 25780,
"s": 25745,
"text": "Step 8: Finally, quit the GUI game"
},
{
"code": null,
"e": 25794,
"s": 25780,
"text": "pygame.quit()"
},
{
"code": null,
"e": 25823,
"s": 25794,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25830,
"s": 25823,
"text": "Python"
},
{
"code": "# Python program to change # the Pygame icon # Import the library Pygameimport pygame # Construct the GUI gamepygame.init() # Set dimensions of game GUIscreen = pygame.display.set_mode([600, 400]) # Take image as inputimg = pygame.image.load('gfg_image.jpg') # Set image as iconpygame.display.set_icon(img) # Set running valuerunning = True # Setting what happens when game # is in running statewhile running: for event in pygame.event.get(): # Close if the user quits the game if event.type == pygame.QUIT: running = False # Set the background color screen.fill((255, 255, 0)) # Draw a circle on the screen pygame.draw.circle(screen, (0, 0, 0), (300, 200), 75) # Update the GUI game pygame.display.update() # Quit the GUI gamepygame.quit()",
"e": 26633,
"s": 25830,
"text": null
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Output:"
},
{
"code": null,
"e": 26648,
"s": 26641,
"text": "Picked"
},
{
"code": null,
"e": 26662,
"s": 26648,
"text": "Python-PyGame"
},
{
"code": null,
"e": 26669,
"s": 26662,
"text": "Python"
},
{
"code": null,
"e": 26767,
"s": 26669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26776,
"s": 26767,
"text": "Comments"
},
{
"code": null,
"e": 26789,
"s": 26776,
"text": "Old Comments"
},
{
"code": null,
"e": 26821,
"s": 26789,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26876,
"s": 26821,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26932,
"s": 26876,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26971,
"s": 26932,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27013,
"s": 26971,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27055,
"s": 27013,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27077,
"s": 27055,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27108,
"s": 27077,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27137,
"s": 27108,
"text": "Create a directory in Python"
}
] |
Number of permutations such that sum of elements at odd index and even index are equal - GeeksforGeeks
|
04 Dec, 2021
Given N numbers, find the number of permutations in which the sum of elements at odd index and sum of elements at even index are equal. Examples:
Input: 1 2 3 Output: 2 The permutations are: 1 3 2 sum at odd index = 1+2 = 3, sum at even index = 3 2 3 1 sum at odd index = 2+1 = 3, sum at even index = 3Input: 1 2 1 2 Output: 3 The permutations are: 1 2 2 1 2 1 1 2 2 2 1 1
The approach to the problem will be to use next_permutation() in C++ STL which helps to generate all the possible permutation of N numbers. If the sum of the odd index elements is equal to the sum of even index elements of the generated permutation, then increase the count. When all permutations are checked, print the count. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of permutations// such that sum of elements at odd index// and even index are equal#include <bits/stdc++.h>using namespace std; // Function that returns the number of permutationsint numberOfPermutations(int a[], int n){ int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2) sumOdd += a[i]; else sumEven += a[i]; } // If condition holds if (sumOdd == sumEven) c++; } while (next_permutation(a, a + n)); // return the number of permutations return c;}// Driver Codeint main(){ int a[] = { 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); // Calling Function cout << numberOfPermutations(a, n); return 0;}
// Java program to find number of permutations// such that sum of elements at odd index// and even index are equalclass GFG { // Function that returns the number of permutations static int numberOfPermutations(int a[], int n) { int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (int b = p.length - 1;; --b) { if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; }// Driver Code public static void main(String args[]) { int a[] = {1, 2, 3}; int n = a.length; System.out.println(numberOfPermutations(a, n)); }}/*This code is contributed by 29AjayKumar*/
# Python3 program to find number of permutations# such that sum of elements at odd index# and even index are equal def next_permutation(arr): arrCount = len(arr); # the head of the suffix i = arrCount - 1; # find longest suffix while (i > 0 and arr[i] <= arr[i - 1]): i-=1; # are we at the last permutation already? if (i <= 0): return [False,arr]; # get the pivot pivotIndex = i - 1; # find rightmost element that exceeds the pivot j = arrCount - 1; while (arr[j] <= arr[pivotIndex]): j-=1; # swap the pivot with j temp = arr[pivotIndex]; arr[pivotIndex] = arr[j]; arr[j] = temp; # reverse the suffix j = arrCount - 1; while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i+=1; j-=1; return [True,arr]; # Function that returns the number# of permutationsdef numberOfPermutations(a, n): sumEven=0; sumOdd=0; c = 0; # iterate for all permutations while (True): # stores the sum of odd and # even index elements sumEven = 0; sumOdd = 0; # iterate for elements in permutation for i in range(n): # if odd index if (i % 2): sumOdd += a[i]; else: sumEven += a[i]; # If condition holds if (sumOdd == sumEven): c+=1; xx=next_permutation(a); if(xx[0]==False): break; a=xx[1]; # return the number of permutations return c; # Driver Codea = [1, 2, 3];n = len(a); # Calling Functionprint(numberOfPermutations(a, n)); # This code is contributed by mits
// C# program to find number of permutations// such that sum of elements at odd index// and even index are equalusing System; public class GFG { // Function that returns the number of permutations static int numberOfPermutations(int []a, int n) { int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } static bool next_permutation(int[] p) { for (int a = p.Length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (int b = p.Length - 1;; --b) { if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; }// Driver Code public static void Main() { int []a = {1, 2, 3}; int n = a.Length; Console.WriteLine(numberOfPermutations(a, n)); }}/*This code is contributed by 29AjayKumar*/
<?php// PHP program to find number of permutations// such that sum of elements at odd index// and even index are equal function next_permutation(&$input){ $inputCount = count($input); // the head of the suffix $i = $inputCount - 1; // find longest suffix while ($i > 0 && $input[$i] <= $input[$i - 1]) { $i--; } // are we at the last permutation already? if ($i <= 0) { return false; } // get the pivot $pivotIndex = $i - 1; // find rightmost element that exceeds the pivot $j = $inputCount - 1; while ($input[$j] <= $input[$pivotIndex]) { $j--; } // swap the pivot with j $temp = $input[$pivotIndex]; $input[$pivotIndex] = $input[$j]; $input[$j] = $temp; // reverse the suffix $j = $inputCount - 1; while ($i < $j) { $temp = $input[$i]; $input[$i] = $input[$j]; $input[$j] = $temp; $i++; $j--; } return true;} // Function that returns the number// of permutationsfunction numberOfPermutations($a, $n){ $sumEven; $sumOdd; $c = 0; // iterate for all permutations do { // stores the sum of odd and // even index elements $sumEven = $sumOdd = 0; // iterate for elements in permutation for ($i = 0; $i < $n; $i++) { // if odd index if ($i % 2) $sumOdd += $a[$i]; else $sumEven += $a[$i]; } // If condition holds if ($sumOdd == $sumEven) $c++; } while (next_permutation($a)); // return the number of permutations return $c;} // Driver Code$a = array(1, 2, 3);$n = count($a); // Calling Functionecho numberOfPermutations($a, $n); // This code is contributed by// Rajput-Ji?>
<script> // javascript program to find number of permutations// such that sum of elements at odd index// and even index are equal // Function that returns the number of permutations function numberOfPermutations( a , n) { var sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (var i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } function next_permutation(p) { for (var a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (var b = p.length - 1;; --b) { if (p[b] > p[a]) { var t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; } // Driver Code var a = [ 1, 2, 3 ]; var n = a.length; document.write(numberOfPermutations(a, n)); // This code contributed by Princi Singh</script>
2
Time Complexity: O(N! * N)
29AjayKumar
Rajput-Ji
Mithun Kumar
princi singh
kk9826225
Constructive Algorithms
CPP-Functions
Permutation and Combination
STL
Arrays
Combinatorial
Arrays
Combinatorial
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number
|
[
{
"code": null,
"e": 26900,
"s": 26872,
"text": "\n04 Dec, 2021"
},
{
"code": null,
"e": 27046,
"s": 26900,
"text": "Given N numbers, find the number of permutations in which the sum of elements at odd index and sum of elements at even index are equal. Examples:"
},
{
"code": null,
"e": 27274,
"s": 27046,
"text": "Input: 1 2 3 Output: 2 The permutations are: 1 3 2 sum at odd index = 1+2 = 3, sum at even index = 3 2 3 1 sum at odd index = 2+1 = 3, sum at even index = 3Input: 1 2 1 2 Output: 3 The permutations are: 1 2 2 1 2 1 1 2 2 2 1 1 "
},
{
"code": null,
"e": 27654,
"s": 27274,
"text": "The approach to the problem will be to use next_permutation() in C++ STL which helps to generate all the possible permutation of N numbers. If the sum of the odd index elements is equal to the sum of even index elements of the generated permutation, then increase the count. When all permutations are checked, print the count. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27658,
"s": 27654,
"text": "C++"
},
{
"code": null,
"e": 27663,
"s": 27658,
"text": "Java"
},
{
"code": null,
"e": 27671,
"s": 27663,
"text": "Python3"
},
{
"code": null,
"e": 27674,
"s": 27671,
"text": "C#"
},
{
"code": null,
"e": 27678,
"s": 27674,
"text": "PHP"
},
{
"code": null,
"e": 27689,
"s": 27678,
"text": "Javascript"
},
{
"code": "// C++ program to find number of permutations// such that sum of elements at odd index// and even index are equal#include <bits/stdc++.h>using namespace std; // Function that returns the number of permutationsint numberOfPermutations(int a[], int n){ int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2) sumOdd += a[i]; else sumEven += a[i]; } // If condition holds if (sumOdd == sumEven) c++; } while (next_permutation(a, a + n)); // return the number of permutations return c;}// Driver Codeint main(){ int a[] = { 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); // Calling Function cout << numberOfPermutations(a, n); return 0;}",
"e": 28662,
"s": 27689,
"text": null
},
{
"code": "// Java program to find number of permutations// such that sum of elements at odd index// and even index are equalclass GFG { // Function that returns the number of permutations static int numberOfPermutations(int a[], int n) { int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (int b = p.length - 1;; --b) { if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; }// Driver Code public static void main(String args[]) { int a[] = {1, 2, 3}; int n = a.length; System.out.println(numberOfPermutations(a, n)); }}/*This code is contributed by 29AjayKumar*/",
"e": 30435,
"s": 28662,
"text": null
},
{
"code": "# Python3 program to find number of permutations# such that sum of elements at odd index# and even index are equal def next_permutation(arr): arrCount = len(arr); # the head of the suffix i = arrCount - 1; # find longest suffix while (i > 0 and arr[i] <= arr[i - 1]): i-=1; # are we at the last permutation already? if (i <= 0): return [False,arr]; # get the pivot pivotIndex = i - 1; # find rightmost element that exceeds the pivot j = arrCount - 1; while (arr[j] <= arr[pivotIndex]): j-=1; # swap the pivot with j temp = arr[pivotIndex]; arr[pivotIndex] = arr[j]; arr[j] = temp; # reverse the suffix j = arrCount - 1; while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i+=1; j-=1; return [True,arr]; # Function that returns the number# of permutationsdef numberOfPermutations(a, n): sumEven=0; sumOdd=0; c = 0; # iterate for all permutations while (True): # stores the sum of odd and # even index elements sumEven = 0; sumOdd = 0; # iterate for elements in permutation for i in range(n): # if odd index if (i % 2): sumOdd += a[i]; else: sumEven += a[i]; # If condition holds if (sumOdd == sumEven): c+=1; xx=next_permutation(a); if(xx[0]==False): break; a=xx[1]; # return the number of permutations return c; # Driver Codea = [1, 2, 3];n = len(a); # Calling Functionprint(numberOfPermutations(a, n)); # This code is contributed by mits",
"e": 32159,
"s": 30435,
"text": null
},
{
"code": "// C# program to find number of permutations// such that sum of elements at odd index// and even index are equalusing System; public class GFG { // Function that returns the number of permutations static int numberOfPermutations(int []a, int n) { int sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (int i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } static bool next_permutation(int[] p) { for (int a = p.Length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (int b = p.Length - 1;; --b) { if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.Length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; }// Driver Code public static void Main() { int []a = {1, 2, 3}; int n = a.Length; Console.WriteLine(numberOfPermutations(a, n)); }}/*This code is contributed by 29AjayKumar*/",
"e": 33943,
"s": 32159,
"text": null
},
{
"code": "<?php// PHP program to find number of permutations// such that sum of elements at odd index// and even index are equal function next_permutation(&$input){ $inputCount = count($input); // the head of the suffix $i = $inputCount - 1; // find longest suffix while ($i > 0 && $input[$i] <= $input[$i - 1]) { $i--; } // are we at the last permutation already? if ($i <= 0) { return false; } // get the pivot $pivotIndex = $i - 1; // find rightmost element that exceeds the pivot $j = $inputCount - 1; while ($input[$j] <= $input[$pivotIndex]) { $j--; } // swap the pivot with j $temp = $input[$pivotIndex]; $input[$pivotIndex] = $input[$j]; $input[$j] = $temp; // reverse the suffix $j = $inputCount - 1; while ($i < $j) { $temp = $input[$i]; $input[$i] = $input[$j]; $input[$j] = $temp; $i++; $j--; } return true;} // Function that returns the number// of permutationsfunction numberOfPermutations($a, $n){ $sumEven; $sumOdd; $c = 0; // iterate for all permutations do { // stores the sum of odd and // even index elements $sumEven = $sumOdd = 0; // iterate for elements in permutation for ($i = 0; $i < $n; $i++) { // if odd index if ($i % 2) $sumOdd += $a[$i]; else $sumEven += $a[$i]; } // If condition holds if ($sumOdd == $sumEven) $c++; } while (next_permutation($a)); // return the number of permutations return $c;} // Driver Code$a = array(1, 2, 3);$n = count($a); // Calling Functionecho numberOfPermutations($a, $n); // This code is contributed by// Rajput-Ji?>",
"e": 35787,
"s": 33943,
"text": null
},
{
"code": "<script> // javascript program to find number of permutations// such that sum of elements at odd index// and even index are equal // Function that returns the number of permutations function numberOfPermutations( a , n) { var sumEven, sumOdd, c = 0; // iterate for all permutations do { // stores the sum of odd and even index elements sumEven = sumOdd = 0; // iterate for elements in permutation for (var i = 0; i < n; i++) { // if odd index if (i % 2 == 0) { sumOdd += a[i]; } else { sumEven += a[i]; } } // If condition holds if (sumOdd == sumEven) { c++; } } while (next_permutation(a)); // return the number of permutations return c; } function next_permutation(p) { for (var a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (var b = p.length - 1;; --b) { if (p[b] > p[a]) { var t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; } // Driver Code var a = [ 1, 2, 3 ]; var n = a.length; document.write(numberOfPermutations(a, n)); // This code contributed by Princi Singh</script>",
"e": 37508,
"s": 35787,
"text": null
},
{
"code": null,
"e": 37510,
"s": 37508,
"text": "2"
},
{
"code": null,
"e": 37541,
"s": 37512,
"text": "Time Complexity: O(N! * N) "
},
{
"code": null,
"e": 37553,
"s": 37541,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37563,
"s": 37553,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37576,
"s": 37563,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 37589,
"s": 37576,
"text": "princi singh"
},
{
"code": null,
"e": 37599,
"s": 37589,
"text": "kk9826225"
},
{
"code": null,
"e": 37623,
"s": 37599,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 37637,
"s": 37623,
"text": "CPP-Functions"
},
{
"code": null,
"e": 37665,
"s": 37637,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 37669,
"s": 37665,
"text": "STL"
},
{
"code": null,
"e": 37676,
"s": 37669,
"text": "Arrays"
},
{
"code": null,
"e": 37690,
"s": 37676,
"text": "Combinatorial"
},
{
"code": null,
"e": 37697,
"s": 37690,
"text": "Arrays"
},
{
"code": null,
"e": 37711,
"s": 37697,
"text": "Combinatorial"
},
{
"code": null,
"e": 37715,
"s": 37711,
"text": "STL"
},
{
"code": null,
"e": 37813,
"s": 37715,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37836,
"s": 37813,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37868,
"s": 37836,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37882,
"s": 37868,
"text": "Linear Search"
},
{
"code": null,
"e": 37903,
"s": 37882,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37988,
"s": 37903,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 38048,
"s": 37988,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38086,
"s": 38048,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 38163,
"s": 38086,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 38181,
"s": 38163,
"text": "Combinational Sum"
}
] |
Accuracy Visualisation: Supervised Machine Learning Classification Algorithms | by Kaushik Choudhury | Towards Data Science
|
Measuring the prediction accuracy of any regression or classification algorithm is vital in different stages during modelling and also when the model is live in production.
We have several ways to measure the accuracy of classification algorithms. In the Scikit-learn package, we have several scores like recall score, accuracy score etc. and then we have out of box summarised reports. In my view, most of these metrics have one or more limitations related to verbosity and difficult to understand, potential chance to misinterpret the accuracy in case of imbalance classes in the dataset, need to refer few of the scores to get holistic view etc.
To better understand the limitation, let us consider the example shown in the table. We have few parameters related to a sample of people and whether they are COVID positive. As we have more people who are COVID negative than people who are infected with the virus hence, I have considered a similar distribution in this example.
A classification algorithm trained on this datasets predicted the results as shown in the last column. The accuracy score of the classification model is close to 90 per cent. It gives us the impression that the model is quite good at predicting the result.
from sklearn.metrics import recall_scorefrom sklearn.metrics import classification_reportfrom sklearn.metrics import accuracy_score# 0- Healthy , 1- Covidy_true = [0, 1, 0,0,0, 1,0,0,0,0,0]y_pred = [0, 0, 0,0,0, 1,0,0,0,0,0]print("The recall Score is" , recall_score(y_true, y_pred))print("The accurracy score is" , accuracy_score(y_true, y_pred))
In reality, the model could predict the COVID positive cases with only 50 per cent times. Deploying such a model only based on one metric or without understanding the areas in which the classification model is making an error can be quite costly.
We can make a full sense of the model fit for production usage after considering both the recall and accuracy score and business use case.
A visual metric, like the confusion matrix, outshines other metrics in several ways. We get an instant view on the model performance in terms of classification areas the model excelled and the areas which require fine-tuning. Based on the business use case, we can judge quickly from the false positive, false negative, true positive and true negative counts whether the model is ready for deployment.
Let us learn to visualise and interpret the result of LinearSVCand LogisticRegression with confusion matrix.
Step 1: We will use the Scikit-learn inbuilt dataset WINE in this article for discussion and Matplotlib for visualisation. In the below code, we have imported the modules which we will be using in our program.
from sklearn.datasets import load_winefrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegressionfrom sklearn.svm import LinearSVCimport matplotlib.pyplot as pltfrom sklearn.metrics import plot_confusion_matrix
Step 2: The features ( attributes) in the Wine datasets divided into independent and dependent variables. Independent (input features) variables denoted by “X” and the dependent variable is denoted by “y”. Using the method train_test_split is divided into training and testing set.
X,y = load_wine(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10,random_state=0)
Step 3: Most of the supervised algorithms in sklearn require standard normally distributed input data centred around zero and have variance in the same order. As the independent variable values in the WINE dataset have a different scale, hence we need to scale it before using it in modelling.
If you would like to learn more about scaling the independent variables and different scalers in Scikit-learn package, then please refer my article Feature Scaling — Effect Of Different Scikit-Learn Scalers: Deep Dive.
SC_X=StandardScaler()X_train_Scaled=SC_X.fit_transform(X_train)X_test=Scaled=SC_X.transform(X_test)
Step 4: In the below code, a list of classifiers defined along with parameters
classifiers=[ LinearSVC(dual=False),LogisticRegression(solver="liblinear",max_iter=100)]
Step 5: Each classifier is used to train the model in sequence, and the confusion matrix is plotted based on the actual and predicted dependent variable value in the training set.
for clf in classifiers: clf.fit(X_train, y_train) y_pred = clf.predict(X_test) fig=plot_confusion_matrix(clf, X_test, y_test, display_labels=["Bad Wine","Fair Wine","Good Wine"]) fig.figure_.suptitle("Confusion Matrix for " + str(clf)) plt.show()
At first glance itself, we can see that the summation of figures from top left to bottom right diagonal is higher in Linear SVC compare to Logistics regression. It immediately suggests that Linear SVC performed better it identifying the true positive records.
Different metric scores can indicate the accuracy, but with confusion matrix, we can immediately see the classes which the algorithm is misclassifying. In the current example, both the classifiers missed in classifying most of the bad wines accurately. This level of detail information helps to perform focus fine-tuning of the model.
We have seen that the confusion matrix provides finer details about the classification model prediction pattern for different classes in a nice crisp way. In a single confusion matrix, We can get the details like false alarms (false positive) and correct rejection rates and decide whether the model is acceptable based on the business case.
|
[
{
"code": null,
"e": 345,
"s": 172,
"text": "Measuring the prediction accuracy of any regression or classification algorithm is vital in different stages during modelling and also when the model is live in production."
},
{
"code": null,
"e": 821,
"s": 345,
"text": "We have several ways to measure the accuracy of classification algorithms. In the Scikit-learn package, we have several scores like recall score, accuracy score etc. and then we have out of box summarised reports. In my view, most of these metrics have one or more limitations related to verbosity and difficult to understand, potential chance to misinterpret the accuracy in case of imbalance classes in the dataset, need to refer few of the scores to get holistic view etc."
},
{
"code": null,
"e": 1151,
"s": 821,
"text": "To better understand the limitation, let us consider the example shown in the table. We have few parameters related to a sample of people and whether they are COVID positive. As we have more people who are COVID negative than people who are infected with the virus hence, I have considered a similar distribution in this example."
},
{
"code": null,
"e": 1408,
"s": 1151,
"text": "A classification algorithm trained on this datasets predicted the results as shown in the last column. The accuracy score of the classification model is close to 90 per cent. It gives us the impression that the model is quite good at predicting the result."
},
{
"code": null,
"e": 1757,
"s": 1408,
"text": "from sklearn.metrics import recall_scorefrom sklearn.metrics import classification_reportfrom sklearn.metrics import accuracy_score# 0- Healthy , 1- Covidy_true = [0, 1, 0,0,0, 1,0,0,0,0,0]y_pred = [0, 0, 0,0,0, 1,0,0,0,0,0]print(\"The recall Score is\" , recall_score(y_true, y_pred))print(\"The accurracy score is\" , accuracy_score(y_true, y_pred))"
},
{
"code": null,
"e": 2004,
"s": 1757,
"text": "In reality, the model could predict the COVID positive cases with only 50 per cent times. Deploying such a model only based on one metric or without understanding the areas in which the classification model is making an error can be quite costly."
},
{
"code": null,
"e": 2143,
"s": 2004,
"text": "We can make a full sense of the model fit for production usage after considering both the recall and accuracy score and business use case."
},
{
"code": null,
"e": 2545,
"s": 2143,
"text": "A visual metric, like the confusion matrix, outshines other metrics in several ways. We get an instant view on the model performance in terms of classification areas the model excelled and the areas which require fine-tuning. Based on the business use case, we can judge quickly from the false positive, false negative, true positive and true negative counts whether the model is ready for deployment."
},
{
"code": null,
"e": 2654,
"s": 2545,
"text": "Let us learn to visualise and interpret the result of LinearSVCand LogisticRegression with confusion matrix."
},
{
"code": null,
"e": 2864,
"s": 2654,
"text": "Step 1: We will use the Scikit-learn inbuilt dataset WINE in this article for discussion and Matplotlib for visualisation. In the below code, we have imported the modules which we will be using in our program."
},
{
"code": null,
"e": 3168,
"s": 2864,
"text": "from sklearn.datasets import load_winefrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegressionfrom sklearn.svm import LinearSVCimport matplotlib.pyplot as pltfrom sklearn.metrics import plot_confusion_matrix"
},
{
"code": null,
"e": 3450,
"s": 3168,
"text": "Step 2: The features ( attributes) in the Wine datasets divided into independent and dependent variables. Independent (input features) variables denoted by “X” and the dependent variable is denoted by “y”. Using the method train_test_split is divided into training and testing set."
},
{
"code": null,
"e": 3571,
"s": 3450,
"text": "X,y = load_wine(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10,random_state=0)"
},
{
"code": null,
"e": 3865,
"s": 3571,
"text": "Step 3: Most of the supervised algorithms in sklearn require standard normally distributed input data centred around zero and have variance in the same order. As the independent variable values in the WINE dataset have a different scale, hence we need to scale it before using it in modelling."
},
{
"code": null,
"e": 4084,
"s": 3865,
"text": "If you would like to learn more about scaling the independent variables and different scalers in Scikit-learn package, then please refer my article Feature Scaling — Effect Of Different Scikit-Learn Scalers: Deep Dive."
},
{
"code": null,
"e": 4184,
"s": 4084,
"text": "SC_X=StandardScaler()X_train_Scaled=SC_X.fit_transform(X_train)X_test=Scaled=SC_X.transform(X_test)"
},
{
"code": null,
"e": 4263,
"s": 4184,
"text": "Step 4: In the below code, a list of classifiers defined along with parameters"
},
{
"code": null,
"e": 4352,
"s": 4263,
"text": "classifiers=[ LinearSVC(dual=False),LogisticRegression(solver=\"liblinear\",max_iter=100)]"
},
{
"code": null,
"e": 4532,
"s": 4352,
"text": "Step 5: Each classifier is used to train the model in sequence, and the confusion matrix is plotted based on the actual and predicted dependent variable value in the training set."
},
{
"code": null,
"e": 4795,
"s": 4532,
"text": "for clf in classifiers: clf.fit(X_train, y_train) y_pred = clf.predict(X_test) fig=plot_confusion_matrix(clf, X_test, y_test, display_labels=[\"Bad Wine\",\"Fair Wine\",\"Good Wine\"]) fig.figure_.suptitle(\"Confusion Matrix for \" + str(clf)) plt.show()"
},
{
"code": null,
"e": 5055,
"s": 4795,
"text": "At first glance itself, we can see that the summation of figures from top left to bottom right diagonal is higher in Linear SVC compare to Logistics regression. It immediately suggests that Linear SVC performed better it identifying the true positive records."
},
{
"code": null,
"e": 5390,
"s": 5055,
"text": "Different metric scores can indicate the accuracy, but with confusion matrix, we can immediately see the classes which the algorithm is misclassifying. In the current example, both the classifiers missed in classifying most of the bad wines accurately. This level of detail information helps to perform focus fine-tuning of the model."
}
] |
CSS :focus Selector - GeeksforGeeks
|
21 Oct, 2021
The :focus CSS pseudo-class Selector is used to target the focused element ie., it selects an element that is currently focused by the user. This selector works on user input elements, generally used in forms, and is triggered as soon as the user clicks on it or taps on an element, or selects any keyboard events.
Syntax:
:focus {
// CSS property
}
Example: This example illustrates the :focus selector to target the selected element.
HTML
<!DOCTYPE html><html><head> <style> input:focus { background-color: limegreen; } </style></head> <body> <h3>Fill this form</h3> <form> Full name: <input type="text" placeholder="Enter Name" name="name"> <br> User Id: <input type="text" placeholder="Enter Username" name="uid"> <br> Password: <input type="password" placeholder="Enter Password" name="pass"> <br> <button type="button" onclick="#">Sign Up</button> </form></body></html>
Output:
Supported Browsers:
Google Chrome 4.0
Microsoft Edge 12.0
Internet Explorer 8.0
Firefox 2.0
Safari 3.1
Opera 9.6
bhaskargeeksforgeeks
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
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": 24425,
"s": 24397,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 24740,
"s": 24425,
"text": "The :focus CSS pseudo-class Selector is used to target the focused element ie., it selects an element that is currently focused by the user. This selector works on user input elements, generally used in forms, and is triggered as soon as the user clicks on it or taps on an element, or selects any keyboard events."
},
{
"code": null,
"e": 24748,
"s": 24740,
"text": "Syntax:"
},
{
"code": null,
"e": 24777,
"s": 24748,
"text": ":focus {\n // CSS property\n}"
},
{
"code": null,
"e": 24863,
"s": 24777,
"text": "Example: This example illustrates the :focus selector to target the selected element."
},
{
"code": null,
"e": 24868,
"s": 24863,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <style> input:focus { background-color: limegreen; } </style></head> <body> <h3>Fill this form</h3> <form> Full name: <input type=\"text\" placeholder=\"Enter Name\" name=\"name\"> <br> User Id: <input type=\"text\" placeholder=\"Enter Username\" name=\"uid\"> <br> Password: <input type=\"password\" placeholder=\"Enter Password\" name=\"pass\"> <br> <button type=\"button\" onclick=\"#\">Sign Up</button> </form></body></html>",
"e": 25479,
"s": 24868,
"text": null
},
{
"code": null,
"e": 25487,
"s": 25479,
"text": "Output:"
},
{
"code": null,
"e": 25507,
"s": 25487,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 25525,
"s": 25507,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 25545,
"s": 25525,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 25567,
"s": 25545,
"text": "Internet Explorer 8.0"
},
{
"code": null,
"e": 25579,
"s": 25567,
"text": "Firefox 2.0"
},
{
"code": null,
"e": 25590,
"s": 25579,
"text": "Safari 3.1"
},
{
"code": null,
"e": 25600,
"s": 25590,
"text": "Opera 9.6"
},
{
"code": null,
"e": 25621,
"s": 25600,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 25635,
"s": 25621,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 25639,
"s": 25635,
"text": "CSS"
},
{
"code": null,
"e": 25656,
"s": 25639,
"text": "Web Technologies"
},
{
"code": null,
"e": 25754,
"s": 25656,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25804,
"s": 25754,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25866,
"s": 25804,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25914,
"s": 25866,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25972,
"s": 25914,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26027,
"s": 25972,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 26067,
"s": 26027,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26100,
"s": 26067,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26145,
"s": 26100,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26188,
"s": 26145,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
10 Surprisingly Useful Base Python Functions | by Emmett Boudreau | Towards Data Science
|
Those that work in Python often consider that maybe Python isn’t the star of the show here — but instead its brilliant ecosystem. Often whenever we are working with Python applications, we are working with a lot of dependencies. Python on its own isn’t particularly good at anything, but it is instead its wonderful packages that bring the functionality to the base.
Whenever I have this discussion, I often think of NumPy as an example. While matrix math might be possible with vanilla Python, utilizing NumPy makes it substantially better — and even faster. That being said, while often it seems Python developers do rely a lot on external tools to process certain datatypes and work mathematically especially, the Python language does have some really cool tricks up its sleeve that do make it appeal to a scientific programming audience. Using these tricks you can keep your dependencies down, free up your time, and generally make programming a lot easier in the Python programming language! Next time you are thinking of installing something with Pip, you’ll be able to also consider the options available in the standard library!
I wrote an article a while back on why I think Python’s lambda makes it a far more viable programming language for statistical computing. Furthermore, since Python disobeys some more restrictive object-oriented rules, it is able to act very functionally and declarative — bringing the conversation to lambda, which can be used to apply mathematical operations to any datatype by using expression evaluation rather than entire functions. This can be used for things that are more simple to program, and likely don’t need an entire function to their name. You could even define these in a global scope, since it is Python, and take Python to another scientific level by leveraging functional-like syntax and methodology in a language that still has class structure.
While this concept might seem like a small bump to some, utilizing it saves time, memory, and can make your code look a lot more concise. Along with lambda, since the return is a Pythonic expression, we also get the ability to use methods like apply() to apply expressions quickly across entire subsets of data. Needless to say, for a Data Scientist these operations come plenty in handy, and being able to do them in one line very effectively makes our global-everything style of programming a lot easier in Python! The syntax goes like this; we start by setting a value equal to the return of lambda followed by the variable we would like to have provided as a positional argument. Then we perform our operation using that provided argument as a variable, for example the mean:
mean = lambda x : sum(x) / len(x)
Now we could call it just as we would any method in the Python programming language:
x = [5, 10, 15, 20]print(mean(x))
If you would like to read more about Lambda, why I love it, and how to use it, I wrote another article on it as well. The great thing about this article is that it goes in-depth and shows various tricks that Lambda can be used with in Python. Check it out!:
towardsdatascience.com
One of the most underrated tools in the Pythonic arsenal is the Shutil module. Like the other modules on this list, this is included in the standard library and can be imported as you usually would any module in the language:
import shutil
So what does shutil do? The shutil module is a high-level interface for the Python programming language for the file-system on your operating system. While these calls are often made using the os module, it is the shutil module that is lesser-known and I think should be used more often. How often have you needed to quickly move a file from directory to directory with a script and had to do a whole surplus of tedious work just to get it done?
Shutil solves these classic problems with files and allocation tables by making a high-level solution to a common problem. Even compared to many other high-level, and sometimes dramatically declarative programming languages, this solution blows them out of the water. For all of your dev-ops implementations, this is certainly a key to save a lot of time and make file operations far faster than they would be otherwise. Below are some examples of the high-level calls that the shutil module provides for some basic file operations:
import shutilshutil.copyfile('mydatabase.db', 'archive.db')shutil.move('/src/High.py', '/packages/High')
While the glob module might not be as cool as shutil, or nearly as useful for programming in a general sense as Lambda, the module is still pretty useful for certain situations. The glob module is used to search directories for wildcards. This means that it can be used to aggregate data about files and file-extensions stored on your machine. Of course, this module is imported precisely how you might expect it to be:
import glob
In all honesty, I am not sure if this module contains more than a single function, but that function is quite commonly used for the module’s exact purpose. This function is the glob() function. This function will take any typical file searches. This includes file-searches with Unix syntax, i.e. *, /, etc. Check it out:
glob.glob('*.ipynb')
This returns a list of file names that correspond to the files found by the glob’s search. This could also be used for aggregating data, or it could be used for working with files that store data!
The argparse module provides a more robust and in-depth method to parse command-line arguments. Many dev-ops tools utilize this concept so that they can be interacted with from the Unix command line. This is useful for many dev-ops tools that are commonly used by Python developers and Data Scientists. A great example of this would be the Python module Gunicorn, which can process passed command-line arguments for workers and various other parameters. Just as before, this module must be imported to be used:
import argparse
In order to use this module, we will build a new type which will be an argument parser:
parser = argparse.ArgumentParser(prog = 'top',description = 'Show top lines from the file')
Now we add arguments to our parser using the add an argument to this new reader. For this case, we will create an argument which can be passed to determine the number of lines we want printed from each file:
parser.add_argument('-l', '--lines', type=int, default=10)
I added a few key-word arguments, one of which will provide the datatype that we are expecting to be passed for this argument, and the other is a default value for when the file is called without this argument in place. Now we can get the arguments out by calling the parse_args() function on our new argument parser type:
args = parser.parse_args()
Now we can call this Python file for compilation while also providing the necessary parameters easily from Bash.
python top.py --lines=5 examplefile.txt
Needless to say, this could certainly come in handy. Some notable situations where I have used this module is when working with Crontab, which can run scripts at specific Unix timestamps. Furthermore, this script could also be used for supervisors, which run Bash commands without a user being present as a worker. If you’d like to learn more about crontab, I have a whole article talking about why I love it here:
towardsdatascience.com
Furthermore, if you’d like to learn more about some of the other applications that I use to deploy Pythonic endpoints and websites, I have a whole article detailing an A-Z deployment with a self-training machine-learning model you can check out here:
medium.com
Of all of the tools I have reviewed today so far, the re module is by-far the most critically underrated. The “ R” and “ E” in re is short for regular expressions. The re module is used to parse strings with regular expressions and provide more options for working with strings in Python. How many times have you ran into making algorithmic decisions based on functions that the string class has like str.split()? No more of that because regular expressions are far simpler, and a lot easier to use!
import re
The re module, unlike some of the others on this list, provides a lot of very useful functions; particularly for working with copious amounts of data as Scientists typically do. That being said, two examples that will get you started are the sub() and findall() functions.
import rere.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')['foot', 'fell', 'fastest']re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')'cat in the hat'
Needless to say, this could be very useful for working with data that is often encountered in this world.
Ok — hear me out. Math might not be the greatest module in the history of the standard library, but it does frequently come in handy. This of course is even more true for scientific computing. The math module gives way to access to everything from sin and cos all the way to logarithms. All of these things can come in handy when working with algorithms, needless to say, and many packages do depend on this basic module to get a lot of things done.
import math
The module can certainly save some time by making mathematical operations easily available without dependencies. For this example, I will be demonstrating the log() function, but you could most certainly look further into this module and find a whole world of mathematical capabilities!
import mathmath.log(1024, 2)
Another package that is almost certainly a no-brainer for scientific computing is the statistics module. This module provides some elementary statistics that might not go as in-depth as something like SciPy, but can still suffice quite frequently for data analysis. While inferential and Bayesian statistics might not be a key focus of this package, mathematical values can such as the mean or standard deviation can tell a lot about the data that you might be working with. I frequently alias this module as st, but I have also seen it aliased as stc or sts, not to be confused with the common alias scs for Scipy.stats.
import statistics as st
There are plenty of useful functions provided by this module that are certainly worth checking out! The great thing about this package is that it will always be there, whether you need it or not, and it won’t require any dependencies. Let’s look at some basic general-purpose statistical operations that are easily provided with this package:
import statistics as stst.mean(data)st.median(data)st.variance(data)
While many of these packages might not be all that well-known, the urllib module is most certainly an exception to that rule. This module can be used to handle many common web-related tasks such as requests. Let’s import it!
import urllib
Often requests are something that Data Scientists do with a dependency. A common too that fits this description is Flask’s requests module. This module is another commonly used solution for requests, and comes with more functionality than urllib, such as the ability to request query arguments from the http request. That being said, it can be convenient to use the standard library and worry a lot less about dependencies so long as the project doesn’t require these extra features.
from urllib.request import urlopendata = nullwith urlopen('http://example_url/') as response: data = response
Although the urlopen function is certainly a great example for a common usage of urllib, there is a lot of functionality to be had in this relatively small package, and it is definitely a tool that is worth learning in my opinion.
Another great example of a tool that is quite common amongst scientific computing is a date-time type. It is very common that data is going to have timestamps, sometimes timestamps are even the predictive feature that is going to be training our model. That being said, working with dates and times might be a relatively important concept for a Data Scientist. We can import the date-time module exactly how you might expect; it is very common to see this module aliased as dt, so for this example I am going to be doing precisely that:
import datetime as dt
Now we can construct date-time types and work with the typical date-time syntax with properties like year, month, and day. This is incredibly useful for re-formatting, parsing, and working with individual sections of dates within your data. Let’s take a look at some basic functionality from this package:
import datetime as dtnow = dt.date.today()print(now.year)print(now.month)
The final contender on this list is the zlib module. The zlib module is an all-around solution for compressing data using the Python programming language. This can come in handy for package distribution, especially if package distribution is entirely automated. One great thing about Python is that it can be used as a fantastic automation tool. That being said, being able to automatically compress a tarball and then even send it somewhere else is a pretty valuable asset.
import zlib
Within the zlib module, the most important functions are probably compress() and decompress(). Using these functions, we can actually see the compression of datatypes before our eyes using this code:
h = " Hello, it is me, you're friend Emmett!"print(len(h))t = zlib.compress(h)print(len(t))z = decompress(t)print(len(z))
Although often in Pythonic programming it can seem like there is a high reliance on dependencies, the Python standard library also has some really neat tools in it! A lot of these tools can quickly be used to save a substantial amount of time by making a high-level interface for complex tasks that is packaged with the programming language itself. This can be used to minimize dependent packages, virtual environments, and general clutter around a server. Furthermore, there is no need to pip install any packages, so a lot of time is saved with this initiative.
These are only some of my favorite modules that are available in the standard library, however there are plenty more! While these modules will certainly come in handy, I am certainly sure that there are plenty of other packages available that will make a lot of programming operations a lot easier than they would be otherwise.
|
[
{
"code": null,
"e": 539,
"s": 172,
"text": "Those that work in Python often consider that maybe Python isn’t the star of the show here — but instead its brilliant ecosystem. Often whenever we are working with Python applications, we are working with a lot of dependencies. Python on its own isn’t particularly good at anything, but it is instead its wonderful packages that bring the functionality to the base."
},
{
"code": null,
"e": 1309,
"s": 539,
"text": "Whenever I have this discussion, I often think of NumPy as an example. While matrix math might be possible with vanilla Python, utilizing NumPy makes it substantially better — and even faster. That being said, while often it seems Python developers do rely a lot on external tools to process certain datatypes and work mathematically especially, the Python language does have some really cool tricks up its sleeve that do make it appeal to a scientific programming audience. Using these tricks you can keep your dependencies down, free up your time, and generally make programming a lot easier in the Python programming language! Next time you are thinking of installing something with Pip, you’ll be able to also consider the options available in the standard library!"
},
{
"code": null,
"e": 2073,
"s": 1309,
"text": "I wrote an article a while back on why I think Python’s lambda makes it a far more viable programming language for statistical computing. Furthermore, since Python disobeys some more restrictive object-oriented rules, it is able to act very functionally and declarative — bringing the conversation to lambda, which can be used to apply mathematical operations to any datatype by using expression evaluation rather than entire functions. This can be used for things that are more simple to program, and likely don’t need an entire function to their name. You could even define these in a global scope, since it is Python, and take Python to another scientific level by leveraging functional-like syntax and methodology in a language that still has class structure."
},
{
"code": null,
"e": 2853,
"s": 2073,
"text": "While this concept might seem like a small bump to some, utilizing it saves time, memory, and can make your code look a lot more concise. Along with lambda, since the return is a Pythonic expression, we also get the ability to use methods like apply() to apply expressions quickly across entire subsets of data. Needless to say, for a Data Scientist these operations come plenty in handy, and being able to do them in one line very effectively makes our global-everything style of programming a lot easier in Python! The syntax goes like this; we start by setting a value equal to the return of lambda followed by the variable we would like to have provided as a positional argument. Then we perform our operation using that provided argument as a variable, for example the mean:"
},
{
"code": null,
"e": 2887,
"s": 2853,
"text": "mean = lambda x : sum(x) / len(x)"
},
{
"code": null,
"e": 2972,
"s": 2887,
"text": "Now we could call it just as we would any method in the Python programming language:"
},
{
"code": null,
"e": 3006,
"s": 2972,
"text": "x = [5, 10, 15, 20]print(mean(x))"
},
{
"code": null,
"e": 3264,
"s": 3006,
"text": "If you would like to read more about Lambda, why I love it, and how to use it, I wrote another article on it as well. The great thing about this article is that it goes in-depth and shows various tricks that Lambda can be used with in Python. Check it out!:"
},
{
"code": null,
"e": 3287,
"s": 3264,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3513,
"s": 3287,
"text": "One of the most underrated tools in the Pythonic arsenal is the Shutil module. Like the other modules on this list, this is included in the standard library and can be imported as you usually would any module in the language:"
},
{
"code": null,
"e": 3527,
"s": 3513,
"text": "import shutil"
},
{
"code": null,
"e": 3973,
"s": 3527,
"text": "So what does shutil do? The shutil module is a high-level interface for the Python programming language for the file-system on your operating system. While these calls are often made using the os module, it is the shutil module that is lesser-known and I think should be used more often. How often have you needed to quickly move a file from directory to directory with a script and had to do a whole surplus of tedious work just to get it done?"
},
{
"code": null,
"e": 4506,
"s": 3973,
"text": "Shutil solves these classic problems with files and allocation tables by making a high-level solution to a common problem. Even compared to many other high-level, and sometimes dramatically declarative programming languages, this solution blows them out of the water. For all of your dev-ops implementations, this is certainly a key to save a lot of time and make file operations far faster than they would be otherwise. Below are some examples of the high-level calls that the shutil module provides for some basic file operations:"
},
{
"code": null,
"e": 4611,
"s": 4506,
"text": "import shutilshutil.copyfile('mydatabase.db', 'archive.db')shutil.move('/src/High.py', '/packages/High')"
},
{
"code": null,
"e": 5031,
"s": 4611,
"text": "While the glob module might not be as cool as shutil, or nearly as useful for programming in a general sense as Lambda, the module is still pretty useful for certain situations. The glob module is used to search directories for wildcards. This means that it can be used to aggregate data about files and file-extensions stored on your machine. Of course, this module is imported precisely how you might expect it to be:"
},
{
"code": null,
"e": 5043,
"s": 5031,
"text": "import glob"
},
{
"code": null,
"e": 5364,
"s": 5043,
"text": "In all honesty, I am not sure if this module contains more than a single function, but that function is quite commonly used for the module’s exact purpose. This function is the glob() function. This function will take any typical file searches. This includes file-searches with Unix syntax, i.e. *, /, etc. Check it out:"
},
{
"code": null,
"e": 5385,
"s": 5364,
"text": "glob.glob('*.ipynb')"
},
{
"code": null,
"e": 5582,
"s": 5385,
"text": "This returns a list of file names that correspond to the files found by the glob’s search. This could also be used for aggregating data, or it could be used for working with files that store data!"
},
{
"code": null,
"e": 6093,
"s": 5582,
"text": "The argparse module provides a more robust and in-depth method to parse command-line arguments. Many dev-ops tools utilize this concept so that they can be interacted with from the Unix command line. This is useful for many dev-ops tools that are commonly used by Python developers and Data Scientists. A great example of this would be the Python module Gunicorn, which can process passed command-line arguments for workers and various other parameters. Just as before, this module must be imported to be used:"
},
{
"code": null,
"e": 6109,
"s": 6093,
"text": "import argparse"
},
{
"code": null,
"e": 6197,
"s": 6109,
"text": "In order to use this module, we will build a new type which will be an argument parser:"
},
{
"code": null,
"e": 6289,
"s": 6197,
"text": "parser = argparse.ArgumentParser(prog = 'top',description = 'Show top lines from the file')"
},
{
"code": null,
"e": 6497,
"s": 6289,
"text": "Now we add arguments to our parser using the add an argument to this new reader. For this case, we will create an argument which can be passed to determine the number of lines we want printed from each file:"
},
{
"code": null,
"e": 6556,
"s": 6497,
"text": "parser.add_argument('-l', '--lines', type=int, default=10)"
},
{
"code": null,
"e": 6879,
"s": 6556,
"text": "I added a few key-word arguments, one of which will provide the datatype that we are expecting to be passed for this argument, and the other is a default value for when the file is called without this argument in place. Now we can get the arguments out by calling the parse_args() function on our new argument parser type:"
},
{
"code": null,
"e": 6906,
"s": 6879,
"text": "args = parser.parse_args()"
},
{
"code": null,
"e": 7019,
"s": 6906,
"text": "Now we can call this Python file for compilation while also providing the necessary parameters easily from Bash."
},
{
"code": null,
"e": 7059,
"s": 7019,
"text": "python top.py --lines=5 examplefile.txt"
},
{
"code": null,
"e": 7474,
"s": 7059,
"text": "Needless to say, this could certainly come in handy. Some notable situations where I have used this module is when working with Crontab, which can run scripts at specific Unix timestamps. Furthermore, this script could also be used for supervisors, which run Bash commands without a user being present as a worker. If you’d like to learn more about crontab, I have a whole article talking about why I love it here:"
},
{
"code": null,
"e": 7497,
"s": 7474,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7748,
"s": 7497,
"text": "Furthermore, if you’d like to learn more about some of the other applications that I use to deploy Pythonic endpoints and websites, I have a whole article detailing an A-Z deployment with a self-training machine-learning model you can check out here:"
},
{
"code": null,
"e": 7759,
"s": 7748,
"text": "medium.com"
},
{
"code": null,
"e": 8259,
"s": 7759,
"text": "Of all of the tools I have reviewed today so far, the re module is by-far the most critically underrated. The “ R” and “ E” in re is short for regular expressions. The re module is used to parse strings with regular expressions and provide more options for working with strings in Python. How many times have you ran into making algorithmic decisions based on functions that the string class has like str.split()? No more of that because regular expressions are far simpler, and a lot easier to use!"
},
{
"code": null,
"e": 8269,
"s": 8259,
"text": "import re"
},
{
"code": null,
"e": 8542,
"s": 8269,
"text": "The re module, unlike some of the others on this list, provides a lot of very useful functions; particularly for working with copious amounts of data as Scientists typically do. That being said, two examples that will get you started are the sub() and findall() functions."
},
{
"code": null,
"e": 8707,
"s": 8542,
"text": "import rere.findall(r'\\bf[a-z]*', 'which foot or hand fell fastest')['foot', 'fell', 'fastest']re.sub(r'(\\b[a-z]+) \\1', r'\\1', 'cat in the the hat')'cat in the hat'"
},
{
"code": null,
"e": 8813,
"s": 8707,
"text": "Needless to say, this could be very useful for working with data that is often encountered in this world."
},
{
"code": null,
"e": 9263,
"s": 8813,
"text": "Ok — hear me out. Math might not be the greatest module in the history of the standard library, but it does frequently come in handy. This of course is even more true for scientific computing. The math module gives way to access to everything from sin and cos all the way to logarithms. All of these things can come in handy when working with algorithms, needless to say, and many packages do depend on this basic module to get a lot of things done."
},
{
"code": null,
"e": 9275,
"s": 9263,
"text": "import math"
},
{
"code": null,
"e": 9562,
"s": 9275,
"text": "The module can certainly save some time by making mathematical operations easily available without dependencies. For this example, I will be demonstrating the log() function, but you could most certainly look further into this module and find a whole world of mathematical capabilities!"
},
{
"code": null,
"e": 9591,
"s": 9562,
"text": "import mathmath.log(1024, 2)"
},
{
"code": null,
"e": 10213,
"s": 9591,
"text": "Another package that is almost certainly a no-brainer for scientific computing is the statistics module. This module provides some elementary statistics that might not go as in-depth as something like SciPy, but can still suffice quite frequently for data analysis. While inferential and Bayesian statistics might not be a key focus of this package, mathematical values can such as the mean or standard deviation can tell a lot about the data that you might be working with. I frequently alias this module as st, but I have also seen it aliased as stc or sts, not to be confused with the common alias scs for Scipy.stats."
},
{
"code": null,
"e": 10237,
"s": 10213,
"text": "import statistics as st"
},
{
"code": null,
"e": 10580,
"s": 10237,
"text": "There are plenty of useful functions provided by this module that are certainly worth checking out! The great thing about this package is that it will always be there, whether you need it or not, and it won’t require any dependencies. Let’s look at some basic general-purpose statistical operations that are easily provided with this package:"
},
{
"code": null,
"e": 10649,
"s": 10580,
"text": "import statistics as stst.mean(data)st.median(data)st.variance(data)"
},
{
"code": null,
"e": 10874,
"s": 10649,
"text": "While many of these packages might not be all that well-known, the urllib module is most certainly an exception to that rule. This module can be used to handle many common web-related tasks such as requests. Let’s import it!"
},
{
"code": null,
"e": 10888,
"s": 10874,
"text": "import urllib"
},
{
"code": null,
"e": 11372,
"s": 10888,
"text": "Often requests are something that Data Scientists do with a dependency. A common too that fits this description is Flask’s requests module. This module is another commonly used solution for requests, and comes with more functionality than urllib, such as the ability to request query arguments from the http request. That being said, it can be convenient to use the standard library and worry a lot less about dependencies so long as the project doesn’t require these extra features."
},
{
"code": null,
"e": 11482,
"s": 11372,
"text": "from urllib.request import urlopendata = nullwith urlopen('http://example_url/') as response: data = response"
},
{
"code": null,
"e": 11713,
"s": 11482,
"text": "Although the urlopen function is certainly a great example for a common usage of urllib, there is a lot of functionality to be had in this relatively small package, and it is definitely a tool that is worth learning in my opinion."
},
{
"code": null,
"e": 12250,
"s": 11713,
"text": "Another great example of a tool that is quite common amongst scientific computing is a date-time type. It is very common that data is going to have timestamps, sometimes timestamps are even the predictive feature that is going to be training our model. That being said, working with dates and times might be a relatively important concept for a Data Scientist. We can import the date-time module exactly how you might expect; it is very common to see this module aliased as dt, so for this example I am going to be doing precisely that:"
},
{
"code": null,
"e": 12272,
"s": 12250,
"text": "import datetime as dt"
},
{
"code": null,
"e": 12578,
"s": 12272,
"text": "Now we can construct date-time types and work with the typical date-time syntax with properties like year, month, and day. This is incredibly useful for re-formatting, parsing, and working with individual sections of dates within your data. Let’s take a look at some basic functionality from this package:"
},
{
"code": null,
"e": 12652,
"s": 12578,
"text": "import datetime as dtnow = dt.date.today()print(now.year)print(now.month)"
},
{
"code": null,
"e": 13127,
"s": 12652,
"text": "The final contender on this list is the zlib module. The zlib module is an all-around solution for compressing data using the Python programming language. This can come in handy for package distribution, especially if package distribution is entirely automated. One great thing about Python is that it can be used as a fantastic automation tool. That being said, being able to automatically compress a tarball and then even send it somewhere else is a pretty valuable asset."
},
{
"code": null,
"e": 13139,
"s": 13127,
"text": "import zlib"
},
{
"code": null,
"e": 13339,
"s": 13139,
"text": "Within the zlib module, the most important functions are probably compress() and decompress(). Using these functions, we can actually see the compression of datatypes before our eyes using this code:"
},
{
"code": null,
"e": 13461,
"s": 13339,
"text": "h = \" Hello, it is me, you're friend Emmett!\"print(len(h))t = zlib.compress(h)print(len(t))z = decompress(t)print(len(z))"
},
{
"code": null,
"e": 14025,
"s": 13461,
"text": "Although often in Pythonic programming it can seem like there is a high reliance on dependencies, the Python standard library also has some really neat tools in it! A lot of these tools can quickly be used to save a substantial amount of time by making a high-level interface for complex tasks that is packaged with the programming language itself. This can be used to minimize dependent packages, virtual environments, and general clutter around a server. Furthermore, there is no need to pip install any packages, so a lot of time is saved with this initiative."
}
] |
Fetching top news using News API - GeeksforGeeks
|
20 Nov, 2021
News API is a simple JSON-based REST API for searching and retrieving news articles from all over the web. Using this, one can fetch the top stories running on a news website or can search top news on a specific topic (or keyword).
News can be retrieved based on some criteria. Say the topic (keyword) to be searched is ‘Geeksforgeeks’ or might be concerned to a specific channel. All can be done, but the API key is needed to get started.
Steps :
1. Visit https://newsapi.org/ to get your own API key.
2. Install requests package.
Below is the implementation of the above idea :
Python3
# importing requests packageimport requests def NewsFromBBC(): # BBC news api # following query parameters are used # source, sortBy and apiKey query_params = { "source": "bbc-news", "sortBy": "top", "apiKey": "4dbc17e007ab436fb66416009dfb59a8" } main_url = " https://newsapi.org/v1/articles" # fetching data in json format res = requests.get(main_url, params=query_params) open_bbc_page = res.json() # getting all articles in a string article article = open_bbc_page["articles"] # empty list which will # contain all trending news results = [] for ar in article: results.append(ar["title"]) for i in range(len(results)): # printing all trending news print(i + 1, results[i]) #to read the news out loud for us from win32com.client import Dispatch speak = Dispatch("SAPI.Spvoice") speak.Speak(results) # Driver Codeif __name__ == '__main__': # function call NewsFromBBC()
Output :
1 Italy to lift coronavirus travel restrictions
2 White House 'Operation Warp Speed' to look for Covid jab
3 Two Americas in the nation's capital
4 Kobe Bryant helicopter crash post-mortem released
5 Little things people are doing while socially distanced
6 The last 'normal' photo on your phone
7 'They came to kill the mothers'
8 EU-UK Brexit trade talks in trouble
9 Trial starts to see if dogs can 'sniff out' virus
10 Beatles photographer Astrid Kirchherr dies aged 81
Note: Output may change based on the top articles at the time.
This approach will work as a cherry on a cake because it will display the news according to the category entered by the user so as work as a filter for those who want to know the news in a particular category/section.
First of all install newsapi and pycountry in your system if it’s not there the install using the command below:
~ pip install newsapi-python
~ pip install pycountry
Python3
from newsapi import NewsApiClientimport pycountry # you have to get your api key from newapi.com and then paste it belownewsapi = NewsApiClient(api_key='Your API Key') # now we will take name of country from user as inputinput_country = input("Country: ")input_countries = [f'{input_country.strip()}']countries = {} # iterate over all the countries in# the world using pycountry modulefor country in pycountry.countries: # and store the unique code of each country # in the dictionary along with it's full name countries[country.name] = country.alpha_2 # now we will check that the entered country name is# valid or invalid using the unique codecodes = [countries.get(country.title(), 'Unknown code') for country in input_countries] # now we have to display all the categories from which user will# decide and enter the name of that categoryoption = input("Which category are you interested in?\n1.Business\n2.Entertainment\n3.General\n4.Health\n5.Science\n6.Technology\n\nEnter here: ") # now we will fetch the new according to the choice of the usertop_headlines = newsapi.get_top_headlines( # getting top headlines from all the news channels category=f'{option.lower()}', language='en', country=f'{codes[0].lower()}') # fetch the top news inder that category Headlines = top_headlines['articles'] # now we will display the that news with a good readability for user if Headlines: for articles in Headlines: b = articles['title'][::-1].index("-") if "news" in (articles['title'][-b+1:]).lower(): print( f"{articles['title'][-b+1:]}: {articles['title'][:-b-2]}.") else: print( f"{articles['title'][-b+1:]} News: {articles['title'][:-b-2]}.") else: print( f"Sorry no articles found for {input_country}, Something Wrong!!!") option = input("Do you want to search again[Yes/No]?") if option.lower() == 'yes': continue else: exit()
Input:
Country: India
Which category are you interested in?
1.Business
2.Entertainment
3.General
4.Health
5.Science
6.Technology
Enter here: Technology
Output:
Gizbot News: Garena Free Fire Redeem Codes For August 16; Get Master of Minds Weapon Loot Crate.
News18: Google Pixel 5a Will Have Biggest Battery On Any Pixel Phone Ever, Launch This Month.
Hindustan Times News: PUBG Mobile: Here’s how to get the Unhinged Mortician set on PUBG Mobile, check details of RPM2 Royale Pass.
Times of India News: New iPhones, Watch, AirPods and more: What Apple may launch in September.
GSMArena.com News: Top 10 trending phones of week 32 - GSMArena.com news.
Hindustan Times News: Study finds if 'people persons' are 'machine persons' when they interact online.
Times of India News: 2021 vs 2020: August gasps for one ‘good’ air day in Gurugram this year.
ScienceAlert News: A Simple Crystal Could Finally Give Us Large-Scale Quantum Computing, Scientists Say.
Engadget News: The Switch is the first console to sweep Japan's game sales chart in 33 years.
GSMArena.com News: Weekly poll: Samsung Galaxy Z Fold3, the new S Pen and the Galaxy Z Flip3 - GSMArena.com news.
Market Research Telecast News: How to import your WhatsApp chats to WhatsApp Plus 17.00 Heymods.
Notebookcheck.net News: Realme will finally debut its first-gen laptop later in August 2021.
NewsBytes: Redmi 10 officially teased; color options revealed.
The Siasat Daily News: Xiaomi removes anti-lost mode from Mi Mix 4.
Zee News: Good news for Motorola Razr owners! Smartphone is finally getting Android 11 update.
EssentiallySports News: Animal Crossing: New Horizons- Predictions for the Next Big Update.
Republic World News: Motorola Edge 20 price in India Leaked: Price to range between Rs 21,499 to Rs 29,999.
Eurogamer.net News: Assassinations have been temporarily removed from Halo Infinite because "people just turn them off".
EssentiallySports News: Call of Duty: Warzone- If You Can Win a Game Despite the Hackers, You Can See a Vanguard Teaser.
Techradar News: Facebook Messenger voice and video calls are getting end-to-end encryption.
Do you want to search again[Yes/No]? No
araxk19
kumarv456
adityatri
arorakashish0911
Python-projects
python-utility
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23969,
"s": 23941,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 24201,
"s": 23969,
"text": "News API is a simple JSON-based REST API for searching and retrieving news articles from all over the web. Using this, one can fetch the top stories running on a news website or can search top news on a specific topic (or keyword)."
},
{
"code": null,
"e": 24410,
"s": 24201,
"text": "News can be retrieved based on some criteria. Say the topic (keyword) to be searched is ‘Geeksforgeeks’ or might be concerned to a specific channel. All can be done, but the API key is needed to get started. "
},
{
"code": null,
"e": 24504,
"s": 24410,
"text": "Steps :\n\n1. Visit https://newsapi.org/ to get your own API key.\n\n2. Install requests package."
},
{
"code": null,
"e": 24553,
"s": 24504,
"text": "Below is the implementation of the above idea : "
},
{
"code": null,
"e": 24561,
"s": 24553,
"text": "Python3"
},
{
"code": "# importing requests packageimport requests def NewsFromBBC(): # BBC news api # following query parameters are used # source, sortBy and apiKey query_params = { \"source\": \"bbc-news\", \"sortBy\": \"top\", \"apiKey\": \"4dbc17e007ab436fb66416009dfb59a8\" } main_url = \" https://newsapi.org/v1/articles\" # fetching data in json format res = requests.get(main_url, params=query_params) open_bbc_page = res.json() # getting all articles in a string article article = open_bbc_page[\"articles\"] # empty list which will # contain all trending news results = [] for ar in article: results.append(ar[\"title\"]) for i in range(len(results)): # printing all trending news print(i + 1, results[i]) #to read the news out loud for us from win32com.client import Dispatch speak = Dispatch(\"SAPI.Spvoice\") speak.Speak(results) # Driver Codeif __name__ == '__main__': # function call NewsFromBBC()",
"e": 25591,
"s": 24561,
"text": null
},
{
"code": null,
"e": 25601,
"s": 25591,
"text": "Output : "
},
{
"code": null,
"e": 26075,
"s": 25601,
"text": "1 Italy to lift coronavirus travel restrictions\n2 White House 'Operation Warp Speed' to look for Covid jab\n3 Two Americas in the nation's capital\n4 Kobe Bryant helicopter crash post-mortem released\n5 Little things people are doing while socially distanced\n6 The last 'normal' photo on your phone\n7 'They came to kill the mothers'\n8 EU-UK Brexit trade talks in trouble\n9 Trial starts to see if dogs can 'sniff out' virus\n10 Beatles photographer Astrid Kirchherr dies aged 81"
},
{
"code": null,
"e": 26138,
"s": 26075,
"text": "Note: Output may change based on the top articles at the time."
},
{
"code": null,
"e": 26356,
"s": 26138,
"text": "This approach will work as a cherry on a cake because it will display the news according to the category entered by the user so as work as a filter for those who want to know the news in a particular category/section."
},
{
"code": null,
"e": 26469,
"s": 26356,
"text": "First of all install newsapi and pycountry in your system if it’s not there the install using the command below:"
},
{
"code": null,
"e": 26522,
"s": 26469,
"text": "~ pip install newsapi-python\n~ pip install pycountry"
},
{
"code": null,
"e": 26530,
"s": 26522,
"text": "Python3"
},
{
"code": "from newsapi import NewsApiClientimport pycountry # you have to get your api key from newapi.com and then paste it belownewsapi = NewsApiClient(api_key='Your API Key') # now we will take name of country from user as inputinput_country = input(\"Country: \")input_countries = [f'{input_country.strip()}']countries = {} # iterate over all the countries in# the world using pycountry modulefor country in pycountry.countries: # and store the unique code of each country # in the dictionary along with it's full name countries[country.name] = country.alpha_2 # now we will check that the entered country name is# valid or invalid using the unique codecodes = [countries.get(country.title(), 'Unknown code') for country in input_countries] # now we have to display all the categories from which user will# decide and enter the name of that categoryoption = input(\"Which category are you interested in?\\n1.Business\\n2.Entertainment\\n3.General\\n4.Health\\n5.Science\\n6.Technology\\n\\nEnter here: \") # now we will fetch the new according to the choice of the usertop_headlines = newsapi.get_top_headlines( # getting top headlines from all the news channels category=f'{option.lower()}', language='en', country=f'{codes[0].lower()}') # fetch the top news inder that category Headlines = top_headlines['articles'] # now we will display the that news with a good readability for user if Headlines: for articles in Headlines: b = articles['title'][::-1].index(\"-\") if \"news\" in (articles['title'][-b+1:]).lower(): print( f\"{articles['title'][-b+1:]}: {articles['title'][:-b-2]}.\") else: print( f\"{articles['title'][-b+1:]} News: {articles['title'][:-b-2]}.\") else: print( f\"Sorry no articles found for {input_country}, Something Wrong!!!\") option = input(\"Do you want to search again[Yes/No]?\") if option.lower() == 'yes': continue else: exit()",
"e": 28544,
"s": 26530,
"text": null
},
{
"code": null,
"e": 28551,
"s": 28544,
"text": "Input:"
},
{
"code": null,
"e": 28697,
"s": 28551,
"text": "Country: India\nWhich category are you interested in?\n1.Business\n2.Entertainment\n3.General\n4.Health\n5.Science\n6.Technology\n\nEnter here: Technology"
},
{
"code": null,
"e": 28705,
"s": 28697,
"text": "Output:"
},
{
"code": null,
"e": 30696,
"s": 28705,
"text": "Gizbot News: Garena Free Fire Redeem Codes For August 16; Get Master of Minds Weapon Loot Crate.\nNews18: Google Pixel 5a Will Have Biggest Battery On Any Pixel Phone Ever, Launch This Month.\nHindustan Times News: PUBG Mobile: Here’s how to get the Unhinged Mortician set on PUBG Mobile, check details of RPM2 Royale Pass.\nTimes of India News: New iPhones, Watch, AirPods and more: What Apple may launch in September.\nGSMArena.com News: Top 10 trending phones of week 32 - GSMArena.com news.\nHindustan Times News: Study finds if 'people persons' are 'machine persons' when they interact online.\nTimes of India News: 2021 vs 2020: August gasps for one ‘good’ air day in Gurugram this year.\nScienceAlert News: A Simple Crystal Could Finally Give Us Large-Scale Quantum Computing, Scientists Say.\nEngadget News: The Switch is the first console to sweep Japan's game sales chart in 33 years.\nGSMArena.com News: Weekly poll: Samsung Galaxy Z Fold3, the new S Pen and the Galaxy Z Flip3 - GSMArena.com news.\nMarket Research Telecast News: How to import your WhatsApp chats to WhatsApp Plus 17.00 Heymods.\nNotebookcheck.net News: Realme will finally debut its first-gen laptop later in August 2021.\nNewsBytes: Redmi 10 officially teased; color options revealed.\nThe Siasat Daily News: Xiaomi removes anti-lost mode from Mi Mix 4.\nZee News: Good news for Motorola Razr owners! Smartphone is finally getting Android 11 update.\nEssentiallySports News: Animal Crossing: New Horizons- Predictions for the Next Big Update.\nRepublic World News: Motorola Edge 20 price in India Leaked: Price to range between Rs 21,499 to Rs 29,999.\nEurogamer.net News: Assassinations have been temporarily removed from Halo Infinite because \"people just turn them off\".\nEssentiallySports News: Call of Duty: Warzone- If You Can Win a Game Despite the Hackers, You Can See a Vanguard Teaser.\nTechradar News: Facebook Messenger voice and video calls are getting end-to-end encryption.\nDo you want to search again[Yes/No]? No"
},
{
"code": null,
"e": 30704,
"s": 30696,
"text": "araxk19"
},
{
"code": null,
"e": 30714,
"s": 30704,
"text": "kumarv456"
},
{
"code": null,
"e": 30724,
"s": 30714,
"text": "adityatri"
},
{
"code": null,
"e": 30741,
"s": 30724,
"text": "arorakashish0911"
},
{
"code": null,
"e": 30757,
"s": 30741,
"text": "Python-projects"
},
{
"code": null,
"e": 30772,
"s": 30757,
"text": "python-utility"
},
{
"code": null,
"e": 30779,
"s": 30772,
"text": "Python"
},
{
"code": null,
"e": 30798,
"s": 30779,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30896,
"s": 30798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30905,
"s": 30896,
"text": "Comments"
},
{
"code": null,
"e": 30918,
"s": 30905,
"text": "Old Comments"
},
{
"code": null,
"e": 30936,
"s": 30918,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30971,
"s": 30936,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30993,
"s": 30971,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31025,
"s": 30993,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31055,
"s": 31025,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31097,
"s": 31055,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31140,
"s": 31097,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31166,
"s": 31140,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31210,
"s": 31166,
"text": "Reading and Writing to text files in Python"
}
] |
AngularJS - First Application
|
Before creating actual Hello World ! application using AngularJS, let us see the parts of a AngularJS application. An AngularJS application consists of following three important parts −
ng-app − This directive defines and links an AngularJS application to HTML.
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML input controls.
ng-model − This directive binds the values of AngularJS application data to HTML input controls.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
Being a pure JavaScript framework, it can be added using <Script> tag.
<script
src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<div ng-app = "">
...
</div>
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
Use the above-mentioned three steps in an HTML page.
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
Open the file testAngularJS.htm in a web browser. Enter your name and see the result.
Enter your Name:
Hello !
The ng-app directive indicates the start of AngularJS application.
The ng-app directive indicates the start of AngularJS application.
The ng-model directive creates a model variable named name, which can be used with the HTML page and within the div having ng-app directive.
The ng-model directive creates a model variable named name, which can be used with the HTML page and within the div having ng-app directive.
The ng-bind then uses the name model to be displayed in the HTML <span> tag whenever user enters input in the text box.
The ng-bind then uses the name model to be displayed in the HTML <span> tag whenever user enters input in the text box.
Closing</div> tag indicates the end of AngularJS application.
Closing</div> tag indicates the end of AngularJS application.
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2885,
"s": 2699,
"text": "Before creating actual Hello World ! application using AngularJS, let us see the parts of a AngularJS application. An AngularJS application consists of following three important parts −"
},
{
"code": null,
"e": 2961,
"s": 2885,
"text": "ng-app − This directive defines and links an AngularJS application to HTML."
},
{
"code": null,
"e": 3037,
"s": 2961,
"text": "ng-app − This directive defines and links an AngularJS application to HTML."
},
{
"code": null,
"e": 3134,
"s": 3037,
"text": "ng-model − This directive binds the values of AngularJS application data to HTML input controls."
},
{
"code": null,
"e": 3231,
"s": 3134,
"text": "ng-model − This directive binds the values of AngularJS application data to HTML input controls."
},
{
"code": null,
"e": 3307,
"s": 3231,
"text": "ng-bind − This directive binds the AngularJS Application data to HTML tags."
},
{
"code": null,
"e": 3383,
"s": 3307,
"text": "ng-bind − This directive binds the AngularJS Application data to HTML tags."
},
{
"code": null,
"e": 3454,
"s": 3383,
"text": "Being a pure JavaScript framework, it can be added using <Script> tag."
},
{
"code": null,
"e": 3556,
"s": 3454,
"text": "<script \n src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n</script>\n"
},
{
"code": null,
"e": 3589,
"s": 3556,
"text": "<div ng-app = \"\">\n ...\n</div>\n"
},
{
"code": null,
"e": 3654,
"s": 3589,
"text": "<p>Enter your Name: <input type = \"text\" ng-model = \"name\"></p>\n"
},
{
"code": null,
"e": 3700,
"s": 3654,
"text": "<p>Hello <span ng-bind = \"name\"></span>!</p>\n"
},
{
"code": null,
"e": 3753,
"s": 3700,
"text": "Use the above-mentioned three steps in an HTML page."
},
{
"code": null,
"e": 4191,
"s": 3753,
"text": "<html>\n <head>\n <title>AngularJS First Application</title>\n </head>\n \n <body>\n <h1>Sample Application</h1>\n \n <div ng-app = \"\">\n <p>Enter your Name: <input type = \"text\" ng-model = \"name\"></p>\n <p>Hello <span ng-bind = \"name\"></span>!</p>\n </div>\n \n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4277,
"s": 4191,
"text": "Open the file testAngularJS.htm in a web browser. Enter your name and see the result."
},
{
"code": null,
"e": 4295,
"s": 4277,
"text": "Enter your Name: "
},
{
"code": null,
"e": 4303,
"s": 4295,
"text": "Hello !"
},
{
"code": null,
"e": 4370,
"s": 4303,
"text": "The ng-app directive indicates the start of AngularJS application."
},
{
"code": null,
"e": 4437,
"s": 4370,
"text": "The ng-app directive indicates the start of AngularJS application."
},
{
"code": null,
"e": 4578,
"s": 4437,
"text": "The ng-model directive creates a model variable named name, which can be used with the HTML page and within the div having ng-app directive."
},
{
"code": null,
"e": 4719,
"s": 4578,
"text": "The ng-model directive creates a model variable named name, which can be used with the HTML page and within the div having ng-app directive."
},
{
"code": null,
"e": 4839,
"s": 4719,
"text": "The ng-bind then uses the name model to be displayed in the HTML <span> tag whenever user enters input in the text box."
},
{
"code": null,
"e": 4959,
"s": 4839,
"text": "The ng-bind then uses the name model to be displayed in the HTML <span> tag whenever user enters input in the text box."
},
{
"code": null,
"e": 5021,
"s": 4959,
"text": "Closing</div> tag indicates the end of AngularJS application."
},
{
"code": null,
"e": 5083,
"s": 5021,
"text": "Closing</div> tag indicates the end of AngularJS application."
},
{
"code": null,
"e": 5118,
"s": 5083,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5132,
"s": 5118,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5167,
"s": 5132,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5187,
"s": 5167,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5194,
"s": 5187,
"text": " Print"
},
{
"code": null,
"e": 5205,
"s": 5194,
"text": " Add Notes"
}
] |
How to remove an element from a list by index in Python?
|
There are two options to remove an element by its index in list. Using del statement, and using pop() method.
The del statement needs index of the element to remove.
>>> L1=[11,22,33,44,55,66,77]
>>> del L1[2]
>>> L1
[11, 22, 44, 55, 66, 77]
The pop() method of built-in list class requires index as argument. The method returns the removed elements and reduces contents of list by one element.
>>> L1=[11,22,33,44,55,66,77]
>>> x=L1.pop(2)
>>> x
33
>>> L1
[11, 22, 44, 55, 66, 77]
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "There are two options to remove an element by its index in list. Using del statement, and using pop() method."
},
{
"code": null,
"e": 1228,
"s": 1172,
"text": "The del statement needs index of the element to remove."
},
{
"code": null,
"e": 1304,
"s": 1228,
"text": ">>> L1=[11,22,33,44,55,66,77]\n>>> del L1[2]\n>>> L1\n[11, 22, 44, 55, 66, 77]"
},
{
"code": null,
"e": 1457,
"s": 1304,
"text": "The pop() method of built-in list class requires index as argument. The method returns the removed elements and reduces contents of list by one element."
},
{
"code": null,
"e": 1544,
"s": 1457,
"text": ">>> L1=[11,22,33,44,55,66,77]\n>>> x=L1.pop(2)\n>>> x\n33\n>>> L1\n[11, 22, 44, 55, 66, 77]"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.