title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
malloc() vs new - GeeksforGeeks | 08 Jul, 2021
Following are the differences between malloc() and operator new.:
Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
CPP
#include<iostream>using namespace std;int main(){ // Initialization with new() int *n = new int(10); cout << *n; getchar(); return 0;}
10
2. operator vs function: new is an operator, while malloc() is a function.
3. return type: new returns exact data type, while malloc() returns void *.
4. Failure Condition: On failure, malloc() returns NULL where as new throws bad_alloc exception.
5. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.
6. Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc().
7. Buffer Size: malloc() allows to change the size of buffer using realloc() while new doesn’t
new
malloc()
Please write comments if you find anything incorrect in the above post, or you want to share more information about the topic discussed above.
Yash Kumar Atri
anukashasingh
r237
singhbishalkumarsingh
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25707,
"s": 25679,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25774,
"s": 25707,
"text": "Following are the differences between malloc() and operator new.: "
},
{
"code": null,
"e": 25971,
"s": 25774,
"text": "Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10."
},
{
"code": null,
"e": 26168,
"s": 25971,
"text": "Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10."
},
{
"code": null,
"e": 26172,
"s": 26168,
"text": "CPP"
},
{
"code": "#include<iostream>using namespace std;int main(){ // Initialization with new() int *n = new int(10); cout << *n; getchar(); return 0;}",
"e": 26322,
"s": 26172,
"text": null
},
{
"code": null,
"e": 26325,
"s": 26322,
"text": "10"
},
{
"code": null,
"e": 26402,
"s": 26327,
"text": "2. operator vs function: new is an operator, while malloc() is a function."
},
{
"code": null,
"e": 26478,
"s": 26402,
"text": "3. return type: new returns exact data type, while malloc() returns void *."
},
{
"code": null,
"e": 26575,
"s": 26478,
"text": "4. Failure Condition: On failure, malloc() returns NULL where as new throws bad_alloc exception."
},
{
"code": null,
"e": 26696,
"s": 26575,
"text": "5. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap."
},
{
"code": null,
"e": 26822,
"s": 26696,
"text": "6. Size: Required size of memory is calculated by compiler for new, where as we have to manually calculate size for malloc()."
},
{
"code": null,
"e": 26917,
"s": 26822,
"text": "7. Buffer Size: malloc() allows to change the size of buffer using realloc() while new doesn’t"
},
{
"code": null,
"e": 26921,
"s": 26917,
"text": "new"
},
{
"code": null,
"e": 26930,
"s": 26921,
"text": "malloc()"
},
{
"code": null,
"e": 27073,
"s": 26930,
"text": "Please write comments if you find anything incorrect in the above post, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27089,
"s": 27073,
"text": "Yash Kumar Atri"
},
{
"code": null,
"e": 27103,
"s": 27089,
"text": "anukashasingh"
},
{
"code": null,
"e": 27108,
"s": 27103,
"text": "r237"
},
{
"code": null,
"e": 27130,
"s": 27108,
"text": "singhbishalkumarsingh"
},
{
"code": null,
"e": 27141,
"s": 27130,
"text": "C Language"
},
{
"code": null,
"e": 27145,
"s": 27141,
"text": "C++"
},
{
"code": null,
"e": 27149,
"s": 27145,
"text": "CPP"
},
{
"code": null,
"e": 27247,
"s": 27149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27264,
"s": 27247,
"text": "Substring in C++"
},
{
"code": null,
"e": 27299,
"s": 27264,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27338,
"s": 27299,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 27384,
"s": 27338,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27406,
"s": 27384,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27424,
"s": 27406,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27470,
"s": 27424,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27489,
"s": 27470,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27532,
"s": 27489,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to create an array with random values with the help of JavaScript ? - GeeksforGeeks | 31 Dec, 2019
The task is to generate an array with random values with the help of JavaScript. There are two approaches which are discussed below:
Approach 1:
Use Math.random() and Math.floor() method to get the random values.
Push the values one by one in the array (But this approach may generate repeated values).
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> create an array with random values </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to generate the array."; function gfg_Run() { el_down.innerHTML = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10)); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Create an array and put the values in it (like, 1 at index 0, 2 at index 1, 3 at index 2 in the same order by a loop.)
Assign variable (tp) = length of the array.
Run a loop on variable(tp).
Inside loop use Math.random() and Math.floor() method to get the random index of the array.
Swap this array value with the index(tp) and decrease the variable(tp) by 1.
Run the loop until variable(tp) becomes 0.
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> create an array with random values. </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); for (var a = [], i = 0; i < 10; ++i) a[i] = i; // Array like[1, 2, 3, 4, ...] el_up.innerHTML = "Click on the button to generate the array."; function createRandom(arr) { var tmp, cur, tp = arr.length; if (tp) // Run until tp becomes 0. while (--tp) { // Generating the random index. cur = Math.floor(Math.random() * (tp + 1)); // Getting the index(cur) value in variable(tmp). tmp = arr[cur]; // Moving the index(tp) value to index(cur). arr[cur] = arr[tp]; // Moving back the tmp value to // index(tp), Swaping is done. arr[tp] = tmp; } return arr; } function gfg_Run() { el_down.innerHTML = createRandom(a); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26083,
"s": 26055,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 26216,
"s": 26083,
"text": "The task is to generate an array with random values with the help of JavaScript. There are two approaches which are discussed below:"
},
{
"code": null,
"e": 26228,
"s": 26216,
"text": "Approach 1:"
},
{
"code": null,
"e": 26296,
"s": 26228,
"text": "Use Math.random() and Math.floor() method to get the random values."
},
{
"code": null,
"e": 26386,
"s": 26296,
"text": "Push the values one by one in the array (But this approach may generate repeated values)."
},
{
"code": null,
"e": 26439,
"s": 26386,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> create an array with random values </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to generate the array.\"; function gfg_Run() { el_down.innerHTML = Array.from({ length: 10 }, () => Math.floor(Math.random() * 10)); } </script></body> </html>",
"e": 27169,
"s": 26439,
"text": null
},
{
"code": null,
"e": 27177,
"s": 27169,
"text": "Output:"
},
{
"code": null,
"e": 27208,
"s": 27177,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27238,
"s": 27208,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27250,
"s": 27238,
"text": "Approach 2:"
},
{
"code": null,
"e": 27369,
"s": 27250,
"text": "Create an array and put the values in it (like, 1 at index 0, 2 at index 1, 3 at index 2 in the same order by a loop.)"
},
{
"code": null,
"e": 27413,
"s": 27369,
"text": "Assign variable (tp) = length of the array."
},
{
"code": null,
"e": 27441,
"s": 27413,
"text": "Run a loop on variable(tp)."
},
{
"code": null,
"e": 27533,
"s": 27441,
"text": "Inside loop use Math.random() and Math.floor() method to get the random index of the array."
},
{
"code": null,
"e": 27610,
"s": 27533,
"text": "Swap this array value with the index(tp) and decrease the variable(tp) by 1."
},
{
"code": null,
"e": 27653,
"s": 27610,
"text": "Run the loop until variable(tp) becomes 0."
},
{
"code": null,
"e": 27706,
"s": 27653,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> create an array with random values. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); for (var a = [], i = 0; i < 10; ++i) a[i] = i; // Array like[1, 2, 3, 4, ...] el_up.innerHTML = \"Click on the button to generate the array.\"; function createRandom(arr) { var tmp, cur, tp = arr.length; if (tp) // Run until tp becomes 0. while (--tp) { // Generating the random index. cur = Math.floor(Math.random() * (tp + 1)); // Getting the index(cur) value in variable(tmp). tmp = arr[cur]; // Moving the index(tp) value to index(cur). arr[cur] = arr[tp]; // Moving back the tmp value to // index(tp), Swaping is done. arr[tp] = tmp; } return arr; } function gfg_Run() { el_down.innerHTML = createRandom(a); } </script></body> </html>",
"e": 29156,
"s": 27706,
"text": null
},
{
"code": null,
"e": 29164,
"s": 29156,
"text": "Output:"
},
{
"code": null,
"e": 29195,
"s": 29164,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29225,
"s": 29195,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29241,
"s": 29225,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29252,
"s": 29241,
"text": "JavaScript"
},
{
"code": null,
"e": 29269,
"s": 29252,
"text": "Web Technologies"
},
{
"code": null,
"e": 29296,
"s": 29269,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29394,
"s": 29296,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29434,
"s": 29394,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29479,
"s": 29434,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29540,
"s": 29479,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29612,
"s": 29540,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29664,
"s": 29612,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29704,
"s": 29664,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29737,
"s": 29704,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29782,
"s": 29737,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29825,
"s": 29782,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Union of Tuples - GeeksforGeeks | 30 Jan, 2020
Sometimes, while working with tuples, we can have a problem in which we need union of two records. This type of application can come in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using set() + “+” operator This task can be performed using union functionality offered by + operator over sets. The conversion to set is done by set().
# Python3 code to demonstrate working of# Union of Tuples# Using set() + "+" operator # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Union of Tuples# Using set() + "+" operatorres = tuple(set(test_tup1 + test_tup2)) # printing resultprint("The union elements from tuples are : " + str(res))
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The union elements from tuples are : (3, 4, 5, 6, 7, 10)
Method #2 : Using union() + set() This is method similar to above method, the difference is that instead of + operator, we use inbuilt function to perform the task of filtering dissimilar elements.
# Python3 code to demonstrate working of# Union of Tuples# Using union() + set() # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Union of Tuples# Using union() + set()res = tuple(set(test_tup1).union(set(test_tup2))) # printing resultprint("The union elements from tuples are : " + str(res))
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The union elements from tuples are : (3, 4, 5, 6, 7, 10)
Python tuple-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25758,
"s": 25537,
"text": "Sometimes, while working with tuples, we can have a problem in which we need union of two records. This type of application can come in Data Science domain. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 25923,
"s": 25758,
"text": "Method #1 : Using set() + “+” operator This task can be performed using union functionality offered by + operator over sets. The conversion to set is done by set()."
},
{
"code": "# Python3 code to demonstrate working of# Union of Tuples# Using set() + \"+\" operator # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Union of Tuples# Using set() + \"+\" operatorres = tuple(set(test_tup1 + test_tup2)) # printing resultprint(\"The union elements from tuples are : \" + str(res))",
"e": 26367,
"s": 25923,
"text": null
},
{
"code": null,
"e": 26499,
"s": 26367,
"text": "The original tuple 1 : (3, 4, 5, 6)\nThe original tuple 2 : (5, 7, 4, 10)\nThe union elements from tuples are : (3, 4, 5, 6, 7, 10)\n\n"
},
{
"code": null,
"e": 26699,
"s": 26499,
"text": " Method #2 : Using union() + set() This is method similar to above method, the difference is that instead of + operator, we use inbuilt function to perform the task of filtering dissimilar elements. "
},
{
"code": "# Python3 code to demonstrate working of# Union of Tuples# Using union() + set() # initialize tuplestest_tup1 = (3, 4, 5, 6)test_tup2 = (5, 7, 4, 10) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Union of Tuples# Using union() + set()res = tuple(set(test_tup1).union(set(test_tup2))) # printing resultprint(\"The union elements from tuples are : \" + str(res))",
"e": 27143,
"s": 26699,
"text": null
},
{
"code": null,
"e": 27275,
"s": 27143,
"text": "The original tuple 1 : (3, 4, 5, 6)\nThe original tuple 2 : (5, 7, 4, 10)\nThe union elements from tuples are : (3, 4, 5, 6, 7, 10)\n\n"
},
{
"code": null,
"e": 27299,
"s": 27277,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27306,
"s": 27299,
"text": "Python"
},
{
"code": null,
"e": 27322,
"s": 27306,
"text": "Python Programs"
},
{
"code": null,
"e": 27420,
"s": 27322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27452,
"s": 27420,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27494,
"s": 27452,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27536,
"s": 27494,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27592,
"s": 27536,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27619,
"s": 27592,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27641,
"s": 27619,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27680,
"s": 27641,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27726,
"s": 27680,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27764,
"s": 27726,
"text": "Python | Convert a list to dictionary"
}
] |
Puzzle | (Basketball shots) - GeeksforGeeks | 26 Jul, 2017
You have a basketball hoop and someone says that you can play one of two games.Game1 : You get one shot to make the hoop.Game2 : You get three shots and you have to make two of three shots.If p is the probability of making a particular shot, for which values of p should you pick one game or the other?
Answer:
Probability of winning the Game 1:The probability of winning game 1 is p, by definition.
Probability of winning the Game 2:Let s(k, n) be the probability of making exactly k shots out of n.The probability of winning the Game 2 is the probability of making exactly two shots out of three OR making all three shots. In other words:
P(winning) = s(2, 3) + s(3, 3)
The probability of making all the three shots is:
s(3, 3) =
The probability of making exactly two shots is:P(making 1 and 2, & missing 3) + P(making 1 and 3, & missing 2) + P(making 2 and 3, & missing 1)
= [p * p * (1-p)] + [p * (1-p) * p] + [(1-p) * p * p]
= 3*(1-p)*
Adding these together, we get:
= + 3(1-p)
= + 3 - 3
= 3 - 2
Which game you should play?You should play Game 1 if P(Game 1) > P(Game 2):
p > 3 - 2
1 > 3p - 2
2 - 3p + 1 > 0
(2p - 1)(p - 1) > 0
Both terms must be positive, or both must be negative, But we know p < 1, so p – 1 < 0. This means both terms must be negative.
2p - 1 < 0
2p < 1
p < 0.5
So, we should play Game 1 if 0 < p < 0.5 and Game 2 if 0.5 < p < 1.If p = 0, 0.5, or 1 then P(Game 1) = P(Game 2), so it doesn't matter which game we play.
This article is contributed by Brahmani Sai. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Probability
Puzzles
Puzzles
Probability
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Algorithm to solve Rubik's Cube
Top 20 Puzzles Commonly Asked During SDE Interviews
Puzzle 15 | (Camel and Banana Puzzle)
Puzzle 21 | (3 Ants and Triangle)
Puzzle 16 | (100 Doors)
Puzzle 18 | (Torch and Bridge)
Container with Most Water
Puzzle | Set 35 (2 Eggs and 100 Floors)
Puzzle 11 | (1000 Coins and 10 Bags) | [
{
"code": null,
"e": 25687,
"s": 25659,
"text": "\n26 Jul, 2017"
},
{
"code": null,
"e": 25990,
"s": 25687,
"text": "You have a basketball hoop and someone says that you can play one of two games.Game1 : You get one shot to make the hoop.Game2 : You get three shots and you have to make two of three shots.If p is the probability of making a particular shot, for which values of p should you pick one game or the other?"
},
{
"code": null,
"e": 25998,
"s": 25990,
"text": "Answer:"
},
{
"code": null,
"e": 26087,
"s": 25998,
"text": "Probability of winning the Game 1:The probability of winning game 1 is p, by definition."
},
{
"code": null,
"e": 26328,
"s": 26087,
"text": "Probability of winning the Game 2:Let s(k, n) be the probability of making exactly k shots out of n.The probability of winning the Game 2 is the probability of making exactly two shots out of three OR making all three shots. In other words:"
},
{
"code": null,
"e": 26359,
"s": 26328,
"text": "P(winning) = s(2, 3) + s(3, 3)"
},
{
"code": null,
"e": 26409,
"s": 26359,
"text": "The probability of making all the three shots is:"
},
{
"code": null,
"e": 26420,
"s": 26409,
"text": "s(3, 3) = "
},
{
"code": null,
"e": 26564,
"s": 26420,
"text": "The probability of making exactly two shots is:P(making 1 and 2, & missing 3) + P(making 1 and 3, & missing 2) + P(making 2 and 3, & missing 1)"
},
{
"code": null,
"e": 26636,
"s": 26564,
"text": " = [p * p * (1-p)] + [p * (1-p) * p] + [(1-p) * p * p]\n = 3*(1-p)*\n"
},
{
"code": null,
"e": 26667,
"s": 26636,
"text": "Adding these together, we get:"
},
{
"code": null,
"e": 26708,
"s": 26667,
"text": " = + 3(1-p)\n = + 3 - 3\n = 3 - 2\n"
},
{
"code": null,
"e": 26784,
"s": 26708,
"text": "Which game you should play?You should play Game 1 if P(Game 1) > P(Game 2):"
},
{
"code": null,
"e": 26857,
"s": 26784,
"text": " p > 3 - 2\n 1 > 3p - 2\n 2 - 3p + 1 > 0\n (2p - 1)(p - 1) > 0\n"
},
{
"code": null,
"e": 26985,
"s": 26857,
"text": "Both terms must be positive, or both must be negative, But we know p < 1, so p – 1 < 0. This means both terms must be negative."
},
{
"code": null,
"e": 27024,
"s": 26985,
"text": " 2p - 1 < 0\n 2p < 1\n p < 0.5\n"
},
{
"code": null,
"e": 27180,
"s": 27024,
"text": "So, we should play Game 1 if 0 < p < 0.5 and Game 2 if 0.5 < p < 1.If p = 0, 0.5, or 1 then P(Game 1) = P(Game 2), so it doesn't matter which game we play."
},
{
"code": null,
"e": 27480,
"s": 27180,
"text": "This article is contributed by Brahmani Sai. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27605,
"s": 27480,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27617,
"s": 27605,
"text": "Probability"
},
{
"code": null,
"e": 27625,
"s": 27617,
"text": "Puzzles"
},
{
"code": null,
"e": 27633,
"s": 27625,
"text": "Puzzles"
},
{
"code": null,
"e": 27645,
"s": 27633,
"text": "Probability"
},
{
"code": null,
"e": 27743,
"s": 27645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27792,
"s": 27743,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 27824,
"s": 27792,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 27876,
"s": 27824,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 27914,
"s": 27876,
"text": "Puzzle 15 | (Camel and Banana Puzzle)"
},
{
"code": null,
"e": 27948,
"s": 27914,
"text": "Puzzle 21 | (3 Ants and Triangle)"
},
{
"code": null,
"e": 27972,
"s": 27948,
"text": "Puzzle 16 | (100 Doors)"
},
{
"code": null,
"e": 28003,
"s": 27972,
"text": "Puzzle 18 | (Torch and Bridge)"
},
{
"code": null,
"e": 28029,
"s": 28003,
"text": "Container with Most Water"
},
{
"code": null,
"e": 28069,
"s": 28029,
"text": "Puzzle | Set 35 (2 Eggs and 100 Floors)"
}
] |
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction) - GeeksforGeeks | 30 Mar, 2022
Let us consider the following problem to understand MO’s Algorithm.We are given an array and a set of query ranges, we are required to find the sum of every query range.
Example:
Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
query[] = [0, 4], [1, 3] [2, 4]
Output: Sum of arr[] elements in range [0, 4] is 8
Sum of arr[] elements in range [1, 3] is 4
Sum of arr[] elements in range [2, 4] is 6
A Naive Solution is to run a loop from L to R and calculate the sum of elements in given range for every query [L, R]
C++
Java
Python3
C#
Javascript
// C++ Program to compute sum of ranges for different range// queries.#include <bits/stdc++.h>using namespace std; // Structure to represent a query rangestruct Query{ int L, R;}; // Prints sum of all query ranges. m is number of queries// n is the size of the array.void printQuerySums(int a[], int n, Query q[], int m){ // One by one compute sum of all queries for (int i=0; i<m; i++) { // Left and right boundaries of current range int L = q[i].L, R = q[i].R; // Compute sum of current query range int sum = 0; for (int j=L; j<=R; j++) sum += a[j]; // Print sum of current query range cout << "Sum of [" << L << ", " << R << "] is " << sum << endl; }} // Driver programint main(){ int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = sizeof(a)/sizeof(a[0]); Query q[] = {{0, 4}, {1, 3}, {2, 4}}; int m = sizeof(q)/sizeof(q[0]); printQuerySums(a, n, q, m); return 0;}
// Java Program to compute sum of ranges for different range// queries.import java.util.*; // Class to represent a query rangeclass Query{ int L; int R; Query(int L, int R){ this.L = L; this.R = R; }} class GFG{ // Prints sum of all query ranges. m is number of queries // n is the size of the array. static void printQuerySums(int a[], int n, ArrayList<Query> q, int m) { // One by one compute sum of all queries for (int i=0; i<m; i++) { // Left and right boundaries of current range int L = q.get(i).L, R = q.get(i).R; // Compute sum of current query range int sum = 0; for (int j=L; j<=R; j++) sum += a[j]; // Print sum of current query range System.out.println("Sum of [" + L + ", " + R + "] is " + sum); } } // Driver program public static void main(String argv[]) { int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = a.length; ArrayList<Query> q = new ArrayList<Query>(); q.add(new Query(0,4)); q.add(new Query(1,3)); q.add(new Query(2,4)); int m = q.size(); printQuerySums(a, n, q, m); }} // This code is contributed by shivanisinghss2110
# Python program to compute sum of ranges for different range queries. # Function that accepts array and list of queries and print sum of each querydef printQuerySum(arr,Q): for q in Q: # Traverse through each query L,R = q # Extract left and right indices s = 0 for i in range(L,R+1): # Compute sum of current query range s += arr[i] print("Sum of",q,"is",s) # Print sum of current query range # Driver scriptarr = [1, 1, 2, 1, 3, 4, 5, 2, 8]Q = [[0, 4], [1, 3], [2, 4]]printQuerySum(arr,Q)#This code is contributed by Shivam Singh
// C# program to compute sum of ranges for// different range queriesusing System;using System.Collections; // Class to represent a query rangepublic class Query{ public int L; public int R; public Query(int L, int R) { this.L = L; this.R = R; }} class GFG{ // Prints sum of all query ranges. m//is number of queries n is the size// of the array.static void printQuerySums(int []a, int n, ArrayList q, int m){ // One by one compute sum of all queries for(int i = 0; i < m; i++) { // Left and right boundaries of // current range int L = ((Query)q[i]).L, R = ((Query)q[i]).R; // Compute sum of current query range int sum = 0; for(int j = L; j <= R; j++) sum += a[j]; // Print sum of current query range Console.Write("Sum of [" + L + ", " + R + "] is " + sum + "\n"); }} // Driver codepublic static void Main(string []argv){ int []a = { 1, 1, 2, 1, 3, 4, 5, 2, 8 }; int n = a.Length; ArrayList q = new ArrayList(); q.Add(new Query(0, 4)); q.Add(new Query(1, 3)); q.Add(new Query(2, 4)); int m = q.Count; printQuerySums(a, n, q, m);}} // This code is contributed by pratham76
<script>// Javascript Program to compute sum of ranges for different range// queries. // Class to represent a query rangeclass Query{ constructor(L, R) { this.L = L; this.R = R; }} // Prints sum of all query ranges. m is number of queries // n is the size of the array.function printQuerySums(a, n, q, m){ // One by one compute sum of all queries for (let i = 0; i < m; i++) { // Left and right boundaries of current range let L = q[i].L, R = q[i].R; // Compute sum of current query range let sum = 0; for (let j = L; j <= R; j++) sum += a[j]; // Print sum of current query range document.write("Sum of [" + L + ", " + R + "] is " + sum+"<br>"); }} // Driver programlet a = [1, 1, 2, 1, 3, 4, 5, 2, 8];let n = a.length; let q = [];q.push(new Query(0,4));q.push(new Query(1,3));q.push(new Query(2,4)); let m = q.length;printQuerySums(a, n, q, m); // This code is contributed by avanitrachhadiya2155</script>
Output:
Sum of [0, 4] is 8
Sum of [1, 3] is 4
Sum of [2, 4] is 6
The time complexity of above solution is O(mn).The idea of MO’s algorithm is to pre-process all queries so that result of one query can be used in next query. Below are steps.
Let a[0...n-1] be input array and q[0..m-1] be array of queries.
Sort all queries in a way that queries with L values from 0 to √n – 1 are put together, then all queries from √n to 2*√n – 1, and so on. All queries within a block are sorted in increasing order of R values.Process all queries one by one in a way that every query uses sum computed in the previous query.Let ‘sum’ be sum of previous query.Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sumAdd new elements of current query. In the same example as above, we add a[9] to sum.
Sort all queries in a way that queries with L values from 0 to √n – 1 are put together, then all queries from √n to 2*√n – 1, and so on. All queries within a block are sorted in increasing order of R values.
Process all queries one by one in a way that every query uses sum computed in the previous query.Let ‘sum’ be sum of previous query.Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sumAdd new elements of current query. In the same example as above, we add a[9] to sum.
Let ‘sum’ be sum of previous query.
Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sum
Add new elements of current query. In the same example as above, we add a[9] to sum.
The great thing about this algorithm is, in step 2, index variable for R change at most O(n * √n) times throughout the run and same for L changes its value at most O(m * √n) times (See below, after the code, for details). All these bounds are possible only because the queries are sorted first in blocks of √n size.
The preprocessing part takes O(m Log m) time.
Processing all queries takes O(n * √n) + O(m * √n) = O((m+n) * √n) time.
Below is the implementation of the above idea.
C++
Java
Python3
// Program to compute sum of ranges for different range// queries#include <bits/stdc++.h>using namespace std; // Variable to represent block size. This is made global// so compare() of sort can use it.int block; // Structure to represent a query rangestruct Query{ int L, R;}; // Function used to sort all queries so that all queries// of the same block are arranged together and within a block,// queries are sorted in increasing order of R values.bool compare(Query x, Query y){ // Different blocks, sort by block. if (x.L/block != y.L/block) return x.L/block < y.L/block; // Same block, sort by R value return x.R < y.R;} // Prints sum of all query ranges. m is number of queries// n is size of array a[].void queryResults(int a[], int n, Query q[], int m){ // Find block size block = (int)sqrt(n); // Sort all queries so that queries of same blocks // are arranged together. sort(q, q + m, compare); // Initialize current L, current R and current sum int currL = 0, currR = 0; int currSum = 0; // Traverse through all queries for (int i=0; i<m; i++) { // L and R values of current range int L = q[i].L, R = q[i].R; // Remove extra elements of previous range. For // example if previous range is [0, 3] and current // range is [2, 5], then a[0] and a[1] are subtracted while (currL < L) { currSum -= a[currL]; currL++; } // Add Elements of current Range while (currL > L) { currSum += a[currL-1]; currL--; } while (currR <= R) { currSum += a[currR]; currR++; } // Remove elements of previous range. For example // when previous range is [0, 10] and current range // is [3, 8], then a[9] and a[10] are subtracted while (currR > R+1) { currSum -= a[currR-1]; currR--; } // Print sum of current range cout << "Sum of [" << L << ", " << R << "] is " << currSum << endl; }} // Driver programint main(){ int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = sizeof(a)/sizeof(a[0]); Query q[] = {{0, 4}, {1, 3}, {2, 4}}; int m = sizeof(q)/sizeof(q[0]); queryResults(a, n, q, m); return 0;}
// Java Program to compute sum of ranges for// different range queries import java.util.*; // Class to represent a query rangeclass Query{ int L; int R; Query(int L, int R){ this.L = L; this.R = R; }} class MO{ // Prints sum of all query ranges. m is number of queries // n is size of array a[]. static void queryResults(int a[], int n, ArrayList<Query> q, int m){ // Find block size int block = (int) Math.sqrt(n); // Sort all queries so that queries of same blocks // are arranged together. Collections.sort(q, new Comparator<Query>(){ // Function used to sort all queries so that all queries // of the same block are arranged together and within a block, // queries are sorted in increasing order of R values. public int compare(Query x, Query y){ // Different blocks, sort by block. if (x.L/block != y.L/block) return (x.L < y.L ? -1 : 1); // Same block, sort by R value return (x.R < y.R ? -1 : 1); } }); // Initialize current L, current R and current sum int currL = 0, currR = 0; int currSum = 0; // Traverse through all queries for (int i=0; i<m; i++) { // L and R values of current range int L = q.get(i).L, R = q.get(i).R; // Remove extra elements of previous range. For // example if previous range is [0, 3] and current // range is [2, 5], then a[0] and a[1] are subtracted while (currL < L) { currSum -= a[currL]; currL++; } // Add Elements of current Range while (currL > L) { currSum += a[currL-1]; currL--; } while (currR <= R) { currSum += a[currR]; currR++; } // Remove elements of previous range. For example // when previous range is [0, 10] and current range // is [3, 8], then a[9] and a[10] are subtracted while (currR > R+1) { currSum -= a[currR-1]; currR--; } // Print sum of current range System.out.println("Sum of [" + L + ", " + R + "] is " + currSum); } } // Driver program public static void main(String argv[]){ ArrayList<Query> q = new ArrayList<Query>(); q.add(new Query(0,4)); q.add(new Query(1,3)); q.add(new Query(2,4)); int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; queryResults(a, a.length, q, q.size()); }}// This code is contributed by Ajay
# Python program to compute sum of ranges for different range queries import math # Function that accepts array and list of queries and print sum of each querydef queryResults(arr,Q): #Q.sort(): # Sort by L #sort all queries so that all queries in the increasing order of R values . Q.sort(key=lambda x: x[1]) # Initialize current L, current R and current sum currL,currR,currSum = 0,0,0 # Traverse through all queries for i in range(len(Q)): L,R = Q[i] # L and R values of current range # Remove extra elements from previous range # if previous range is [0, 3] and current # range is [2, 5], then a[0] and a[1] are subtracted while currL<L: currSum-=arr[currL] currL+=1 # Add elements of current range while currL>L: currSum+=arr[currL-1] currL-=1 while currR<=R: currSum+=arr[currR] currR+=1 # Remove elements of previous range # when previous range is [0, 10] and current range # is [3, 8], then a[9] and a[10] are subtracted while currR>R+1: currSum-=arr[currR-1] currR-=1 # Print the sum of current range print("Sum of",Q[i],"is",currSum) arr = [1, 1, 2, 1, 3, 4, 5, 2, 8]Q = [[0, 4], [1, 3], [2, 4]]queryResults(arr,Q)#This code is contributed by Shivam Singh
Output:
Sum of [1, 3] is 4
Sum of [0, 4] is 8
Sum of [2, 4] is 6
The output of above program doesn’t print results of queries in same order as input, because queries are sorted. The program can be easily extended to keep the same order.
Important Observations:
All queries are known beforehead so that they can be preprocessedIt cannot work for problems where we have update operations also mixed with sum queries.MO’s algorithm can only be used for query problems where a query can be computed from results of the previous query. One more such example is maximum or minimum.
All queries are known beforehead so that they can be preprocessed
It cannot work for problems where we have update operations also mixed with sum queries.
MO’s algorithm can only be used for query problems where a query can be computed from results of the previous query. One more such example is maximum or minimum.
Time Complexity Analysis: The function mainly runs a for loop for all sorted queries. Inside the for loop, there are four while queries that move ‘currL’ and ‘currR’.
How much currR is moved? For each block, queries are sorted in increasing order of R. So, for a block, currR moves in increasing order. In worst case, before beginning of every block, currR at extreme right and current block moves it back the extreme left. This means that for every block, currR moves at most O(n). Since there are O(√n) blocks, total movement of currR is O(n * √n).
How much currL is moved? Since all queries are sorted in a way that L values are grouped by blocks, movement is O(√n) when we move from one query to another quert. For m queries, total movement of currL is O(m * √n)Please note that a Simple and more Efficient solution to solve this problem is to compute prefix sum for all elements from 0 to n-1. Let the prefix sum be stored in an array preSum[] (The value of preSum[i] stores sum of arr[0..i]). Once we have built preSum[], we can traverse through all queries one by one. For every query [L, R], we return value of preSum[R] – preSum[L]. Here processing every query takes O(1) time.
Auxiliary Space: O(1)
The idea of this article is to introduce MO’s algorithm with a very simple example. We will soon be discussing more interesting problems using MO’s algorithm.
Range Minimum Query (Square Root Decomposition and Sparse Table)
References: http://blog.anudeep2011.com/mos-algorithm/This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
AjayChaudhary
shivanisinghss2110
SHIVAMSINGH67
pratham76
avanitrachhadiya2155
simmytarika5
rishavnitro
array-range-queries
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to Start Learning DSA?
Playfair Cipher with Examples
Recursive Practice Problems with Solutions
Difference between NP hard and NP complete problem
Converting Roman Numerals to Decimal lying between 1 to 3999 | [
{
"code": null,
"e": 25959,
"s": 25931,
"text": "\n30 Mar, 2022"
},
{
"code": null,
"e": 26129,
"s": 25959,
"text": "Let us consider the following problem to understand MO’s Algorithm.We are given an array and a set of query ranges, we are required to find the sum of every query range."
},
{
"code": null,
"e": 26139,
"s": 26129,
"text": "Example: "
},
{
"code": null,
"e": 26381,
"s": 26139,
"text": "Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};\n query[] = [0, 4], [1, 3] [2, 4]\nOutput: Sum of arr[] elements in range [0, 4] is 8\n Sum of arr[] elements in range [1, 3] is 4 \n Sum of arr[] elements in range [2, 4] is 6"
},
{
"code": null,
"e": 26499,
"s": 26381,
"text": "A Naive Solution is to run a loop from L to R and calculate the sum of elements in given range for every query [L, R]"
},
{
"code": null,
"e": 26503,
"s": 26499,
"text": "C++"
},
{
"code": null,
"e": 26508,
"s": 26503,
"text": "Java"
},
{
"code": null,
"e": 26516,
"s": 26508,
"text": "Python3"
},
{
"code": null,
"e": 26519,
"s": 26516,
"text": "C#"
},
{
"code": null,
"e": 26530,
"s": 26519,
"text": "Javascript"
},
{
"code": "// C++ Program to compute sum of ranges for different range// queries.#include <bits/stdc++.h>using namespace std; // Structure to represent a query rangestruct Query{ int L, R;}; // Prints sum of all query ranges. m is number of queries// n is the size of the array.void printQuerySums(int a[], int n, Query q[], int m){ // One by one compute sum of all queries for (int i=0; i<m; i++) { // Left and right boundaries of current range int L = q[i].L, R = q[i].R; // Compute sum of current query range int sum = 0; for (int j=L; j<=R; j++) sum += a[j]; // Print sum of current query range cout << \"Sum of [\" << L << \", \" << R << \"] is \" << sum << endl; }} // Driver programint main(){ int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = sizeof(a)/sizeof(a[0]); Query q[] = {{0, 4}, {1, 3}, {2, 4}}; int m = sizeof(q)/sizeof(q[0]); printQuerySums(a, n, q, m); return 0;}",
"e": 27501,
"s": 26530,
"text": null
},
{
"code": "// Java Program to compute sum of ranges for different range// queries.import java.util.*; // Class to represent a query rangeclass Query{ int L; int R; Query(int L, int R){ this.L = L; this.R = R; }} class GFG{ // Prints sum of all query ranges. m is number of queries // n is the size of the array. static void printQuerySums(int a[], int n, ArrayList<Query> q, int m) { // One by one compute sum of all queries for (int i=0; i<m; i++) { // Left and right boundaries of current range int L = q.get(i).L, R = q.get(i).R; // Compute sum of current query range int sum = 0; for (int j=L; j<=R; j++) sum += a[j]; // Print sum of current query range System.out.println(\"Sum of [\" + L + \", \" + R + \"] is \" + sum); } } // Driver program public static void main(String argv[]) { int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = a.length; ArrayList<Query> q = new ArrayList<Query>(); q.add(new Query(0,4)); q.add(new Query(1,3)); q.add(new Query(2,4)); int m = q.size(); printQuerySums(a, n, q, m); }} // This code is contributed by shivanisinghss2110",
"e": 28834,
"s": 27501,
"text": null
},
{
"code": "# Python program to compute sum of ranges for different range queries. # Function that accepts array and list of queries and print sum of each querydef printQuerySum(arr,Q): for q in Q: # Traverse through each query L,R = q # Extract left and right indices s = 0 for i in range(L,R+1): # Compute sum of current query range s += arr[i] print(\"Sum of\",q,\"is\",s) # Print sum of current query range # Driver scriptarr = [1, 1, 2, 1, 3, 4, 5, 2, 8]Q = [[0, 4], [1, 3], [2, 4]]printQuerySum(arr,Q)#This code is contributed by Shivam Singh",
"e": 29427,
"s": 28834,
"text": null
},
{
"code": "// C# program to compute sum of ranges for// different range queriesusing System;using System.Collections; // Class to represent a query rangepublic class Query{ public int L; public int R; public Query(int L, int R) { this.L = L; this.R = R; }} class GFG{ // Prints sum of all query ranges. m//is number of queries n is the size// of the array.static void printQuerySums(int []a, int n, ArrayList q, int m){ // One by one compute sum of all queries for(int i = 0; i < m; i++) { // Left and right boundaries of // current range int L = ((Query)q[i]).L, R = ((Query)q[i]).R; // Compute sum of current query range int sum = 0; for(int j = L; j <= R; j++) sum += a[j]; // Print sum of current query range Console.Write(\"Sum of [\" + L + \", \" + R + \"] is \" + sum + \"\\n\"); }} // Driver codepublic static void Main(string []argv){ int []a = { 1, 1, 2, 1, 3, 4, 5, 2, 8 }; int n = a.Length; ArrayList q = new ArrayList(); q.Add(new Query(0, 4)); q.Add(new Query(1, 3)); q.Add(new Query(2, 4)); int m = q.Count; printQuerySums(a, n, q, m);}} // This code is contributed by pratham76",
"e": 30745,
"s": 29427,
"text": null
},
{
"code": "<script>// Javascript Program to compute sum of ranges for different range// queries. // Class to represent a query rangeclass Query{ constructor(L, R) { this.L = L; this.R = R; }} // Prints sum of all query ranges. m is number of queries // n is the size of the array.function printQuerySums(a, n, q, m){ // One by one compute sum of all queries for (let i = 0; i < m; i++) { // Left and right boundaries of current range let L = q[i].L, R = q[i].R; // Compute sum of current query range let sum = 0; for (let j = L; j <= R; j++) sum += a[j]; // Print sum of current query range document.write(\"Sum of [\" + L + \", \" + R + \"] is \" + sum+\"<br>\"); }} // Driver programlet a = [1, 1, 2, 1, 3, 4, 5, 2, 8];let n = a.length; let q = [];q.push(new Query(0,4));q.push(new Query(1,3));q.push(new Query(2,4)); let m = q.length;printQuerySums(a, n, q, m); // This code is contributed by avanitrachhadiya2155</script>",
"e": 31834,
"s": 30745,
"text": null
},
{
"code": null,
"e": 31843,
"s": 31834,
"text": "Output: "
},
{
"code": null,
"e": 31900,
"s": 31843,
"text": "Sum of [0, 4] is 8\nSum of [1, 3] is 4\nSum of [2, 4] is 6"
},
{
"code": null,
"e": 32076,
"s": 31900,
"text": "The time complexity of above solution is O(mn).The idea of MO’s algorithm is to pre-process all queries so that result of one query can be used in next query. Below are steps."
},
{
"code": null,
"e": 32142,
"s": 32076,
"text": "Let a[0...n-1] be input array and q[0..m-1] be array of queries. "
},
{
"code": null,
"e": 32720,
"s": 32142,
"text": "Sort all queries in a way that queries with L values from 0 to √n – 1 are put together, then all queries from √n to 2*√n – 1, and so on. All queries within a block are sorted in increasing order of R values.Process all queries one by one in a way that every query uses sum computed in the previous query.Let ‘sum’ be sum of previous query.Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sumAdd new elements of current query. In the same example as above, we add a[9] to sum."
},
{
"code": null,
"e": 32928,
"s": 32720,
"text": "Sort all queries in a way that queries with L values from 0 to √n – 1 are put together, then all queries from √n to 2*√n – 1, and so on. All queries within a block are sorted in increasing order of R values."
},
{
"code": null,
"e": 33299,
"s": 32928,
"text": "Process all queries one by one in a way that every query uses sum computed in the previous query.Let ‘sum’ be sum of previous query.Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sumAdd new elements of current query. In the same example as above, we add a[9] to sum."
},
{
"code": null,
"e": 33335,
"s": 33299,
"text": "Let ‘sum’ be sum of previous query."
},
{
"code": null,
"e": 33490,
"s": 33335,
"text": "Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sum"
},
{
"code": null,
"e": 33575,
"s": 33490,
"text": "Add new elements of current query. In the same example as above, we add a[9] to sum."
},
{
"code": null,
"e": 33891,
"s": 33575,
"text": "The great thing about this algorithm is, in step 2, index variable for R change at most O(n * √n) times throughout the run and same for L changes its value at most O(m * √n) times (See below, after the code, for details). All these bounds are possible only because the queries are sorted first in blocks of √n size."
},
{
"code": null,
"e": 33937,
"s": 33891,
"text": "The preprocessing part takes O(m Log m) time."
},
{
"code": null,
"e": 34011,
"s": 33937,
"text": "Processing all queries takes O(n * √n) + O(m * √n) = O((m+n) * √n) time. "
},
{
"code": null,
"e": 34058,
"s": 34011,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 34062,
"s": 34058,
"text": "C++"
},
{
"code": null,
"e": 34067,
"s": 34062,
"text": "Java"
},
{
"code": null,
"e": 34075,
"s": 34067,
"text": "Python3"
},
{
"code": "// Program to compute sum of ranges for different range// queries#include <bits/stdc++.h>using namespace std; // Variable to represent block size. This is made global// so compare() of sort can use it.int block; // Structure to represent a query rangestruct Query{ int L, R;}; // Function used to sort all queries so that all queries// of the same block are arranged together and within a block,// queries are sorted in increasing order of R values.bool compare(Query x, Query y){ // Different blocks, sort by block. if (x.L/block != y.L/block) return x.L/block < y.L/block; // Same block, sort by R value return x.R < y.R;} // Prints sum of all query ranges. m is number of queries// n is size of array a[].void queryResults(int a[], int n, Query q[], int m){ // Find block size block = (int)sqrt(n); // Sort all queries so that queries of same blocks // are arranged together. sort(q, q + m, compare); // Initialize current L, current R and current sum int currL = 0, currR = 0; int currSum = 0; // Traverse through all queries for (int i=0; i<m; i++) { // L and R values of current range int L = q[i].L, R = q[i].R; // Remove extra elements of previous range. For // example if previous range is [0, 3] and current // range is [2, 5], then a[0] and a[1] are subtracted while (currL < L) { currSum -= a[currL]; currL++; } // Add Elements of current Range while (currL > L) { currSum += a[currL-1]; currL--; } while (currR <= R) { currSum += a[currR]; currR++; } // Remove elements of previous range. For example // when previous range is [0, 10] and current range // is [3, 8], then a[9] and a[10] are subtracted while (currR > R+1) { currSum -= a[currR-1]; currR--; } // Print sum of current range cout << \"Sum of [\" << L << \", \" << R << \"] is \" << currSum << endl; }} // Driver programint main(){ int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; int n = sizeof(a)/sizeof(a[0]); Query q[] = {{0, 4}, {1, 3}, {2, 4}}; int m = sizeof(q)/sizeof(q[0]); queryResults(a, n, q, m); return 0;}",
"e": 36401,
"s": 34075,
"text": null
},
{
"code": "// Java Program to compute sum of ranges for// different range queries import java.util.*; // Class to represent a query rangeclass Query{ int L; int R; Query(int L, int R){ this.L = L; this.R = R; }} class MO{ // Prints sum of all query ranges. m is number of queries // n is size of array a[]. static void queryResults(int a[], int n, ArrayList<Query> q, int m){ // Find block size int block = (int) Math.sqrt(n); // Sort all queries so that queries of same blocks // are arranged together. Collections.sort(q, new Comparator<Query>(){ // Function used to sort all queries so that all queries // of the same block are arranged together and within a block, // queries are sorted in increasing order of R values. public int compare(Query x, Query y){ // Different blocks, sort by block. if (x.L/block != y.L/block) return (x.L < y.L ? -1 : 1); // Same block, sort by R value return (x.R < y.R ? -1 : 1); } }); // Initialize current L, current R and current sum int currL = 0, currR = 0; int currSum = 0; // Traverse through all queries for (int i=0; i<m; i++) { // L and R values of current range int L = q.get(i).L, R = q.get(i).R; // Remove extra elements of previous range. For // example if previous range is [0, 3] and current // range is [2, 5], then a[0] and a[1] are subtracted while (currL < L) { currSum -= a[currL]; currL++; } // Add Elements of current Range while (currL > L) { currSum += a[currL-1]; currL--; } while (currR <= R) { currSum += a[currR]; currR++; } // Remove elements of previous range. For example // when previous range is [0, 10] and current range // is [3, 8], then a[9] and a[10] are subtracted while (currR > R+1) { currSum -= a[currR-1]; currR--; } // Print sum of current range System.out.println(\"Sum of [\" + L + \", \" + R + \"] is \" + currSum); } } // Driver program public static void main(String argv[]){ ArrayList<Query> q = new ArrayList<Query>(); q.add(new Query(0,4)); q.add(new Query(1,3)); q.add(new Query(2,4)); int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; queryResults(a, a.length, q, q.size()); }}// This code is contributed by Ajay",
"e": 39234,
"s": 36401,
"text": null
},
{
"code": "# Python program to compute sum of ranges for different range queries import math # Function that accepts array and list of queries and print sum of each querydef queryResults(arr,Q): #Q.sort(): # Sort by L #sort all queries so that all queries in the increasing order of R values . Q.sort(key=lambda x: x[1]) # Initialize current L, current R and current sum currL,currR,currSum = 0,0,0 # Traverse through all queries for i in range(len(Q)): L,R = Q[i] # L and R values of current range # Remove extra elements from previous range # if previous range is [0, 3] and current # range is [2, 5], then a[0] and a[1] are subtracted while currL<L: currSum-=arr[currL] currL+=1 # Add elements of current range while currL>L: currSum+=arr[currL-1] currL-=1 while currR<=R: currSum+=arr[currR] currR+=1 # Remove elements of previous range # when previous range is [0, 10] and current range # is [3, 8], then a[9] and a[10] are subtracted while currR>R+1: currSum-=arr[currR-1] currR-=1 # Print the sum of current range print(\"Sum of\",Q[i],\"is\",currSum) arr = [1, 1, 2, 1, 3, 4, 5, 2, 8]Q = [[0, 4], [1, 3], [2, 4]]queryResults(arr,Q)#This code is contributed by Shivam Singh",
"e": 40671,
"s": 39234,
"text": null
},
{
"code": null,
"e": 40680,
"s": 40671,
"text": "Output: "
},
{
"code": null,
"e": 40737,
"s": 40680,
"text": "Sum of [1, 3] is 4\nSum of [0, 4] is 8\nSum of [2, 4] is 6"
},
{
"code": null,
"e": 40909,
"s": 40737,
"text": "The output of above program doesn’t print results of queries in same order as input, because queries are sorted. The program can be easily extended to keep the same order."
},
{
"code": null,
"e": 40934,
"s": 40909,
"text": "Important Observations: "
},
{
"code": null,
"e": 41249,
"s": 40934,
"text": "All queries are known beforehead so that they can be preprocessedIt cannot work for problems where we have update operations also mixed with sum queries.MO’s algorithm can only be used for query problems where a query can be computed from results of the previous query. One more such example is maximum or minimum."
},
{
"code": null,
"e": 41315,
"s": 41249,
"text": "All queries are known beforehead so that they can be preprocessed"
},
{
"code": null,
"e": 41404,
"s": 41315,
"text": "It cannot work for problems where we have update operations also mixed with sum queries."
},
{
"code": null,
"e": 41566,
"s": 41404,
"text": "MO’s algorithm can only be used for query problems where a query can be computed from results of the previous query. One more such example is maximum or minimum."
},
{
"code": null,
"e": 41734,
"s": 41566,
"text": "Time Complexity Analysis: The function mainly runs a for loop for all sorted queries. Inside the for loop, there are four while queries that move ‘currL’ and ‘currR’. "
},
{
"code": null,
"e": 42119,
"s": 41734,
"text": "How much currR is moved? For each block, queries are sorted in increasing order of R. So, for a block, currR moves in increasing order. In worst case, before beginning of every block, currR at extreme right and current block moves it back the extreme left. This means that for every block, currR moves at most O(n). Since there are O(√n) blocks, total movement of currR is O(n * √n). "
},
{
"code": null,
"e": 42756,
"s": 42119,
"text": "How much currL is moved? Since all queries are sorted in a way that L values are grouped by blocks, movement is O(√n) when we move from one query to another quert. For m queries, total movement of currL is O(m * √n)Please note that a Simple and more Efficient solution to solve this problem is to compute prefix sum for all elements from 0 to n-1. Let the prefix sum be stored in an array preSum[] (The value of preSum[i] stores sum of arr[0..i]). Once we have built preSum[], we can traverse through all queries one by one. For every query [L, R], we return value of preSum[R] – preSum[L]. Here processing every query takes O(1) time. "
},
{
"code": null,
"e": 42778,
"s": 42756,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 42937,
"s": 42778,
"text": "The idea of this article is to introduce MO’s algorithm with a very simple example. We will soon be discussing more interesting problems using MO’s algorithm."
},
{
"code": null,
"e": 43002,
"s": 42937,
"text": "Range Minimum Query (Square Root Decomposition and Sparse Table)"
},
{
"code": null,
"e": 43225,
"s": 43002,
"text": "References: http://blog.anudeep2011.com/mos-algorithm/This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 43239,
"s": 43225,
"text": "AjayChaudhary"
},
{
"code": null,
"e": 43258,
"s": 43239,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 43272,
"s": 43258,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 43282,
"s": 43272,
"text": "pratham76"
},
{
"code": null,
"e": 43303,
"s": 43282,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 43316,
"s": 43303,
"text": "simmytarika5"
},
{
"code": null,
"e": 43328,
"s": 43316,
"text": "rishavnitro"
},
{
"code": null,
"e": 43348,
"s": 43328,
"text": "array-range-queries"
},
{
"code": null,
"e": 43359,
"s": 43348,
"text": "Algorithms"
},
{
"code": null,
"e": 43370,
"s": 43359,
"text": "Algorithms"
},
{
"code": null,
"e": 43468,
"s": 43370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43517,
"s": 43468,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 43542,
"s": 43517,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 43570,
"s": 43542,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 43621,
"s": 43570,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 43648,
"s": 43621,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 43675,
"s": 43648,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 43705,
"s": 43675,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 43748,
"s": 43705,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 43799,
"s": 43748,
"text": "Difference between NP hard and NP complete problem"
}
] |
Difference between preventDefault() and stopPropagation() methods in JavaScript | 04 Apr, 2022
In this article, we will be discussing the PreventDefault & stopPropagation methods with suitable code examples for each condition & then we will see the difference between the PreventDefault vs stopPropagation.
preventDefault() Method: It is a method present in the event interface. This method prevents the browser from executing the default behavior of the selected element. This method can cancel the event only if the event is cancelable. For example, there are some events that can not be prevented, such as the scroll and wheel event.
Syntax:
event.preventDefault();
Parameter: This method does not accept any parameter.
We will see the approaches for applying both methods with the help of the examples.
Example 1: Preventing a link from following the URL so that the browser can not go to another page.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <a id="first" href="www.geeksforgeeks.com"> GeeksForGeeks </a> <script> $("#first").click(function () { event.preventDefault(); alert("Event prevented, Can't go there."); }); </script></body> </html>
Output:
Example 2: It prevents the user from checking the checkboxes. Usually, when we click on the checkboxes, it toggles but nothing will work, after calling the preventDefault() method.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- Using jquery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <input type="checkbox" id="f" /> click on this box <script> $("#f").click(function () { event.preventDefault(); alert("Event prevented"); }); </script></body> </html>
Output:
stopPropagation() event method: This method is used to prevent the parent element from accessing the event. Basically, this method is used to prevent the propagation of the same event from being called. For eg, we have a button element inside a div tag and there is an onclick event on both of them, then whenever we try to activate the event attached to the button element, then the event attached to the div element also gets executed because div is the parent of the button element.
syntax:
event.stopPropagation();
We can solve this problem by using the stopPropagation() method because this will prevent the parent from accessing the event.
Example 1:
HTML
<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <div class="first" onclick="functionFirst()"> <button onclick="functionSecond()"> Button </button> </div> <script> function functionSecond() { alert("button hello"); } function functionFirst() { alert("div hello"); } </script></body> </html>
Output:
Here, after clicking on the button, both functions will be executed.
Example 2:
HTML
<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src="https://code.jquery.com/jquery-git.js"> </script></head> <body> <div class="first" onclick="functionFirst()"> <button onclick="functionSecond()"> Button </button> </div> <script> function functionSecond() { event.stopPropagation(); alert("button hello"); } function functionFirst() { alert("div hello"); } </script></body> </html>
Output:
Now, in this case, we have added an event.stopPropagation() method, then the only function of the button element will be executed.
event.preventDefault() Method
event.stopPropagation() Method
Its syntax is -:
event.preventDefault();
Its syntax is -:
event.stopPropagation();
mayank007rawa
JavaScript-Methods
JavaScript-Questions
Picked
Difference Between
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": "\n04 Apr, 2022"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "In this article, we will be discussing the PreventDefault & stopPropagation methods with suitable code examples for each condition & then we will see the difference between the PreventDefault vs stopPropagation."
},
{
"code": null,
"e": 570,
"s": 240,
"text": "preventDefault() Method: It is a method present in the event interface. This method prevents the browser from executing the default behavior of the selected element. This method can cancel the event only if the event is cancelable. For example, there are some events that can not be prevented, such as the scroll and wheel event."
},
{
"code": null,
"e": 578,
"s": 570,
"text": "Syntax:"
},
{
"code": null,
"e": 602,
"s": 578,
"text": "event.preventDefault();"
},
{
"code": null,
"e": 656,
"s": 602,
"text": "Parameter: This method does not accept any parameter."
},
{
"code": null,
"e": 740,
"s": 656,
"text": "We will see the approaches for applying both methods with the help of the examples."
},
{
"code": null,
"e": 840,
"s": 740,
"text": "Example 1: Preventing a link from following the URL so that the browser can not go to another page."
},
{
"code": null,
"e": 845,
"s": 840,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <a id=\"first\" href=\"www.geeksforgeeks.com\"> GeeksForGeeks </a> <script> $(\"#first\").click(function () { event.preventDefault(); alert(\"Event prevented, Can't go there.\"); }); </script></body> </html>",
"e": 1261,
"s": 845,
"text": null
},
{
"code": null,
"e": 1269,
"s": 1261,
"text": "Output:"
},
{
"code": null,
"e": 1450,
"s": 1269,
"text": "Example 2: It prevents the user from checking the checkboxes. Usually, when we click on the checkboxes, it toggles but nothing will work, after calling the preventDefault() method."
},
{
"code": null,
"e": 1455,
"s": 1450,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Using jquery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <input type=\"checkbox\" id=\"f\" /> click on this box <script> $(\"#f\").click(function () { event.preventDefault(); alert(\"Event prevented\"); }); </script></body> </html>",
"e": 1831,
"s": 1455,
"text": null
},
{
"code": null,
"e": 1839,
"s": 1831,
"text": "Output:"
},
{
"code": null,
"e": 2326,
"s": 1839,
"text": "stopPropagation() event method: This method is used to prevent the parent element from accessing the event. Basically, this method is used to prevent the propagation of the same event from being called. For eg, we have a button element inside a div tag and there is an onclick event on both of them, then whenever we try to activate the event attached to the button element, then the event attached to the div element also gets executed because div is the parent of the button element."
},
{
"code": null,
"e": 2334,
"s": 2326,
"text": "syntax:"
},
{
"code": null,
"e": 2359,
"s": 2334,
"text": "event.stopPropagation();"
},
{
"code": null,
"e": 2486,
"s": 2359,
"text": "We can solve this problem by using the stopPropagation() method because this will prevent the parent from accessing the event."
},
{
"code": null,
"e": 2497,
"s": 2486,
"text": "Example 1:"
},
{
"code": null,
"e": 2502,
"s": 2497,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <div class=\"first\" onclick=\"functionFirst()\"> <button onclick=\"functionSecond()\"> Button </button> </div> <script> function functionSecond() { alert(\"button hello\"); } function functionFirst() { alert(\"div hello\"); } </script></body> </html>",
"e": 2976,
"s": 2502,
"text": null
},
{
"code": null,
"e": 2984,
"s": 2976,
"text": "Output:"
},
{
"code": null,
"e": 3053,
"s": 2984,
"text": "Here, after clicking on the button, both functions will be executed."
},
{
"code": null,
"e": 3064,
"s": 3053,
"text": "Example 2:"
},
{
"code": null,
"e": 3069,
"s": 3064,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery library --> <script src=\"https://code.jquery.com/jquery-git.js\"> </script></head> <body> <div class=\"first\" onclick=\"functionFirst()\"> <button onclick=\"functionSecond()\"> Button </button> </div> <script> function functionSecond() { event.stopPropagation(); alert(\"button hello\"); } function functionFirst() { alert(\"div hello\"); } </script></body> </html>",
"e": 3579,
"s": 3069,
"text": null
},
{
"code": null,
"e": 3587,
"s": 3579,
"text": "Output:"
},
{
"code": null,
"e": 3718,
"s": 3587,
"text": "Now, in this case, we have added an event.stopPropagation() method, then the only function of the button element will be executed."
},
{
"code": null,
"e": 3748,
"s": 3718,
"text": "event.preventDefault() Method"
},
{
"code": null,
"e": 3779,
"s": 3748,
"text": "event.stopPropagation() Method"
},
{
"code": null,
"e": 3796,
"s": 3779,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3820,
"s": 3796,
"text": "event.preventDefault();"
},
{
"code": null,
"e": 3837,
"s": 3820,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3862,
"s": 3837,
"text": "event.stopPropagation();"
},
{
"code": null,
"e": 3876,
"s": 3862,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3895,
"s": 3876,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3916,
"s": 3895,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3923,
"s": 3916,
"text": "Picked"
},
{
"code": null,
"e": 3942,
"s": 3923,
"text": "Difference Between"
},
{
"code": null,
"e": 3953,
"s": 3942,
"text": "JavaScript"
},
{
"code": null,
"e": 3970,
"s": 3953,
"text": "Web Technologies"
}
] |
Python | Split strings in list with same prefix in all elements | 25 Apr, 2019
Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension + list slicing
This task can be performed using list comprehension and list slicing. List slicing can be used to remove the unwanted letters and list comprehension can be used to extend the logic to the entire string.
# Python3 code to demonstrate# Split strings in list# Using list comprehension + list slicing # initializing listtest_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + list slicing# Split strings in listres = [sub[3:] for sub in test_list] # print resultprint("The list after string slicing : " + str(res))
The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
The list after string slicing : ['25', '100', '143', '12', '4010']
Method #2 : Using map() + slicing + lambda
This particular task can be performed using map function as well. The task of performing the same for each string is handled by lambda function and map function.
# Python3 code to demonstrate# Split strings in list# Using map() + slicing + lambda # initializing listtest_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] # printing original listprint("The original list : " + str(test_list)) # using map() + slicing + lambda# Split strings in listres = list(map(lambda sub: sub[3:], test_list)) # print resultprint("The list after string slicing : " + str(res))
The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']
The list after string slicing : ['25', '100', '143', '12', '4010']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Apr, 2019"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 364,
"s": 312,
"text": "Method #1 : Using list comprehension + list slicing"
},
{
"code": null,
"e": 567,
"s": 364,
"text": "This task can be performed using list comprehension and list slicing. List slicing can be used to remove the unwanted letters and list comprehension can be used to extend the logic to the entire string."
},
{
"code": "# Python3 code to demonstrate# Split strings in list# Using list comprehension + list slicing # initializing listtest_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + list slicing# Split strings in listres = [sub[3:] for sub in test_list] # print resultprint(\"The list after string slicing : \" + str(res))",
"e": 985,
"s": 567,
"text": null
},
{
"code": null,
"e": 1123,
"s": 985,
"text": "The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']\nThe list after string slicing : ['25', '100', '143', '12', '4010']\n"
},
{
"code": null,
"e": 1168,
"s": 1125,
"text": "Method #2 : Using map() + slicing + lambda"
},
{
"code": null,
"e": 1330,
"s": 1168,
"text": "This particular task can be performed using map function as well. The task of performing the same for each string is handled by lambda function and map function."
},
{
"code": "# Python3 code to demonstrate# Split strings in list# Using map() + slicing + lambda # initializing listtest_list = ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010'] # printing original listprint(\"The original list : \" + str(test_list)) # using map() + slicing + lambda# Split strings in listres = list(map(lambda sub: sub[3:], test_list)) # print resultprint(\"The list after string slicing : \" + str(res))",
"e": 1741,
"s": 1330,
"text": null
},
{
"code": null,
"e": 1879,
"s": 1741,
"text": "The original list : ['Rs.25', 'Rs.100', 'Rs.143', 'Rs.12', 'Rs.4010']\nThe list after string slicing : ['25', '100', '143', '12', '4010']\n"
},
{
"code": null,
"e": 1900,
"s": 1879,
"text": "Python list-programs"
},
{
"code": null,
"e": 1907,
"s": 1900,
"text": "Python"
},
{
"code": null,
"e": 1923,
"s": 1907,
"text": "Python Programs"
},
{
"code": null,
"e": 2021,
"s": 1923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2039,
"s": 2021,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2081,
"s": 2039,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2103,
"s": 2081,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2129,
"s": 2103,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2161,
"s": 2129,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2183,
"s": 2161,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2222,
"s": 2183,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2260,
"s": 2222,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2309,
"s": 2260,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Represent Tree using graphics in C/C++ | 05 May, 2021
Prerequisite: graphics.h, How to include graphics.h?
In C/C++ there is graphics.h header file which is used to create the object like line, circle, etc. Given an array arr[] of N integers, the task is to write C++ program to create the Tree using graphics.h.
Approach: To run the program we have the include the below header file:
#include
We will create a Tree with the help below functions:
setcolor(color): This function present in graphic.h header file which is used to set the current drawing color to the new color.floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color is used to fill the area.circle(x, y, radius): The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius.outtextxy(): The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen.
setcolor(color): This function present in graphic.h header file which is used to set the current drawing color to the new color.
floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color is used to fill the area.
circle(x, y, radius): The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius.
outtextxy(): The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen.
Below is the implementation of to draw Tree using graphics in C++:
C++
// C++ program to draw the tree// in graphics.h#include <graphics.h>#include <iostream>#include <math.h>#include <sstream>using namespace std; // Function that prints Tree using// functions graphic.h header filevoid printTree(int x, int y, int* array, int index, int total_elements){ // Base Case if (index >= total_elements) return NULL; // Convert int value into string ostringstream str1; str1 << array[index]; string str2 = str1.str(); char* str = &str2[0u]; // Set color of the boundary of // circle as green setcolor(GREEN); // Draw the circle of radius 15 // that represent node of Tree circle(x, y, 15); floodfill(x, y, GREEN); // Print the values of the node // in the circle outtextxy(x - 2, y - 3, str); // Set the color of the line // from parent to child as green setcolor(GREEN); // Evaluating left and right child int left = 2 * index + 1; int right = 2 * index + 2; // Recursively draw the left subtree // and the right subtree printTree(x - y / (index + 1), y + 50, array, left, total_elements); printTree(x + y / (index + 1), y + 50, array, right, total_elements); // Draw the line (or link) when the // node is not the leaf node if (left < total_elements) { line(x, y, x - y / (index + 1), y + 50); } if (right < total_elements) { line(x, y, x + y / (index + 1), y + 50); } return NULL;} // Driver Codeint main(){ // Initialize graphic driver int gd = DETECT, gm; initgraph(&gd, &gm, "None"); // Consider the tree as represented /* 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / 8 9 10 */ // Given array arr[] int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Function Call printTree(300, 100, array, 0, 10); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph();}
Output:
arpit7714
arorakashish0911
computer-graphics
Trees
C++ Programs
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
C++ Program for QuickSort
How to find the minimum and maximum element of a Vector using STL in C++?
delete keyword in C++
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 106,
"s": 52,
"text": "Prerequisite: graphics.h, How to include graphics.h? "
},
{
"code": null,
"e": 312,
"s": 106,
"text": "In C/C++ there is graphics.h header file which is used to create the object like line, circle, etc. Given an array arr[] of N integers, the task is to write C++ program to create the Tree using graphics.h."
},
{
"code": null,
"e": 385,
"s": 312,
"text": "Approach: To run the program we have the include the below header file: "
},
{
"code": null,
"e": 395,
"s": 385,
"text": "#include "
},
{
"code": null,
"e": 449,
"s": 395,
"text": "We will create a Tree with the help below functions: "
},
{
"code": null,
"e": 995,
"s": 449,
"text": "setcolor(color): This function present in graphic.h header file which is used to set the current drawing color to the new color.floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color is used to fill the area.circle(x, y, radius): The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius.outtextxy(): The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen."
},
{
"code": null,
"e": 1124,
"s": 995,
"text": "setcolor(color): This function present in graphic.h header file which is used to set the current drawing color to the new color."
},
{
"code": null,
"e": 1260,
"s": 1124,
"text": "floodfill(pattern, color): function is used to fill an enclosed area. The current fill pattern and fill color is used to fill the area."
},
{
"code": null,
"e": 1397,
"s": 1260,
"text": "circle(x, y, radius): The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius."
},
{
"code": null,
"e": 1544,
"s": 1397,
"text": "outtextxy(): The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen."
},
{
"code": null,
"e": 1611,
"s": 1544,
"text": "Below is the implementation of to draw Tree using graphics in C++:"
},
{
"code": null,
"e": 1615,
"s": 1611,
"text": "C++"
},
{
"code": "// C++ program to draw the tree// in graphics.h#include <graphics.h>#include <iostream>#include <math.h>#include <sstream>using namespace std; // Function that prints Tree using// functions graphic.h header filevoid printTree(int x, int y, int* array, int index, int total_elements){ // Base Case if (index >= total_elements) return NULL; // Convert int value into string ostringstream str1; str1 << array[index]; string str2 = str1.str(); char* str = &str2[0u]; // Set color of the boundary of // circle as green setcolor(GREEN); // Draw the circle of radius 15 // that represent node of Tree circle(x, y, 15); floodfill(x, y, GREEN); // Print the values of the node // in the circle outtextxy(x - 2, y - 3, str); // Set the color of the line // from parent to child as green setcolor(GREEN); // Evaluating left and right child int left = 2 * index + 1; int right = 2 * index + 2; // Recursively draw the left subtree // and the right subtree printTree(x - y / (index + 1), y + 50, array, left, total_elements); printTree(x + y / (index + 1), y + 50, array, right, total_elements); // Draw the line (or link) when the // node is not the leaf node if (left < total_elements) { line(x, y, x - y / (index + 1), y + 50); } if (right < total_elements) { line(x, y, x + y / (index + 1), y + 50); } return NULL;} // Driver Codeint main(){ // Initialize graphic driver int gd = DETECT, gm; initgraph(&gd, &gm, \"None\"); // Consider the tree as represented /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 / \\ / 8 9 10 */ // Given array arr[] int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Function Call printTree(300, 100, array, 0, 10); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system closegraph();}",
"e": 3700,
"s": 1615,
"text": null
},
{
"code": null,
"e": 3709,
"s": 3700,
"text": "Output: "
},
{
"code": null,
"e": 3721,
"s": 3711,
"text": "arpit7714"
},
{
"code": null,
"e": 3738,
"s": 3721,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3756,
"s": 3738,
"text": "computer-graphics"
},
{
"code": null,
"e": 3762,
"s": 3756,
"text": "Trees"
},
{
"code": null,
"e": 3775,
"s": 3762,
"text": "C++ Programs"
},
{
"code": null,
"e": 3780,
"s": 3775,
"text": "Tree"
},
{
"code": null,
"e": 3785,
"s": 3780,
"text": "Tree"
},
{
"code": null,
"e": 3883,
"s": 3785,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3917,
"s": 3883,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 3977,
"s": 3917,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 4003,
"s": 3977,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 4077,
"s": 4003,
"text": "How to find the minimum and maximum element of a Vector using STL in C++?"
},
{
"code": null,
"e": 4099,
"s": 4077,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 4149,
"s": 4099,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 4184,
"s": 4149,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 4218,
"s": 4184,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 4247,
"s": 4218,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Print level order traversal line by line | Set 1 | 24 Jun, 2022
Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.For example consider the following tree
Example 1:
Output for above tree should be
20
8 22
4 12
10 14
Example 2:
1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
Note that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels in different lines.A simple solution is to print use the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel().
C++
Java
Python3
C#
Javascript
/* Function to line by line print level order traversal a tree*/void printLevelOrder(struct node* root){ int h = height(root); int i; for (i=1; i<=h; i++) { printGivenLevel(root, i); printf("\n"); }} /* Print nodes at a given level */void printGivenLevel(struct node* root, int level){ if (root == NULL) return; if (level == 1) printf("%d ", root->data); else if (level > 1) { printGivenLevel(root->left, level-1); printGivenLevel(root->right, level-1); }}
/* Function to line by line print level order traversal a tree*/static void printLevelOrder(Node root){ int h = height(root); int i; for (i=1; i<=h; i++) { printGivenLevel(root, i); System.out.println(); }}/* Print nodes at a given level */void printGivenLevel(Node root, int level){ if (root == null) return; if (level == 1) System.out.println(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}
# Python3 program for above approach def printlevelorder(root): h = height(root) for i in range(1, h + 1): givenspirallevel(root, i) def printGivenLevel(root, level): if root is None: return root if level == 1: print(root.val, end = ' ') elif level > 1: printGivenLevel(root.left, level - 1) printGivenLevel(root.right, level - 1) # This code is contributed by Praveen kumar
/* Print nodes at a given level */static void printGivenLevel(Node root, int level){ if (root == null) return; if (level == 1) Console.WriteLine(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}
/* Print nodes at a given level */function printGivenLevel(root, level){ if (root == null) return; if (level == 1) document.write(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}
Time complexity: O(n2)
Auxiliary Space: O(n)
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.
How to modify the iterative level order traversal (Method 2 of this) to levels line by line? The idea is similar to this post. We count the nodes at current level. And for every node, we enqueue its children to queue.
C++
Java
Python3
C#
Javascript
/* Iterative program to print levels line by line */#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct node{ struct node *left; int data; struct node *right;}; // Iterative method to do level order traversal// line by linevoid printLevelOrder(node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { node *node = q.front(); cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Utility function to create a new tree nodenode* newNode(int data){ node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown above node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); printLevelOrder(root); return 0;}
/* An Iterative Java program to print levels line by line */ import java.util.LinkedList;import java.util.Queue; public class LevelOrder{ // A Binary Tree Node static class Node { int data; Node left; Node right; // constructor Node(int data){ this.data = data; left = null; right =null; } } // Iterative method to do level order traversal line by line static void printLevelOrder(Node root) { // Base Case if(root == null) return; // Create an empty queue for level order traversal Queue<Node> q =new LinkedList<Node>(); // Enqueue Root and initialize height q.add(root); while(true) { // nodeCount (queue size) indicates number of nodes // at current level. int nodeCount = q.size(); if(nodeCount == 0) break; // Dequeue all nodes of current level and Enqueue all // nodes of next level while(nodeCount > 0) { Node node = q.peek(); System.out.print(node.data + " "); q.remove(); if(node.left != null) q.add(node.left); if(node.right != null) q.add(node.right); nodeCount--; } System.out.println(); } } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree shown in above diagram /* 1 / \ 2 3 / \ \ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); } }//This code is contributed by Sumit Ghosh
# Python3 program for above approachclass newNode: def __init__(self, data): self.val = data self.left = None self.right = None # Iterative method to do level order traversal# line by linedef printLevelOrder(root): # Base case if root is None: return # Create an empty queue for level order traversal q = [] # Enqueue root and initialize height q.append(root) while q: # nodeCount (queue size) indicates number # of nodes at current level. count = len(q) # Dequeue all nodes of current level and # Enqueue all nodes of next level while count > 0: temp = q.pop(0) print(temp.val, end = ' ') if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) count -= 1 print(' ') # Driver Coderoot = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(6); printLevelOrder(root); # This code is contributed by Praveen kumar
/* An Iterative C# program to printlevels line by line */using System;using System.Collections.Generic; public class LevelOrder{ // A Binary Tree Node class Node { public int data; public Node left; public Node right; // constructor public Node(int data) { this.data = data; left = null; right =null; } } // Iterative method to do level order // traversal line by line static void printLevelOrder(Node root) { // Base Case if(root == null) return; // Create an empty queue for level // order traversal Queue<Node> q =new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(root); while(true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if(nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while(nodeCount > 0) { Node node = q.Peek(); Console.Write(node.data + " "); q.Dequeue(); if(node.left != null) q.Enqueue(node.left); if(node.right != null) q.Enqueue(node.right); nodeCount--; } Console.WriteLine(); } } // Driver Code public static void Main(String[] args) { // Let us create binary tree shown // in above diagram /* 1 / \ 2 3 / \ \ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); }} // This code is contributed 29AjayKumar
<script> /* An Iterative Javascript program to print levels line by line */ class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Iterative method to do level order traversal line by line function printLevelOrder(root) { // Base Case if(root == null) return; // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(root); while(true) { // nodeCount (queue size) indicates number of nodes // at current level. let nodeCount = q.length; if(nodeCount == 0) break; // Dequeue all nodes of current level and Enqueue all // nodes of next level while(nodeCount > 0) { let node = q[0]; document.write(node.data + " "); q.shift(); if(node.left != null) q.push(node.left); if(node.right != null) q.push(node.right); nodeCount--; } document.write("</br>"); } } // Let us create binary tree shown in above diagram /* 1 / \ 2 3 / \ \ 4 5 6 */ let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); </script>
Output:
1
2 3
4 5 6
Time complexity: O(n) where n is no of nodes of binary tree
Auxiliary Space: O(n) for queue
Print level order traversal line by line | Set 1 | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint level order traversal line by line | Set 1 | 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 / 7:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WheCF0n2Hl4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Time complexity of this method is O(n) where n is number of nodes in given binary tree.Level order traversal line by line | Set 2 (Using Two Queues)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
29AjayKumar
princiraj1992
mepky
anikakapoor
noob2000
mukesh07
technophpfij
Amazon
cpp-queue
Hike
Microsoft
Morgan Stanley
tree-level-order
Tree
Morgan Stanley
Amazon
Microsoft
Hike
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 207,
"s": 52,
"text": "Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.For example consider the following tree "
},
{
"code": null,
"e": 218,
"s": 207,
"text": "Example 1:"
},
{
"code": null,
"e": 449,
"s": 218,
"text": "Output for above tree should be\n20\n8 22\n4 12\n10 14\n\nExample 2:\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9\nOutput for above tree should be\n1\n2 3\n4 5 6\n7 8 9<"
},
{
"code": null,
"e": 783,
"s": 449,
"text": "Note that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels in different lines.A simple solution is to print use the recursive function discussed in the level order traversal post and print a new line after every call to printGivenLevel(). "
},
{
"code": null,
"e": 787,
"s": 783,
"text": "C++"
},
{
"code": null,
"e": 792,
"s": 787,
"text": "Java"
},
{
"code": null,
"e": 800,
"s": 792,
"text": "Python3"
},
{
"code": null,
"e": 803,
"s": 800,
"text": "C#"
},
{
"code": null,
"e": 814,
"s": 803,
"text": "Javascript"
},
{
"code": "/* Function to line by line print level order traversal a tree*/void printLevelOrder(struct node* root){ int h = height(root); int i; for (i=1; i<=h; i++) { printGivenLevel(root, i); printf(\"\\n\"); }} /* Print nodes at a given level */void printGivenLevel(struct node* root, int level){ if (root == NULL) return; if (level == 1) printf(\"%d \", root->data); else if (level > 1) { printGivenLevel(root->left, level-1); printGivenLevel(root->right, level-1); }}",
"e": 1343,
"s": 814,
"text": null
},
{
"code": "/* Function to line by line print level order traversal a tree*/static void printLevelOrder(Node root){ int h = height(root); int i; for (i=1; i<=h; i++) { printGivenLevel(root, i); System.out.println(); }}/* Print nodes at a given level */void printGivenLevel(Node root, int level){ if (root == null) return; if (level == 1) System.out.println(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}",
"e": 1872,
"s": 1343,
"text": null
},
{
"code": "# Python3 program for above approach def printlevelorder(root): h = height(root) for i in range(1, h + 1): givenspirallevel(root, i) def printGivenLevel(root, level): if root is None: return root if level == 1: print(root.val, end = ' ') elif level > 1: printGivenLevel(root.left, level - 1) printGivenLevel(root.right, level - 1) # This code is contributed by Praveen kumar",
"e": 2302,
"s": 1872,
"text": null
},
{
"code": "/* Print nodes at a given level */static void printGivenLevel(Node root, int level){ if (root == null) return; if (level == 1) Console.WriteLine(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}",
"e": 2602,
"s": 2302,
"text": null
},
{
"code": "/* Print nodes at a given level */function printGivenLevel(root, level){ if (root == null) return; if (level == 1) document.write(root.data); else if (level > 1) { printGivenLevel(root.left, level-1); printGivenLevel(root.right, level-1); }}",
"e": 2887,
"s": 2602,
"text": null
},
{
"code": null,
"e": 2910,
"s": 2887,
"text": "Time complexity: O(n2)"
},
{
"code": null,
"e": 2932,
"s": 2910,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 2941,
"s": 2932,
"text": "Chapters"
},
{
"code": null,
"e": 2968,
"s": 2941,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 3018,
"s": 2968,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 3041,
"s": 3018,
"text": "captions off, selected"
},
{
"code": null,
"e": 3049,
"s": 3041,
"text": "English"
},
{
"code": null,
"e": 3073,
"s": 3049,
"text": "This is a modal window."
},
{
"code": null,
"e": 3142,
"s": 3073,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 3164,
"s": 3142,
"text": "End of dialog window."
},
{
"code": null,
"e": 3384,
"s": 3164,
"text": "How to modify the iterative level order traversal (Method 2 of this) to levels line by line? The idea is similar to this post. We count the nodes at current level. And for every node, we enqueue its children to queue. "
},
{
"code": null,
"e": 3388,
"s": 3384,
"text": "C++"
},
{
"code": null,
"e": 3393,
"s": 3388,
"text": "Java"
},
{
"code": null,
"e": 3401,
"s": 3393,
"text": "Python3"
},
{
"code": null,
"e": 3404,
"s": 3401,
"text": "C#"
},
{
"code": null,
"e": 3415,
"s": 3404,
"text": "Javascript"
},
{
"code": "/* Iterative program to print levels line by line */#include <iostream>#include <queue>using namespace std; // A Binary Tree Nodestruct node{ struct node *left; int data; struct node *right;}; // Iterative method to do level order traversal// line by linevoid printLevelOrder(node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<node *> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { node *node = q.front(); cout << node->data << \" \"; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Utility function to create a new tree nodenode* newNode(int data){ node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown above node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); printLevelOrder(root); return 0;}",
"e": 4981,
"s": 3415,
"text": null
},
{
"code": "/* An Iterative Java program to print levels line by line */ import java.util.LinkedList;import java.util.Queue; public class LevelOrder{ // A Binary Tree Node static class Node { int data; Node left; Node right; // constructor Node(int data){ this.data = data; left = null; right =null; } } // Iterative method to do level order traversal line by line static void printLevelOrder(Node root) { // Base Case if(root == null) return; // Create an empty queue for level order traversal Queue<Node> q =new LinkedList<Node>(); // Enqueue Root and initialize height q.add(root); while(true) { // nodeCount (queue size) indicates number of nodes // at current level. int nodeCount = q.size(); if(nodeCount == 0) break; // Dequeue all nodes of current level and Enqueue all // nodes of next level while(nodeCount > 0) { Node node = q.peek(); System.out.print(node.data + \" \"); q.remove(); if(node.left != null) q.add(node.left); if(node.right != null) q.add(node.right); nodeCount--; } System.out.println(); } } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree shown in above diagram /* 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); } }//This code is contributed by Sumit Ghosh",
"e": 7098,
"s": 4981,
"text": null
},
{
"code": "# Python3 program for above approachclass newNode: def __init__(self, data): self.val = data self.left = None self.right = None # Iterative method to do level order traversal# line by linedef printLevelOrder(root): # Base case if root is None: return # Create an empty queue for level order traversal q = [] # Enqueue root and initialize height q.append(root) while q: # nodeCount (queue size) indicates number # of nodes at current level. count = len(q) # Dequeue all nodes of current level and # Enqueue all nodes of next level while count > 0: temp = q.pop(0) print(temp.val, end = ' ') if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) count -= 1 print(' ') # Driver Coderoot = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.left = newNode(4);root.left.right = newNode(5);root.right.right = newNode(6); printLevelOrder(root); # This code is contributed by Praveen kumar",
"e": 8249,
"s": 7098,
"text": null
},
{
"code": "/* An Iterative C# program to printlevels line by line */using System;using System.Collections.Generic; public class LevelOrder{ // A Binary Tree Node class Node { public int data; public Node left; public Node right; // constructor public Node(int data) { this.data = data; left = null; right =null; } } // Iterative method to do level order // traversal line by line static void printLevelOrder(Node root) { // Base Case if(root == null) return; // Create an empty queue for level // order traversal Queue<Node> q =new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(root); while(true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if(nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while(nodeCount > 0) { Node node = q.Peek(); Console.Write(node.data + \" \"); q.Dequeue(); if(node.left != null) q.Enqueue(node.left); if(node.right != null) q.Enqueue(node.right); nodeCount--; } Console.WriteLine(); } } // Driver Code public static void Main(String[] args) { // Let us create binary tree shown // in above diagram /* 1 / \\ 2 3 / \\ \\ 4 5 6 */ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); }} // This code is contributed 29AjayKumar",
"e": 10346,
"s": 8249,
"text": null
},
{
"code": "<script> /* An Iterative Javascript program to print levels line by line */ class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Iterative method to do level order traversal line by line function printLevelOrder(root) { // Base Case if(root == null) return; // Create an empty queue for level order traversal let q = []; // Enqueue Root and initialize height q.push(root); while(true) { // nodeCount (queue size) indicates number of nodes // at current level. let nodeCount = q.length; if(nodeCount == 0) break; // Dequeue all nodes of current level and Enqueue all // nodes of next level while(nodeCount > 0) { let node = q[0]; document.write(node.data + \" \"); q.shift(); if(node.left != null) q.push(node.left); if(node.right != null) q.push(node.right); nodeCount--; } document.write(\"</br>\"); } } // Let us create binary tree shown in above diagram /* 1 / \\ 2 3 / \\ \\ 4 5 6 */ let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(6); printLevelOrder(root); </script>",
"e": 12114,
"s": 10346,
"text": null
},
{
"code": null,
"e": 12124,
"s": 12114,
"text": "Output: "
},
{
"code": null,
"e": 12136,
"s": 12124,
"text": "1\n2 3\n4 5 6"
},
{
"code": null,
"e": 12196,
"s": 12136,
"text": "Time complexity: O(n) where n is no of nodes of binary tree"
},
{
"code": null,
"e": 12228,
"s": 12196,
"text": "Auxiliary Space: O(n) for queue"
},
{
"code": null,
"e": 13144,
"s": 12230,
"text": "Print level order traversal line by line | Set 1 | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPrint level order traversal line by line | Set 1 | 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 / 7:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WheCF0n2Hl4\" 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": 13417,
"s": 13144,
"text": "Time complexity of this method is O(n) where n is number of nodes in given binary tree.Level order traversal line by line | Set 2 (Using Two Queues)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 13429,
"s": 13417,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13443,
"s": 13429,
"text": "princiraj1992"
},
{
"code": null,
"e": 13449,
"s": 13443,
"text": "mepky"
},
{
"code": null,
"e": 13461,
"s": 13449,
"text": "anikakapoor"
},
{
"code": null,
"e": 13470,
"s": 13461,
"text": "noob2000"
},
{
"code": null,
"e": 13479,
"s": 13470,
"text": "mukesh07"
},
{
"code": null,
"e": 13492,
"s": 13479,
"text": "technophpfij"
},
{
"code": null,
"e": 13499,
"s": 13492,
"text": "Amazon"
},
{
"code": null,
"e": 13509,
"s": 13499,
"text": "cpp-queue"
},
{
"code": null,
"e": 13514,
"s": 13509,
"text": "Hike"
},
{
"code": null,
"e": 13524,
"s": 13514,
"text": "Microsoft"
},
{
"code": null,
"e": 13539,
"s": 13524,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 13556,
"s": 13539,
"text": "tree-level-order"
},
{
"code": null,
"e": 13561,
"s": 13556,
"text": "Tree"
},
{
"code": null,
"e": 13576,
"s": 13561,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 13583,
"s": 13576,
"text": "Amazon"
},
{
"code": null,
"e": 13593,
"s": 13583,
"text": "Microsoft"
},
{
"code": null,
"e": 13598,
"s": 13593,
"text": "Hike"
},
{
"code": null,
"e": 13603,
"s": 13598,
"text": "Tree"
}
] |
Overview of Scaling: Vertical And Horizontal Scaling | 06 Aug, 2020
Given architecture is an example of a client-server based system. In this, there is a client who sends requests to the server and then the client receives a response from the server accordingly but when the number of users/clients increases, the load on the server increases enormously which makes it difficult for the server to perform efficiently and hence becomes slow. Therefore, it is important to make the server scalable in a way such that the server capacity increases according to the increasing traffic without any sort of failure.
It can be defined as a process to expand the existing configuration (servers/computers) to handle a large number of user requests or to manage the amount of load on the server. This process is called scalability. This can be done either by increasing the current system configuration (increasing RAM, number of servers) or adding more power to the configuration. Scalability plays a vital role in the designing of a system as it helps in responding to a large number of user requests more effectively and quickly.
There are two ways to do this :
Vertical Scaling Horizontal Scaling
Vertical Scaling
Horizontal Scaling
It is defined as the process of increasing the capacity of a single machine by adding more resources such as memory, storage, etc. to increase the throughput of the system. No new resource is added, rather the capability of the existing resources is made more efficient. This is called Vertical scaling. Vertical Scaling is also called the Scale-up approach.
Example: MySQL
It is easy to implementReduced software costs as no new resources are addedFewer efforts required to maintain this single system
It is easy to implement
Reduced software costs as no new resources are added
Fewer efforts required to maintain this single system
Single-point failureSince when the system (server) fails, the downtime is high because we only have a single serverHigh risk of hardware failures
Single-point failure
Since when the system (server) fails, the downtime is high because we only have a single server
High risk of hardware failures
When traffic increases, the server degrades in performance. The first possible solution that everyone has is to increase the power of their system. For instance, if earlier they used 8 GB RAM and 128 GB hard drive now with increasing traffic, the power of the system is affected. So a possible solution is to increase the existing RAM or hard drive storage, for e.g. the resources could be increased to 16 GB of RAM and 500 GB of a hard drive but this is not an ultimate solution as after a point of time, these capacities will reach a saturation point.
It is defined as the process of adding more instances of the same type to the existing pool of resources and not increasing the capacity of existing resources like in vertical scaling. This kind of scaling also helps in decreasing the load on the server. This is called Horizontal Scaling Horizontal Scaling is also called the Scale-out approach.
In this process, the number of servers is increased and not the individual capacity of the server. This is done with the help of a Load Balancer which basically routes the user requests to different servers according to the availability of the server. Thereby, increasing the overall performance of the system. In this way, the entire process is distributed among all servers rather than just depending on a single server. Example: NoSQL, Cassandra, and MongoDB
Fault Tolerance means that there is no single point of failure in this kind of scale because there are 5 servers here instead of 1 powerful server. So if anyone of the servers fails then there will be other servers for backup. Whereas, in Vertical Scaling there is single point failure i.e: if a server fails then the whole service is stopped.Low Latency: Latency refers to how late or delayed our request is being processed.Built-in backup
Fault Tolerance means that there is no single point of failure in this kind of scale because there are 5 servers here instead of 1 powerful server. So if anyone of the servers fails then there will be other servers for backup. Whereas, in Vertical Scaling there is single point failure i.e: if a server fails then the whole service is stopped.
Low Latency: Latency refers to how late or delayed our request is being processed.
Built-in backup
Not easy to implement as there are a number of components in this kind of scaleCost is highNetworking components like, router, load balancer are required
Not easy to implement as there are a number of components in this kind of scale
Cost is high
Networking components like, router, load balancer are required
For example, if there exists a system of the capacity of 8 GB of RAM and in future, there is a requirement of 16 GB of RAM then, rather than the increasing capacity of 8 GB RAM to 16 GB of RAM, similar instances of 8 GB RAM could be used to meet the requirements.
System-Design
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
Markov Decision Process
How to Run a Python Script using Docker?
Basics of API Testing Using Postman
ML | Underfitting and Overfitting
Copying Files to and from Docker Containers
Clustering in Machine Learning | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 596,
"s": 54,
"text": "Given architecture is an example of a client-server based system. In this, there is a client who sends requests to the server and then the client receives a response from the server accordingly but when the number of users/clients increases, the load on the server increases enormously which makes it difficult for the server to perform efficiently and hence becomes slow. Therefore, it is important to make the server scalable in a way such that the server capacity increases according to the increasing traffic without any sort of failure."
},
{
"code": null,
"e": 1110,
"s": 596,
"text": "It can be defined as a process to expand the existing configuration (servers/computers) to handle a large number of user requests or to manage the amount of load on the server. This process is called scalability. This can be done either by increasing the current system configuration (increasing RAM, number of servers) or adding more power to the configuration. Scalability plays a vital role in the designing of a system as it helps in responding to a large number of user requests more effectively and quickly."
},
{
"code": null,
"e": 1143,
"s": 1110,
"text": "There are two ways to do this : "
},
{
"code": null,
"e": 1180,
"s": 1143,
"text": "Vertical Scaling Horizontal Scaling "
},
{
"code": null,
"e": 1198,
"s": 1180,
"text": "Vertical Scaling "
},
{
"code": null,
"e": 1218,
"s": 1198,
"text": "Horizontal Scaling "
},
{
"code": null,
"e": 1578,
"s": 1218,
"text": "It is defined as the process of increasing the capacity of a single machine by adding more resources such as memory, storage, etc. to increase the throughput of the system. No new resource is added, rather the capability of the existing resources is made more efficient. This is called Vertical scaling. Vertical Scaling is also called the Scale-up approach. "
},
{
"code": null,
"e": 1595,
"s": 1578,
"text": "Example: MySQL "
},
{
"code": null,
"e": 1724,
"s": 1595,
"text": "It is easy to implementReduced software costs as no new resources are addedFewer efforts required to maintain this single system"
},
{
"code": null,
"e": 1748,
"s": 1724,
"text": "It is easy to implement"
},
{
"code": null,
"e": 1801,
"s": 1748,
"text": "Reduced software costs as no new resources are added"
},
{
"code": null,
"e": 1855,
"s": 1801,
"text": "Fewer efforts required to maintain this single system"
},
{
"code": null,
"e": 2001,
"s": 1855,
"text": "Single-point failureSince when the system (server) fails, the downtime is high because we only have a single serverHigh risk of hardware failures"
},
{
"code": null,
"e": 2022,
"s": 2001,
"text": "Single-point failure"
},
{
"code": null,
"e": 2118,
"s": 2022,
"text": "Since when the system (server) fails, the downtime is high because we only have a single server"
},
{
"code": null,
"e": 2149,
"s": 2118,
"text": "High risk of hardware failures"
},
{
"code": null,
"e": 2705,
"s": 2149,
"text": "When traffic increases, the server degrades in performance. The first possible solution that everyone has is to increase the power of their system. For instance, if earlier they used 8 GB RAM and 128 GB hard drive now with increasing traffic, the power of the system is affected. So a possible solution is to increase the existing RAM or hard drive storage, for e.g. the resources could be increased to 16 GB of RAM and 500 GB of a hard drive but this is not an ultimate solution as after a point of time, these capacities will reach a saturation point. "
},
{
"code": null,
"e": 3053,
"s": 2705,
"text": "It is defined as the process of adding more instances of the same type to the existing pool of resources and not increasing the capacity of existing resources like in vertical scaling. This kind of scaling also helps in decreasing the load on the server. This is called Horizontal Scaling Horizontal Scaling is also called the Scale-out approach. "
},
{
"code": null,
"e": 3517,
"s": 3053,
"text": "In this process, the number of servers is increased and not the individual capacity of the server. This is done with the help of a Load Balancer which basically routes the user requests to different servers according to the availability of the server. Thereby, increasing the overall performance of the system. In this way, the entire process is distributed among all servers rather than just depending on a single server. Example: NoSQL, Cassandra, and MongoDB "
},
{
"code": null,
"e": 3958,
"s": 3517,
"text": "Fault Tolerance means that there is no single point of failure in this kind of scale because there are 5 servers here instead of 1 powerful server. So if anyone of the servers fails then there will be other servers for backup. Whereas, in Vertical Scaling there is single point failure i.e: if a server fails then the whole service is stopped.Low Latency: Latency refers to how late or delayed our request is being processed.Built-in backup"
},
{
"code": null,
"e": 4302,
"s": 3958,
"text": "Fault Tolerance means that there is no single point of failure in this kind of scale because there are 5 servers here instead of 1 powerful server. So if anyone of the servers fails then there will be other servers for backup. Whereas, in Vertical Scaling there is single point failure i.e: if a server fails then the whole service is stopped."
},
{
"code": null,
"e": 4385,
"s": 4302,
"text": "Low Latency: Latency refers to how late or delayed our request is being processed."
},
{
"code": null,
"e": 4401,
"s": 4385,
"text": "Built-in backup"
},
{
"code": null,
"e": 4555,
"s": 4401,
"text": "Not easy to implement as there are a number of components in this kind of scaleCost is highNetworking components like, router, load balancer are required"
},
{
"code": null,
"e": 4635,
"s": 4555,
"text": "Not easy to implement as there are a number of components in this kind of scale"
},
{
"code": null,
"e": 4648,
"s": 4635,
"text": "Cost is high"
},
{
"code": null,
"e": 4711,
"s": 4648,
"text": "Networking components like, router, load balancer are required"
},
{
"code": null,
"e": 4977,
"s": 4711,
"text": "For example, if there exists a system of the capacity of 8 GB of RAM and in future, there is a requirement of 16 GB of RAM then, rather than the increasing capacity of 8 GB RAM to 16 GB of RAM, similar instances of 8 GB RAM could be used to meet the requirements. "
},
{
"code": null,
"e": 4991,
"s": 4977,
"text": "System-Design"
},
{
"code": null,
"e": 5017,
"s": 4991,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 5115,
"s": 5017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5138,
"s": 5115,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 5164,
"s": 5138,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5200,
"s": 5164,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5238,
"s": 5200,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 5262,
"s": 5238,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5303,
"s": 5262,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 5339,
"s": 5303,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 5373,
"s": 5339,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 5417,
"s": 5373,
"text": "Copying Files to and from Docker Containers"
}
] |
Matplotlib.pyplot.set_cmap() in Python | 19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The set_cmap() function in pyplot module of matplotlib library is used to set the default colormap, and applies it to the current image if any.
Syntax: matplotlib.pyplot.set_cmap(cmap)
Parameters:
cmap : This parameter is the colormap instance or the name of a registered colormap.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.pyplot.set_cmap() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as npang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1) angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.set_cmap("Greens")plt.title('matplotlib.pyplot.set_cmap() Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent) plt.set_cmap("gist_rainbow")plt.title('matplotlib.pyplot.set_cmap() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc."
},
{
"code": null,
"e": 477,
"s": 333,
"text": "The set_cmap() function in pyplot module of matplotlib library is used to set the default colormap, and applies it to the current image if any."
},
{
"code": null,
"e": 518,
"s": 477,
"text": "Syntax: matplotlib.pyplot.set_cmap(cmap)"
},
{
"code": null,
"e": 530,
"s": 518,
"text": "Parameters:"
},
{
"code": null,
"e": 615,
"s": 530,
"text": "cmap : This parameter is the colormap instance or the name of a registered colormap."
},
{
"code": null,
"e": 663,
"s": 615,
"text": "Returns: This method does not return any value."
},
{
"code": null,
"e": 753,
"s": 663,
"text": "Below examples illustrate the matplotlib.pyplot.set_cmap() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 764,
"s": 753,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as npang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1) angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat')plt.set_cmap(\"Greens\")plt.title('matplotlib.pyplot.set_cmap() Example')plt.show()",
"e": 1553,
"s": 764,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Output:"
},
{
"code": null,
"e": 1572,
"s": 1561,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent) plt.set_cmap(\"gist_rainbow\")plt.title('matplotlib.pyplot.set_cmap() Example')plt.show()",
"e": 2294,
"s": 1572,
"text": null
},
{
"code": null,
"e": 2302,
"s": 2294,
"text": "Output:"
},
{
"code": null,
"e": 2320,
"s": 2302,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2327,
"s": 2320,
"text": "Python"
},
{
"code": null,
"e": 2425,
"s": 2327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2443,
"s": 2425,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2485,
"s": 2443,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2507,
"s": 2485,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2542,
"s": 2507,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2568,
"s": 2542,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2600,
"s": 2568,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2629,
"s": 2600,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2656,
"s": 2629,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2686,
"s": 2656,
"text": "Iterate over a list in Python"
}
] |
Netcracker Interview Experience | 22 Feb, 2021
Round 1: The first round was an aptitude and coding test, an aptitude round quantitative aptitude, logical reasoning, and technical questions were asked. They were more intuitive. They were not very difficult but were very tricky.
Suggestion: Practice aptitude to gain confidence, accuracy, and speed.
There were 2 coding questions
https://www.geeksforgeeks.org/find-water-in-a-glass/A dynamic programming question, A 2D matrix was given with children as rows and toys as columns. The values at indexes are 0 or 1 as either a child can have this toy or not. I had to find a way to allocate a child a toy with a one-to-one relation. If exists then print “YES” then “NO”.
https://www.geeksforgeeks.org/find-water-in-a-glass/
A dynamic programming question, A 2D matrix was given with children as rows and toys as columns. The values at indexes are 0 or 1 as either a child can have this toy or not. I had to find a way to allocate a child a toy with a one-to-one relation. If exists then print “YES” then “NO”.
Round 2 (Technical round): The interviewer starts with some easy questions like personal questions to break the ice. After this, he starts asking questions based on my resume like projects, etc. He asked me to explain my projects and gave him my experience with creating projects and concepts used in them. The questions were based on OOPS. He then asked me some basic data structure questions.
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/
The interview goes about 40 minutes.
ROUND 3 (HR round):
Basic HR questions were asked.
Conclusion: Got selected
Marketing
Netcracker
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
TCS Ninja Interview Experience (2020 batch)
Amazon Interview Experience SDE-2 (3 Years Experienced)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
Tiger Analytics Interview Experience for Data Analyst (On-Campus) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "Round 1: The first round was an aptitude and coding test, an aptitude round quantitative aptitude, logical reasoning, and technical questions were asked. They were more intuitive. They were not very difficult but were very tricky."
},
{
"code": null,
"e": 330,
"s": 259,
"text": "Suggestion: Practice aptitude to gain confidence, accuracy, and speed."
},
{
"code": null,
"e": 360,
"s": 330,
"text": "There were 2 coding questions"
},
{
"code": null,
"e": 698,
"s": 360,
"text": "https://www.geeksforgeeks.org/find-water-in-a-glass/A dynamic programming question, A 2D matrix was given with children as rows and toys as columns. The values at indexes are 0 or 1 as either a child can have this toy or not. I had to find a way to allocate a child a toy with a one-to-one relation. If exists then print “YES” then “NO”."
},
{
"code": null,
"e": 751,
"s": 698,
"text": "https://www.geeksforgeeks.org/find-water-in-a-glass/"
},
{
"code": null,
"e": 1037,
"s": 751,
"text": "A dynamic programming question, A 2D matrix was given with children as rows and toys as columns. The values at indexes are 0 or 1 as either a child can have this toy or not. I had to find a way to allocate a child a toy with a one-to-one relation. If exists then print “YES” then “NO”."
},
{
"code": null,
"e": 1433,
"s": 1037,
"text": "Round 2 (Technical round): The interviewer starts with some easy questions like personal questions to break the ice. After this, he starts asking questions based on my resume like projects, etc. He asked me to explain my projects and gave him my experience with creating projects and concepts used in them. The questions were based on OOPS. He then asked me some basic data structure questions. "
},
{
"code": null,
"e": 1494,
"s": 1433,
"text": "https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/"
},
{
"code": null,
"e": 1555,
"s": 1494,
"text": "https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/"
},
{
"code": null,
"e": 1592,
"s": 1555,
"text": "The interview goes about 40 minutes."
},
{
"code": null,
"e": 1612,
"s": 1592,
"text": "ROUND 3 (HR round):"
},
{
"code": null,
"e": 1643,
"s": 1612,
"text": "Basic HR questions were asked."
},
{
"code": null,
"e": 1668,
"s": 1643,
"text": "Conclusion: Got selected"
},
{
"code": null,
"e": 1678,
"s": 1668,
"text": "Marketing"
},
{
"code": null,
"e": 1689,
"s": 1678,
"text": "Netcracker"
},
{
"code": null,
"e": 1711,
"s": 1689,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1809,
"s": 1711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1879,
"s": 1809,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 1952,
"s": 1879,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 1990,
"s": 1952,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 2034,
"s": 1990,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 2090,
"s": 2034,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 2136,
"s": 2090,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 2171,
"s": 2136,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 2209,
"s": 2171,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 2238,
"s": 2209,
"text": "Nagarro Interview Experience"
}
] |
Sorting 2D Vector in C++ | Set 1 (By row and column) | 18 Jan, 2022
A 2D vector is a vector of vectors. In C++, 2D vectors are used for creating matrices, tables, or any other structures, dynamically. Basically, It is a matrix implemented with the help of vectors. They are created using the <vector> header file.
Following is a program to demonstrate 2D vectors in C++:
CPP
// C++ code to demonstrate 2D vector#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver Codeint main(){ // Initializing 2D vector "vect" with // values vector<vector<int> > vect{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Displaying the 2D vector for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) cout << vect[i][j] << " "; cout << endl; } return 0;}
1 2 3
4 5 6
7 8 9
Case 1: To sort a particular row of 2D vector This type of sorting arranges a selected row of 2D vector in ascending order. This is achieved by using sort() and passing iterators of 1D vector as its arguments. In sort(), it generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. This function is included in <algorithm> header file.
CPP
// C++ code to demonstrate sorting of a// row of 2D vector#include <algorithm> // for sort()#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver Codeint main(){ // Initializing 2D vector "vect" with // values vector<vector<int> > vect{ { 3, 5, 1 }, { 4, 8, 6 }, { 7, 2, 9 } }; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << "The Matrix before sorting 1st row is:\n"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << " "; cout << endl; } // Use of "sort()" for sorting first row sort(vect[0].begin(), vect[0].end()); // Displaying the 2D vector after sorting cout << "The Matrix after sorting 1st row is:\n"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << " "; cout << endl; } return 0;}
The Matrix before sorting 1st row is:
3 5 1
4 8 6
7 2 9
The Matrix after sorting 1st row is:
1 3 5
4 8 6
7 2 9
Case 2: To sort the entire 2D vector on basis of a particular column
In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest value in the second column becomes the first row, the second smallest value in the second column becomes the second row, and so on.
{3, 5, 1},
{4, 8, 6},
{7, 2, 9};
After sorting this matrix by the second column, we get
{7, 2, 9} // Row with smallest value in second column
{3, 5, 1} // Row with smallest value in second column
{4, 8, 6}
This is achieved by passing a third argument in sort() as a call to the user-defined explicit function.
CPP
// C++ code to demonstrate sorting of a// 2D vector on basis of a column#include <algorithm> // for sort()#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver function to sort the 2D vector// on basis of a particular columnbool sortcol(const vector<int>& v1, const vector<int>& v2){ return v1[1] < v2[1];} // Driver Codeint main(){ // Initializing 2D vector "vect" with // values vector<vector<int> > vect{ { 3, 5, 1 }, { 4, 8, 6 }, { 7, 2, 9 } }; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:\n"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << " "; cout << endl; } // Use of "sort()" for sorting on basis // of 2nd column sort(vect.begin(), vect.end(), sortcol); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:\n"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << " "; cout << endl; } return 0;}
The Matrix before sorting is:
3 5 1
4 8 6
7 2 9
The Matrix after sorting is:
7 2 9
3 5 1
4 8 6
Must Read:
Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)
Sorting a Vector in C++
This article is contributed by Manjeet 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
CPP-Library
cpp-vector
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 300,
"s": 54,
"text": "A 2D vector is a vector of vectors. In C++, 2D vectors are used for creating matrices, tables, or any other structures, dynamically. Basically, It is a matrix implemented with the help of vectors. They are created using the <vector> header file."
},
{
"code": null,
"e": 357,
"s": 300,
"text": "Following is a program to demonstrate 2D vectors in C++:"
},
{
"code": null,
"e": 361,
"s": 357,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate 2D vector#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver Codeint main(){ // Initializing 2D vector \"vect\" with // values vector<vector<int> > vect{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Displaying the 2D vector for (int i = 0; i < vect.size(); i++) { for (int j = 0; j < vect[i].size(); j++) cout << vect[i][j] << \" \"; cout << endl; } return 0;}",
"e": 884,
"s": 361,
"text": null
},
{
"code": null,
"e": 905,
"s": 884,
"text": "1 2 3 \n4 5 6 \n7 8 9 "
},
{
"code": null,
"e": 1398,
"s": 905,
"text": "Case 1: To sort a particular row of 2D vector This type of sorting arranges a selected row of 2D vector in ascending order. This is achieved by using sort() and passing iterators of 1D vector as its arguments. In sort(), it generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. This function is included in <algorithm> header file. "
},
{
"code": null,
"e": 1402,
"s": 1398,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate sorting of a// row of 2D vector#include <algorithm> // for sort()#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver Codeint main(){ // Initializing 2D vector \"vect\" with // values vector<vector<int> > vect{ { 3, 5, 1 }, { 4, 8, 6 }, { 7, 2, 9 } }; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << \"The Matrix before sorting 1st row is:\\n\"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << \" \"; cout << endl; } // Use of \"sort()\" for sorting first row sort(vect[0].begin(), vect[0].end()); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting 1st row is:\\n\"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << \" \"; cout << endl; } return 0;}",
"e": 2540,
"s": 1402,
"text": null
},
{
"code": null,
"e": 2657,
"s": 2540,
"text": "The Matrix before sorting 1st row is:\n3 5 1 \n4 8 6 \n7 2 9 \nThe Matrix after sorting 1st row is:\n1 3 5 \n4 8 6 \n7 2 9 "
},
{
"code": null,
"e": 2726,
"s": 2657,
"text": "Case 2: To sort the entire 2D vector on basis of a particular column"
},
{
"code": null,
"e": 3011,
"s": 2726,
"text": "In this type of sorting 2D vector is entirely sorted on basis of a chosen column. For example, if the chosen column is second, the row with the smallest value in the second column becomes the first row, the second smallest value in the second column becomes the second row, and so on."
},
{
"code": null,
"e": 3046,
"s": 3011,
"text": "{3, 5, 1}, \n{4, 8, 6}, \n{7, 2, 9};"
},
{
"code": null,
"e": 3101,
"s": 3046,
"text": "After sorting this matrix by the second column, we get"
},
{
"code": null,
"e": 3221,
"s": 3101,
"text": "{7, 2, 9} // Row with smallest value in second column \n{3, 5, 1} // Row with smallest value in second column \n{4, 8, 6}"
},
{
"code": null,
"e": 3325,
"s": 3221,
"text": "This is achieved by passing a third argument in sort() as a call to the user-defined explicit function."
},
{
"code": null,
"e": 3329,
"s": 3325,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate sorting of a// 2D vector on basis of a column#include <algorithm> // for sort()#include <iostream>#include <vector> // for 2D vectorusing namespace std; // Driver function to sort the 2D vector// on basis of a particular columnbool sortcol(const vector<int>& v1, const vector<int>& v2){ return v1[1] < v2[1];} // Driver Codeint main(){ // Initializing 2D vector \"vect\" with // values vector<vector<int> > vect{ { 3, 5, 1 }, { 4, 8, 6 }, { 7, 2, 9 } }; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << \"The Matrix before sorting is:\\n\"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << \" \"; cout << endl; } // Use of \"sort()\" for sorting on basis // of 2nd column sort(vect.begin(), vect.end(), sortcol); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting is:\\n\"; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << vect[i][j] << \" \"; cout << endl; } return 0;}",
"e": 4647,
"s": 3329,
"text": null
},
{
"code": null,
"e": 4748,
"s": 4647,
"text": "The Matrix before sorting is:\n3 5 1 \n4 8 6 \n7 2 9 \nThe Matrix after sorting is:\n7 2 9 \n3 5 1 \n4 8 6 "
},
{
"code": null,
"e": 4759,
"s": 4748,
"text": "Must Read:"
},
{
"code": null,
"e": 4832,
"s": 4759,
"text": "Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)"
},
{
"code": null,
"e": 4856,
"s": 4832,
"text": "Sorting a Vector in C++"
},
{
"code": null,
"e": 5278,
"s": 4856,
"text": "This article is contributed by Manjeet 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5292,
"s": 5278,
"text": "anshikajain26"
},
{
"code": null,
"e": 5304,
"s": 5292,
"text": "CPP-Library"
},
{
"code": null,
"e": 5315,
"s": 5304,
"text": "cpp-vector"
},
{
"code": null,
"e": 5319,
"s": 5315,
"text": "STL"
},
{
"code": null,
"e": 5330,
"s": 5319,
"text": "C Language"
},
{
"code": null,
"e": 5334,
"s": 5330,
"text": "C++"
},
{
"code": null,
"e": 5338,
"s": 5334,
"text": "STL"
},
{
"code": null,
"e": 5342,
"s": 5338,
"text": "CPP"
},
{
"code": null,
"e": 5440,
"s": 5342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5457,
"s": 5440,
"text": "Substring in C++"
},
{
"code": null,
"e": 5479,
"s": 5457,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 5525,
"s": 5479,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 5570,
"s": 5525,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 5595,
"s": 5570,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5638,
"s": 5595,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5684,
"s": 5638,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 5738,
"s": 5684,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5781,
"s": 5738,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
TypeScript | Array push() Method | 18 Jun, 2020
The Array.push() is an inbuilt TypeScript function which is used to append the given element(s) in the last of the array and returns the length of the new array. Syntax:
array.push(element1, ..., elementN)
Parameter: This method accept a single parameter as mentioned above and described below:
element1, ..., elementN : This parameter is the elements to add to the end of the array.
Return Value: This method returns the length of the new array. Below examples illustrate Array push() method in TypeScript:
Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of push() method var val = arr.push(8) // printing element console.log( arr );</script>
Output:
[11,89,23,7,98,8]
Example 2:
JavaScript
<script> // Driver code var arr = [2, 5, 6, 3, 8, 9]; var val,j=0; // use of push() method for(j=0; j<4 ; j++){ var y = arr[j]; var x = y * j; val = arr.push(x); } // printing element console.log( arr );</script>
Output:
[2,5,6,3,8,9,0,5,12,9]
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 223,
"s": 53,
"text": "The Array.push() is an inbuilt TypeScript function which is used to append the given element(s) in the last of the array and returns the length of the new array. Syntax:"
},
{
"code": null,
"e": 260,
"s": 223,
"text": " array.push(element1, ..., elementN)"
},
{
"code": null,
"e": 349,
"s": 260,
"text": "Parameter: This method accept a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 438,
"s": 349,
"text": "element1, ..., elementN : This parameter is the elements to add to the end of the array."
},
{
"code": null,
"e": 562,
"s": 438,
"text": "Return Value: This method returns the length of the new array. Below examples illustrate Array push() method in TypeScript:"
},
{
"code": null,
"e": 574,
"s": 562,
"text": "Example 1: "
},
{
"code": null,
"e": 585,
"s": 574,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of push() method var val = arr.push(8) // printing element console.log( arr );</script>",
"e": 766,
"s": 585,
"text": null
},
{
"code": null,
"e": 775,
"s": 766,
"text": "Output: "
},
{
"code": null,
"e": 794,
"s": 775,
"text": "[11,89,23,7,98,8]\n"
},
{
"code": null,
"e": 806,
"s": 794,
"text": "Example 2: "
},
{
"code": null,
"e": 817,
"s": 806,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [2, 5, 6, 3, 8, 9]; var val,j=0; // use of push() method for(j=0; j<4 ; j++){ var y = arr[j]; var x = y * j; val = arr.push(x); } // printing element console.log( arr );</script>",
"e": 1077,
"s": 817,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1077,
"text": "Output: "
},
{
"code": null,
"e": 1110,
"s": 1086,
"text": "[2,5,6,3,8,9,0,5,12,9]\n"
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": "TypeScript"
},
{
"code": null,
"e": 1132,
"s": 1121,
"text": "JavaScript"
},
{
"code": null,
"e": 1149,
"s": 1132,
"text": "Web Technologies"
},
{
"code": null,
"e": 1247,
"s": 1149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1308,
"s": 1247,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1380,
"s": 1308,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1420,
"s": 1380,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1472,
"s": 1420,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1513,
"s": 1472,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1575,
"s": 1513,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1608,
"s": 1575,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1669,
"s": 1608,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1719,
"s": 1669,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Interview Preparation for Software Developer - GeeksforGeeks | 28 Jun, 2021
Most Important ones
Interview Preparation Course (Free)
How to prepare for ACM-ICPC
Internship Interview Experiences Company-Wise
How to prepare for Google Kickstart – a CodeJam competition?
How to prepare for Facebook Hacker Cup?
A step by step guide for placement preparation Set 1 – Basic
A step by step guide for placement preparation Set 2- Advanced
Top 10 algorithms in Interview Questions
Top 20 Greedy Algorithms Interview Questions
Top 20 Dynamic Programming Interview Questions
Top 20 Backtracking Algorithm Interview Questions
Top 20 Linked List Interview Question
Top 20 Hashing Technique based Interview Questions
Top 10 Interview Questions on Depth First Search (DFS)
Top 25 Interview Questions
Commonly asked Interview Questions for Front End Developers
Frequently asked questions for Java Developer Position from a fresher
Competitive Programming Contests
How to begin with Competitive Programming
Top 10 Algorithms and Data Structures for Competitive Programming
How to prepare for Google Asia Pacific University (APAC) Test ?
Subject Wise
10 Most asked Questions from Java Programmers
Commonly Asked C Programming Interview Questions | Set 1
Commonly Asked C Programming Interview Questions | Set 2
Commonly Asked Java Programming Interview Questions | Set 1
Commonly Asked Java Programming Interview Questions | Set 2
Commonly Asked OOP Interview Questions
Commonly Asked C++ Interview Questions
Commonly asked DBMS interview questions | Set 1
Commonly asked DBMS interview questions | Set 2
Commonly Asked Operating Systems Interview Questions | Set 1
Commonly Asked Data Structure Interview Questions.
Commonly Asked Algorithm Interview Questions
Commonly asked Computer Networks Interview Questions
Company Wise
Amazon’s most asked interview questions Set 1 Set 2
Microsoft’s most asked interview questions Set 1 Set 2
Accenture’s most asked Interview Questions
Prepare Yourself
Behavioral10 mistakes people tend to do in an Interview6 Tips to Prepare Behavioral Interview QuestionsTop 5 Common Mistakes in Technical On-site Interviews
10 mistakes people tend to do in an Interview
6 Tips to Prepare Behavioral Interview Questions
Top 5 Common Mistakes in Technical On-site Interviews
ProgrammingC++ STL TutorialJava Collections Tutorial
C++ STL Tutorial
Java Collections Tutorial
Aptitude, Reasoning and EnglishCampus Placement Preparation Course
Campus Placement Preparation Course
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. | [
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 29597,
"s": 29577,
"text": "Most Important ones"
},
{
"code": null,
"e": 29633,
"s": 29597,
"text": "Interview Preparation Course (Free)"
},
{
"code": null,
"e": 29661,
"s": 29633,
"text": "How to prepare for ACM-ICPC"
},
{
"code": null,
"e": 29707,
"s": 29661,
"text": "Internship Interview Experiences Company-Wise"
},
{
"code": null,
"e": 29768,
"s": 29707,
"text": "How to prepare for Google Kickstart – a CodeJam competition?"
},
{
"code": null,
"e": 29808,
"s": 29768,
"text": "How to prepare for Facebook Hacker Cup?"
},
{
"code": null,
"e": 29869,
"s": 29808,
"text": "A step by step guide for placement preparation Set 1 – Basic"
},
{
"code": null,
"e": 29932,
"s": 29869,
"text": "A step by step guide for placement preparation Set 2- Advanced"
},
{
"code": null,
"e": 29973,
"s": 29932,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 30018,
"s": 29973,
"text": "Top 20 Greedy Algorithms Interview Questions"
},
{
"code": null,
"e": 30065,
"s": 30018,
"text": "Top 20 Dynamic Programming Interview Questions"
},
{
"code": null,
"e": 30115,
"s": 30065,
"text": "Top 20 Backtracking Algorithm Interview Questions"
},
{
"code": null,
"e": 30153,
"s": 30115,
"text": "Top 20 Linked List Interview Question"
},
{
"code": null,
"e": 30204,
"s": 30153,
"text": "Top 20 Hashing Technique based Interview Questions"
},
{
"code": null,
"e": 30259,
"s": 30204,
"text": "Top 10 Interview Questions on Depth First Search (DFS)"
},
{
"code": null,
"e": 30286,
"s": 30259,
"text": "Top 25 Interview Questions"
},
{
"code": null,
"e": 30346,
"s": 30286,
"text": "Commonly asked Interview Questions for Front End Developers"
},
{
"code": null,
"e": 30416,
"s": 30346,
"text": "Frequently asked questions for Java Developer Position from a fresher"
},
{
"code": null,
"e": 30449,
"s": 30416,
"text": "Competitive Programming Contests"
},
{
"code": null,
"e": 30491,
"s": 30449,
"text": "How to begin with Competitive Programming"
},
{
"code": null,
"e": 30557,
"s": 30491,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
},
{
"code": null,
"e": 30621,
"s": 30557,
"text": "How to prepare for Google Asia Pacific University (APAC) Test ?"
},
{
"code": null,
"e": 30634,
"s": 30621,
"text": "Subject Wise"
},
{
"code": null,
"e": 30680,
"s": 30634,
"text": "10 Most asked Questions from Java Programmers"
},
{
"code": null,
"e": 30737,
"s": 30680,
"text": "Commonly Asked C Programming Interview Questions | Set 1"
},
{
"code": null,
"e": 30794,
"s": 30737,
"text": "Commonly Asked C Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 30854,
"s": 30794,
"text": "Commonly Asked Java Programming Interview Questions | Set 1"
},
{
"code": null,
"e": 30914,
"s": 30854,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 30953,
"s": 30914,
"text": "Commonly Asked OOP Interview Questions"
},
{
"code": null,
"e": 30992,
"s": 30953,
"text": "Commonly Asked C++ Interview Questions"
},
{
"code": null,
"e": 31040,
"s": 30992,
"text": "Commonly asked DBMS interview questions | Set 1"
},
{
"code": null,
"e": 31088,
"s": 31040,
"text": "Commonly asked DBMS interview questions | Set 2"
},
{
"code": null,
"e": 31149,
"s": 31088,
"text": "Commonly Asked Operating Systems Interview Questions | Set 1"
},
{
"code": null,
"e": 31200,
"s": 31149,
"text": "Commonly Asked Data Structure Interview Questions."
},
{
"code": null,
"e": 31245,
"s": 31200,
"text": "Commonly Asked Algorithm Interview Questions"
},
{
"code": null,
"e": 31298,
"s": 31245,
"text": "Commonly asked Computer Networks Interview Questions"
},
{
"code": null,
"e": 31311,
"s": 31298,
"text": "Company Wise"
},
{
"code": null,
"e": 31363,
"s": 31311,
"text": "Amazon’s most asked interview questions Set 1 Set 2"
},
{
"code": null,
"e": 31418,
"s": 31363,
"text": "Microsoft’s most asked interview questions Set 1 Set 2"
},
{
"code": null,
"e": 31461,
"s": 31418,
"text": "Accenture’s most asked Interview Questions"
},
{
"code": null,
"e": 31478,
"s": 31461,
"text": "Prepare Yourself"
},
{
"code": null,
"e": 31635,
"s": 31478,
"text": "Behavioral10 mistakes people tend to do in an Interview6 Tips to Prepare Behavioral Interview QuestionsTop 5 Common Mistakes in Technical On-site Interviews"
},
{
"code": null,
"e": 31681,
"s": 31635,
"text": "10 mistakes people tend to do in an Interview"
},
{
"code": null,
"e": 31730,
"s": 31681,
"text": "6 Tips to Prepare Behavioral Interview Questions"
},
{
"code": null,
"e": 31784,
"s": 31730,
"text": "Top 5 Common Mistakes in Technical On-site Interviews"
},
{
"code": null,
"e": 31837,
"s": 31784,
"text": "ProgrammingC++ STL TutorialJava Collections Tutorial"
},
{
"code": null,
"e": 31854,
"s": 31837,
"text": "C++ STL Tutorial"
},
{
"code": null,
"e": 31880,
"s": 31854,
"text": "Java Collections Tutorial"
},
{
"code": null,
"e": 31947,
"s": 31880,
"text": "Aptitude, Reasoning and EnglishCampus Placement Preparation Course"
},
{
"code": null,
"e": 31983,
"s": 31947,
"text": "Campus Placement Preparation Course"
}
] |
PriorityQueue toArray() Method in Java | 10 Dec, 2018
The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array.Syntax:Object[] arr = Priority_Queue.toArray()Parameters: The method does not take any parameters.Return Value: The method returns an array containing the elements similar to the priority queue.Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The array is:
For
Geeks
To
Welcome
Geeks
Program 2:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [5, 10, 25, 20, 15, 30]
The array is:
5
10
25
20
15
30
The java.util.PriorityQueue.toArray(arr[]) method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. It creates multiple arrays, unlike the previous method without parameters. This method copies all of the elements into the arr[].Syntax:Object[] arr1 = Priority_Queue.toArray(arr[])Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied.Return Value: The method returns an array containing the elements similar to the priority queue.Exception: The method might throw two types of exception:ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue.NullPointerException: If the array is Null, then this exception is thrown.Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method.// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println("The arr1[] is:"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The arr[] is:
For
Geeks
To
Welcome
Geeks
The arr1[] is:
For
Geeks
To
Welcome
Geeks
The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array.Syntax:Object[] arr = Priority_Queue.toArray()Parameters: The method does not take any parameters.Return Value: The method returns an array containing the elements similar to the priority queue.Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The array is:
For
Geeks
To
Welcome
Geeks
Program 2:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [5, 10, 25, 20, 15, 30]
The array is:
5
10
25
20
15
30
Syntax:
Object[] arr = Priority_Queue.toArray()
Parameters: The method does not take any parameters.
Return Value: The method returns an array containing the elements similar to the priority queue.
Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:
// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}
The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The array is:
For
Geeks
To
Welcome
Geeks
Program 2:
// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println("The array is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}
The PriorityQueue: [5, 10, 25, 20, 15, 30]
The array is:
5
10
25
20
15
30
The java.util.PriorityQueue.toArray(arr[]) method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. It creates multiple arrays, unlike the previous method without parameters. This method copies all of the elements into the arr[].Syntax:Object[] arr1 = Priority_Queue.toArray(arr[])Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied.Return Value: The method returns an array containing the elements similar to the priority queue.Exception: The method might throw two types of exception:ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue.NullPointerException: If the array is Null, then this exception is thrown.Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method.// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println("The arr1[] is:"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The arr[] is:
For
Geeks
To
Welcome
Geeks
The arr1[] is:
For
Geeks
To
Welcome
Geeks
Object[] arr1 = Priority_Queue.toArray(arr[])
Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied.
Return Value: The method returns an array containing the elements similar to the priority queue.
ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue.
NullPointerException: If the array is Null, then this exception is thrown.
Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method.
// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Displaying the PriorityQueue System.out.println("The PriorityQueue: " + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println("The arr[] is:"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println("The arr1[] is:"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}
The PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The arr[] is:
For
Geeks
To
Welcome
Geeks
The arr1[] is:
For
Geeks
To
Welcome
Geeks
Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 4385,
"s": 52,
"text": "The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array.Syntax:Object[] arr = Priority_Queue.toArray()Parameters: The method does not take any parameters.Return Value: The method returns an array containing the elements similar to the priority queue.Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe array is:\nFor\nGeeks\nTo\nWelcome\nGeeks\nProgram 2:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [5, 10, 25, 20, 15, 30]\nThe array is:\n5\n10\n25\n20\n15\n30\nThe java.util.PriorityQueue.toArray(arr[]) method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. It creates multiple arrays, unlike the previous method without parameters. This method copies all of the elements into the arr[].Syntax:Object[] arr1 = Priority_Queue.toArray(arr[])Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied.Return Value: The method returns an array containing the elements similar to the priority queue.Exception: The method might throw two types of exception:ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue.NullPointerException: If the array is Null, then this exception is thrown.Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method.// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println(\"The arr[] is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println(\"The arr1[] is:\"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe arr[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n\nThe arr1[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n"
},
{
"code": null,
"e": 6577,
"s": 4385,
"text": "The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array.Syntax:Object[] arr = Priority_Queue.toArray()Parameters: The method does not take any parameters.Return Value: The method returns an array containing the elements similar to the priority queue.Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe array is:\nFor\nGeeks\nTo\nWelcome\nGeeks\nProgram 2:// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}Output:The PriorityQueue: [5, 10, 25, 20, 15, 30]\nThe array is:\n5\n10\n25\n20\n15\n30\n"
},
{
"code": null,
"e": 6585,
"s": 6577,
"text": "Syntax:"
},
{
"code": null,
"e": 6625,
"s": 6585,
"text": "Object[] arr = Priority_Queue.toArray()"
},
{
"code": null,
"e": 6678,
"s": 6625,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 6775,
"s": 6678,
"text": "Return Value: The method returns an array containing the elements similar to the priority queue."
},
{
"code": null,
"e": 6857,
"s": 6775,
"text": "Below programs illustrate the java.util.PriorityQueue.toArray() method.Program 1:"
},
{
"code": "// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}",
"e": 7618,
"s": 6857,
"text": null
},
{
"code": null,
"e": 7712,
"s": 7618,
"text": "The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe array is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n"
},
{
"code": null,
"e": 7723,
"s": 7712,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate toArray()import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Use add() method to add elements into the Queue queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); queue.add(25); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() Object[] arr = queue.toArray(); System.out.println(\"The array is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); }}",
"e": 8485,
"s": 7723,
"text": null
},
{
"code": null,
"e": 8560,
"s": 8485,
"text": "The PriorityQueue: [5, 10, 25, 20, 15, 30]\nThe array is:\n5\n10\n25\n20\n15\n30\n"
},
{
"code": null,
"e": 10702,
"s": 8560,
"text": "The java.util.PriorityQueue.toArray(arr[]) method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. It creates multiple arrays, unlike the previous method without parameters. This method copies all of the elements into the arr[].Syntax:Object[] arr1 = Priority_Queue.toArray(arr[])Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied.Return Value: The method returns an array containing the elements similar to the priority queue.Exception: The method might throw two types of exception:ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue.NullPointerException: If the array is Null, then this exception is thrown.Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method.// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println(\"The arr[] is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println(\"The arr1[] is:\"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}Output:The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe arr[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n\nThe arr1[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n"
},
{
"code": null,
"e": 10748,
"s": 10702,
"text": "Object[] arr1 = Priority_Queue.toArray(arr[])"
},
{
"code": null,
"e": 10861,
"s": 10748,
"text": "Parameters: The method accepts one parameter arr[] into which all of the elements of the queue are to be copied."
},
{
"code": null,
"e": 10958,
"s": 10861,
"text": "Return Value: The method returns an array containing the elements similar to the priority queue."
},
{
"code": null,
"e": 11098,
"s": 10958,
"text": "ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the queue."
},
{
"code": null,
"e": 11173,
"s": 11098,
"text": "NullPointerException: If the array is Null, then this exception is thrown."
},
{
"code": null,
"e": 11265,
"s": 11173,
"text": "Below program illustrates the working of the java.util.PriorityQueue.toArray(arr[]) method."
},
{
"code": "// Java code to illustrate toArray(arr[])import java.util.*; public class PriorityQueueDemo { public static void main(String args[]) { // Creating an empty PriorityQueue PriorityQueue<String> queue = new PriorityQueue<String>(); // Use add() method to add elements into the Queue queue.add(\"Welcome\"); queue.add(\"To\"); queue.add(\"Geeks\"); queue.add(\"For\"); queue.add(\"Geeks\"); // Displaying the PriorityQueue System.out.println(\"The PriorityQueue: \" + queue); // Creating the array and using toArray() String[] arr = new String[5]; String[] arr1 = queue.toArray(arr); // Displaying arr System.out.println(\"The arr[] is:\"); for (int j = 0; j < arr.length; j++) System.out.println(arr[j]); // Displaying arr1 System.out.println(); System.out.println(\"The arr1[] is:\"); for (int i = 0; i < arr1.length; i++) System.out.println(arr1[i]); }}",
"e": 12304,
"s": 11265,
"text": null
},
{
"code": null,
"e": 12441,
"s": 12304,
"text": "The PriorityQueue: [For, Geeks, To, Welcome, Geeks]\nThe arr[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n\nThe arr1[] is:\nFor\nGeeks\nTo\nWelcome\nGeeks\n"
},
{
"code": null,
"e": 12461,
"s": 12441,
"text": "Java - util package"
},
{
"code": null,
"e": 12478,
"s": 12461,
"text": "Java-Collections"
},
{
"code": null,
"e": 12493,
"s": 12478,
"text": "Java-Functions"
},
{
"code": null,
"e": 12513,
"s": 12493,
"text": "java-priority-queue"
},
{
"code": null,
"e": 12518,
"s": 12513,
"text": "Java"
},
{
"code": null,
"e": 12523,
"s": 12518,
"text": "Java"
},
{
"code": null,
"e": 12540,
"s": 12523,
"text": "Java-Collections"
},
{
"code": null,
"e": 12638,
"s": 12540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12653,
"s": 12638,
"text": "Stream In Java"
},
{
"code": null,
"e": 12674,
"s": 12653,
"text": "Introduction to Java"
},
{
"code": null,
"e": 12695,
"s": 12674,
"text": "Constructors in Java"
},
{
"code": null,
"e": 12714,
"s": 12695,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 12731,
"s": 12714,
"text": "Generics in Java"
},
{
"code": null,
"e": 12761,
"s": 12731,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 12787,
"s": 12761,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 12803,
"s": 12787,
"text": "Strings in Java"
},
{
"code": null,
"e": 12840,
"s": 12803,
"text": "Differences between JDK, JRE and JVM"
}
] |
Maximum size square sub-matrix with all 1s | 25 Jun, 2022
Given a binary matrix, find out the maximum size square sub-matrix with all 1s.
For example, consider the below binary matrix.
Algorithm: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents the size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottom-most entry in sub-matrix.
1) Construct a sum matrix S[R][C] for the given M[R][C].
a) Copy first row and first columns as it is from M[][] to S[][]
b) For other entries, use following expressions to construct S[][]
If M[i][j] is 1 then
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
Else /*If M[i][j] is 0*/
S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print
sub-matrix of M[][]
For the given M[R][C] in the above example, constructed S[R][C] would be:
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.
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 2 2 0
1 2 2 3 1
0 0 0 0 0
The value of the maximum entry in the above matrix is 3 and the coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code for Maximum size square // sub-matrix with all 1s #include <bits/stdc++.h>#define bool int #define R 6 #define C 5 using namespace std; void printMaxSubSquare(bool M[R][C]) { int i,j; int S[R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = min({S[i][j-1], S[i-1][j], S[i-1][j-1]}) + 1; //better of using min in case of arguments more than 2 else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } cout<<"Maximum size sub-matrix is: \n"; for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { cout << M[i][j] << " "; } cout << "\n"; } } /* Driver code */int main() { bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } // This code is contributed by rathbhupendra
// C code for Maximum size square // sub-matrix with all 1s#include<stdio.h>#define bool int#define R 6#define C 5 void printMaxSubSquare(bool M[R][C]){int i,j;int S[R][C];int max_of_s, max_i, max_j; /* Set first column of S[][]*/for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/for(i = 1; i < R; i++){ for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */max_of_s = S[0][0]; max_i = 0; max_j = 0;for(i = 0; i < R; i++){ for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } printf("Maximum size sub-matrix is: \n");for(i = max_i; i > max_i - max_of_s; i--){ for(j = max_j; j > max_j - max_of_s; j--) { printf("%d ", M[i][j]); } printf("\n");} } /* UTILITY FUNCTIONS *//* Function to get minimum of three values */int min(int a, int b, int c){int m = a;if (m > b) m = b;if (m > c) m = c;return m;} /* Driver function to test above functions */int main(){bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M);getchar(); }
// JAVA Code for Maximum size square // sub-matrix with all 1spublic class GFG{ // method for Maximum size square sub-matrix with all 1s static void printMaxSubSquare(int M[][]) { int i,j; int R = M.length; //no of rows in M[][] int C = M[0].length; //no of columns in M[][] int S[][] = new int[R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = Math.min(S[i][j-1], Math.min(S[i-1][j], S[i-1][j-1])) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } System.out.println("Maximum size sub-matrix is: "); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { System.out.print(M[i][j] + " "); } System.out.println(); } } // Driver program public static void main(String[] args) { int M[][] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } }
# Python3 code for Maximum size# square sub-matrix with all 1s def printMaxSubSquare(M): R = len(M) # no. of rows in M[][] C = len(M[0]) # no. of columns in M[][] S = [] for i in range(R): temp = [] for j in range(C): if i==0 or j==0: temp += M[i][j], else: temp += 0, S += temp, # here we have set the first row and first column of S same as input matrix, other entries are set to 0 # Update other entries for i in range(1, R): for j in range(1, C): if (M[i][j] == 1): S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 else: S[i][j] = 0 # Find the maximum entry and # indices of maximum entry in S[][] max_of_s = S[0][0] max_i = 0 max_j = 0 for i in range(R): for j in range(C): if (max_of_s < S[i][j]): max_of_s = S[i][j] max_i = i max_j = j print("Maximum size sub-matrix is: ") for i in range(max_i, max_i - max_of_s, -1): for j in range(max_j, max_j - max_of_s, -1): print (M[i][j], end = " ") print("") # Driver ProgramM = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) # This code is contributed by Soumen Ghosh
// C# Code for Maximum size square // sub-matrix with all 1s using System; public class GFG{ // method for Maximum size square sub-matrix with all 1s static void printMaxSubSquare(int [,]M) { int i,j; //no of rows in M[,] int R = M.GetLength(0); //no of columns in M[,] int C = M.GetLength(1); int [,]S = new int[R,C]; int max_of_s, max_i, max_j; /* Set first column of S[,]*/ for(i = 0; i < R; i++) S[i,0] = M[i,0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0,j] = M[0,j]; /* Construct other entries of S[,]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i,j] == 1) S[i,j] = Math.Min(S[i,j-1], Math.Min(S[i-1,j], S[i-1,j-1])) + 1; else S[i,j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[,] */ max_of_s = S[0,0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i,j]) { max_of_s = S[i,j]; max_i = i; max_j = j; } } } Console.WriteLine("Maximum size sub-matrix is: "); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { Console.Write(M[i,j] + " "); } Console.WriteLine(); } } // Driver program public static void Main() { int [,]M = new int[6,5]{{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } }
<?php// PHP code for Maximum size square // sub-matrix with all 1s function printMaxSubSquare($M, $R, $C) { $S = array(array()) ; /* Set first column of S[][]*/ for($i = 0; $i < $R; $i++) $S[$i][0] = $M[$i][0]; /* Set first row of S[][]*/ for($j = 0; $j < $C; $j++) $S[0][$j] = $M[0][$j]; /* Construct other entries of S[][]*/ for($i = 1; $i < $R; $i++) { for($j = 1; $j < $C; $j++) { if($M[$i][$j] == 1) $S[$i][$j] = min($S[$i][$j - 1], $S[$i - 1][$j], $S[$i - 1][$j - 1]) + 1; else $S[$i][$j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ $max_of_s = $S[0][0]; $max_i = 0; $max_j = 0; for($i = 0; $i < $R; $i++) { for($j = 0; $j < $C; $j++) { if($max_of_s < $S[$i][$j]) { $max_of_s = $S[$i][$j]; $max_i = $i; $max_j = $j; } } } printf("Maximum size sub-matrix is: \n"); for($i = $max_i; $i > $max_i - $max_of_s; $i--) { for($j = $max_j; $j > $max_j - $max_of_s; $j--) { echo $M[$i][$j], " " ; } echo "\n" ; } } # Driver code$M = array(array(0, 1, 1, 0, 1), array(1, 1, 0, 1, 0), array(0, 1, 1, 1, 0), array(1, 1, 1, 1, 0), array(1, 1, 1, 1, 1), array(0, 0, 0, 0, 0)); $R = 6 ;$C = 5 ; printMaxSubSquare($M, $R, $C); // This code is contributed by Ryuga?>
<script>// JavaScript code for Maximum size square // sub-matrix with all 1s let R = 6;let C = 5; function printMaxSubSquare(M) { let i,j; let S = []; for ( var y = 0; y < R; y++ ) { S[ y ] = []; for ( var x = 0; x < C; x++ ) { S[ y ][ x ] = 0; }} let max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = Math.min(S[i][j-1],Math.min( S[i-1][j], S[i-1][j-1])) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } document.write("Maximum size sub-matrix is: <br>"); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { document.write( M[i][j] , " "); } document.write("<br>"); } } /* Driver code */let M = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]]; printMaxSubSquare(M); </script>
Output:
Maximum size sub-matrix is:
1 1 1
1 1 1
1 1 1
Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Auxiliary Space: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Algorithmic Paradigm: Dynamic Programming
Space Optimized Solution: In order to compute an entry at any position in the matrix we only need the current row and the previous row.
C++
Java
Javascript
Python3
C#
// C++ code for Maximum size square // sub-matrix with all 1s// (space optimized solution)#include <bits/stdc++.h> using namespace std; #define R 6 #define C 5 void printMaxSubSquare(bool M[R][C]) { int S[2][C], Max = 0; // set all elements of S to 0 first memset(S, 0, sizeof(S)); // Construct the entries for (int i = 0; i < R;i++) for (int j = 0; j < C;j++){ // Compute the entrie at the current position int Entrie = M[i][j]; if(Entrie) if(j) Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j])); // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = max(Max, Entrie); } // Print the square cout << "Maximum size sub-matrix is: \n"; for (int i = 0; i < Max; i++, cout << '\n') for (int j = 0; j < Max;j++) cout << "1 ";} // Driver codeint main (){ bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); return 0; // This code is contributed // by Gatea David}
// Java program for the above approachimport java.util.*; class GFG { static int R = 6 ; static int C = 5 ; static void printMaxSubSquare(int M[][]) { int S[][] = new int[2][C], Max = 0; // set all elements of S to 0 first for (int i = 0; i < 2;i++){ for (int j = 0; j < C;j++){ S[i][j] =0; } } // Construct the entries for (int i = 0; i < R; i++){ for (int j = 0; j < C; j++){ // Compute the entrie at the current position int Entrie = M[i][j]; if(Entrie != 0){ if(j != 0){ Entrie = 1 + Math.min(S[1][j - 1], Math.min(S[0][j - 1], S[1][j]));}} // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = Math.max(Max, Entrie); } } // Print the square System.out.print("Maximum size sub-matrix is: \n"); for (int i = 0; i < Max; i++){ for (int j = 0; j < Max;j++){ System.out.print( "1 ");} System.out.println(); } } // Driver Code public static void main(String[] args) { int M[][] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); }} // This code is contributed by code_hunt.
<script> // JavaScript code for Maximum size square // sub-matrix with all 1s// (space optimized solution)const R = 6 const C = 5 function printMaxSubSquare(M) { let Max = 0 let S = new Array(2) // set all elements of S to 0 first for(let i=0;i<2;i++){ S[i] = new Array(C).fill(0) } // Construct the entries for (let i = 0; i < R;i++) for (let j = 0; j < C;j++){ // Compute the entrie at the current position let Entrie = M[i][j]; if(Entrie) if(j) Entrie = 1 + Math.min(S[1][j - 1], Math.min(S[0][j - 1], S[1][j])); // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = Math.max(Max, Entrie); } // Print the square document.write("Maximum size sub-matrix is: ","</br>") for (let i = 0; i < Max; i++){ for (let j = 0; j < Max;j++) document.write("1 ") document.write("</br>") } } // Driver codeconst M = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) // This code is contributed by shinjanpatra </script>
# Python code for Maximum size square # sub-matrix with all 1s# (space optimized solution) R = 6 C = 5 def printMaxSubSquare(M): global R,C Max = 0 # set all elements of S to 0 first S = [[0 for col in range(C)]for row in range(2)] # Construct the entries for i in range(R): for j in range(C): # Compute the entrie at the current position Entrie = M[i][j] if(Entrie): if(j): Entrie = 1 + min(S[1][j - 1],min(S[0][j - 1], S[1][j])) # Save the last entrie and add the new one S[0][j] = S[1][j] S[1][j] = Entrie # Keep track of the max square length Max = max(Max, Entrie) # Print the square print("Maximum size sub-matrix is: ") for i in range(Max): for j in range(Max): print("1",end=" ") print() # Driver codeM = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) # This code is contributed by shinjanpatra
// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { static int R = 6 ; static int C = 5 ; static void printMaxSubSquare(int[,] M) { int[,] S = new int[2, C]; int Maxx = 0; // set all elements of S to 0 first for (int i = 0; i < 2;i++){ for (int j = 0; j < C;j++){ S[i, j] =0; } } // Construct the entries for (int i = 0; i < R; i++){ for (int j = 0; j < C; j++){ // Compute the entrie at the current position int Entrie = M[i, j]; if(Entrie != 0){ if(j != 0){ Entrie = 1 + Math.Min(S[1, j - 1], Math.Min(S[0, j - 1], S[1, j]));}} // Save the last entrie and add the new one S[0,j] = S[1,j]; S[1,j] = Entrie; // Keep track of the max square length Maxx = Math.Max(Maxx, Entrie); } } // Print the square Console.Write("Maximum size sub-matrix is: \n"); for (int i = 0; i < Maxx; i++){ for (int j = 0; j < Maxx;j++){ Console.Write( "1 ");} Console.WriteLine(); } } // Driver Codepublic static void Main(string[] args){ int[,] M = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M);}}
Maximum size sub-matrix is:
1 1 1
1 1 1
1 1 1
Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Auxiliary space: O(n) where n is the number of columns in the given matrix.
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem
tufan_gupta2000
ankthon
rathbhupendra
rohitsingh07052
sarques
davidgatea21
germanshephered48
code_hunt
djs
shinjanpatra
sanjoy_62
Amazon
Samsung
Dynamic Programming
Matrix
Amazon
Samsung
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 54,
"text": "Given a binary matrix, find out the maximum size square sub-matrix with all 1s. "
},
{
"code": null,
"e": 183,
"s": 135,
"text": "For example, consider the below binary matrix. "
},
{
"code": null,
"e": 479,
"s": 183,
"text": "Algorithm: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents the size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottom-most entry in sub-matrix. "
},
{
"code": null,
"e": 965,
"s": 479,
"text": "1) Construct a sum matrix S[R][C] for the given M[R][C].\n a) Copy first row and first columns as it is from M[][] to S[][]\n b) For other entries, use following expressions to construct S[][]\n If M[i][j] is 1 then\n S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1\n Else /*If M[i][j] is 0*/\n S[i][j] = 0\n2) Find the maximum entry in S[R][C]\n3) Using the value and coordinates of maximum entry in S[i], print \n sub-matrix of M[][]"
},
{
"code": null,
"e": 1039,
"s": 965,
"text": "For the given M[R][C] in the above example, constructed S[R][C] would be:"
},
{
"code": null,
"e": 1048,
"s": 1039,
"text": "Chapters"
},
{
"code": null,
"e": 1075,
"s": 1048,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1125,
"s": 1075,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1148,
"s": 1125,
"text": "captions off, selected"
},
{
"code": null,
"e": 1156,
"s": 1148,
"text": "English"
},
{
"code": null,
"e": 1180,
"s": 1156,
"text": "This is a modal window."
},
{
"code": null,
"e": 1249,
"s": 1180,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1271,
"s": 1249,
"text": "End of dialog window."
},
{
"code": null,
"e": 1373,
"s": 1271,
"text": " 0 1 1 0 1\n 1 1 0 1 0\n 0 1 1 1 0\n 1 1 2 2 0\n 1 2 2 3 1\n 0 0 0 0 0"
},
{
"code": null,
"e": 1561,
"s": 1373,
"text": "The value of the maximum entry in the above matrix is 3 and the coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix. "
},
{
"code": null,
"e": 1565,
"s": 1561,
"text": "C++"
},
{
"code": null,
"e": 1567,
"s": 1565,
"text": "C"
},
{
"code": null,
"e": 1572,
"s": 1567,
"text": "Java"
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Python3"
},
{
"code": null,
"e": 1583,
"s": 1580,
"text": "C#"
},
{
"code": null,
"e": 1587,
"s": 1583,
"text": "PHP"
},
{
"code": null,
"e": 1598,
"s": 1587,
"text": "Javascript"
},
{
"code": "// C++ code for Maximum size square // sub-matrix with all 1s #include <bits/stdc++.h>#define bool int #define R 6 #define C 5 using namespace std; void printMaxSubSquare(bool M[R][C]) { int i,j; int S[R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = min({S[i][j-1], S[i-1][j], S[i-1][j-1]}) + 1; //better of using min in case of arguments more than 2 else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } cout<<\"Maximum size sub-matrix is: \\n\"; for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { cout << M[i][j] << \" \"; } cout << \"\\n\"; } } /* Driver code */int main() { bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } // This code is contributed by rathbhupendra",
"e": 3382,
"s": 1598,
"text": null
},
{
"code": "// C code for Maximum size square // sub-matrix with all 1s#include<stdio.h>#define bool int#define R 6#define C 5 void printMaxSubSquare(bool M[R][C]){int i,j;int S[R][C];int max_of_s, max_i, max_j; /* Set first column of S[][]*/for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/for(i = 1; i < R; i++){ for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */max_of_s = S[0][0]; max_i = 0; max_j = 0;for(i = 0; i < R; i++){ for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } printf(\"Maximum size sub-matrix is: \\n\");for(i = max_i; i > max_i - max_of_s; i--){ for(j = max_j; j > max_j - max_of_s; j--) { printf(\"%d \", M[i][j]); } printf(\"\\n\");} } /* UTILITY FUNCTIONS *//* Function to get minimum of three values */int min(int a, int b, int c){int m = a;if (m > b) m = b;if (m > c) m = c;return m;} /* Driver function to test above functions */int main(){bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M);getchar(); } ",
"e": 4936,
"s": 3382,
"text": null
},
{
"code": "// JAVA Code for Maximum size square // sub-matrix with all 1spublic class GFG{ // method for Maximum size square sub-matrix with all 1s static void printMaxSubSquare(int M[][]) { int i,j; int R = M.length; //no of rows in M[][] int C = M[0].length; //no of columns in M[][] int S[][] = new int[R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = Math.min(S[i][j-1], Math.min(S[i-1][j], S[i-1][j-1])) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } System.out.println(\"Maximum size sub-matrix is: \"); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { System.out.print(M[i][j] + \" \"); } System.out.println(); } } // Driver program public static void main(String[] args) { int M[][] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } }",
"e": 7020,
"s": 4936,
"text": null
},
{
"code": "# Python3 code for Maximum size# square sub-matrix with all 1s def printMaxSubSquare(M): R = len(M) # no. of rows in M[][] C = len(M[0]) # no. of columns in M[][] S = [] for i in range(R): temp = [] for j in range(C): if i==0 or j==0: temp += M[i][j], else: temp += 0, S += temp, # here we have set the first row and first column of S same as input matrix, other entries are set to 0 # Update other entries for i in range(1, R): for j in range(1, C): if (M[i][j] == 1): S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 else: S[i][j] = 0 # Find the maximum entry and # indices of maximum entry in S[][] max_of_s = S[0][0] max_i = 0 max_j = 0 for i in range(R): for j in range(C): if (max_of_s < S[i][j]): max_of_s = S[i][j] max_i = i max_j = j print(\"Maximum size sub-matrix is: \") for i in range(max_i, max_i - max_of_s, -1): for j in range(max_j, max_j - max_of_s, -1): print (M[i][j], end = \" \") print(\"\") # Driver ProgramM = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) # This code is contributed by Soumen Ghosh",
"e": 8416,
"s": 7020,
"text": null
},
{
"code": "// C# Code for Maximum size square // sub-matrix with all 1s using System; public class GFG{ // method for Maximum size square sub-matrix with all 1s static void printMaxSubSquare(int [,]M) { int i,j; //no of rows in M[,] int R = M.GetLength(0); //no of columns in M[,] int C = M.GetLength(1); int [,]S = new int[R,C]; int max_of_s, max_i, max_j; /* Set first column of S[,]*/ for(i = 0; i < R; i++) S[i,0] = M[i,0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0,j] = M[0,j]; /* Construct other entries of S[,]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i,j] == 1) S[i,j] = Math.Min(S[i,j-1], Math.Min(S[i-1,j], S[i-1,j-1])) + 1; else S[i,j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[,] */ max_of_s = S[0,0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i,j]) { max_of_s = S[i,j]; max_i = i; max_j = j; } } } Console.WriteLine(\"Maximum size sub-matrix is: \"); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { Console.Write(M[i,j] + \" \"); } Console.WriteLine(); } } // Driver program public static void Main() { int [,]M = new int[6,5]{{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); } }",
"e": 10516,
"s": 8416,
"text": null
},
{
"code": "<?php// PHP code for Maximum size square // sub-matrix with all 1s function printMaxSubSquare($M, $R, $C) { $S = array(array()) ; /* Set first column of S[][]*/ for($i = 0; $i < $R; $i++) $S[$i][0] = $M[$i][0]; /* Set first row of S[][]*/ for($j = 0; $j < $C; $j++) $S[0][$j] = $M[0][$j]; /* Construct other entries of S[][]*/ for($i = 1; $i < $R; $i++) { for($j = 1; $j < $C; $j++) { if($M[$i][$j] == 1) $S[$i][$j] = min($S[$i][$j - 1], $S[$i - 1][$j], $S[$i - 1][$j - 1]) + 1; else $S[$i][$j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ $max_of_s = $S[0][0]; $max_i = 0; $max_j = 0; for($i = 0; $i < $R; $i++) { for($j = 0; $j < $C; $j++) { if($max_of_s < $S[$i][$j]) { $max_of_s = $S[$i][$j]; $max_i = $i; $max_j = $j; } } } printf(\"Maximum size sub-matrix is: \\n\"); for($i = $max_i; $i > $max_i - $max_of_s; $i--) { for($j = $max_j; $j > $max_j - $max_of_s; $j--) { echo $M[$i][$j], \" \" ; } echo \"\\n\" ; } } # Driver code$M = array(array(0, 1, 1, 0, 1), array(1, 1, 0, 1, 0), array(0, 1, 1, 1, 0), array(1, 1, 1, 1, 0), array(1, 1, 1, 1, 1), array(0, 0, 0, 0, 0)); $R = 6 ;$C = 5 ; printMaxSubSquare($M, $R, $C); // This code is contributed by Ryuga?>",
"e": 12207,
"s": 10516,
"text": null
},
{
"code": "<script>// JavaScript code for Maximum size square // sub-matrix with all 1s let R = 6;let C = 5; function printMaxSubSquare(M) { let i,j; let S = []; for ( var y = 0; y < R; y++ ) { S[ y ] = []; for ( var x = 0; x < C; x++ ) { S[ y ][ x ] = 0; }} let max_of_s, max_i, max_j; /* Set first column of S[][]*/ for(i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for(j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == 1) S[i][j] = Math.min(S[i][j-1],Math.min( S[i-1][j], S[i-1][j-1])) + 1; else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } document.write(\"Maximum size sub-matrix is: <br>\"); for(i = max_i; i > max_i - max_of_s; i--) { for(j = max_j; j > max_j - max_of_s; j--) { document.write( M[i][j] , \" \"); } document.write(\"<br>\"); } } /* Driver code */let M = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]]; printMaxSubSquare(M); </script>",
"e": 13911,
"s": 12207,
"text": null
},
{
"code": null,
"e": 13920,
"s": 13911,
"text": "Output: "
},
{
"code": null,
"e": 13970,
"s": 13920,
"text": "Maximum size sub-matrix is: \n1 1 1 \n1 1 1 \n1 1 1 "
},
{
"code": null,
"e": 14224,
"s": 13970,
"text": "Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Auxiliary Space: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Algorithmic Paradigm: Dynamic Programming"
},
{
"code": null,
"e": 14360,
"s": 14224,
"text": "Space Optimized Solution: In order to compute an entry at any position in the matrix we only need the current row and the previous row."
},
{
"code": null,
"e": 14364,
"s": 14360,
"text": "C++"
},
{
"code": null,
"e": 14369,
"s": 14364,
"text": "Java"
},
{
"code": null,
"e": 14380,
"s": 14369,
"text": "Javascript"
},
{
"code": null,
"e": 14388,
"s": 14380,
"text": "Python3"
},
{
"code": null,
"e": 14391,
"s": 14388,
"text": "C#"
},
{
"code": "// C++ code for Maximum size square // sub-matrix with all 1s// (space optimized solution)#include <bits/stdc++.h> using namespace std; #define R 6 #define C 5 void printMaxSubSquare(bool M[R][C]) { int S[2][C], Max = 0; // set all elements of S to 0 first memset(S, 0, sizeof(S)); // Construct the entries for (int i = 0; i < R;i++) for (int j = 0; j < C;j++){ // Compute the entrie at the current position int Entrie = M[i][j]; if(Entrie) if(j) Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j])); // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = max(Max, Entrie); } // Print the square cout << \"Maximum size sub-matrix is: \\n\"; for (int i = 0; i < Max; i++, cout << '\\n') for (int j = 0; j < Max;j++) cout << \"1 \";} // Driver codeint main (){ bool M[R][C] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); return 0; // This code is contributed // by Gatea David}",
"e": 15756,
"s": 14391,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { static int R = 6 ; static int C = 5 ; static void printMaxSubSquare(int M[][]) { int S[][] = new int[2][C], Max = 0; // set all elements of S to 0 first for (int i = 0; i < 2;i++){ for (int j = 0; j < C;j++){ S[i][j] =0; } } // Construct the entries for (int i = 0; i < R; i++){ for (int j = 0; j < C; j++){ // Compute the entrie at the current position int Entrie = M[i][j]; if(Entrie != 0){ if(j != 0){ Entrie = 1 + Math.min(S[1][j - 1], Math.min(S[0][j - 1], S[1][j]));}} // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = Math.max(Max, Entrie); } } // Print the square System.out.print(\"Maximum size sub-matrix is: \\n\"); for (int i = 0; i < Max; i++){ for (int j = 0; j < Max;j++){ System.out.print( \"1 \");} System.out.println(); } } // Driver Code public static void main(String[] args) { int M[][] = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M); }} // This code is contributed by code_hunt.",
"e": 17151,
"s": 15756,
"text": null
},
{
"code": "<script> // JavaScript code for Maximum size square // sub-matrix with all 1s// (space optimized solution)const R = 6 const C = 5 function printMaxSubSquare(M) { let Max = 0 let S = new Array(2) // set all elements of S to 0 first for(let i=0;i<2;i++){ S[i] = new Array(C).fill(0) } // Construct the entries for (let i = 0; i < R;i++) for (let j = 0; j < C;j++){ // Compute the entrie at the current position let Entrie = M[i][j]; if(Entrie) if(j) Entrie = 1 + Math.min(S[1][j - 1], Math.min(S[0][j - 1], S[1][j])); // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = Math.max(Max, Entrie); } // Print the square document.write(\"Maximum size sub-matrix is: \",\"</br>\") for (let i = 0; i < Max; i++){ for (let j = 0; j < Max;j++) document.write(\"1 \") document.write(\"</br>\") } } // Driver codeconst M = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) // This code is contributed by shinjanpatra </script>",
"e": 18576,
"s": 17151,
"text": null
},
{
"code": "# Python code for Maximum size square # sub-matrix with all 1s# (space optimized solution) R = 6 C = 5 def printMaxSubSquare(M): global R,C Max = 0 # set all elements of S to 0 first S = [[0 for col in range(C)]for row in range(2)] # Construct the entries for i in range(R): for j in range(C): # Compute the entrie at the current position Entrie = M[i][j] if(Entrie): if(j): Entrie = 1 + min(S[1][j - 1],min(S[0][j - 1], S[1][j])) # Save the last entrie and add the new one S[0][j] = S[1][j] S[1][j] = Entrie # Keep track of the max square length Max = max(Max, Entrie) # Print the square print(\"Maximum size sub-matrix is: \") for i in range(Max): for j in range(Max): print(\"1\",end=\" \") print() # Driver codeM = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) # This code is contributed by shinjanpatra",
"e": 19789,
"s": 18576,
"text": null
},
{
"code": "// C# code to implement the approachusing System;using System.Numerics;using System.Collections.Generic; public class GFG { static int R = 6 ; static int C = 5 ; static void printMaxSubSquare(int[,] M) { int[,] S = new int[2, C]; int Maxx = 0; // set all elements of S to 0 first for (int i = 0; i < 2;i++){ for (int j = 0; j < C;j++){ S[i, j] =0; } } // Construct the entries for (int i = 0; i < R; i++){ for (int j = 0; j < C; j++){ // Compute the entrie at the current position int Entrie = M[i, j]; if(Entrie != 0){ if(j != 0){ Entrie = 1 + Math.Min(S[1, j - 1], Math.Min(S[0, j - 1], S[1, j]));}} // Save the last entrie and add the new one S[0,j] = S[1,j]; S[1,j] = Entrie; // Keep track of the max square length Maxx = Math.Max(Maxx, Entrie); } } // Print the square Console.Write(\"Maximum size sub-matrix is: \\n\"); for (int i = 0; i < Maxx; i++){ for (int j = 0; j < Maxx;j++){ Console.Write( \"1 \");} Console.WriteLine(); } } // Driver Codepublic static void Main(string[] args){ int[,] M = {{0, 1, 1, 0, 1}, {1, 1, 0, 1, 0}, {0, 1, 1, 1, 0}, {1, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {0, 0, 0, 0, 0}}; printMaxSubSquare(M);}}",
"e": 21191,
"s": 19789,
"text": null
},
{
"code": null,
"e": 21241,
"s": 21191,
"text": "Maximum size sub-matrix is: \n1 1 1 \n1 1 1 \n1 1 1 "
},
{
"code": null,
"e": 21424,
"s": 21241,
"text": "Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the given matrix. Auxiliary space: O(n) where n is the number of columns in the given matrix. "
},
{
"code": null,
"e": 21541,
"s": 21424,
"text": "Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem "
},
{
"code": null,
"e": 21557,
"s": 21541,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 21565,
"s": 21557,
"text": "ankthon"
},
{
"code": null,
"e": 21579,
"s": 21565,
"text": "rathbhupendra"
},
{
"code": null,
"e": 21595,
"s": 21579,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 21603,
"s": 21595,
"text": "sarques"
},
{
"code": null,
"e": 21616,
"s": 21603,
"text": "davidgatea21"
},
{
"code": null,
"e": 21634,
"s": 21616,
"text": "germanshephered48"
},
{
"code": null,
"e": 21644,
"s": 21634,
"text": "code_hunt"
},
{
"code": null,
"e": 21648,
"s": 21644,
"text": "djs"
},
{
"code": null,
"e": 21661,
"s": 21648,
"text": "shinjanpatra"
},
{
"code": null,
"e": 21671,
"s": 21661,
"text": "sanjoy_62"
},
{
"code": null,
"e": 21678,
"s": 21671,
"text": "Amazon"
},
{
"code": null,
"e": 21686,
"s": 21678,
"text": "Samsung"
},
{
"code": null,
"e": 21706,
"s": 21686,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21713,
"s": 21706,
"text": "Matrix"
},
{
"code": null,
"e": 21720,
"s": 21713,
"text": "Amazon"
},
{
"code": null,
"e": 21728,
"s": 21720,
"text": "Samsung"
},
{
"code": null,
"e": 21748,
"s": 21728,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 21755,
"s": 21748,
"text": "Matrix"
},
{
"code": null,
"e": 21853,
"s": 21755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21885,
"s": 21853,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 21915,
"s": 21885,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 21944,
"s": 21915,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 21978,
"s": 21944,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 22005,
"s": 21978,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 22040,
"s": 22005,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 22084,
"s": 22040,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 22115,
"s": 22084,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 22139,
"s": 22115,
"text": "Sudoku | Backtracking-7"
}
] |
JavaScript Comma operator | 06 Jan, 2022
Below is the example of the Comma operator.
Example:<script> function x() { document.write('one'+"</br>"); return 'one'; } function y() { document.write('two'+"</br>"); return 'two'; } function z() { document.write('three'+"</br>"); return 'three'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x); </script>
Example:
<script> function x() { document.write('one'+"</br>"); return 'one'; } function y() { document.write('two'+"</br>"); return 'two'; } function z() { document.write('three'+"</br>"); return 'three'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x); </script>
Output:one
two
three
three
Output:
one
two
three
three
A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++ etc. This operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. A comma operator is used as a separator for multiple expressions at a place that requires a single expression. When a comma operator is placed in an expression, it executes each expression and returns the rightmost expression.
Syntax:
Expression1, Expression2, Expression3, ....so on
In the above syntax, multiple expressions are separated using a comma operator. During execution, each expression will be executed from left to right and the rightmost expression will be returned.
Example:
<script> function x() { document.write('Welcome'); return 'Welcome'; } function y() { document.write('to'); return 'to'; } function z() { document.write('Geeksforgeeks'); return 'Geeksforgeeks'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x);</script>
Output:
In the output, first of all the function x() is executed then y() and lastly z(). Finally, comma operator returns rightmost expression.
The most useful application of comma operator is in loops. In loops, it is used to update multiple variables in the same expression.
Example:
<script> for (var a = 0, b =5; a <= 5; a++, b--) { document.write(a, b);}</script>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
javascript-basics
javascript-operators
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 97,
"s": 53,
"text": "Below is the example of the Comma operator."
},
{
"code": null,
"e": 498,
"s": 97,
"text": "Example:<script> function x() { document.write('one'+\"</br>\"); return 'one'; } function y() { document.write('two'+\"</br>\"); return 'two'; } function z() { document.write('three'+\"</br>\"); return 'three'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x); </script> "
},
{
"code": null,
"e": 507,
"s": 498,
"text": "Example:"
},
{
"code": "<script> function x() { document.write('one'+\"</br>\"); return 'one'; } function y() { document.write('two'+\"</br>\"); return 'two'; } function z() { document.write('three'+\"</br>\"); return 'three'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x); </script> ",
"e": 900,
"s": 507,
"text": null
},
{
"code": null,
"e": 927,
"s": 900,
"text": "Output:one\ntwo\nthree\nthree"
},
{
"code": null,
"e": 935,
"s": 927,
"text": "Output:"
},
{
"code": null,
"e": 955,
"s": 935,
"text": "one\ntwo\nthree\nthree"
},
{
"code": null,
"e": 1426,
"s": 955,
"text": "A comma operator (,) in JavaScript is used in the same way as it is used in many programming languages like C, C++ etc. This operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. A comma operator is used as a separator for multiple expressions at a place that requires a single expression. When a comma operator is placed in an expression, it executes each expression and returns the rightmost expression."
},
{
"code": null,
"e": 1434,
"s": 1426,
"text": "Syntax:"
},
{
"code": null,
"e": 1483,
"s": 1434,
"text": "Expression1, Expression2, Expression3, ....so on"
},
{
"code": null,
"e": 1680,
"s": 1483,
"text": "In the above syntax, multiple expressions are separated using a comma operator. During execution, each expression will be executed from left to right and the rightmost expression will be returned."
},
{
"code": null,
"e": 1689,
"s": 1680,
"text": "Example:"
},
{
"code": "<script> function x() { document.write('Welcome'); return 'Welcome'; } function y() { document.write('to'); return 'to'; } function z() { document.write('Geeksforgeeks'); return 'Geeksforgeeks'; } // Three expressions are // given at one place var x = (x(), y(), z()); document.write(x);</script>",
"e": 2063,
"s": 1689,
"text": null
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Output:"
},
{
"code": null,
"e": 2207,
"s": 2071,
"text": "In the output, first of all the function x() is executed then y() and lastly z(). Finally, comma operator returns rightmost expression."
},
{
"code": null,
"e": 2340,
"s": 2207,
"text": "The most useful application of comma operator is in loops. In loops, it is used to update multiple variables in the same expression."
},
{
"code": null,
"e": 2349,
"s": 2340,
"text": "Example:"
},
{
"code": "<script> for (var a = 0, b =5; a <= 5; a++, b--) { document.write(a, b);}</script> ",
"e": 2434,
"s": 2349,
"text": null
},
{
"code": null,
"e": 2442,
"s": 2434,
"text": "Output:"
},
{
"code": null,
"e": 2462,
"s": 2442,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 2476,
"s": 2462,
"text": "Google Chrome"
},
{
"code": null,
"e": 2494,
"s": 2476,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2502,
"s": 2494,
"text": "Firefox"
},
{
"code": null,
"e": 2515,
"s": 2502,
"text": "Apple Safari"
},
{
"code": null,
"e": 2521,
"s": 2515,
"text": "Opera"
},
{
"code": null,
"e": 2539,
"s": 2521,
"text": "javascript-basics"
},
{
"code": null,
"e": 2560,
"s": 2539,
"text": "javascript-operators"
},
{
"code": null,
"e": 2567,
"s": 2560,
"text": "Picked"
},
{
"code": null,
"e": 2578,
"s": 2567,
"text": "JavaScript"
},
{
"code": null,
"e": 2595,
"s": 2578,
"text": "Web Technologies"
}
] |
Introduction to Excel Spreadsheet | 26 Sep, 2021
A spreadsheet is a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Or in other words, spreadsheets are scalable grid-based files that are used to organize data and perform calculations. People all across the world use spreadsheets to create tables for personal and business usage. You can also use the tool’s features and formulas to help you make sense of your data. You could, for example, track data in a spreadsheet and see sums, differences, multiplication, division, and fill dates automatically, among other things. Microsoft Excel, Google sheets, Apache open office, LibreOffice, etc are some spreadsheet software. Among all these software, Microsoft Excel is the most commonly used spreadsheet tool and it is available for Windows, macOS, Android, etc.
A collection of spreadsheets is known as a workbook. Every Excel file is called a workbook. Every time when you start a new project in Excel, you’ll need to create a new workbook. There are several methods for getting started with an Excel workbook. To create a new worksheet or access an existing one, you can either start from scratch or utilize a pre-designed template.
A single Excel worksheet is a tabular spreadsheet that consists of a matrix of rectangular cells grouped in rows and columns. It has a total of 1,048,576 rows and 16,384 columns, resulting in 17,179,869,184 cells on a single page of a Microsoft Excel spreadsheet where you may write, modify, and manage your data.
In the same way as a file or a book is made up of one or more worksheets that contain various types of related data, an Excel workbook is made up of one or more worksheets. You can also create and save an endless number of worksheets. The major purpose is to collect all relevant data in one place, but in many categories (worksheet).
As we know that there are so many spreadsheet applications available in the market. So these applications provide the following basic features:
1. Rows and columns: Rows and columns are two distinct features in a spreadsheet that come together to make a cell, a range, or a table. In general, columns are the vertical portion of an excel worksheet, and there can be 256 of them in a worksheet, whereas rows are the horizontal portion, and there can be 1048576 of them.
The color light green is used to highlight Row 3 while the color green is used to highlight Column B. Each column has 1048576 rows and each row has 256 columns.
2. Formulas: In spreadsheets, formulas process data automatically. It takes data from the specified area of the spreadsheet as input then processes that data, and then displays the output into the new area of the spreadsheet according to where the formula is written. In Excel, we can use formulas simply by typing “=Formula Name(Arguments)” to use predefined Excel formulas. When you write the first few characters of any formula, Excel displays a drop-down menu of formulas that match that character sequence. Some of the commonly used formulas are:
=SUM(Arg1: Arg2): It is used to find the sum of all the numeric data specified in the given range of numbers.
=COUNT(Arg1: Arg2): It is used to count all the number of cells(it will count only number) specified in the given range of numbers.
=MAX(Arg1: Arg2): It is used to find the maximum number from the given range of numbers.
=MIN(Arg1: Arg2): It is used to find the minimum number from the given range of numbers.
=TODAY(): It is used to find today’s date.
=SQRT(Arg1): It is used to find the square root of the specified cell.
For example, you can use the formula to find the average of the integers in column C from row 2 to row 7:
= AVERAGE(D2:D7)
The range of values on which you want to average is defined by D2:D6. The formula is located near the name field on the formula tab.
We wrote =AVERAGE(D2:D6) in cell D9, therefore the average becomes (2 + 3 + 4 + 5 + 6 + 7)/6 = 27/6 = 4.5. So you can quickly create a workbook, work on it, browse through it, and save it in this manner.
3. Function: In spreadsheets, the function uses a specified formula on the input and generates output. Or in other words, functions are created to perform complicated math problems in spreadsheets without using actual formulas. For example, you want to find the total of the numeric data present in the column then use the SUM function instead of adding all the values present in the column.
4. Text Manipulation: The spreadsheet provides various types of commands to manipulate the data present in it.
5. Pivot Tables: It is the most commonly used feature of the spreadsheet. Using this table users can organize, group, total, or sort data using the toolbar. Or in other words, pivot tables are used to summarize lots of data. It converts tons of data into a few rows and columns.
The use of Spreadsheets is endless. It is generally used with anything that contains numbers. Some of the common use of spreadsheets are:
Finance: Spreadsheets are used for financial data like it is used for checking account information, taxes, transaction, billing, budgets, etc.
Forms: Spreadsheet is used to create form templates to manage performance review, timesheets, surveys, etc.
School and colleges: Spreadsheets are most commonly used in schools and colleges to manage student’s data like their attendance, grades, etc.
Lists: Spreadsheets are also used to create lists like grocery lists, to-do lists, contact detail, etc.
Hotels: Spreadsheets are also used in hotels to manage the data of their customers like their personal information, room numbers, check-in date, check-out date, etc.
The basic components of spreadsheets are:
1. TitleBar: The title bar displays the name of the spreadsheet and application.
2. Toolbar: It displays all the options or commands available in Excel for use.
3. NameBox: It displays the address of the current or active cell.
4. Formula Bar: It is used to display the data entered by us in the active cell. Also, this bar is used to apply formulas to the data of the spreadsheet.
5. Column Headings: Every excel spreadsheet contains 256 columns and each column present in the spreadsheet is named by letters or a combination of letters.
6. Row Headings: Every excel spreadsheet contains 65,536 rows and each row present in the spreadsheet is named by a number.
7. Cell: In a spreadsheet, everything like a numeric value, functions, expressions, etc., is recorded in the cell. Or we can say that an intersection of rows and columns is known as a cell. Every cell has its own name or address according to its column and rows and when the cursor is present on the first cell then that cell is known as an active cell.
8. Cell referring: A cell reference, also known as a cell address, is a way for describing a cell on a worksheet that combines a column letter and a row number. We can refer to any cell on the worksheet using cell references (in excel formulae). As shown in the above image the cell in column A and row 1 is referred to as A1. Such notations can be used in any formula or to duplicate the value of one cell to another (by using = A1).
9. Navigation buttons: A spreadsheet contains first, previous, next, and last navigation buttons. These buttons are used to move from one worksheet to another workbook.
10. Sheet tabs: As we know that a workbook is a collection of worksheets. So this tab contains all the worksheets present in the workbook, by default it contains three worksheets but you can add more according to your requirement.
To create a new spreadsheet follow the following steps:
Step 1: Click on the top-left, Microsoft office button and a drop-down menu appear.
Step 2: Now select New from the menu.
Step 3: After selecting the New option a New Workbook dialogue box will appear and then in Create tab, click on the blank Document.
A new blank worksheet is created and is shown on your screen.
Note: When you open MS Excel on your computer, it creates a new Workbook for you.
In Excel we can save a workbook using the following steps:
Step 1: Click on the top-left, Microsoft office button and we get a drop-down menu:
Step 2: Now Save or Save As are the options to save the workbook, so choose one.
Save As: To name the spreadsheet and then save it to a specific location. Select Save As if you wish to save the file for the first time, or if you want to save it with a new name.
Save: To save your work, select Save/ click ctrl + S if the file has already been named.
So this is how you can save a workbook in Excel.
Excel consists of many rows and columns, each rectangular box in a row or column is referred to as a Cell. So, the combination of a column letter and a row number can be used to find a cell address on a worksheet or spreadsheet. We can refer to any cell in the worksheet using these addresses (in excel formulas). The name box on the top left(below the Home tab) displays the cell’s address whenever you click the cell.
To insert the data into the cell follow the following steps:
Step 1: Go to a cell and click on it
Step 2: By typing something on the keyboard, you can insert your data (In that selected cell).
Whatever text you type displays in the formula bar as well (for that cell).
To delete cell content follow the following steps:
Step 1: To alter or delete the text in a cell, first select it.
Step 2: Press the Backspace key on your keyboard to delete and correct text. Alternatively, hit the Delete key to delete the whole contents of a cell. You can also edit and delete text using the formula bar. Simply select the cell and move the pointer to the formula bar.
Picked
Class 9
Excel
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Application Software?
Natural Vegetation in India
Introduction to Scratch Programming
Diffusion in Solids, Liquids, and Gases
France abolishes Monarchy and Becomes a Republic
How to Find Correlation Coefficient in Excel?
How to Remove Time from Date/Timestamp in Excel?
How to Automatically Insert Date and Timestamp in Excel?
Introduction to MS-Excel
How to Find Duplicate Values in Excel Using VLOOKUP? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 978,
"s": 53,
"text": "A spreadsheet is a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Or in other words, spreadsheets are scalable grid-based files that are used to organize data and perform calculations. People all across the world use spreadsheets to create tables for personal and business usage. You can also use the tool’s features and formulas to help you make sense of your data. You could, for example, track data in a spreadsheet and see sums, differences, multiplication, division, and fill dates automatically, among other things. Microsoft Excel, Google sheets, Apache open office, LibreOffice, etc are some spreadsheet software. Among all these software, Microsoft Excel is the most commonly used spreadsheet tool and it is available for Windows, macOS, Android, etc. "
},
{
"code": null,
"e": 1351,
"s": 978,
"text": "A collection of spreadsheets is known as a workbook. Every Excel file is called a workbook. Every time when you start a new project in Excel, you’ll need to create a new workbook. There are several methods for getting started with an Excel workbook. To create a new worksheet or access an existing one, you can either start from scratch or utilize a pre-designed template."
},
{
"code": null,
"e": 1665,
"s": 1351,
"text": "A single Excel worksheet is a tabular spreadsheet that consists of a matrix of rectangular cells grouped in rows and columns. It has a total of 1,048,576 rows and 16,384 columns, resulting in 17,179,869,184 cells on a single page of a Microsoft Excel spreadsheet where you may write, modify, and manage your data."
},
{
"code": null,
"e": 2000,
"s": 1665,
"text": "In the same way as a file or a book is made up of one or more worksheets that contain various types of related data, an Excel workbook is made up of one or more worksheets. You can also create and save an endless number of worksheets. The major purpose is to collect all relevant data in one place, but in many categories (worksheet)."
},
{
"code": null,
"e": 2144,
"s": 2000,
"text": "As we know that there are so many spreadsheet applications available in the market. So these applications provide the following basic features:"
},
{
"code": null,
"e": 2469,
"s": 2144,
"text": "1. Rows and columns: Rows and columns are two distinct features in a spreadsheet that come together to make a cell, a range, or a table. In general, columns are the vertical portion of an excel worksheet, and there can be 256 of them in a worksheet, whereas rows are the horizontal portion, and there can be 1048576 of them."
},
{
"code": null,
"e": 2630,
"s": 2469,
"text": "The color light green is used to highlight Row 3 while the color green is used to highlight Column B. Each column has 1048576 rows and each row has 256 columns."
},
{
"code": null,
"e": 3182,
"s": 2630,
"text": "2. Formulas: In spreadsheets, formulas process data automatically. It takes data from the specified area of the spreadsheet as input then processes that data, and then displays the output into the new area of the spreadsheet according to where the formula is written. In Excel, we can use formulas simply by typing “=Formula Name(Arguments)” to use predefined Excel formulas. When you write the first few characters of any formula, Excel displays a drop-down menu of formulas that match that character sequence. Some of the commonly used formulas are:"
},
{
"code": null,
"e": 3292,
"s": 3182,
"text": "=SUM(Arg1: Arg2): It is used to find the sum of all the numeric data specified in the given range of numbers."
},
{
"code": null,
"e": 3425,
"s": 3292,
"text": "=COUNT(Arg1: Arg2): It is used to count all the number of cells(it will count only number) specified in the given range of numbers."
},
{
"code": null,
"e": 3514,
"s": 3425,
"text": "=MAX(Arg1: Arg2): It is used to find the maximum number from the given range of numbers."
},
{
"code": null,
"e": 3603,
"s": 3514,
"text": "=MIN(Arg1: Arg2): It is used to find the minimum number from the given range of numbers."
},
{
"code": null,
"e": 3646,
"s": 3603,
"text": "=TODAY(): It is used to find today’s date."
},
{
"code": null,
"e": 3717,
"s": 3646,
"text": "=SQRT(Arg1): It is used to find the square root of the specified cell."
},
{
"code": null,
"e": 3823,
"s": 3717,
"text": "For example, you can use the formula to find the average of the integers in column C from row 2 to row 7:"
},
{
"code": null,
"e": 3840,
"s": 3823,
"text": "= AVERAGE(D2:D7)"
},
{
"code": null,
"e": 3973,
"s": 3840,
"text": "The range of values on which you want to average is defined by D2:D6. The formula is located near the name field on the formula tab."
},
{
"code": null,
"e": 4177,
"s": 3973,
"text": "We wrote =AVERAGE(D2:D6) in cell D9, therefore the average becomes (2 + 3 + 4 + 5 + 6 + 7)/6 = 27/6 = 4.5. So you can quickly create a workbook, work on it, browse through it, and save it in this manner."
},
{
"code": null,
"e": 4570,
"s": 4177,
"text": "3. Function: In spreadsheets, the function uses a specified formula on the input and generates output. Or in other words, functions are created to perform complicated math problems in spreadsheets without using actual formulas. For example, you want to find the total of the numeric data present in the column then use the SUM function instead of adding all the values present in the column. "
},
{
"code": null,
"e": 4682,
"s": 4570,
"text": "4. Text Manipulation: The spreadsheet provides various types of commands to manipulate the data present in it. "
},
{
"code": null,
"e": 4961,
"s": 4682,
"text": "5. Pivot Tables: It is the most commonly used feature of the spreadsheet. Using this table users can organize, group, total, or sort data using the toolbar. Or in other words, pivot tables are used to summarize lots of data. It converts tons of data into a few rows and columns."
},
{
"code": null,
"e": 5099,
"s": 4961,
"text": "The use of Spreadsheets is endless. It is generally used with anything that contains numbers. Some of the common use of spreadsheets are:"
},
{
"code": null,
"e": 5242,
"s": 5099,
"text": "Finance: Spreadsheets are used for financial data like it is used for checking account information, taxes, transaction, billing, budgets, etc."
},
{
"code": null,
"e": 5350,
"s": 5242,
"text": "Forms: Spreadsheet is used to create form templates to manage performance review, timesheets, surveys, etc."
},
{
"code": null,
"e": 5492,
"s": 5350,
"text": "School and colleges: Spreadsheets are most commonly used in schools and colleges to manage student’s data like their attendance, grades, etc."
},
{
"code": null,
"e": 5596,
"s": 5492,
"text": "Lists: Spreadsheets are also used to create lists like grocery lists, to-do lists, contact detail, etc."
},
{
"code": null,
"e": 5762,
"s": 5596,
"text": "Hotels: Spreadsheets are also used in hotels to manage the data of their customers like their personal information, room numbers, check-in date, check-out date, etc."
},
{
"code": null,
"e": 5804,
"s": 5762,
"text": "The basic components of spreadsheets are:"
},
{
"code": null,
"e": 5886,
"s": 5804,
"text": "1. TitleBar: The title bar displays the name of the spreadsheet and application. "
},
{
"code": null,
"e": 5968,
"s": 5886,
"text": "2. Toolbar: It displays all the options or commands available in Excel for use. "
},
{
"code": null,
"e": 6035,
"s": 5968,
"text": "3. NameBox: It displays the address of the current or active cell."
},
{
"code": null,
"e": 6190,
"s": 6035,
"text": "4. Formula Bar: It is used to display the data entered by us in the active cell. Also, this bar is used to apply formulas to the data of the spreadsheet. "
},
{
"code": null,
"e": 6348,
"s": 6190,
"text": "5. Column Headings: Every excel spreadsheet contains 256 columns and each column present in the spreadsheet is named by letters or a combination of letters. "
},
{
"code": null,
"e": 6472,
"s": 6348,
"text": "6. Row Headings: Every excel spreadsheet contains 65,536 rows and each row present in the spreadsheet is named by a number."
},
{
"code": null,
"e": 6826,
"s": 6472,
"text": "7. Cell: In a spreadsheet, everything like a numeric value, functions, expressions, etc., is recorded in the cell. Or we can say that an intersection of rows and columns is known as a cell. Every cell has its own name or address according to its column and rows and when the cursor is present on the first cell then that cell is known as an active cell."
},
{
"code": null,
"e": 7261,
"s": 6826,
"text": "8. Cell referring: A cell reference, also known as a cell address, is a way for describing a cell on a worksheet that combines a column letter and a row number. We can refer to any cell on the worksheet using cell references (in excel formulae). As shown in the above image the cell in column A and row 1 is referred to as A1. Such notations can be used in any formula or to duplicate the value of one cell to another (by using = A1)."
},
{
"code": null,
"e": 7431,
"s": 7261,
"text": "9. Navigation buttons: A spreadsheet contains first, previous, next, and last navigation buttons. These buttons are used to move from one worksheet to another workbook. "
},
{
"code": null,
"e": 7662,
"s": 7431,
"text": "10. Sheet tabs: As we know that a workbook is a collection of worksheets. So this tab contains all the worksheets present in the workbook, by default it contains three worksheets but you can add more according to your requirement."
},
{
"code": null,
"e": 7718,
"s": 7662,
"text": "To create a new spreadsheet follow the following steps:"
},
{
"code": null,
"e": 7802,
"s": 7718,
"text": "Step 1: Click on the top-left, Microsoft office button and a drop-down menu appear."
},
{
"code": null,
"e": 7840,
"s": 7802,
"text": "Step 2: Now select New from the menu."
},
{
"code": null,
"e": 7972,
"s": 7840,
"text": "Step 3: After selecting the New option a New Workbook dialogue box will appear and then in Create tab, click on the blank Document."
},
{
"code": null,
"e": 8035,
"s": 7972,
"text": "A new blank worksheet is created and is shown on your screen. "
},
{
"code": null,
"e": 8117,
"s": 8035,
"text": "Note: When you open MS Excel on your computer, it creates a new Workbook for you."
},
{
"code": null,
"e": 8176,
"s": 8117,
"text": "In Excel we can save a workbook using the following steps:"
},
{
"code": null,
"e": 8260,
"s": 8176,
"text": "Step 1: Click on the top-left, Microsoft office button and we get a drop-down menu:"
},
{
"code": null,
"e": 8341,
"s": 8260,
"text": "Step 2: Now Save or Save As are the options to save the workbook, so choose one."
},
{
"code": null,
"e": 8522,
"s": 8341,
"text": "Save As: To name the spreadsheet and then save it to a specific location. Select Save As if you wish to save the file for the first time, or if you want to save it with a new name."
},
{
"code": null,
"e": 8611,
"s": 8522,
"text": "Save: To save your work, select Save/ click ctrl + S if the file has already been named."
},
{
"code": null,
"e": 8660,
"s": 8611,
"text": "So this is how you can save a workbook in Excel."
},
{
"code": null,
"e": 9080,
"s": 8660,
"text": "Excel consists of many rows and columns, each rectangular box in a row or column is referred to as a Cell. So, the combination of a column letter and a row number can be used to find a cell address on a worksheet or spreadsheet. We can refer to any cell in the worksheet using these addresses (in excel formulas). The name box on the top left(below the Home tab) displays the cell’s address whenever you click the cell."
},
{
"code": null,
"e": 9141,
"s": 9080,
"text": "To insert the data into the cell follow the following steps:"
},
{
"code": null,
"e": 9178,
"s": 9141,
"text": "Step 1: Go to a cell and click on it"
},
{
"code": null,
"e": 9273,
"s": 9178,
"text": "Step 2: By typing something on the keyboard, you can insert your data (In that selected cell)."
},
{
"code": null,
"e": 9349,
"s": 9273,
"text": "Whatever text you type displays in the formula bar as well (for that cell)."
},
{
"code": null,
"e": 9400,
"s": 9349,
"text": "To delete cell content follow the following steps:"
},
{
"code": null,
"e": 9465,
"s": 9400,
"text": "Step 1: To alter or delete the text in a cell, first select it. "
},
{
"code": null,
"e": 9737,
"s": 9465,
"text": "Step 2: Press the Backspace key on your keyboard to delete and correct text. Alternatively, hit the Delete key to delete the whole contents of a cell. You can also edit and delete text using the formula bar. Simply select the cell and move the pointer to the formula bar."
},
{
"code": null,
"e": 9744,
"s": 9737,
"text": "Picked"
},
{
"code": null,
"e": 9752,
"s": 9744,
"text": "Class 9"
},
{
"code": null,
"e": 9758,
"s": 9752,
"text": "Excel"
},
{
"code": null,
"e": 9774,
"s": 9758,
"text": "School Learning"
},
{
"code": null,
"e": 9793,
"s": 9774,
"text": "School Programming"
},
{
"code": null,
"e": 9891,
"s": 9793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9921,
"s": 9891,
"text": "What is Application Software?"
},
{
"code": null,
"e": 9949,
"s": 9921,
"text": "Natural Vegetation in India"
},
{
"code": null,
"e": 9985,
"s": 9949,
"text": "Introduction to Scratch Programming"
},
{
"code": null,
"e": 10025,
"s": 9985,
"text": "Diffusion in Solids, Liquids, and Gases"
},
{
"code": null,
"e": 10074,
"s": 10025,
"text": "France abolishes Monarchy and Becomes a Republic"
},
{
"code": null,
"e": 10120,
"s": 10074,
"text": "How to Find Correlation Coefficient in Excel?"
},
{
"code": null,
"e": 10169,
"s": 10120,
"text": "How to Remove Time from Date/Timestamp in Excel?"
},
{
"code": null,
"e": 10226,
"s": 10169,
"text": "How to Automatically Insert Date and Timestamp in Excel?"
},
{
"code": null,
"e": 10251,
"s": 10226,
"text": "Introduction to MS-Excel"
}
] |
Python | Text Summarizer | 27 Feb, 2020
Today various organizations, be it online shopping, government and private sector organizations, catering and tourism industry or other institutions that offer customer services are concerned about their customers and ask for feedback every single time we use their services. Consider the fact, that these companies may be receiving enormous amounts of user feedback every single day. And it would become quite tedious for the management to sit and analyze each of those.But, the technologies today have reached to an extent where they can do all the tasks of human beings. And the field which makes these things happen is Machine Learning. The machines have become capable of understanding human languages using Natural Language Processing. Today researches are being done in the field of text analytics.And one such application of text analytics and NLP is a Feedback Summarizer which helps in summarizing and shortening the text in the user feedback. This can be done an algorithm to reduce bodies of text but keeping its original meaning, or giving a great insight into the original text.
If you’re interested in Data Analytics, you will find learning about Natural Language Processing very useful. Python provides immense library support for NLP. We will be using NLTK – the Natural Language Toolkit. which will serve our purpose right.
Install NLTK module on your system using :sudo pip install nltk
Let’s understand the steps –Step 1: Importing required libraries
There are two NLTK libraries that will be necessary for building an efficient feedback summarizer.
from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenize
Terms Used :
CorpusCorpus means a collection of text. It could be data sets of anything containing texts be it poems by a certain poet, bodies of work by a certain author, etc. In this case, we are going to use a data set of pre-determined stop words.
Tokenizersit divides a text into a series of tokens. There are three main tokenizers – word, sentence, and regex tokenizer. We will only use the word and sentence tokenizer
Step 2: Removing Stop Words and storing them in a separate array of words.
Stop Word
Any word like (is, a, an, the, for) that does not add value to the meaning of a sentence. For example, let’s say we have the sentence
GeeksForGeeks is one of the most useful websites for competitive programming.
After removing stop words, we can narrow the number of words and preserve the meaning as follows:
['GeeksForGeeks', 'one', 'useful', 'website', 'competitive', 'programming', '.']
Step 3: Create a frequency table of wordsA python dictionary that’ll keep a record of how many times each word appears in the feedback after removing the stop words.we can use the dictionary over every sentence to know which sentences have the most relevant content in the overall text.
stopWords = set(stopwords.words("english"))words = word_tokenize(text)freqTable = dict()
Step 4: Assign score to each sentence depending on the words it contains and the frequency table
We can use the sent_tokenize() method to create the array of sentences. Secondly, we will need a dictionary to keep the score of each sentence, we will later go through the dictionary to generate the summary.
sentences = sent_tokenize(text)sentenceValue = dict()
Step 5: Assign a certain score to compare the sentences within the feedback.A simple approach to compare our scores would be to find the average score of a sentence. The average itself can be a good threshold.
sumValues = 0for sentence in sentenceValue: sumValues += sentenceValue[sentence]average = int(sumValues / len(sentenceValue))
Apply the threshold value and store sentences in order into the summary.
Code : Complete implementation of Text Summarizer using Python
# importing librariesimport nltkfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenize # Input text - to summarize text = """ """ # Tokenizing the textstopWords = set(stopwords.words("english"))words = word_tokenize(text) # Creating a frequency table to keep the # score of each word freqTable = dict()for word in words: word = word.lower() if word in stopWords: continue if word in freqTable: freqTable[word] += 1 else: freqTable[word] = 1 # Creating a dictionary to keep the score# of each sentencesentences = sent_tokenize(text)sentenceValue = dict() for sentence in sentences: for word, freq in freqTable.items(): if word in sentence.lower(): if sentence in sentenceValue: sentenceValue[sentence] += freq else: sentenceValue[sentence] = freq sumValues = 0for sentence in sentenceValue: sumValues += sentenceValue[sentence] # Average value of a sentence from the original text average = int(sumValues / len(sentenceValue)) # Storing sentences into our summary.summary = ''for sentence in sentences: if (sentence in sentenceValue) and (sentenceValue[sentence] > (1.2 * average)): summary += " " + sentenceprint(summary)
Input:
There are many techniques available to generate extractive summarization to keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning. One benefit of this will be, you don’t need to train and build a model prior start using it for your project. It’s good to understand Cosine similarity to make the best use of the code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Its measures cosine of the angle between vectors. The angle will be 0 if sentences are similar.
Output
There are many techniques available to generate extractive summarization. Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning. One benefit of this will be, you don’t need to train and build a model prior start using it for your project. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them.
Python-nltk
Technical Scripter 2019
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 1147,
"s": 54,
"text": "Today various organizations, be it online shopping, government and private sector organizations, catering and tourism industry or other institutions that offer customer services are concerned about their customers and ask for feedback every single time we use their services. Consider the fact, that these companies may be receiving enormous amounts of user feedback every single day. And it would become quite tedious for the management to sit and analyze each of those.But, the technologies today have reached to an extent where they can do all the tasks of human beings. And the field which makes these things happen is Machine Learning. The machines have become capable of understanding human languages using Natural Language Processing. Today researches are being done in the field of text analytics.And one such application of text analytics and NLP is a Feedback Summarizer which helps in summarizing and shortening the text in the user feedback. This can be done an algorithm to reduce bodies of text but keeping its original meaning, or giving a great insight into the original text."
},
{
"code": null,
"e": 1396,
"s": 1147,
"text": "If you’re interested in Data Analytics, you will find learning about Natural Language Processing very useful. Python provides immense library support for NLP. We will be using NLTK – the Natural Language Toolkit. which will serve our purpose right."
},
{
"code": null,
"e": 1460,
"s": 1396,
"text": "Install NLTK module on your system using :sudo pip install nltk"
},
{
"code": null,
"e": 1525,
"s": 1460,
"text": "Let’s understand the steps –Step 1: Importing required libraries"
},
{
"code": null,
"e": 1624,
"s": 1525,
"text": "There are two NLTK libraries that will be necessary for building an efficient feedback summarizer."
},
{
"code": "from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenize",
"e": 1712,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1725,
"s": 1712,
"text": "Terms Used :"
},
{
"code": null,
"e": 1964,
"s": 1725,
"text": "CorpusCorpus means a collection of text. It could be data sets of anything containing texts be it poems by a certain poet, bodies of work by a certain author, etc. In this case, we are going to use a data set of pre-determined stop words."
},
{
"code": null,
"e": 2137,
"s": 1964,
"text": "Tokenizersit divides a text into a series of tokens. There are three main tokenizers – word, sentence, and regex tokenizer. We will only use the word and sentence tokenizer"
},
{
"code": null,
"e": 2212,
"s": 2137,
"text": "Step 2: Removing Stop Words and storing them in a separate array of words."
},
{
"code": null,
"e": 2222,
"s": 2212,
"text": "Stop Word"
},
{
"code": null,
"e": 2356,
"s": 2222,
"text": "Any word like (is, a, an, the, for) that does not add value to the meaning of a sentence. For example, let’s say we have the sentence"
},
{
"code": null,
"e": 2436,
"s": 2356,
"text": " GeeksForGeeks is one of the most useful websites for competitive programming.\n"
},
{
"code": null,
"e": 2534,
"s": 2436,
"text": "After removing stop words, we can narrow the number of words and preserve the meaning as follows:"
},
{
"code": null,
"e": 2616,
"s": 2534,
"text": "['GeeksForGeeks', 'one', 'useful', 'website', 'competitive', 'programming', '.']\n"
},
{
"code": null,
"e": 2903,
"s": 2616,
"text": "Step 3: Create a frequency table of wordsA python dictionary that’ll keep a record of how many times each word appears in the feedback after removing the stop words.we can use the dictionary over every sentence to know which sentences have the most relevant content in the overall text."
},
{
"code": "stopWords = set(stopwords.words(\"english\"))words = word_tokenize(text)freqTable = dict()",
"e": 2992,
"s": 2903,
"text": null
},
{
"code": null,
"e": 3089,
"s": 2992,
"text": "Step 4: Assign score to each sentence depending on the words it contains and the frequency table"
},
{
"code": null,
"e": 3298,
"s": 3089,
"text": "We can use the sent_tokenize() method to create the array of sentences. Secondly, we will need a dictionary to keep the score of each sentence, we will later go through the dictionary to generate the summary."
},
{
"code": "sentences = sent_tokenize(text)sentenceValue = dict()",
"e": 3352,
"s": 3298,
"text": null
},
{
"code": null,
"e": 3562,
"s": 3352,
"text": "Step 5: Assign a certain score to compare the sentences within the feedback.A simple approach to compare our scores would be to find the average score of a sentence. The average itself can be a good threshold."
},
{
"code": "sumValues = 0for sentence in sentenceValue: sumValues += sentenceValue[sentence]average = int(sumValues / len(sentenceValue))",
"e": 3691,
"s": 3562,
"text": null
},
{
"code": null,
"e": 3764,
"s": 3691,
"text": "Apply the threshold value and store sentences in order into the summary."
},
{
"code": null,
"e": 3827,
"s": 3764,
"text": "Code : Complete implementation of Text Summarizer using Python"
},
{
"code": "# importing librariesimport nltkfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenize # Input text - to summarize text = \"\"\" \"\"\" # Tokenizing the textstopWords = set(stopwords.words(\"english\"))words = word_tokenize(text) # Creating a frequency table to keep the # score of each word freqTable = dict()for word in words: word = word.lower() if word in stopWords: continue if word in freqTable: freqTable[word] += 1 else: freqTable[word] = 1 # Creating a dictionary to keep the score# of each sentencesentences = sent_tokenize(text)sentenceValue = dict() for sentence in sentences: for word, freq in freqTable.items(): if word in sentence.lower(): if sentence in sentenceValue: sentenceValue[sentence] += freq else: sentenceValue[sentence] = freq sumValues = 0for sentence in sentenceValue: sumValues += sentenceValue[sentence] # Average value of a sentence from the original text average = int(sumValues / len(sentenceValue)) # Storing sentences into our summary.summary = ''for sentence in sentences: if (sentence in sentenceValue) and (sentenceValue[sentence] > (1.2 * average)): summary += \" \" + sentenceprint(summary)",
"e": 5116,
"s": 3827,
"text": null
},
{
"code": null,
"e": 5123,
"s": 5116,
"text": "Input:"
},
{
"code": null,
"e": 5903,
"s": 5123,
"text": "There are many techniques available to generate extractive summarization to keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning. One benefit of this will be, you don’t need to train and build a model prior start using it for your project. It’s good to understand Cosine similarity to make the best use of the code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Its measures cosine of the angle between vectors. The angle will be 0 if sentences are similar."
},
{
"code": null,
"e": 5910,
"s": 5903,
"text": "Output"
},
{
"code": null,
"e": 6381,
"s": 5910,
"text": "There are many techniques available to generate extractive summarization. Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning. One benefit of this will be, you don’t need to train and build a model prior start using it for your project. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them."
},
{
"code": null,
"e": 6393,
"s": 6381,
"text": "Python-nltk"
},
{
"code": null,
"e": 6417,
"s": 6393,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 6424,
"s": 6417,
"text": "Python"
},
{
"code": null,
"e": 6440,
"s": 6424,
"text": "Python Programs"
},
{
"code": null,
"e": 6459,
"s": 6440,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6557,
"s": 6459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6575,
"s": 6557,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6617,
"s": 6575,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6639,
"s": 6617,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6665,
"s": 6639,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6697,
"s": 6665,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6719,
"s": 6697,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 6758,
"s": 6719,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 6796,
"s": 6758,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 6845,
"s": 6796,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to Run Multiple Versions of Node.js ? | 17 Aug, 2021
Usually, we work on different versions for our Node.js project and it’s hard to manage them, but fortunately, there is a tool called NVM(node version manager) which helps to manage your node version and switch between them according to your projects.
Install NVM Module:
You can install the nvm module using the following command:
Using curl: $ curl -o- https://raw.githubusercontent.com/nvm-sh/v0.34.0/install.sh | bash
After installation, you need to add a bit of configuration in your .bashrc file as shown below:
$ nano ~/.bashrc
Then add the following code to the end of the file:
export NVM_DIR="${XDG_CONFIG_HOME/:-$HOME/.}nvm"
[ -s :$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
Reload your bash using the following command:
$ source ~/.bashrc
Module Installation: To install the latest version of Node, the following command can be used:
$ nvm install node
To install the specific version of Node, the following command can be used:
$ nvm install {node_version}
$ nvm install 10.10.0
List all Node Version: To list out all the versions installed, the following command can be used:
$ nvm ls
Switch Node Version: The switching between different node versions can be done using the following command:
$ nvm use node # to use latest version
$ nvm use 10.0.0 # for a specific version
Deleting Node versions: The node versions can be uninstalled using the following command:
$ nvm uninstall 10.0.0
Conclusion: Managing the node versions is very useful if you are working on multiple projects which requires a different version of node. Above given are some important commands for doing so.
Reference:
About NVM: https://github.com/nvm-sh/nvm
About the Linux Command line: https://btholt.github.io/complete-intro-to-linux-and-the-cli/
abhishek0719kadiyan
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 279,
"s": 28,
"text": "Usually, we work on different versions for our Node.js project and it’s hard to manage them, but fortunately, there is a tool called NVM(node version manager) which helps to manage your node version and switch between them according to your projects."
},
{
"code": null,
"e": 299,
"s": 279,
"text": "Install NVM Module:"
},
{
"code": null,
"e": 359,
"s": 299,
"text": "You can install the nvm module using the following command:"
},
{
"code": null,
"e": 449,
"s": 359,
"text": "Using curl: $ curl -o- https://raw.githubusercontent.com/nvm-sh/v0.34.0/install.sh | bash"
},
{
"code": null,
"e": 549,
"s": 453,
"text": "After installation, you need to add a bit of configuration in your .bashrc file as shown below:"
},
{
"code": null,
"e": 568,
"s": 551,
"text": "$ nano ~/.bashrc"
},
{
"code": null,
"e": 621,
"s": 568,
"text": "Then add the following code to the end of the file: "
},
{
"code": null,
"e": 721,
"s": 623,
"text": "export NVM_DIR=\"${XDG_CONFIG_HOME/:-$HOME/.}nvm\"\n[ -s :$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\""
},
{
"code": null,
"e": 767,
"s": 721,
"text": "Reload your bash using the following command:"
},
{
"code": null,
"e": 789,
"s": 769,
"text": "$ source ~/.bashrc "
},
{
"code": null,
"e": 884,
"s": 789,
"text": "Module Installation: To install the latest version of Node, the following command can be used:"
},
{
"code": null,
"e": 905,
"s": 886,
"text": "$ nvm install node"
},
{
"code": null,
"e": 981,
"s": 905,
"text": "To install the specific version of Node, the following command can be used:"
},
{
"code": null,
"e": 1034,
"s": 983,
"text": "$ nvm install {node_version}\n$ nvm install 10.10.0"
},
{
"code": null,
"e": 1132,
"s": 1034,
"text": "List all Node Version: To list out all the versions installed, the following command can be used:"
},
{
"code": null,
"e": 1143,
"s": 1134,
"text": "$ nvm ls"
},
{
"code": null,
"e": 1251,
"s": 1143,
"text": "Switch Node Version: The switching between different node versions can be done using the following command:"
},
{
"code": null,
"e": 1336,
"s": 1253,
"text": "$ nvm use node # to use latest version\n$ nvm use 10.0.0 # for a specific version"
},
{
"code": null,
"e": 1426,
"s": 1336,
"text": "Deleting Node versions: The node versions can be uninstalled using the following command:"
},
{
"code": null,
"e": 1451,
"s": 1428,
"text": "$ nvm uninstall 10.0.0"
},
{
"code": null,
"e": 1643,
"s": 1451,
"text": "Conclusion: Managing the node versions is very useful if you are working on multiple projects which requires a different version of node. Above given are some important commands for doing so."
},
{
"code": null,
"e": 1657,
"s": 1645,
"text": "Reference: "
},
{
"code": null,
"e": 1700,
"s": 1659,
"text": "About NVM: https://github.com/nvm-sh/nvm"
},
{
"code": null,
"e": 1794,
"s": 1700,
"text": "About the Linux Command line: https://btholt.github.io/complete-intro-to-linux-and-the-cli/ "
},
{
"code": null,
"e": 1816,
"s": 1796,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 1829,
"s": 1816,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 1840,
"s": 1829,
"text": "JavaScript"
},
{
"code": null,
"e": 1848,
"s": 1840,
"text": "Node.js"
},
{
"code": null,
"e": 1865,
"s": 1848,
"text": "Web Technologies"
},
{
"code": null,
"e": 1963,
"s": 1865,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2024,
"s": 1963,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2064,
"s": 2024,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2105,
"s": 2064,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2147,
"s": 2105,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2169,
"s": 2147,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2217,
"s": 2169,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2250,
"s": 2217,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2283,
"s": 2250,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2313,
"s": 2283,
"text": "Node.js fs.writeFile() Method"
}
] |
Python Program to Generate Random binary string | 08 Oct, 2021
Given a number n, the task is to generate a random binary string of length n.Examples:
Input: 7
Output: Desired length random binary string is: 1000001
Input: 5
Output: Desired length random binary string is: 01001
Approach
Initialize an empty string, say key
Generate a randomly either “0” or “1” using randint function from random package.
Append the randomly generated “0” or “1” to the string, key
Repeat step 2 and 3 for the desired length of the string
Below is the implementation.
Python3
# Python program for random# binary string generation import random # Function to create the# random binary stringdef rand_key(p): # Variable to store the # string key1 = "" # Loop to find the string # of desired length for i in range(p): # randint function to generate # 0, 1 randomly and converting # the result into str temp = str(random.randint(0, 1)) # Concatenation the random 0, 1 # to the final result key1 += temp return(key1) # Driver Coden = 7str1 = rand_key(n)print("Desired length random binary string is: ", str1)
Output:
Desired length random binary string is: 1000001
simmytarika5
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 116,
"s": 28,
"text": "Given a number n, the task is to generate a random binary string of length n.Examples: "
},
{
"code": null,
"e": 247,
"s": 116,
"text": "Input: 7\nOutput: Desired length random binary string is: 1000001\n\nInput: 5\nOutput: Desired length random binary string is: 01001"
},
{
"code": null,
"e": 256,
"s": 247,
"text": "Approach"
},
{
"code": null,
"e": 293,
"s": 256,
"text": "Initialize an empty string, say key "
},
{
"code": null,
"e": 376,
"s": 293,
"text": "Generate a randomly either “0” or “1” using randint function from random package. "
},
{
"code": null,
"e": 437,
"s": 376,
"text": "Append the randomly generated “0” or “1” to the string, key "
},
{
"code": null,
"e": 496,
"s": 437,
"text": "Repeat step 2 and 3 for the desired length of the string "
},
{
"code": null,
"e": 525,
"s": 496,
"text": "Below is the implementation."
},
{
"code": null,
"e": 533,
"s": 525,
"text": "Python3"
},
{
"code": "# Python program for random# binary string generation import random # Function to create the# random binary stringdef rand_key(p): # Variable to store the # string key1 = \"\" # Loop to find the string # of desired length for i in range(p): # randint function to generate # 0, 1 randomly and converting # the result into str temp = str(random.randint(0, 1)) # Concatenation the random 0, 1 # to the final result key1 += temp return(key1) # Driver Coden = 7str1 = rand_key(n)print(\"Desired length random binary string is: \", str1)",
"e": 1156,
"s": 533,
"text": null
},
{
"code": null,
"e": 1164,
"s": 1156,
"text": "Output:"
},
{
"code": null,
"e": 1213,
"s": 1164,
"text": "Desired length random binary string is: 1000001"
},
{
"code": null,
"e": 1226,
"s": 1213,
"text": "simmytarika5"
},
{
"code": null,
"e": 1249,
"s": 1226,
"text": "Python string-programs"
},
{
"code": null,
"e": 1256,
"s": 1249,
"text": "Python"
},
{
"code": null,
"e": 1272,
"s": 1256,
"text": "Python Programs"
},
{
"code": null,
"e": 1370,
"s": 1272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1402,
"s": 1370,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1429,
"s": 1402,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1460,
"s": 1429,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1481,
"s": 1460,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1537,
"s": 1481,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1559,
"s": 1537,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1598,
"s": 1559,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1636,
"s": 1598,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1685,
"s": 1636,
"text": "Python | Convert string dictionary to dictionary"
}
] |
DorkScout – Automate google dork scan against the entiere internet or specific targets | 23 Sep, 2021
Dorking is the technique used for advanced searching. Dorking can be useful in target domain detection or forgetting some sensitive data from the target domain, This can be done through automated tools which can reduce the time of manual searching. DorkScout is a tool to automate the finding of vulnerable applications or hidden files around the internet through google searches, dorkscout first starts by retrieving the dork’s lists from https://www.exploit-db.com/google-hacking-database, and then it scans a given target or everything it endows. DorkScout tool is developed in Golang language and is available on the GitHub platform. DorkScout tool is open-source and free-to-use.
Note: DorkScout is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux
Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command.
go version
Step 2: Get the DorkScout repository or clone the DorkScout tool from Github, use the following command.
sudo GO111MODULE=on go get -u github.com/R4yGM/dorkscout
Step 3: Change the directory to access the tool. Use the following command
cd go/bin
Step 4: Check the help menu page to get a better understanding of the DorkScout tool, use the following command.
dorkscout -h
Example 1: Scans a specific website for a list of dorks
dorkscout scan -d= “/home/kali/Desktop/dorkscout/dorks/Sensitive\ Directories.dorkscout” -H= “/home/kali/Desktop/dorkscout/results/”
We are displaying the list of dorks in the below screenshot.
We have got the results for our Dorking scan.
.html formatted results and displayed in the below screenshot.
Example 2: Install a list of dorks from exploit-db.com/ Install word-lists
dorkscout install -o /home/kali/Desktop/
In this example, we will be installing new and updated dorking lists for the exploit-db database.
Dorks are installed in the Desktop directory.
In the above screenshot, we can see that all the dork files are installed on the desktop directory. In the below screenshot, we have opened the “Network or Vulnerability Data.dorkscout” file which contains the dork query related to Network.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 713,
"s": 28,
"text": "Dorking is the technique used for advanced searching. Dorking can be useful in target domain detection or forgetting some sensitive data from the target domain, This can be done through automated tools which can reduce the time of manual searching. DorkScout is a tool to automate the finding of vulnerable applications or hidden files around the internet through google searches, dorkscout first starts by retrieving the dork’s lists from https://www.exploit-db.com/google-hacking-database, and then it scans a given target or everything it endows. DorkScout tool is developed in Golang language and is available on the GitHub platform. DorkScout tool is open-source and free-to-use."
},
{
"code": null,
"e": 908,
"s": 713,
"text": "Note: DorkScout is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux"
},
{
"code": null,
"e": 1048,
"s": 908,
"text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command."
},
{
"code": null,
"e": 1059,
"s": 1048,
"text": "go version"
},
{
"code": null,
"e": 1164,
"s": 1059,
"text": "Step 2: Get the DorkScout repository or clone the DorkScout tool from Github, use the following command."
},
{
"code": null,
"e": 1221,
"s": 1164,
"text": "sudo GO111MODULE=on go get -u github.com/R4yGM/dorkscout"
},
{
"code": null,
"e": 1296,
"s": 1221,
"text": "Step 3: Change the directory to access the tool. Use the following command"
},
{
"code": null,
"e": 1306,
"s": 1296,
"text": "cd go/bin"
},
{
"code": null,
"e": 1419,
"s": 1306,
"text": "Step 4: Check the help menu page to get a better understanding of the DorkScout tool, use the following command."
},
{
"code": null,
"e": 1432,
"s": 1419,
"text": "dorkscout -h"
},
{
"code": null,
"e": 1489,
"s": 1432,
"text": "Example 1: Scans a specific website for a list of dorks"
},
{
"code": null,
"e": 1622,
"s": 1489,
"text": "dorkscout scan -d= “/home/kali/Desktop/dorkscout/dorks/Sensitive\\ Directories.dorkscout” -H= “/home/kali/Desktop/dorkscout/results/”"
},
{
"code": null,
"e": 1683,
"s": 1622,
"text": "We are displaying the list of dorks in the below screenshot."
},
{
"code": null,
"e": 1729,
"s": 1683,
"text": "We have got the results for our Dorking scan."
},
{
"code": null,
"e": 1792,
"s": 1729,
"text": ".html formatted results and displayed in the below screenshot."
},
{
"code": null,
"e": 1867,
"s": 1792,
"text": "Example 2: Install a list of dorks from exploit-db.com/ Install word-lists"
},
{
"code": null,
"e": 1908,
"s": 1867,
"text": "dorkscout install -o /home/kali/Desktop/"
},
{
"code": null,
"e": 2006,
"s": 1908,
"text": "In this example, we will be installing new and updated dorking lists for the exploit-db database."
},
{
"code": null,
"e": 2052,
"s": 2006,
"text": "Dorks are installed in the Desktop directory."
},
{
"code": null,
"e": 2293,
"s": 2052,
"text": "In the above screenshot, we can see that all the dork files are installed on the desktop directory. In the below screenshot, we have opened the “Network or Vulnerability Data.dorkscout” file which contains the dork query related to Network."
},
{
"code": null,
"e": 2304,
"s": 2293,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2316,
"s": 2304,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2327,
"s": 2316,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2425,
"s": 2327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2451,
"s": 2425,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2486,
"s": 2451,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2523,
"s": 2486,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2552,
"s": 2523,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2589,
"s": 2552,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2623,
"s": 2589,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2660,
"s": 2623,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2700,
"s": 2660,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2739,
"s": 2700,
"text": "Introduction to Linux Operating System"
}
] |
How to highlight text based on user input with React.js ? - GeeksforGeeks | 12 Mar, 2021
The following approach covers how to highlight text input given by users in ReactJS. It is a simple effect you can add to any ReactJS website.
Prerequisite:
Basic knowledge of npm & create-react-app command.
Basic knowledge of styled-components.
Knowledge of useState() React hooks.
Knowledge of onChange() event.
Basic Setup: You will start a new project using create-react-app so open your terminal and type:
npx create-react-app react-highlight-text
Now go to your react-highlight-text folder by typing the given command in the terminal:
cd react-highlight-text
Required module: Install the dependencies required in this project by typing the given command in the terminal:
npm install --save styled-components
Now go to the src folder and create a file AppStyles.js.
Project Structure: The file structure in the project will look like this:
Example: We create a state with the first element input as an initial state with a value of the empty string and the second element as function setInput() for updating the state. Then a function is created by the name toggleInput which sets the value of the state to the value we enter in our input field.
We set up our input field as a controlled component so that it updates the state accordingly. When we enter a value in our Input field, toggleInput function gets triggered through onChange event which sets the state to that entered value. We also use the state value just below our input field in InputHighlighter element styled with a top border (which covers our input field’s bottom border). This way, we use React state to update the value of both the Input field and InputHighlighter. So, when we enter a value in our input field, that value also gets updated in the InputHighlighter. That’s why the latter’s borderline keeps on increasing while we enter a text, but we don’t see it because we have set the CSS overflow property to none for our InputHighlighter.
This makes the webpage users think that the input field is actually highlighting the text they are entering. But in reality, it doesn’t happen that way. They just see the top border of another element as an input highlighter.
App.js
import React,{useState} from 'react';import { InputContainer, Input, InputHighlighter, Heading} from './AppStyles'; const App = () => { const [input, setInput] = useState(''); const toggleInput = (e) => { setInput(e.target.value); } return ( <InputContainer> <Heading>GeeksforGeeks</Heading> <Input onChange={toggleInput} placeholder='Type your name' value={input} /> <InputHighlighter> {input} </InputHighlighter> </InputContainer> );} export default App;
AppStyles.js
import styled from 'styled-components'; export const InputContainer = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input = styled.input` height: 70px; width: 100%; padding: 0; font-size: 35px; border: none; outline: none; border-bottom: 4px solid rgba(192, 192, 192);` export const InputHighlighter = styled.span` font-size: 35px; border-top: 4px solid green; position: absolute; left: 0; bottom: 0; height: 0; overflow: hidden;`;
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. See how borderline increases when we enter a text and starts decreasing when we remove the characters one by one.
Picked
React-Questions
Styled-components
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
ReactJS useNavigate() Hook
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24423,
"s": 24395,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 24566,
"s": 24423,
"text": "The following approach covers how to highlight text input given by users in ReactJS. It is a simple effect you can add to any ReactJS website."
},
{
"code": null,
"e": 24580,
"s": 24566,
"text": "Prerequisite:"
},
{
"code": null,
"e": 24631,
"s": 24580,
"text": "Basic knowledge of npm & create-react-app command."
},
{
"code": null,
"e": 24669,
"s": 24631,
"text": "Basic knowledge of styled-components."
},
{
"code": null,
"e": 24706,
"s": 24669,
"text": "Knowledge of useState() React hooks."
},
{
"code": null,
"e": 24737,
"s": 24706,
"text": "Knowledge of onChange() event."
},
{
"code": null,
"e": 24834,
"s": 24737,
"text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type:"
},
{
"code": null,
"e": 24876,
"s": 24834,
"text": "npx create-react-app react-highlight-text"
},
{
"code": null,
"e": 24964,
"s": 24876,
"text": "Now go to your react-highlight-text folder by typing the given command in the terminal:"
},
{
"code": null,
"e": 24988,
"s": 24964,
"text": "cd react-highlight-text"
},
{
"code": null,
"e": 25100,
"s": 24988,
"text": "Required module: Install the dependencies required in this project by typing the given command in the terminal:"
},
{
"code": null,
"e": 25137,
"s": 25100,
"text": "npm install --save styled-components"
},
{
"code": null,
"e": 25194,
"s": 25137,
"text": "Now go to the src folder and create a file AppStyles.js."
},
{
"code": null,
"e": 25268,
"s": 25194,
"text": "Project Structure: The file structure in the project will look like this:"
},
{
"code": null,
"e": 25574,
"s": 25268,
"text": "Example: We create a state with the first element input as an initial state with a value of the empty string and the second element as function setInput() for updating the state. Then a function is created by the name toggleInput which sets the value of the state to the value we enter in our input field."
},
{
"code": null,
"e": 26343,
"s": 25574,
"text": "We set up our input field as a controlled component so that it updates the state accordingly. When we enter a value in our Input field, toggleInput function gets triggered through onChange event which sets the state to that entered value. We also use the state value just below our input field in InputHighlighter element styled with a top border (which covers our input field’s bottom border). This way, we use React state to update the value of both the Input field and InputHighlighter. So, when we enter a value in our input field, that value also gets updated in the InputHighlighter. That’s why the latter’s borderline keeps on increasing while we enter a text, but we don’t see it because we have set the CSS overflow property to none for our InputHighlighter. "
},
{
"code": null,
"e": 26569,
"s": 26343,
"text": "This makes the webpage users think that the input field is actually highlighting the text they are entering. But in reality, it doesn’t happen that way. They just see the top border of another element as an input highlighter."
},
{
"code": null,
"e": 26576,
"s": 26569,
"text": "App.js"
},
{
"code": "import React,{useState} from 'react';import { InputContainer, Input, InputHighlighter, Heading} from './AppStyles'; const App = () => { const [input, setInput] = useState(''); const toggleInput = (e) => { setInput(e.target.value); } return ( <InputContainer> <Heading>GeeksforGeeks</Heading> <Input onChange={toggleInput} placeholder='Type your name' value={input} /> <InputHighlighter> {input} </InputHighlighter> </InputContainer> );} export default App;",
"e": 27119,
"s": 26576,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27119,
"text": "AppStyles.js"
},
{
"code": "import styled from 'styled-components'; export const InputContainer = styled.div` width: 600px; margin: 40px auto; position: relative;`export const Heading = styled.h1` text-align: center; color: green;`; export const Input = styled.input` height: 70px; width: 100%; padding: 0; font-size: 35px; border: none; outline: none; border-bottom: 4px solid rgba(192, 192, 192);` export const InputHighlighter = styled.span` font-size: 35px; border-top: 4px solid green; position: absolute; left: 0; bottom: 0; height: 0; overflow: hidden;`;",
"e": 27707,
"s": 27132,
"text": null
},
{
"code": null,
"e": 27820,
"s": 27707,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 27830,
"s": 27820,
"text": "npm start"
},
{
"code": null,
"e": 28043,
"s": 27830,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. See how borderline increases when we enter a text and starts decreasing when we remove the characters one by one."
},
{
"code": null,
"e": 28050,
"s": 28043,
"text": "Picked"
},
{
"code": null,
"e": 28066,
"s": 28050,
"text": "React-Questions"
},
{
"code": null,
"e": 28084,
"s": 28066,
"text": "Styled-components"
},
{
"code": null,
"e": 28092,
"s": 28084,
"text": "ReactJS"
},
{
"code": null,
"e": 28109,
"s": 28092,
"text": "Web Technologies"
},
{
"code": null,
"e": 28207,
"s": 28109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28216,
"s": 28207,
"text": "Comments"
},
{
"code": null,
"e": 28229,
"s": 28216,
"text": "Old Comments"
},
{
"code": null,
"e": 28271,
"s": 28229,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28306,
"s": 28271,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28364,
"s": 28306,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28416,
"s": 28364,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 28443,
"s": 28416,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28499,
"s": 28443,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28532,
"s": 28499,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28594,
"s": 28532,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28644,
"s": 28594,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Wait for user input to start a sketch in Arduino | A problem faced by several people using Arduino, or any microcontroller board for that matter, is that you may forget to start the Serial Monitor before programming the board, and miss some print statements by the time you open the Serial Monitor.
One way to overcome this is to start the sketch only after an input is received from the user, via the Serial Monitor. This will ensure that you don’t miss any prints on the Serial Monitor because of the delay in starting the Serial Monitor.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
Serial.println("Please send a character to start the sketch");
while (Serial.available() == 0) {
Serial.print(".");
delay(500);
}
while (Serial.available() > 0) {
Serial.read(); //Empty the read buffer
}
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("Looping!");
delay(1000);
}
As you can see, the sketch first waits for the user input. As soon as the user input is received, the sketch clears the read buffer, and then proceeds with the rest of the tasks.
The Serial Monitor Outputs show that
Please note that waiting for user input should only be done in the test code, and not in the production code, where there is no possibility of getting the user input. | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "A problem faced by several people using Arduino, or any microcontroller board for that matter, is that you may forget to start the Serial Monitor before programming the board, and miss some print statements by the time you open the Serial Monitor."
},
{
"code": null,
"e": 1552,
"s": 1310,
"text": "One way to overcome this is to start the sketch only after an input is received from the user, via the Serial Monitor. This will ensure that you don’t miss any prints on the Serial Monitor because of the delay in starting the Serial Monitor."
},
{
"code": null,
"e": 2009,
"s": 1552,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n Serial.println(\"Please send a character to start the sketch\");\n while (Serial.available() == 0) {\n Serial.print(\".\");\n delay(500);\n }\n while (Serial.available() > 0) {\n Serial.read(); //Empty the read buffer\n }\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n Serial.println(\"Looping!\");\n delay(1000);\n}"
},
{
"code": null,
"e": 2188,
"s": 2009,
"text": "As you can see, the sketch first waits for the user input. As soon as the user input is received, the sketch clears the read buffer, and then proceeds with the rest of the tasks."
},
{
"code": null,
"e": 2225,
"s": 2188,
"text": "The Serial Monitor Outputs show that"
},
{
"code": null,
"e": 2392,
"s": 2225,
"text": "Please note that waiting for user input should only be done in the test code, and not in the production code, where there is no possibility of getting the user input."
}
] |
Retrieving specific documents from collection by _id in MongoDB | To retrieve document from collection by _id, use find() with $in. Let us create a collection with documents −
> db.demo281.insertOne({"Name":"Chris","Age":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4aac28dd099650a5401a66")
}
> db.demo281.insertOne({"Name":"Bob","Age":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4aac46dd099650a5401a67")
}
> db.demo281.insertOne({"Name":"David","Age":28});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4aac4fdd099650a5401a68")
}
Display all documents from a collection with the help of find() method −
> db.demo281.find();
This will produce the following output −
{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5e4aac4fdd099650a5401a68"), "Name" : "David", "Age" : 28 }
Following is the query to retrieve specific documents from collection by _id −
>db.demo281.find({_id:{$in:[ObjectId("5e4aac28dd099650a5401a66"),ObjectId("5e4aac46dd099650a5401a67")]}});
This will produce the following output −
{ "_id" : ObjectId("5e4aac28dd099650a5401a66"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e4aac46dd099650a5401a67"), "Name" : "Bob", "Age" : 23 } | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "To retrieve document from collection by _id, use find() with $in. Let us create a collection with documents −"
},
{
"code": null,
"e": 1578,
"s": 1172,
"text": "> db.demo281.insertOne({\"Name\":\"Chris\",\"Age\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4aac28dd099650a5401a66\")\n}\n> db.demo281.insertOne({\"Name\":\"Bob\",\"Age\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4aac46dd099650a5401a67\")\n}\n> db.demo281.insertOne({\"Name\":\"David\",\"Age\":28});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e4aac4fdd099650a5401a68\")\n}"
},
{
"code": null,
"e": 1651,
"s": 1578,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1672,
"s": 1651,
"text": "> db.demo281.find();"
},
{
"code": null,
"e": 1713,
"s": 1672,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1948,
"s": 1713,
"text": "{ \"_id\" : ObjectId(\"5e4aac28dd099650a5401a66\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e4aac46dd099650a5401a67\"), \"Name\" : \"Bob\", \"Age\" : 23 }\n{ \"_id\" : ObjectId(\"5e4aac4fdd099650a5401a68\"), \"Name\" : \"David\", \"Age\" : 28 }"
},
{
"code": null,
"e": 2027,
"s": 1948,
"text": "Following is the query to retrieve specific documents from collection by _id −"
},
{
"code": null,
"e": 2134,
"s": 2027,
"text": ">db.demo281.find({_id:{$in:[ObjectId(\"5e4aac28dd099650a5401a66\"),ObjectId(\"5e4aac46dd099650a5401a67\")]}});"
},
{
"code": null,
"e": 2175,
"s": 2134,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2331,
"s": 2175,
"text": "{ \"_id\" : ObjectId(\"5e4aac28dd099650a5401a66\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e4aac46dd099650a5401a67\"), \"Name\" : \"Bob\", \"Age\" : 23 }"
}
] |
How to call JavaScript function in an alert box? | To call a JavaScript function in an alert box, you can try to run the following code −
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(warning) {
alert(warning);
catchedAlert();
}
function catchedAlert() {
alert('Alert called!');
}
</script>
<button onclick="myFunction('This is an alert box!')">Click me!</button>
</body>
</html> | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To call a JavaScript function in an alert box, you can try to run the following code −"
},
{
"code": null,
"e": 1159,
"s": 1149,
"text": "Live Demo"
},
{
"code": null,
"e": 1510,
"s": 1159,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n function myFunction(warning) {\n alert(warning);\n catchedAlert();\n }\n function catchedAlert() {\n alert('Alert called!');\n }\n </script>\n <button onclick=\"myFunction('This is an alert box!')\">Click me!</button>\n </body>\n</html>"
}
] |
C# | Char.Equals() Method - GeeksforGeeks | 01 Feb, 2019
In C#, Char.Equals() is a System.Char struct method which is used to return a value by checking whether current instance is equal to a specified object or Char value. This method can be overloaded by passing different type of arguments to it.
Char.Equals(Char) MethodChar.Equals(Object) Method
Char.Equals(Char) Method
Char.Equals(Object) Method
This method is used to returns a value by checking whether the current instance is equal to the specified Char object or not.
Syntax:
public bool Equals(Char ob);
Parameter:
ob: It is the required object which is to be compared with the value of current instance.
Return Type: If the given ob parameter is equal to the value of current instance then it returns true otherwise false. The return type of this method is System.Boolean.
Example:
// C# program to illustrate the// Char.Equals(Char) Methodusing System; public class GeeksforGeeks { // Main method public static void Main() { // declaration of datatype bool result; char ch1 = 'G'; // checking if 'G' is equal or not // Here we are passing char G as the // parameter to the Equals Method result = ch1.Equals('G'); Console.WriteLine(result); // checking if 'v' is equal or not char ch2 = 'v'; // Here we are passing char W as the // parameter to the Equals Method result = ch2.Equals('W'); Console.WriteLine(result); }}
True
False
This method is used to returns a value by checking whether the current instance is equal to the specified object or not.
Syntax:
public override bool Equals(object ob);
Parameter:
ob: It is the required object which is to be compared with the current instance or null.
Return Type: If the given ob parameter is an instance of Char and equals to the value of current instance then it returns true otherwise false. The return type of this method is System.Boolean.
Example:
// C# program to illustrate the// Char.Equals(Object) Methodusing System; public class GeeksforGeeks { // Main method public static void Main() { // Declaration of data type bool result; // Checking if 'G' is equal or not char ch1 = 'G'; // Here we are passing object ch1 as the // parameter to the Equals Method result = 'G'.Equals(ch1); Console.WriteLine(result); // Checking if 'v' is equal or not char ch2 = 'v'; // Here we are passing object ch2 as the // parameter to the Equals Method result = 'x'.Equals(ch2); Console.WriteLine(result); }}
True
False
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.equals?view=netframework-4.7.2
CSharp-Char-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | Constructors
C# Dictionary with examples
C# | Method Overriding
Difference between Ref and Out keywords in C#
C# | Delegates
C# | Class and Object
C# | Arrays of Strings
Extension Method in C# | [
{
"code": null,
"e": 23952,
"s": 23924,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24195,
"s": 23952,
"text": "In C#, Char.Equals() is a System.Char struct method which is used to return a value by checking whether current instance is equal to a specified object or Char value. This method can be overloaded by passing different type of arguments to it."
},
{
"code": null,
"e": 24246,
"s": 24195,
"text": "Char.Equals(Char) MethodChar.Equals(Object) Method"
},
{
"code": null,
"e": 24271,
"s": 24246,
"text": "Char.Equals(Char) Method"
},
{
"code": null,
"e": 24298,
"s": 24271,
"text": "Char.Equals(Object) Method"
},
{
"code": null,
"e": 24424,
"s": 24298,
"text": "This method is used to returns a value by checking whether the current instance is equal to the specified Char object or not."
},
{
"code": null,
"e": 24432,
"s": 24424,
"text": "Syntax:"
},
{
"code": null,
"e": 24461,
"s": 24432,
"text": "public bool Equals(Char ob);"
},
{
"code": null,
"e": 24472,
"s": 24461,
"text": "Parameter:"
},
{
"code": null,
"e": 24562,
"s": 24472,
"text": "ob: It is the required object which is to be compared with the value of current instance."
},
{
"code": null,
"e": 24731,
"s": 24562,
"text": "Return Type: If the given ob parameter is equal to the value of current instance then it returns true otherwise false. The return type of this method is System.Boolean."
},
{
"code": null,
"e": 24740,
"s": 24731,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Char.Equals(Char) Methodusing System; public class GeeksforGeeks { // Main method public static void Main() { // declaration of datatype bool result; char ch1 = 'G'; // checking if 'G' is equal or not // Here we are passing char G as the // parameter to the Equals Method result = ch1.Equals('G'); Console.WriteLine(result); // checking if 'v' is equal or not char ch2 = 'v'; // Here we are passing char W as the // parameter to the Equals Method result = ch2.Equals('W'); Console.WriteLine(result); }}",
"e": 25421,
"s": 24740,
"text": null
},
{
"code": null,
"e": 25433,
"s": 25421,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 25554,
"s": 25433,
"text": "This method is used to returns a value by checking whether the current instance is equal to the specified object or not."
},
{
"code": null,
"e": 25562,
"s": 25554,
"text": "Syntax:"
},
{
"code": null,
"e": 25602,
"s": 25562,
"text": "public override bool Equals(object ob);"
},
{
"code": null,
"e": 25613,
"s": 25602,
"text": "Parameter:"
},
{
"code": null,
"e": 25702,
"s": 25613,
"text": "ob: It is the required object which is to be compared with the current instance or null."
},
{
"code": null,
"e": 25896,
"s": 25702,
"text": "Return Type: If the given ob parameter is an instance of Char and equals to the value of current instance then it returns true otherwise false. The return type of this method is System.Boolean."
},
{
"code": null,
"e": 25905,
"s": 25896,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Char.Equals(Object) Methodusing System; public class GeeksforGeeks { // Main method public static void Main() { // Declaration of data type bool result; // Checking if 'G' is equal or not char ch1 = 'G'; // Here we are passing object ch1 as the // parameter to the Equals Method result = 'G'.Equals(ch1); Console.WriteLine(result); // Checking if 'v' is equal or not char ch2 = 'v'; // Here we are passing object ch2 as the // parameter to the Equals Method result = 'x'.Equals(ch2); Console.WriteLine(result); }}",
"e": 26581,
"s": 25905,
"text": null
},
{
"code": null,
"e": 26593,
"s": 26581,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 26691,
"s": 26593,
"text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.char.equals?view=netframework-4.7.2"
},
{
"code": null,
"e": 26710,
"s": 26691,
"text": "CSharp-Char-Struct"
},
{
"code": null,
"e": 26724,
"s": 26710,
"text": "CSharp-method"
},
{
"code": null,
"e": 26727,
"s": 26724,
"text": "C#"
},
{
"code": null,
"e": 26825,
"s": 26727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26834,
"s": 26825,
"text": "Comments"
},
{
"code": null,
"e": 26847,
"s": 26834,
"text": "Old Comments"
},
{
"code": null,
"e": 26901,
"s": 26847,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 26929,
"s": 26901,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 26947,
"s": 26929,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26975,
"s": 26947,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 26998,
"s": 26975,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27044,
"s": 26998,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27059,
"s": 27044,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27081,
"s": 27059,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27104,
"s": 27081,
"text": "C# | Arrays of Strings"
}
] |
Examples of Big-O analysis - GeeksforGeeks | 20 Jan, 2022
Prerequisite: Analysis of Algorithms | Big-O analysis
In the previous article, the analysis of the algorithm using Big O asymptotic notation is discussed. In this article, some examples are discussed to illustrate the Big O time complexity notation and also learn how to compute the time complexity of any program.
There are different asymptotic notations in which the time complexities of algorithms are measured. Here, the ”O”(Big O) notation is used to get the time complexities. Time complexity estimates the time to run an algorithm. It’s calculated by counting the elementary operations. It is always a good practice to know the reason for execution time in a way that depends only on the algorithm and its input. This can be achieved by choosing an elementary operation, which the algorithm performs repeatedly, and define the time complexity T(N) as the number of such operations the algorithm performs given an array of length N.
Example 1:
The time complexity for the loop with elementary operations: Assuming these operations take unit time for execution. This unit time can be denoted by O(1). If the loop runs for N times without any comparison. Below is the illustration for the same:
C++
Java
Python3
C#
Javascript
// C++ program to illustrate time// complexity for single for-loop#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } cout << a << ' ' << b; return 0;}
// Java program to illustrate time// complexity for single for-loopclass GFG{ // Driver Code public static void main(String[] args) { int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } System.out.print(a + " " + b); }} // This code is contributed by rutvik_56
# Python program to illustrate time# complexity for single for-loopa = 0b = 0N = 4M = 4 # This loop runs for N timefor i in range(N): a = a + 10 # This loop runs for M timefor i in range(M): b = b + 40 print(a,b) # This code is contributed by Shubham Singh
// C# program to illustrate time// complexity for single for-loopusing System;class GFG{ // Driver Code public static void Main(string[] args) { int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } Console.Write(a + " " + b); }} // This code is contributed by pratham76.
<script>// Javascript program to illustrate time// complexity for single for-loop // Driver Codelet a = 0;let b = 0;let N = 4;let M = 4; // This loop runs for N timefor (let i = 0; i < N; i++) { a = a + 10;} // This loop runs for M timefor (let i = 0; i < M; i++) { b = b + 40;} document.write(a +' ' + b); // This code is contributed by Shubham Singh</script>
40 160
Explanation: The Time complexity here will be O(N + M). Loop one is a single for-loop that runs N times and calculation inside it takes O(1) time. Similarly, another loop takes M times by combining both the different loops takes by adding them is O( N + M + 1) = O( N + M).
Example 2:
After getting familiar with the elementary operations and the single loop. Now, to find the time complexity for nested loops, assume that two loops with a different number of iterations. It can be seen that, if the outer loop runs once, the inner will run M times, giving us a series as M + M + M + M + M..........N times, this can be written as N * M. Below is the illustration for the same:
C++
Java
Python3
C#
Javascript
// C++ program to illustrate time// complexity for nested loop#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a = 0, b = 0; int N = 4, M = 5; // Nested loops for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { a = a + j; // Print the current // value of a cout << a << ' '; } cout << endl; } return 0;}
// Java program to illustrate time// complexity for nested loopimport java.io.*; class GFG{ // Driver Codepublic static void main (String[] args){ int a = 0; int b = 0; int N = 4; int M = 5; // Nested loops for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { a = a + j; // Print the current // value of a System.out.print(a + " "); } System.out.println(); }}} // This code is contributed by Shubham Singh
# Python program to illustrate time# complexity for nested loop # Driver Codea = 0b = 0N = 4M = 5 # Nested loopsfor i in range(N): for j in range(M): a = a + j # Print the current # value of a print(a, end = " ") print() # This code is contributed by Shubham Singh
// C# program to illustrate time// complexity for nested loopusing System;public class GFG{ // Driver Code public static void Main () { int a = 0; // int b = 0; int N = 4; int M = 5; // Nested loops for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { a = a + j; // Print the current // value of a Console.Write(a + " "); } Console.WriteLine(); } }} // This code is contributed by Shubham Singh
<script>// Javascript program to illustrate time// complexity for Nested loops // Driver Codelet a = 0;let b = 0;let N = 4;let M = 5; // Nested loopsfor (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { a = a + j; // Print the current // value of a document.write(a +' '); } document.write('<br>');} // This code is contributed by Shubham Singh</script>
0 1 3 6 10
10 11 13 16 20
20 21 23 26 30
30 31 33 36 40
Example 3:
After getting the above problems. Let’s have two iterators in which, outer one runs N/2 times, and we know that the time complexity of a loop is considered as O(log N), if the iterator is divided / multiplied by a constant amount K then the time complexity is considered as O(logK N). Below is the illustration of the same:
C++
Java
Python3
C#
Javascript
// C++ program to illustrate time// complexity of the form O(log2 N)#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k cout << k << ' '; k = k + N / 2; } } return 0;}
// Program to illustrate time// complexity of the form O(log2 N)import java.util.*; class GFG { // Driver Code public static void main (String[] args) { int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k System.out.print(k + " "); k = k + N / 2; } } }} // This code is contributed by Shubham Singh
# Python program to illustrate time# complexity of the form O(log2 N) # Driver CodeN = 8k = 0 # First loop run N/2 timesfor i in range(N//2, N+1): # Inner loop run log N # times for all i j = 2 while j <= N: j = j * 2 # Print the value k print(k, end = ' ') k = k + N // 2 # This code is contributed by Shubham Singh
// Program to illustrate time// complexity of the form O(log2 N)using System;using System.Linq; public class GFG{ // Driver Code public static void Main () { int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k Console.Write(k + " "); k = k + N / 2; } } }} // This code is contributed by Shubham Singh
<script>// Javascript program to illustrate time// complexity of the form O(log2 N) // Driver Codevar N = 8, k = 0; // First loop run N/2 timesfor (var i = parseInt(N / 2); i <= N; i++) { // Inner loop run log N // times for all i for (var j = 2; j <= N;j = j * 2) { // Print the value k document.write(k +" "); k = k + parseInt(N / 2); }} //This code is contributed By Shubham Singh</script>
0 4 8 12 16 20 24 28 32 36 40 44 48 52 56
Example 4:
Now, let’s understand the while loop and try to update the iterator as an expression. Below is the illustration for the same:
C++
Java
Python3
C#
Javascript
// C++ program to illustrate time// complexity while updating the// iteration#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a cout << a << ' '; a = a + i; // Update i i = i / 2; } return 0;}
// Java program to illustrate time// complexity while updating the// iterationimport java.io.*; class GFG { // Driver Code public static void main (String[] args) { int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a System.out.print(a + " "); a = a + i; // Update i i = i / 2; } }} // This code is contributed by Shubham Singh
# Python program to illustrate time# complexity while updating the# iteration # Driver CodeN = 18i = Na = 0 # Iterate until i is greater# than 0while (i > 0): # Print the value of a print(a, end = ' ') a = a + i # Update i i = i // 2 # This code is contributed by Shubham Singh
// Java program to illustrate time// complexity while updating the// iterationusing System; public class GFG{ // Driver Code public static void Main () { int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a Console.Write(a + " "); a = a + i; // Update i i = i / 2; } }} // This code is contributed by Shubham Singh
<script>// javaScript program to illustrate time// complexity while updating the// iteration // Driver Codefunction main(){ var N = 18; var i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a document.write(a +" "); a = a + i; // Update i i = parseInt(i / 2); }} main(); // This code is contributed by Shubham Singh</script>
0 18 27 31 33
Explanation: The equation for above code can be given as:
=> (N/2)K = 1 (for k iterations) => N = 2k (taking log on both sides) => k = log(N) base 2. Therefore, the time complexity will be T(N) = O(log N)
Example 5: Another way of finding the time complexity is converting them into an expression and use the following to get the required result. Given an expression based on the algorithm, the task is to solve and find the time complexity. This methodology is easier as it uses a basic mathematical calculation to expand a given formula to get a particular solution. Below are the two examples to understand the method.
Steps:
Find the solution for (N – 1)th iteration/step.
Similarly, calculate for the next step.
Once, you get familiar with the pattern, find a solution for the Kth step.
Find the solution for N times, and solve for obtained expression.
Below is the illustration for the same:
Let the expression be:T(N) = 3*T(N – 1).
T(N) = 3*(3T(N-2))T(N) = 3*3*(3T(N – 3))
For k times:T(N) = (3^k – 1)*(3T(N – k))
For N times:T(N) = 3^N – 1 (3T(N – N))T(N) = 3^N – 1 *3(T(0))T(N) = 3^N * 1 T(N) = 3^N
The third and the simplest method is to use the Master’s Theorem or calculating time complexities. For finding time complexity using the Master’s Theorem, please refer to this article.
rutvik_56
pratham76
SHUBHAMSINGH10
khushboogoyal499
surinderdawra388
Algorithms-Analysis of Algorithms (Recurrences)
Analysis of Algorithms
time complexity
Analysis
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
3-coloring is NP Complete
Proof that Dominant Set of a Graph is NP-Complete
Difference between Deterministic and Non-deterministic Algorithms
Set partition is NP complete
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Mutex vs Semaphore
Understanding "extern" keyword in C | [
{
"code": null,
"e": 24653,
"s": 24625,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 24707,
"s": 24653,
"text": "Prerequisite: Analysis of Algorithms | Big-O analysis"
},
{
"code": null,
"e": 24968,
"s": 24707,
"text": "In the previous article, the analysis of the algorithm using Big O asymptotic notation is discussed. In this article, some examples are discussed to illustrate the Big O time complexity notation and also learn how to compute the time complexity of any program."
},
{
"code": null,
"e": 25597,
"s": 24968,
"text": "There are different asymptotic notations in which the time complexities of algorithms are measured. Here, the ”O”(Big O) notation is used to get the time complexities. Time complexity estimates the time to run an algorithm. It’s calculated by counting the elementary operations. It is always a good practice to know the reason for execution time in a way that depends only on the algorithm and its input. This can be achieved by choosing an elementary operation, which the algorithm performs repeatedly, and define the time complexity T(N) as the number of such operations the algorithm performs given an array of length N."
},
{
"code": null,
"e": 25608,
"s": 25597,
"text": "Example 1:"
},
{
"code": null,
"e": 25857,
"s": 25608,
"text": "The time complexity for the loop with elementary operations: Assuming these operations take unit time for execution. This unit time can be denoted by O(1). If the loop runs for N times without any comparison. Below is the illustration for the same:"
},
{
"code": null,
"e": 25861,
"s": 25857,
"text": "C++"
},
{
"code": null,
"e": 25866,
"s": 25861,
"text": "Java"
},
{
"code": null,
"e": 25874,
"s": 25866,
"text": "Python3"
},
{
"code": null,
"e": 25877,
"s": 25874,
"text": "C#"
},
{
"code": null,
"e": 25888,
"s": 25877,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate time// complexity for single for-loop#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } cout << a << ' ' << b; return 0;}",
"e": 26288,
"s": 25888,
"text": null
},
{
"code": "// Java program to illustrate time// complexity for single for-loopclass GFG{ // Driver Code public static void main(String[] args) { int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } System.out.print(a + \" \" + b); }} // This code is contributed by rutvik_56",
"e": 26729,
"s": 26288,
"text": null
},
{
"code": "# Python program to illustrate time# complexity for single for-loopa = 0b = 0N = 4M = 4 # This loop runs for N timefor i in range(N): a = a + 10 # This loop runs for M timefor i in range(M): b = b + 40 print(a,b) # This code is contributed by Shubham Singh",
"e": 26996,
"s": 26729,
"text": null
},
{
"code": "// C# program to illustrate time// complexity for single for-loopusing System;class GFG{ // Driver Code public static void Main(string[] args) { int a = 0, b = 0; int N = 4, M = 4; // This loop runs for N time for (int i = 0; i < N; i++) { a = a + 10; } // This loop runs for M time for (int i = 0; i < M; i++) { b = b + 40; } Console.Write(a + \" \" + b); }} // This code is contributed by pratham76.",
"e": 27446,
"s": 26996,
"text": null
},
{
"code": "<script>// Javascript program to illustrate time// complexity for single for-loop // Driver Codelet a = 0;let b = 0;let N = 4;let M = 4; // This loop runs for N timefor (let i = 0; i < N; i++) { a = a + 10;} // This loop runs for M timefor (let i = 0; i < M; i++) { b = b + 40;} document.write(a +' ' + b); // This code is contributed by Shubham Singh</script>",
"e": 27814,
"s": 27446,
"text": null
},
{
"code": null,
"e": 27821,
"s": 27814,
"text": "40 160"
},
{
"code": null,
"e": 28097,
"s": 27823,
"text": "Explanation: The Time complexity here will be O(N + M). Loop one is a single for-loop that runs N times and calculation inside it takes O(1) time. Similarly, another loop takes M times by combining both the different loops takes by adding them is O( N + M + 1) = O( N + M)."
},
{
"code": null,
"e": 28108,
"s": 28097,
"text": "Example 2:"
},
{
"code": null,
"e": 28501,
"s": 28108,
"text": "After getting familiar with the elementary operations and the single loop. Now, to find the time complexity for nested loops, assume that two loops with a different number of iterations. It can be seen that, if the outer loop runs once, the inner will run M times, giving us a series as M + M + M + M + M..........N times, this can be written as N * M. Below is the illustration for the same:"
},
{
"code": null,
"e": 28505,
"s": 28501,
"text": "C++"
},
{
"code": null,
"e": 28510,
"s": 28505,
"text": "Java"
},
{
"code": null,
"e": 28518,
"s": 28510,
"text": "Python3"
},
{
"code": null,
"e": 28521,
"s": 28518,
"text": "C#"
},
{
"code": null,
"e": 28532,
"s": 28521,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate time// complexity for nested loop#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int a = 0, b = 0; int N = 4, M = 5; // Nested loops for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { a = a + j; // Print the current // value of a cout << a << ' '; } cout << endl; } return 0;}",
"e": 28955,
"s": 28532,
"text": null
},
{
"code": "// Java program to illustrate time// complexity for nested loopimport java.io.*; class GFG{ // Driver Codepublic static void main (String[] args){ int a = 0; int b = 0; int N = 4; int M = 5; // Nested loops for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { a = a + j; // Print the current // value of a System.out.print(a + \" \"); } System.out.println(); }}} // This code is contributed by Shubham Singh",
"e": 29476,
"s": 28955,
"text": null
},
{
"code": "# Python program to illustrate time# complexity for nested loop # Driver Codea = 0b = 0N = 4M = 5 # Nested loopsfor i in range(N): for j in range(M): a = a + j # Print the current # value of a print(a, end = \" \") print() # This code is contributed by Shubham Singh",
"e": 29789,
"s": 29476,
"text": null
},
{
"code": "// C# program to illustrate time// complexity for nested loopusing System;public class GFG{ // Driver Code public static void Main () { int a = 0; // int b = 0; int N = 4; int M = 5; // Nested loops for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { a = a + j; // Print the current // value of a Console.Write(a + \" \"); } Console.WriteLine(); } }} // This code is contributed by Shubham Singh",
"e": 30269,
"s": 29789,
"text": null
},
{
"code": "<script>// Javascript program to illustrate time// complexity for Nested loops // Driver Codelet a = 0;let b = 0;let N = 4;let M = 5; // Nested loopsfor (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { a = a + j; // Print the current // value of a document.write(a +' '); } document.write('<br>');} // This code is contributed by Shubham Singh</script>",
"e": 30680,
"s": 30269,
"text": null
},
{
"code": null,
"e": 30739,
"s": 30680,
"text": "0 1 3 6 10 \n10 11 13 16 20 \n20 21 23 26 30 \n30 31 33 36 40"
},
{
"code": null,
"e": 30752,
"s": 30741,
"text": "Example 3:"
},
{
"code": null,
"e": 31076,
"s": 30752,
"text": "After getting the above problems. Let’s have two iterators in which, outer one runs N/2 times, and we know that the time complexity of a loop is considered as O(log N), if the iterator is divided / multiplied by a constant amount K then the time complexity is considered as O(logK N). Below is the illustration of the same:"
},
{
"code": null,
"e": 31080,
"s": 31076,
"text": "C++"
},
{
"code": null,
"e": 31085,
"s": 31080,
"text": "Java"
},
{
"code": null,
"e": 31093,
"s": 31085,
"text": "Python3"
},
{
"code": null,
"e": 31096,
"s": 31093,
"text": "C#"
},
{
"code": null,
"e": 31107,
"s": 31096,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate time// complexity of the form O(log2 N)#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k cout << k << ' '; k = k + N / 2; } } return 0;}",
"e": 31569,
"s": 31107,
"text": null
},
{
"code": "// Program to illustrate time// complexity of the form O(log2 N)import java.util.*; class GFG { // Driver Code public static void main (String[] args) { int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k System.out.print(k + \" \"); k = k + N / 2; } } }} // This code is contributed by Shubham Singh",
"e": 32169,
"s": 31569,
"text": null
},
{
"code": "# Python program to illustrate time# complexity of the form O(log2 N) # Driver CodeN = 8k = 0 # First loop run N/2 timesfor i in range(N//2, N+1): # Inner loop run log N # times for all i j = 2 while j <= N: j = j * 2 # Print the value k print(k, end = ' ') k = k + N // 2 # This code is contributed by Shubham Singh",
"e": 32557,
"s": 32169,
"text": null
},
{
"code": "// Program to illustrate time// complexity of the form O(log2 N)using System;using System.Linq; public class GFG{ // Driver Code public static void Main () { int N = 8, k = 0; // First loop run N/2 times for (int i = N / 2; i <= N; i++) { // Inner loop run log N // times for all i for (int j = 2; j <= N; j = j * 2) { // Print the value k Console.Write(k + \" \"); k = k + N / 2; } } }} // This code is contributed by Shubham Singh",
"e": 33163,
"s": 32557,
"text": null
},
{
"code": "<script>// Javascript program to illustrate time// complexity of the form O(log2 N) // Driver Codevar N = 8, k = 0; // First loop run N/2 timesfor (var i = parseInt(N / 2); i <= N; i++) { // Inner loop run log N // times for all i for (var j = 2; j <= N;j = j * 2) { // Print the value k document.write(k +\" \"); k = k + parseInt(N / 2); }} //This code is contributed By Shubham Singh</script>",
"e": 33594,
"s": 33163,
"text": null
},
{
"code": null,
"e": 33636,
"s": 33594,
"text": "0 4 8 12 16 20 24 28 32 36 40 44 48 52 56"
},
{
"code": null,
"e": 33649,
"s": 33638,
"text": "Example 4:"
},
{
"code": null,
"e": 33776,
"s": 33649,
"text": "Now, let’s understand the while loop and try to update the iterator as an expression. Below is the illustration for the same: "
},
{
"code": null,
"e": 33780,
"s": 33776,
"text": "C++"
},
{
"code": null,
"e": 33785,
"s": 33780,
"text": "Java"
},
{
"code": null,
"e": 33793,
"s": 33785,
"text": "Python3"
},
{
"code": null,
"e": 33796,
"s": 33793,
"text": "C#"
},
{
"code": null,
"e": 33807,
"s": 33796,
"text": "Javascript"
},
{
"code": "// C++ program to illustrate time// complexity while updating the// iteration#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a cout << a << ' '; a = a + i; // Update i i = i / 2; } return 0;}",
"e": 34190,
"s": 33807,
"text": null
},
{
"code": "// Java program to illustrate time// complexity while updating the// iterationimport java.io.*; class GFG { // Driver Code public static void main (String[] args) { int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a System.out.print(a + \" \"); a = a + i; // Update i i = i / 2; } }} // This code is contributed by Shubham Singh",
"e": 34627,
"s": 34190,
"text": null
},
{
"code": "# Python program to illustrate time# complexity while updating the# iteration # Driver CodeN = 18i = Na = 0 # Iterate until i is greater# than 0while (i > 0): # Print the value of a print(a, end = ' ') a = a + i # Update i i = i // 2 # This code is contributed by Shubham Singh",
"e": 34934,
"s": 34627,
"text": null
},
{
"code": "// Java program to illustrate time// complexity while updating the// iterationusing System; public class GFG{ // Driver Code public static void Main () { int N = 18; int i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a Console.Write(a + \" \"); a = a + i; // Update i i = i / 2; } }} // This code is contributed by Shubham Singh",
"e": 35357,
"s": 34934,
"text": null
},
{
"code": "<script>// javaScript program to illustrate time// complexity while updating the// iteration // Driver Codefunction main(){ var N = 18; var i = N, a = 0; // Iterate until i is greater // than 0 while (i > 0) { // Print the value of a document.write(a +\" \"); a = a + i; // Update i i = parseInt(i / 2); }} main(); // This code is contributed by Shubham Singh</script>",
"e": 35781,
"s": 35357,
"text": null
},
{
"code": null,
"e": 35795,
"s": 35781,
"text": "0 18 27 31 33"
},
{
"code": null,
"e": 35857,
"s": 35797,
"text": "Explanation: The equation for above code can be given as: "
},
{
"code": null,
"e": 36004,
"s": 35857,
"text": "=> (N/2)K = 1 (for k iterations) => N = 2k (taking log on both sides) => k = log(N) base 2. Therefore, the time complexity will be T(N) = O(log N)"
},
{
"code": null,
"e": 36421,
"s": 36004,
"text": "Example 5: Another way of finding the time complexity is converting them into an expression and use the following to get the required result. Given an expression based on the algorithm, the task is to solve and find the time complexity. This methodology is easier as it uses a basic mathematical calculation to expand a given formula to get a particular solution. Below are the two examples to understand the method."
},
{
"code": null,
"e": 36429,
"s": 36421,
"text": "Steps: "
},
{
"code": null,
"e": 36477,
"s": 36429,
"text": "Find the solution for (N – 1)th iteration/step."
},
{
"code": null,
"e": 36517,
"s": 36477,
"text": "Similarly, calculate for the next step."
},
{
"code": null,
"e": 36592,
"s": 36517,
"text": "Once, you get familiar with the pattern, find a solution for the Kth step."
},
{
"code": null,
"e": 36658,
"s": 36592,
"text": "Find the solution for N times, and solve for obtained expression."
},
{
"code": null,
"e": 36699,
"s": 36658,
"text": "Below is the illustration for the same: "
},
{
"code": null,
"e": 36740,
"s": 36699,
"text": "Let the expression be:T(N) = 3*T(N – 1)."
},
{
"code": null,
"e": 36781,
"s": 36740,
"text": "T(N) = 3*(3T(N-2))T(N) = 3*3*(3T(N – 3))"
},
{
"code": null,
"e": 36824,
"s": 36781,
"text": "For k times:T(N) = (3^k – 1)*(3T(N – k)) "
},
{
"code": null,
"e": 36913,
"s": 36824,
"text": "For N times:T(N) = 3^N – 1 (3T(N – N))T(N) = 3^N – 1 *3(T(0))T(N) = 3^N * 1 T(N) = 3^N "
},
{
"code": null,
"e": 37098,
"s": 36913,
"text": "The third and the simplest method is to use the Master’s Theorem or calculating time complexities. For finding time complexity using the Master’s Theorem, please refer to this article."
},
{
"code": null,
"e": 37110,
"s": 37100,
"text": "rutvik_56"
},
{
"code": null,
"e": 37120,
"s": 37110,
"text": "pratham76"
},
{
"code": null,
"e": 37135,
"s": 37120,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37152,
"s": 37135,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 37169,
"s": 37152,
"text": "surinderdawra388"
},
{
"code": null,
"e": 37217,
"s": 37169,
"text": "Algorithms-Analysis of Algorithms (Recurrences)"
},
{
"code": null,
"e": 37240,
"s": 37217,
"text": "Analysis of Algorithms"
},
{
"code": null,
"e": 37256,
"s": 37240,
"text": "time complexity"
},
{
"code": null,
"e": 37265,
"s": 37256,
"text": "Analysis"
},
{
"code": null,
"e": 37274,
"s": 37265,
"text": "Articles"
},
{
"code": null,
"e": 37372,
"s": 37274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37381,
"s": 37372,
"text": "Comments"
},
{
"code": null,
"e": 37394,
"s": 37381,
"text": "Old Comments"
},
{
"code": null,
"e": 37461,
"s": 37394,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 37487,
"s": 37461,
"text": "3-coloring is NP Complete"
},
{
"code": null,
"e": 37537,
"s": 37487,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 37603,
"s": 37537,
"text": "Difference between Deterministic and Non-deterministic Algorithms"
},
{
"code": null,
"e": 37632,
"s": 37603,
"text": "Set partition is NP complete"
},
{
"code": null,
"e": 37682,
"s": 37632,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 37729,
"s": 37682,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 37765,
"s": 37729,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 37784,
"s": 37765,
"text": "Mutex vs Semaphore"
}
] |
An Extensive Step by Step Guide to Exploratory Data Analysis | by Terence Shin | Towards Data Science | Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
Exploratory Data Analysis (EDA), also known as Data Exploration, is a step in the Data Analysis Process, where a number of techniques are used to better understand the dataset being used.
‘Understanding the dataset’ can refer to a number of things including but not limited to...
Extracting important variables and leaving behind useless variables
Identifying outliers, missing values, or human error
Understanding the relationship(s), or lack of, between variables
Ultimately, maximizing your insights of a dataset and minimizing potential error that may occur later in the process
Here’s why this is important.
Have you heard of the phrase, “garbage in, garbage out”?
With EDA, it’s more like, “garbage in, perform EDA, possibly garbage out.”
By conducting EDA, you can turn an almost useable dataset into a completely useable dataset. I’m not saying that EDA can magically make any dataset clean — that is not true. However, many EDA techniques can remedy some common problems that are present in every dataset.
Exploratory Data Analysis does two main things:
1. It helps clean up a dataset.
2. It gives you a better understanding of the variables and the relationships between them.
To me, there are main components of exploring data:
Understanding your variablesCleaning your datasetAnalyzing relationships between variables
Understanding your variables
Cleaning your dataset
Analyzing relationships between variables
In this article, we’ll take a look at the first two components.
Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
You don’t know what you don’t know. And if you don’t know what you don’t know, then how are you supposed to know whether your insights make sense or not? You won’t.
To give an example, I was exploring data provided by the NFL (data here) to see if I could discover any insights regarding variables that increase the likelihood of injury. One insight that I got was that Linebackers accumulated more than eight times as many injuries as Tight Ends. However, I had no idea what the difference between a Linebacker and a Tight End was, and because of this, I didn’t know if my insights made sense or not. Sure, I can Google what the differences between the two are, but I won’t always be able to rely on Google! Now you can see why understanding your data is so important. Let’s see how we can do this in practice.
As an example, I used the same dataset that I used to create my first Random Forest model, the Used Car Dataset here. First, I imported all of the libraries that I knew I’d need for my analysis and conducted some preliminary analyses.
#Import Librariesimport numpy as npimport pandas as pdimport matplotlib.pylab as pltimport seaborn as sns#Understanding my variablesdf.shapedf.head()df.columns
.shape returns the number of rows by the number of columns for my dataset. My output was (525839, 22), meaning the dataset has 525839 rows and 22 columns.
.head() returns the first 5 rows of my dataset. This is useful if you want to see some example values for each variable.
.columns returns the name of all of your columns in the dataset.
Once I knew all of the variables in the dataset, I wanted to get a better understanding of the different values for each variable.
df.nunique(axis=0)df.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))
.nunique(axis=0) returns the number of unique values for each variable.
.describe() summarizes the count, mean, standard deviation, min, and max for numeric variables. The code that follows this simply formats each row to the regular format and suppresses scientific notation (see here).
Immediately, I noticed an issue with price, year, and odometer. For example, the minimum and maximum price are $0.00 and $3,048,344,231.00 respectively. You’ll see how I dealt with this in the next section. I still wanted to get a better understanding of my discrete variables.
df.condition.unique()
Using .unique(), I took a look at my discrete variables, including ‘condition’.
You can see that there are many synonyms of each other, like ‘excellent’ and ‘like new’. While this isn’t the greatest example, there will be some instances where it‘s ideal to clump together different words. For example, if you were analyzing weather patterns, you may want to reclassify ‘cloudy’, ‘grey’, ‘cloudy with a chance of rain’, and ‘mostly cloudy’ simply as ‘cloudy’.
Later you’ll see that I end up omitting this column due to having too many null values, but if you wanted to re-classify the condition values, you could use the code below:
# Reclassify condition columndef clean_condition(row): good = ['good','fair'] excellent = ['excellent','like new'] if row.condition in good: return 'good' if row.condition in excellent: return 'excellent' return row.condition# Clean dataframedef clean_df(playlist): df_cleaned = df.copy() df_cleaned['condition'] = df_cleaned.apply(lambda row: clean_condition(row), axis=1) return df_cleaned# Get df with reclassfied 'condition' columndf_cleaned = clean_df(df)print(df_cleaned.condition.unique())
And you can see that the values have been re-classified below.
You now know how to reclassify discrete data if needed, but there are a number of things that still need to be looked at.
a. Removing Redundant variables
First I got rid of variables that I thought were redundant. This includes url, image_url, and city_url.
df_cleaned = df_cleaned.copy().drop(['url','image_url','city_url'], axis=1)
b. Variable Selection
Next, I wanted to get rid of any columns that had too many null values. Thanks to my friend, Richie, I used the following code to remove any columns that had 40% or more of its data as null values. Depending on the situation, I may want to increase or decrease the threshold. The remaining columns are shown below.
NA_val = df_cleaned.isna().sum()def na_filter(na, threshold = .4): #only select variables that passees the threshold col_pass = [] for i in na.keys(): if na[i]/df_cleaned.shape[0]<threshold: col_pass.append(i) return col_passdf_cleaned = df_cleaned[na_filter(NA_val)]df_cleaned.columns
c. Removing Outliers
Revisiting the issue previously addressed, I set parameters for price, year, and odometer to remove any values outside of the set boundaries. In this case, I used my intuition to determine parameters — I’m sure there are methods to determine the optimal boundaries, but I haven’t looked into it yet!
df_cleaned = df_cleaned[df_cleaned['price'].between(999.99, 99999.00)]df_cleaned = df_cleaned[df_cleaned['year'] > 1990]df_cleaned = df_cleaned[df_cleaned['odometer'] < 899999.00]df_cleaned.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))
You can see that the minimum and maximum values have changed in the results below.
d. Removing Rows with Null Values
Lastly, I used .dropna(axis=0) to remove any rows with null values. After the code below, I went from 371982 to 208765 rows.
df_cleaned = df_cleaned.dropna(axis=0)df_cleaned.shape
The first thing I like to do when analyzing my variables is visualizing it through a correlation matrix because it’s the fastest way to develop a general understanding of all of my variables. To review, correlation is a measurement that describes the relationship between two variables — if you want to learn more about it, you can check out my statistics cheat sheet here.) Thus, a correlation matrix is a table that shows the correlation coefficients between many variables. I used sns.heatmap() to plot a correlation matrix of all of the variables in the used car dataset.
# calculate correlation matrixcorr = df_cleaned.corr()# plot the heatmapsns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))
We can see that there is a positive correlation between price and year and a negative correlation between price and odometer. This makes sense as newer cars are generally more expensive, and cars with more mileage are relatively cheaper. We can also see that there is a negative correlation between year and odometer — the newer a car the less number of miles on the car.
It’s pretty hard to beat correlation heatmaps when it comes to data visualizations, but scatterplots are arguably one of the most useful visualizations when it comes to data.
A scatterplot is a type of graph which ‘plots’ the values of two variables along two axes, like age and height. Scatterplots are useful for many reasons: like correlation matrices, it allows you to quickly understand a relationship between two variables, it’s useful for identifying outliers, and it’s instrumental when polynomial multiple regression models (which we’ll get to in the next article). I used .plot() and set the ‘kind’ of graph as scatter. I also set the x-axis to ‘odometer’ and y-axis as ‘price’, since we want to see how different levels of mileage affects price.
df_cleaned.plot(kind='scatter', x='odometer', y='price')
This narrates the same story as a correlation matrix — there’s a negative correlation between odometer and price. What’s neat about scatterplots is that it communicates more information than just that. Another insight that you can assume is that mileage has a diminishing effect on price. In other words, the amount of mileage that a car accumulates early in its life impacts price much more than later on when a car is older. You can see this as the plots show a steep drop at first, but becomes less steep as more mileage is added. This is why people say that it’s not a good investment to buy a brand new car!
df_cleaned.plot(kind='scatter', x='year', y='price')
To give another example, the scatterplot above shows the relationship between year and price — the newer the car is, the more expensive it’s likely to be.
As a bonus, sns.pairplot() is a great way to create scatterplots between all of your variables.
sns.pairplot(df_cleaned)
Correlation matrices and scatterplots are useful for exploring the relationship between two variables. But what if you only wanted to explore a single variable by itself? This is when histograms come into play. Histograms look like bar graphs but they show the distribution of a variable’s set of values.
df_cleaned['odometer'].plot(kind='hist', bins=50, figsize=(12,6), facecolor='grey',edgecolor='black')df_cleaned['year'].plot(kind='hist', bins=20, figsize=(12,6), facecolor='grey',edgecolor='black')
df_cleaned['year'].plot(kind='hist', bins=20, figsize=(12,6), facecolor='grey',edgecolor='black')
We can quickly notice that the average car has an odometer from 0 to just over 200,000 km and a year of around 2000 to 2020. The difference between the two graphs is that the distribution of ‘odometer’ is positively skewed while the distribution of ‘year’ is negatively skewed. Skewness is important, especially in areas like finance, because a lot of models assume that all variables are normally distributed, which typically isn’t the case.
Another way to visualize the distribution of a variable is a boxplot. We’re going to look at ‘price’ this time as an example.
df_cleaned.boxplot('price')
Boxplots are not as intuitive as the other graphs shown above, but it communicates a lot of information in its own way. The image below explains how to read a boxplot. Immediately, you can see that there are a number of outliers for price in the upper range and that most of the prices fall between 0 and $40,000.
There are several other types of visualizations that weren’t covered that you can use depending on the dataset like stacked bar graphs, area plots, violin plots, and even geospatial visuals.
By going through the three steps of exploratory data analysis, you’ll have a much better understanding of your data, which will make it easier to choose your model, your attributes, and refine it overall.
If you enjoyed this be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! | [
{
"code": null,
"e": 323,
"s": 172,
"text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!"
},
{
"code": null,
"e": 511,
"s": 323,
"text": "Exploratory Data Analysis (EDA), also known as Data Exploration, is a step in the Data Analysis Process, where a number of techniques are used to better understand the dataset being used."
},
{
"code": null,
"e": 603,
"s": 511,
"text": "‘Understanding the dataset’ can refer to a number of things including but not limited to..."
},
{
"code": null,
"e": 671,
"s": 603,
"text": "Extracting important variables and leaving behind useless variables"
},
{
"code": null,
"e": 724,
"s": 671,
"text": "Identifying outliers, missing values, or human error"
},
{
"code": null,
"e": 789,
"s": 724,
"text": "Understanding the relationship(s), or lack of, between variables"
},
{
"code": null,
"e": 906,
"s": 789,
"text": "Ultimately, maximizing your insights of a dataset and minimizing potential error that may occur later in the process"
},
{
"code": null,
"e": 936,
"s": 906,
"text": "Here’s why this is important."
},
{
"code": null,
"e": 993,
"s": 936,
"text": "Have you heard of the phrase, “garbage in, garbage out”?"
},
{
"code": null,
"e": 1068,
"s": 993,
"text": "With EDA, it’s more like, “garbage in, perform EDA, possibly garbage out.”"
},
{
"code": null,
"e": 1338,
"s": 1068,
"text": "By conducting EDA, you can turn an almost useable dataset into a completely useable dataset. I’m not saying that EDA can magically make any dataset clean — that is not true. However, many EDA techniques can remedy some common problems that are present in every dataset."
},
{
"code": null,
"e": 1386,
"s": 1338,
"text": "Exploratory Data Analysis does two main things:"
},
{
"code": null,
"e": 1418,
"s": 1386,
"text": "1. It helps clean up a dataset."
},
{
"code": null,
"e": 1510,
"s": 1418,
"text": "2. It gives you a better understanding of the variables and the relationships between them."
},
{
"code": null,
"e": 1562,
"s": 1510,
"text": "To me, there are main components of exploring data:"
},
{
"code": null,
"e": 1653,
"s": 1562,
"text": "Understanding your variablesCleaning your datasetAnalyzing relationships between variables"
},
{
"code": null,
"e": 1682,
"s": 1653,
"text": "Understanding your variables"
},
{
"code": null,
"e": 1704,
"s": 1682,
"text": "Cleaning your dataset"
},
{
"code": null,
"e": 1746,
"s": 1704,
"text": "Analyzing relationships between variables"
},
{
"code": null,
"e": 1810,
"s": 1746,
"text": "In this article, we’ll take a look at the first two components."
},
{
"code": null,
"e": 1961,
"s": 1810,
"text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!"
},
{
"code": null,
"e": 2126,
"s": 1961,
"text": "You don’t know what you don’t know. And if you don’t know what you don’t know, then how are you supposed to know whether your insights make sense or not? You won’t."
},
{
"code": null,
"e": 2773,
"s": 2126,
"text": "To give an example, I was exploring data provided by the NFL (data here) to see if I could discover any insights regarding variables that increase the likelihood of injury. One insight that I got was that Linebackers accumulated more than eight times as many injuries as Tight Ends. However, I had no idea what the difference between a Linebacker and a Tight End was, and because of this, I didn’t know if my insights made sense or not. Sure, I can Google what the differences between the two are, but I won’t always be able to rely on Google! Now you can see why understanding your data is so important. Let’s see how we can do this in practice."
},
{
"code": null,
"e": 3008,
"s": 2773,
"text": "As an example, I used the same dataset that I used to create my first Random Forest model, the Used Car Dataset here. First, I imported all of the libraries that I knew I’d need for my analysis and conducted some preliminary analyses."
},
{
"code": null,
"e": 3168,
"s": 3008,
"text": "#Import Librariesimport numpy as npimport pandas as pdimport matplotlib.pylab as pltimport seaborn as sns#Understanding my variablesdf.shapedf.head()df.columns"
},
{
"code": null,
"e": 3323,
"s": 3168,
"text": ".shape returns the number of rows by the number of columns for my dataset. My output was (525839, 22), meaning the dataset has 525839 rows and 22 columns."
},
{
"code": null,
"e": 3444,
"s": 3323,
"text": ".head() returns the first 5 rows of my dataset. This is useful if you want to see some example values for each variable."
},
{
"code": null,
"e": 3509,
"s": 3444,
"text": ".columns returns the name of all of your columns in the dataset."
},
{
"code": null,
"e": 3640,
"s": 3509,
"text": "Once I knew all of the variables in the dataset, I wanted to get a better understanding of the different values for each variable."
},
{
"code": null,
"e": 3723,
"s": 3640,
"text": "df.nunique(axis=0)df.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))"
},
{
"code": null,
"e": 3795,
"s": 3723,
"text": ".nunique(axis=0) returns the number of unique values for each variable."
},
{
"code": null,
"e": 4011,
"s": 3795,
"text": ".describe() summarizes the count, mean, standard deviation, min, and max for numeric variables. The code that follows this simply formats each row to the regular format and suppresses scientific notation (see here)."
},
{
"code": null,
"e": 4289,
"s": 4011,
"text": "Immediately, I noticed an issue with price, year, and odometer. For example, the minimum and maximum price are $0.00 and $3,048,344,231.00 respectively. You’ll see how I dealt with this in the next section. I still wanted to get a better understanding of my discrete variables."
},
{
"code": null,
"e": 4311,
"s": 4289,
"text": "df.condition.unique()"
},
{
"code": null,
"e": 4391,
"s": 4311,
"text": "Using .unique(), I took a look at my discrete variables, including ‘condition’."
},
{
"code": null,
"e": 4770,
"s": 4391,
"text": "You can see that there are many synonyms of each other, like ‘excellent’ and ‘like new’. While this isn’t the greatest example, there will be some instances where it‘s ideal to clump together different words. For example, if you were analyzing weather patterns, you may want to reclassify ‘cloudy’, ‘grey’, ‘cloudy with a chance of rain’, and ‘mostly cloudy’ simply as ‘cloudy’."
},
{
"code": null,
"e": 4943,
"s": 4770,
"text": "Later you’ll see that I end up omitting this column due to having too many null values, but if you wanted to re-classify the condition values, you could use the code below:"
},
{
"code": null,
"e": 5500,
"s": 4943,
"text": "# Reclassify condition columndef clean_condition(row): good = ['good','fair'] excellent = ['excellent','like new'] if row.condition in good: return 'good' if row.condition in excellent: return 'excellent' return row.condition# Clean dataframedef clean_df(playlist): df_cleaned = df.copy() df_cleaned['condition'] = df_cleaned.apply(lambda row: clean_condition(row), axis=1) return df_cleaned# Get df with reclassfied 'condition' columndf_cleaned = clean_df(df)print(df_cleaned.condition.unique())"
},
{
"code": null,
"e": 5563,
"s": 5500,
"text": "And you can see that the values have been re-classified below."
},
{
"code": null,
"e": 5685,
"s": 5563,
"text": "You now know how to reclassify discrete data if needed, but there are a number of things that still need to be looked at."
},
{
"code": null,
"e": 5717,
"s": 5685,
"text": "a. Removing Redundant variables"
},
{
"code": null,
"e": 5821,
"s": 5717,
"text": "First I got rid of variables that I thought were redundant. This includes url, image_url, and city_url."
},
{
"code": null,
"e": 5897,
"s": 5821,
"text": "df_cleaned = df_cleaned.copy().drop(['url','image_url','city_url'], axis=1)"
},
{
"code": null,
"e": 5919,
"s": 5897,
"text": "b. Variable Selection"
},
{
"code": null,
"e": 6234,
"s": 5919,
"text": "Next, I wanted to get rid of any columns that had too many null values. Thanks to my friend, Richie, I used the following code to remove any columns that had 40% or more of its data as null values. Depending on the situation, I may want to increase or decrease the threshold. The remaining columns are shown below."
},
{
"code": null,
"e": 6547,
"s": 6234,
"text": "NA_val = df_cleaned.isna().sum()def na_filter(na, threshold = .4): #only select variables that passees the threshold col_pass = [] for i in na.keys(): if na[i]/df_cleaned.shape[0]<threshold: col_pass.append(i) return col_passdf_cleaned = df_cleaned[na_filter(NA_val)]df_cleaned.columns"
},
{
"code": null,
"e": 6568,
"s": 6547,
"text": "c. Removing Outliers"
},
{
"code": null,
"e": 6868,
"s": 6568,
"text": "Revisiting the issue previously addressed, I set parameters for price, year, and odometer to remove any values outside of the set boundaries. In this case, I used my intuition to determine parameters — I’m sure there are methods to determine the optimal boundaries, but I haven’t looked into it yet!"
},
{
"code": null,
"e": 7120,
"s": 6868,
"text": "df_cleaned = df_cleaned[df_cleaned['price'].between(999.99, 99999.00)]df_cleaned = df_cleaned[df_cleaned['year'] > 1990]df_cleaned = df_cleaned[df_cleaned['odometer'] < 899999.00]df_cleaned.describe().apply(lambda s: s.apply(lambda x: format(x, 'f')))"
},
{
"code": null,
"e": 7203,
"s": 7120,
"text": "You can see that the minimum and maximum values have changed in the results below."
},
{
"code": null,
"e": 7237,
"s": 7203,
"text": "d. Removing Rows with Null Values"
},
{
"code": null,
"e": 7362,
"s": 7237,
"text": "Lastly, I used .dropna(axis=0) to remove any rows with null values. After the code below, I went from 371982 to 208765 rows."
},
{
"code": null,
"e": 7417,
"s": 7362,
"text": "df_cleaned = df_cleaned.dropna(axis=0)df_cleaned.shape"
},
{
"code": null,
"e": 7993,
"s": 7417,
"text": "The first thing I like to do when analyzing my variables is visualizing it through a correlation matrix because it’s the fastest way to develop a general understanding of all of my variables. To review, correlation is a measurement that describes the relationship between two variables — if you want to learn more about it, you can check out my statistics cheat sheet here.) Thus, a correlation matrix is a table that shows the correlation coefficients between many variables. I used sns.heatmap() to plot a correlation matrix of all of the variables in the used car dataset."
},
{
"code": null,
"e": 8198,
"s": 7993,
"text": "# calculate correlation matrixcorr = df_cleaned.corr()# plot the heatmapsns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))"
},
{
"code": null,
"e": 8570,
"s": 8198,
"text": "We can see that there is a positive correlation between price and year and a negative correlation between price and odometer. This makes sense as newer cars are generally more expensive, and cars with more mileage are relatively cheaper. We can also see that there is a negative correlation between year and odometer — the newer a car the less number of miles on the car."
},
{
"code": null,
"e": 8745,
"s": 8570,
"text": "It’s pretty hard to beat correlation heatmaps when it comes to data visualizations, but scatterplots are arguably one of the most useful visualizations when it comes to data."
},
{
"code": null,
"e": 9327,
"s": 8745,
"text": "A scatterplot is a type of graph which ‘plots’ the values of two variables along two axes, like age and height. Scatterplots are useful for many reasons: like correlation matrices, it allows you to quickly understand a relationship between two variables, it’s useful for identifying outliers, and it’s instrumental when polynomial multiple regression models (which we’ll get to in the next article). I used .plot() and set the ‘kind’ of graph as scatter. I also set the x-axis to ‘odometer’ and y-axis as ‘price’, since we want to see how different levels of mileage affects price."
},
{
"code": null,
"e": 9384,
"s": 9327,
"text": "df_cleaned.plot(kind='scatter', x='odometer', y='price')"
},
{
"code": null,
"e": 9997,
"s": 9384,
"text": "This narrates the same story as a correlation matrix — there’s a negative correlation between odometer and price. What’s neat about scatterplots is that it communicates more information than just that. Another insight that you can assume is that mileage has a diminishing effect on price. In other words, the amount of mileage that a car accumulates early in its life impacts price much more than later on when a car is older. You can see this as the plots show a steep drop at first, but becomes less steep as more mileage is added. This is why people say that it’s not a good investment to buy a brand new car!"
},
{
"code": null,
"e": 10050,
"s": 9997,
"text": "df_cleaned.plot(kind='scatter', x='year', y='price')"
},
{
"code": null,
"e": 10205,
"s": 10050,
"text": "To give another example, the scatterplot above shows the relationship between year and price — the newer the car is, the more expensive it’s likely to be."
},
{
"code": null,
"e": 10301,
"s": 10205,
"text": "As a bonus, sns.pairplot() is a great way to create scatterplots between all of your variables."
},
{
"code": null,
"e": 10326,
"s": 10301,
"text": "sns.pairplot(df_cleaned)"
},
{
"code": null,
"e": 10631,
"s": 10326,
"text": "Correlation matrices and scatterplots are useful for exploring the relationship between two variables. But what if you only wanted to explore a single variable by itself? This is when histograms come into play. Histograms look like bar graphs but they show the distribution of a variable’s set of values."
},
{
"code": null,
"e": 10830,
"s": 10631,
"text": "df_cleaned['odometer'].plot(kind='hist', bins=50, figsize=(12,6), facecolor='grey',edgecolor='black')df_cleaned['year'].plot(kind='hist', bins=20, figsize=(12,6), facecolor='grey',edgecolor='black')"
},
{
"code": null,
"e": 10928,
"s": 10830,
"text": "df_cleaned['year'].plot(kind='hist', bins=20, figsize=(12,6), facecolor='grey',edgecolor='black')"
},
{
"code": null,
"e": 11371,
"s": 10928,
"text": "We can quickly notice that the average car has an odometer from 0 to just over 200,000 km and a year of around 2000 to 2020. The difference between the two graphs is that the distribution of ‘odometer’ is positively skewed while the distribution of ‘year’ is negatively skewed. Skewness is important, especially in areas like finance, because a lot of models assume that all variables are normally distributed, which typically isn’t the case."
},
{
"code": null,
"e": 11497,
"s": 11371,
"text": "Another way to visualize the distribution of a variable is a boxplot. We’re going to look at ‘price’ this time as an example."
},
{
"code": null,
"e": 11525,
"s": 11497,
"text": "df_cleaned.boxplot('price')"
},
{
"code": null,
"e": 11839,
"s": 11525,
"text": "Boxplots are not as intuitive as the other graphs shown above, but it communicates a lot of information in its own way. The image below explains how to read a boxplot. Immediately, you can see that there are a number of outliers for price in the upper range and that most of the prices fall between 0 and $40,000."
},
{
"code": null,
"e": 12030,
"s": 11839,
"text": "There are several other types of visualizations that weren’t covered that you can use depending on the dataset like stacked bar graphs, area plots, violin plots, and even geospatial visuals."
},
{
"code": null,
"e": 12235,
"s": 12030,
"text": "By going through the three steps of exploratory data analysis, you’ll have a much better understanding of your data, which will make it easier to choose your model, your attributes, and refine it overall."
}
] |
How to check whether a passed string is palindrome or not in JavaScript ? | 23 Jun, 2022
Given a string, our task is to find string is palindrome or not.
Example:
Input : "race"
Output : passed string is not a palindrome
Explanation : if we write "race" in reverse that is "ecer" it not
matches with first string so it is not a palindrome.
Example 2:
Input : "hellolleh"
Output : passed string is palindrome.
Approach 1: In this approach we use following steps.
First we iterate over a string in forward and backward direction.
Check if all forward and backward character matches, return true.
If all forward and backward character does not matches, return false.
If return is true, it is a palindrome.
Example:
Javascript
<script> // function that check str is palindrome or not function check_palindrome( str ) { let j = str.length -1; for( let i = 0 ; i < j/2 ;i++) { let x = str[i] ;//forward character let y = str[j-i];//backward character if( x != y) { // return false if string not match return false; } } /// return true if string is palindrome return true; } //function that print output is string is palindrome function is_palindrome( str ) { // variable that is true ig string is palindrome let ans = check_palindrome(str); //condition checking ans is true or not if( ans == true ) { console.log("passed string is palindrome "); } else { console.log("passed string not a palindrome"); } } // test variable let test = "racecar"; is_palindrome(test);</script>
Output :
passed string is palindrome.
Approach 2: Another approach is to reverse a string and check if the initial string matches with the reverse string or not.
Follow the following steps :
Initialize reverse_str a variable which stores reverse of the passed string.
Compare the string to reverse_str .
If matches, it is a palindrome.
Else string is not a palindrome.
Example:
Javascript
<script> // function to reverse the string function reverse( str ) { // variable holds reverse string let rev_str = ""; for( let i = str.length-1 ;i >= 0 ;i--) { rev_str+= str[i]; } // return reverse string return rev_str; } // function checking string is palindrome or not function is_palindrome( str ) { reverse_str = reverse(str); // condition checking if reverse str is // same as string it is palindrome // else not a palindrome if( reverse_str === str) { console.log("passed string is palindrome "); } else { console.log("passed string is not palindrome") } } let test = "hellolleh"; is_palindrome(test);</script>
Output :
passed string is palindrome.
Approach-3: Another approach, which is though the shortest approach, uses split(), reverse() and join() method.
Split the string of characters into several different characters (which is though unsorted at the moment).
Use reverse() method to reverse all the characters of the string alphabetically.
Then apply join() method in order to join all the characters of string (which are now sorted).
Below is the implementation of the above approach:
Javascript
// JavaScript code in order to check string palindrome... let checkPalindrome = (stringg) => { return stringg === stringg.split("").reverse().join("");}; console.log("Is Palindrome? : " + checkPalindrome("noon"));console.log("Is Palindrome?: " + checkPalindrome("apple")); // This code is contributed by Aman Singla...
Output:
Is Palindrome? : true
Is Palindrome?: false
as5853535
adnanirshad158
germanshephered48
amansingla
JavaScript-Questions
javascript-string
palindrome
Picked
JavaScript
Web Technologies
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 93,
"s": 28,
"text": "Given a string, our task is to find string is palindrome or not."
},
{
"code": null,
"e": 349,
"s": 93,
"text": "Example:\nInput : \"race\"\nOutput : passed string is not a palindrome\nExplanation : if we write \"race\" in reverse that is \"ecer\" it not \nmatches with first string so it is not a palindrome.\nExample 2:\nInput : \"hellolleh\"\nOutput : passed string is palindrome."
},
{
"code": null,
"e": 402,
"s": 349,
"text": "Approach 1: In this approach we use following steps."
},
{
"code": null,
"e": 468,
"s": 402,
"text": "First we iterate over a string in forward and backward direction."
},
{
"code": null,
"e": 534,
"s": 468,
"text": "Check if all forward and backward character matches, return true."
},
{
"code": null,
"e": 604,
"s": 534,
"text": "If all forward and backward character does not matches, return false."
},
{
"code": null,
"e": 643,
"s": 604,
"text": "If return is true, it is a palindrome."
},
{
"code": null,
"e": 654,
"s": 643,
"text": "Example: "
},
{
"code": null,
"e": 665,
"s": 654,
"text": "Javascript"
},
{
"code": "<script> // function that check str is palindrome or not function check_palindrome( str ) { let j = str.length -1; for( let i = 0 ; i < j/2 ;i++) { let x = str[i] ;//forward character let y = str[j-i];//backward character if( x != y) { // return false if string not match return false; } } /// return true if string is palindrome return true; } //function that print output is string is palindrome function is_palindrome( str ) { // variable that is true ig string is palindrome let ans = check_palindrome(str); //condition checking ans is true or not if( ans == true ) { console.log(\"passed string is palindrome \"); } else { console.log(\"passed string not a palindrome\"); } } // test variable let test = \"racecar\"; is_palindrome(test);</script>",
"e": 1522,
"s": 665,
"text": null
},
{
"code": null,
"e": 1532,
"s": 1522,
"text": " Output :"
},
{
"code": null,
"e": 1561,
"s": 1532,
"text": "passed string is palindrome."
},
{
"code": null,
"e": 1685,
"s": 1561,
"text": "Approach 2: Another approach is to reverse a string and check if the initial string matches with the reverse string or not."
},
{
"code": null,
"e": 1715,
"s": 1685,
"text": "Follow the following steps : "
},
{
"code": null,
"e": 1792,
"s": 1715,
"text": "Initialize reverse_str a variable which stores reverse of the passed string."
},
{
"code": null,
"e": 1828,
"s": 1792,
"text": "Compare the string to reverse_str ."
},
{
"code": null,
"e": 1860,
"s": 1828,
"text": "If matches, it is a palindrome."
},
{
"code": null,
"e": 1893,
"s": 1860,
"text": "Else string is not a palindrome."
},
{
"code": null,
"e": 1903,
"s": 1893,
"text": "Example: "
},
{
"code": null,
"e": 1914,
"s": 1903,
"text": "Javascript"
},
{
"code": "<script> // function to reverse the string function reverse( str ) { // variable holds reverse string let rev_str = \"\"; for( let i = str.length-1 ;i >= 0 ;i--) { rev_str+= str[i]; } // return reverse string return rev_str; } // function checking string is palindrome or not function is_palindrome( str ) { reverse_str = reverse(str); // condition checking if reverse str is // same as string it is palindrome // else not a palindrome if( reverse_str === str) { console.log(\"passed string is palindrome \"); } else { console.log(\"passed string is not palindrome\") } } let test = \"hellolleh\"; is_palindrome(test);</script>",
"e": 2613,
"s": 1914,
"text": null
},
{
"code": null,
"e": 2623,
"s": 2613,
"text": " Output :"
},
{
"code": null,
"e": 2652,
"s": 2623,
"text": "passed string is palindrome."
},
{
"code": null,
"e": 2764,
"s": 2652,
"text": "Approach-3: Another approach, which is though the shortest approach, uses split(), reverse() and join() method."
},
{
"code": null,
"e": 2871,
"s": 2764,
"text": "Split the string of characters into several different characters (which is though unsorted at the moment)."
},
{
"code": null,
"e": 2952,
"s": 2871,
"text": "Use reverse() method to reverse all the characters of the string alphabetically."
},
{
"code": null,
"e": 3047,
"s": 2952,
"text": "Then apply join() method in order to join all the characters of string (which are now sorted)."
},
{
"code": null,
"e": 3098,
"s": 3047,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3109,
"s": 3098,
"text": "Javascript"
},
{
"code": "// JavaScript code in order to check string palindrome... let checkPalindrome = (stringg) => { return stringg === stringg.split(\"\").reverse().join(\"\");}; console.log(\"Is Palindrome? : \" + checkPalindrome(\"noon\"));console.log(\"Is Palindrome?: \" + checkPalindrome(\"apple\")); // This code is contributed by Aman Singla...",
"e": 3429,
"s": 3109,
"text": null
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "Output:"
},
{
"code": null,
"e": 3481,
"s": 3437,
"text": "Is Palindrome? : true\nIs Palindrome?: false"
},
{
"code": null,
"e": 3491,
"s": 3481,
"text": "as5853535"
},
{
"code": null,
"e": 3506,
"s": 3491,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3524,
"s": 3506,
"text": "germanshephered48"
},
{
"code": null,
"e": 3535,
"s": 3524,
"text": "amansingla"
},
{
"code": null,
"e": 3556,
"s": 3535,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3574,
"s": 3556,
"text": "javascript-string"
},
{
"code": null,
"e": 3585,
"s": 3574,
"text": "palindrome"
},
{
"code": null,
"e": 3592,
"s": 3585,
"text": "Picked"
},
{
"code": null,
"e": 3603,
"s": 3592,
"text": "JavaScript"
},
{
"code": null,
"e": 3620,
"s": 3603,
"text": "Web Technologies"
},
{
"code": null,
"e": 3631,
"s": 3620,
"text": "palindrome"
}
] |
LRU Approximation (Second Chance Algorithm) | 30 Apr, 2019
If you are not familiar with Least Recently Used Algorithm, check Least Recently Used Algorithm(Page Replacement)
This algorithm is a combination of using a queue, similar to FIFO (FIFO (Page Replacement)) alongside using an array to keep track of the bits used to give the queued page a “second chance”.How does the algorithm work:
Set all the values of the bitref as False (Let it be the size of max capacity of queue).Set an empty queue to have a max capacity.Check if the queue is not full:If the element is in the queue, set its corresponding bitref = 1.If the element is not in the queue, then push it into the queue.If the queue is full:Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.Remove that element from the queue.Push the current element from the input array into the queue.
Set all the values of the bitref as False (Let it be the size of max capacity of queue).
Set an empty queue to have a max capacity.
Check if the queue is not full:If the element is in the queue, set its corresponding bitref = 1.If the element is not in the queue, then push it into the queue.
If the element is in the queue, set its corresponding bitref = 1.
If the element is not in the queue, then push it into the queue.
If the queue is full:Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.Remove that element from the queue.Push the current element from the input array into the queue.
Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.
Remove that element from the queue.
Push the current element from the input array into the queue.
Explanation:The bits are set as usual in this case to one for the indices in the bitref until the queue is full.Once the queue becomes full, according to FIFO Page Replacement Algorithm, we should get rid of the front of the queue (if the element is a fault/miss). But here we don’t do that.
Instead we first check its reference bit (aka bitref) if its 0 or 1 (False or True). If it is 0 (false), we pop it from the queue and push the waiting element into the queue. But if it is 1 (true), we then set its reference bit (bitref) to 0 and move it to the back of the queue. We keep on doing this until we come across the front of the queue to have its front value’s reference bit (bitref) as 0 (false).
Then we follow the usual by removing it from the queue and pushing the waiting element into the queue.
What if the waiting element is in the queue already? We just set its reference bit (bitref) to 1 (true).
We now move all the values like 2, 4, 1 to the back until we encounter 3, whose bitref is 0. While moving 2, 4, 1 to the back, we set their bitref values to 0.
So now, the question how is this an approximation of LRU, when it clearly implements FIFO instead of LRU. Well, this works by giving a second chance to the front of the queue (which in FIFO‘s case would have been popped and replaced). Here, the second chance is based on the fact that if the element is seen “recently” its reference bit (bitref) is set to 1 (true). If it was not seen recently, we would not have set its reference bit (bitref) to 1 (true) and thus removed it. Hence, this is why, it is an approximation and not LRU nor FIFO.
Below is the implementation of the above approach:
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find an element in the queue as// std::find does not work for a queuebool findQueue(queue<int> q, int x){ while (!q.empty()) { if (x == q.front()) return true; q.pop(); } // Element not found return false;} // Function to implement LRU Approximationvoid LRU_Approximation(vector<int> t, int capacity){ int n = t.size(); queue<int> q; // Capacity is the size of the queue // hits is number of times page was // found in cache and faults is the number // of times the page was not found in the cache int hits = 0, faults = 0; // Array to keep track of bits set when a // certain value is already in the queue // Set bit --> 1, if its a hit // find the index and set bitref[index] = 1 // Set bit --> 0, if its a fault, and the front // of the queue has bitref[front] = 1, send front // to back and set bitref[front] = 0 bool bitref[capacity] = { false }; // To find the first element that does not // have the bitref set to true int ptr = 0; // To check if the queue is filled up or not int count = 0; for (int i = 0; i < t.size(); i++) { if (!findQueue(q, t[i])) { // Queue is not filled up to capacity if (count < capacity) { q.push(t[i]); count++; } // Queue is filled up to capacity else { ptr = 0; // Find the first value that has its // bit set to 0 while (!q.empty()) { // If the value has bit set to 1 // Set it to 0 if (bitref[ptr % capacity]) bitref[ptr % capacity] = !bitref[ptr % capacity]; // Found the bit value 0 else break; ptr++; } // If the queue was empty if (q.empty()) { q.pop(); q.push(t[i]); } // If queue was not empty else { int j = 0; // Rotate the queue and set the front's // bit value to 0 until the value where // the bitref = 0 while (j < (ptr % capacity)) { int t1 = q.front(); q.pop(); q.push(t1); bool temp = bitref[0]; // Rotate the bitref array for (int counter = 0; counter < capacity - 1; counter++) bitref[counter] = bitref[counter + 1]; bitref[capacity - 1] = temp; j++; } // Remove front element // (the element with the bitref = 0) q.pop(); // Push the element from the // page array (next input) q.push(t[i]); } } faults++; } // If the input for the iteration was a hit else { queue<int> temp = q; int counter = 0; while (!q.empty()) { if (q.front() == t[i]) bitref[counter] = true; counter++; q.pop(); } q = temp; hits++; } } cout << "Hits: " << hits << "\nFaults: " << faults << '\n';} // Driver codeint main(){ vector<int> t = { 2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2 }; int capacity = 4; LRU_Approximation(t, capacity); return 0;}
Hits: 6
Faults: 6
Arrays
Operating Systems
Queue
Operating Systems
Arrays
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "If you are not familiar with Least Recently Used Algorithm, check Least Recently Used Algorithm(Page Replacement)"
},
{
"code": null,
"e": 361,
"s": 142,
"text": "This algorithm is a combination of using a queue, similar to FIFO (FIFO (Page Replacement)) alongside using an array to keep track of the bits used to give the queued page a “second chance”.How does the algorithm work:"
},
{
"code": null,
"e": 949,
"s": 361,
"text": "Set all the values of the bitref as False (Let it be the size of max capacity of queue).Set an empty queue to have a max capacity.Check if the queue is not full:If the element is in the queue, set its corresponding bitref = 1.If the element is not in the queue, then push it into the queue.If the queue is full:Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.Remove that element from the queue.Push the current element from the input array into the queue."
},
{
"code": null,
"e": 1038,
"s": 949,
"text": "Set all the values of the bitref as False (Let it be the size of max capacity of queue)."
},
{
"code": null,
"e": 1081,
"s": 1038,
"text": "Set an empty queue to have a max capacity."
},
{
"code": null,
"e": 1242,
"s": 1081,
"text": "Check if the queue is not full:If the element is in the queue, set its corresponding bitref = 1.If the element is not in the queue, then push it into the queue."
},
{
"code": null,
"e": 1308,
"s": 1242,
"text": "If the element is in the queue, set its corresponding bitref = 1."
},
{
"code": null,
"e": 1373,
"s": 1308,
"text": "If the element is not in the queue, then push it into the queue."
},
{
"code": null,
"e": 1671,
"s": 1373,
"text": "If the queue is full:Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0.Remove that element from the queue.Push the current element from the input array into the queue."
},
{
"code": null,
"e": 1852,
"s": 1671,
"text": "Find the first element of the queue that has its bitref = 0 and if any element in the front has bitref = 1, set it to 0. Rotate the queue until you find an element with bitref = 0."
},
{
"code": null,
"e": 1888,
"s": 1852,
"text": "Remove that element from the queue."
},
{
"code": null,
"e": 1950,
"s": 1888,
"text": "Push the current element from the input array into the queue."
},
{
"code": null,
"e": 2242,
"s": 1950,
"text": "Explanation:The bits are set as usual in this case to one for the indices in the bitref until the queue is full.Once the queue becomes full, according to FIFO Page Replacement Algorithm, we should get rid of the front of the queue (if the element is a fault/miss). But here we don’t do that."
},
{
"code": null,
"e": 2651,
"s": 2242,
"text": "Instead we first check its reference bit (aka bitref) if its 0 or 1 (False or True). If it is 0 (false), we pop it from the queue and push the waiting element into the queue. But if it is 1 (true), we then set its reference bit (bitref) to 0 and move it to the back of the queue. We keep on doing this until we come across the front of the queue to have its front value’s reference bit (bitref) as 0 (false)."
},
{
"code": null,
"e": 2754,
"s": 2651,
"text": "Then we follow the usual by removing it from the queue and pushing the waiting element into the queue."
},
{
"code": null,
"e": 2859,
"s": 2754,
"text": "What if the waiting element is in the queue already? We just set its reference bit (bitref) to 1 (true)."
},
{
"code": null,
"e": 3019,
"s": 2859,
"text": "We now move all the values like 2, 4, 1 to the back until we encounter 3, whose bitref is 0. While moving 2, 4, 1 to the back, we set their bitref values to 0."
},
{
"code": null,
"e": 3561,
"s": 3019,
"text": "So now, the question how is this an approximation of LRU, when it clearly implements FIFO instead of LRU. Well, this works by giving a second chance to the front of the queue (which in FIFO‘s case would have been popped and replaced). Here, the second chance is based on the fact that if the element is seen “recently” its reference bit (bitref) is set to 1 (true). If it was not seen recently, we would not have set its reference bit (bitref) to 1 (true) and thus removed it. Hence, this is why, it is an approximation and not LRU nor FIFO."
},
{
"code": null,
"e": 3612,
"s": 3561,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find an element in the queue as// std::find does not work for a queuebool findQueue(queue<int> q, int x){ while (!q.empty()) { if (x == q.front()) return true; q.pop(); } // Element not found return false;} // Function to implement LRU Approximationvoid LRU_Approximation(vector<int> t, int capacity){ int n = t.size(); queue<int> q; // Capacity is the size of the queue // hits is number of times page was // found in cache and faults is the number // of times the page was not found in the cache int hits = 0, faults = 0; // Array to keep track of bits set when a // certain value is already in the queue // Set bit --> 1, if its a hit // find the index and set bitref[index] = 1 // Set bit --> 0, if its a fault, and the front // of the queue has bitref[front] = 1, send front // to back and set bitref[front] = 0 bool bitref[capacity] = { false }; // To find the first element that does not // have the bitref set to true int ptr = 0; // To check if the queue is filled up or not int count = 0; for (int i = 0; i < t.size(); i++) { if (!findQueue(q, t[i])) { // Queue is not filled up to capacity if (count < capacity) { q.push(t[i]); count++; } // Queue is filled up to capacity else { ptr = 0; // Find the first value that has its // bit set to 0 while (!q.empty()) { // If the value has bit set to 1 // Set it to 0 if (bitref[ptr % capacity]) bitref[ptr % capacity] = !bitref[ptr % capacity]; // Found the bit value 0 else break; ptr++; } // If the queue was empty if (q.empty()) { q.pop(); q.push(t[i]); } // If queue was not empty else { int j = 0; // Rotate the queue and set the front's // bit value to 0 until the value where // the bitref = 0 while (j < (ptr % capacity)) { int t1 = q.front(); q.pop(); q.push(t1); bool temp = bitref[0]; // Rotate the bitref array for (int counter = 0; counter < capacity - 1; counter++) bitref[counter] = bitref[counter + 1]; bitref[capacity - 1] = temp; j++; } // Remove front element // (the element with the bitref = 0) q.pop(); // Push the element from the // page array (next input) q.push(t[i]); } } faults++; } // If the input for the iteration was a hit else { queue<int> temp = q; int counter = 0; while (!q.empty()) { if (q.front() == t[i]) bitref[counter] = true; counter++; q.pop(); } q = temp; hits++; } } cout << \"Hits: \" << hits << \"\\nFaults: \" << faults << '\\n';} // Driver codeint main(){ vector<int> t = { 2, 3, 2, 1, 5, 2, 4, 5, 3, 2, 5, 2 }; int capacity = 4; LRU_Approximation(t, capacity); return 0;}",
"e": 7411,
"s": 3612,
"text": null
},
{
"code": null,
"e": 7430,
"s": 7411,
"text": "Hits: 6\nFaults: 6\n"
},
{
"code": null,
"e": 7437,
"s": 7430,
"text": "Arrays"
},
{
"code": null,
"e": 7455,
"s": 7437,
"text": "Operating Systems"
},
{
"code": null,
"e": 7461,
"s": 7455,
"text": "Queue"
},
{
"code": null,
"e": 7479,
"s": 7461,
"text": "Operating Systems"
},
{
"code": null,
"e": 7486,
"s": 7479,
"text": "Arrays"
},
{
"code": null,
"e": 7492,
"s": 7486,
"text": "Queue"
},
{
"code": null,
"e": 7590,
"s": 7492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7622,
"s": 7590,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7669,
"s": 7622,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7694,
"s": 7669,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7725,
"s": 7694,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7783,
"s": 7725,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 7810,
"s": 7783,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 7849,
"s": 7810,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 7898,
"s": 7849,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 7925,
"s": 7898,
"text": "Disk Scheduling Algorithms"
}
] |
ML | Kaggle Breast Cancer Wisconsin Diagnosis using KNN and Cross Validation | 21 Aug, 2020
Dataset :It is given by Kaggle from UCI Machine Learning Repository, in one of its challenges.https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It is a dataset of Breast Cancer patients with Malignant and Benign tumor.K-nearest neighbour algorithm is used to predict whether is patient is having cancer (Malignant tumour) or not (Benign tumour).
Implementation of KNN algorithm for classification.
Code : Importing Libraries
# performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as plt
Code : Loading dataset
df = pd.read_csv("..\\breast-cancer-wisconsin-data\\data.csv") print (data.head)
Output :
Code: Data Info
df.info()
Output :
RangeIndex: 569 entries, 0 to 568
Data columns (total 33 columns):
id 569 non-null int64
diagnosis 569 non-null object
radius_mean 569 non-null float64
texture_mean 569 non-null float64
perimeter_mean 569 non-null float64
area_mean 569 non-null float64
smoothness_mean 569 non-null float64
compactness_mean 569 non-null float64
concavity_mean 569 non-null float64
concave points_mean 569 non-null float64
symmetry_mean 569 non-null float64
fractal_dimension_mean 569 non-null float64
radius_se 569 non-null float64
texture_se 569 non-null float64
perimeter_se 569 non-null float64
area_se 569 non-null float64
smoothness_se 569 non-null float64
compactness_se 569 non-null float64
concavity_se 569 non-null float64
concave points_se 569 non-null float64
symmetry_se 569 non-null float64
fractal_dimension_se 569 non-null float64
radius_worst 569 non-null float64
texture_worst 569 non-null float64
perimeter_worst 569 non-null float64
area_worst 569 non-null float64
smoothness_worst 569 non-null float64
compactness_worst 569 non-null float64
concavity_worst 569 non-null float64
concave points_worst 569 non-null float64
symmetry_worst 569 non-null float64
fractal_dimension_worst 569 non-null float64
Unnamed: 32 0 non-null float64
dtypes: float64(31), int64(1), object(1)
memory usage: 146.8+ KB
Code: We are dropping columns – ‘id’ and ‘Unnamed: 32’ as they have no role in prediction
df.drop(['Unnamed: 32', 'id'], axis = 1)print(df.shape)
Output:
(569, 31)
Code: Converting the diagnosis value of M and B to a numerical value where M (Malignant) = 1 and B (Benign) = 0
def diagnosis_value(diagnosis): if diagnosis == 'M': return 1 else: return 0 df['diagnosis'] = df['diagnosis'].apply(diagnosis_value)
Code :
sns.lmplot(x = 'radius_mean', y = 'texture_mean', hue = 'diagnosis', data = df)
Output:
Code :
sns.lmplot(x ='smoothness_mean', y = 'compactness_mean', data = df, hue = 'diagnosis')
Output:
Code : Input and Output data
X = np.array(df.iloc[:, 1:])y = np.array(df['diagnosis'])
Code : Splitting data to training and testing
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.33, random_state = 42)
Code : Using Sklearn
knn = KNeighborsClassifier(n_neighbors = 13)knn.fit(X_train, y_train)
Output:
KNeighborsClassifier(algorithm='auto', leaf_size=30,
metric='minkowski', metric_params=None,
n_jobs=None, n_neighbors=13, p=2,
weights='uniform')
Code : Prediction Score
knn.score(X_test, y_test)
Output:
0.9627659574468085
Code : Performing Cross Validation
neighbors = []cv_scores = [] from sklearn.model_selection import cross_val_score# perform 10 fold cross validationfor k in range(1, 51, 2): neighbors.append(k) knn = KNeighborsClassifier(n_neighbors = k) scores = cross_val_score( knn, X_train, y_train, cv = 10, scoring = 'accuracy') cv_scores.append(scores.mean())
Code : Misclassification error versus k
MSE = [1-x for x in cv_scores] # determining the best koptimal_k = neighbors[MSE.index(min(MSE))]print('The optimal number of neighbors is % d ' % optimal_k) # plot misclassification error versus kplt.figure(figsize = (10, 6))plt.plot(neighbors, MSE)plt.xlabel('Number of neighbors')plt.ylabel('Misclassification Error')plt.show()
Output:
The optimal number of neighbors is 13
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 383,
"s": 28,
"text": "Dataset :It is given by Kaggle from UCI Machine Learning Repository, in one of its challenges.https://www.kaggle.com/uciml/breast-cancer-wisconsin-data. It is a dataset of Breast Cancer patients with Malignant and Benign tumor.K-nearest neighbour algorithm is used to predict whether is patient is having cancer (Malignant tumour) or not (Benign tumour)."
},
{
"code": null,
"e": 435,
"s": 383,
"text": "Implementation of KNN algorithm for classification."
},
{
"code": null,
"e": 462,
"s": 435,
"text": "Code : Importing Libraries"
},
{
"code": "# performing linear algebraimport numpy as np # data processingimport pandas as pd # visualisationimport matplotlib.pyplot as plt",
"e": 595,
"s": 462,
"text": null
},
{
"code": null,
"e": 618,
"s": 595,
"text": "Code : Loading dataset"
},
{
"code": "df = pd.read_csv(\"..\\\\breast-cancer-wisconsin-data\\\\data.csv\") print (data.head)",
"e": 700,
"s": 618,
"text": null
},
{
"code": null,
"e": 709,
"s": 700,
"text": "Output :"
},
{
"code": null,
"e": 725,
"s": 709,
"text": "Code: Data Info"
},
{
"code": "df.info()",
"e": 735,
"s": 725,
"text": null
},
{
"code": null,
"e": 744,
"s": 735,
"text": "Output :"
},
{
"code": null,
"e": 2456,
"s": 744,
"text": "RangeIndex: 569 entries, 0 to 568\nData columns (total 33 columns):\nid 569 non-null int64\ndiagnosis 569 non-null object\nradius_mean 569 non-null float64\ntexture_mean 569 non-null float64\nperimeter_mean 569 non-null float64\narea_mean 569 non-null float64\nsmoothness_mean 569 non-null float64\ncompactness_mean 569 non-null float64\nconcavity_mean 569 non-null float64\nconcave points_mean 569 non-null float64\nsymmetry_mean 569 non-null float64\nfractal_dimension_mean 569 non-null float64\nradius_se 569 non-null float64\ntexture_se 569 non-null float64\nperimeter_se 569 non-null float64\narea_se 569 non-null float64\nsmoothness_se 569 non-null float64\ncompactness_se 569 non-null float64\nconcavity_se 569 non-null float64\nconcave points_se 569 non-null float64\nsymmetry_se 569 non-null float64\nfractal_dimension_se 569 non-null float64\nradius_worst 569 non-null float64\ntexture_worst 569 non-null float64\nperimeter_worst 569 non-null float64\narea_worst 569 non-null float64\nsmoothness_worst 569 non-null float64\ncompactness_worst 569 non-null float64\nconcavity_worst 569 non-null float64\nconcave points_worst 569 non-null float64\nsymmetry_worst 569 non-null float64\nfractal_dimension_worst 569 non-null float64\nUnnamed: 32 0 non-null float64\ndtypes: float64(31), int64(1), object(1)\nmemory usage: 146.8+ KB\n"
},
{
"code": null,
"e": 2546,
"s": 2456,
"text": "Code: We are dropping columns – ‘id’ and ‘Unnamed: 32’ as they have no role in prediction"
},
{
"code": "df.drop(['Unnamed: 32', 'id'], axis = 1)print(df.shape)",
"e": 2602,
"s": 2546,
"text": null
},
{
"code": null,
"e": 2610,
"s": 2602,
"text": "Output:"
},
{
"code": null,
"e": 2620,
"s": 2610,
"text": "(569, 31)"
},
{
"code": null,
"e": 2732,
"s": 2620,
"text": "Code: Converting the diagnosis value of M and B to a numerical value where M (Malignant) = 1 and B (Benign) = 0"
},
{
"code": "def diagnosis_value(diagnosis): if diagnosis == 'M': return 1 else: return 0 df['diagnosis'] = df['diagnosis'].apply(diagnosis_value)",
"e": 2887,
"s": 2732,
"text": null
},
{
"code": null,
"e": 2894,
"s": 2887,
"text": "Code :"
},
{
"code": "sns.lmplot(x = 'radius_mean', y = 'texture_mean', hue = 'diagnosis', data = df)",
"e": 2974,
"s": 2894,
"text": null
},
{
"code": null,
"e": 2982,
"s": 2974,
"text": "Output:"
},
{
"code": null,
"e": 2991,
"s": 2984,
"text": "Code :"
},
{
"code": "sns.lmplot(x ='smoothness_mean', y = 'compactness_mean', data = df, hue = 'diagnosis')",
"e": 3089,
"s": 2991,
"text": null
},
{
"code": null,
"e": 3097,
"s": 3089,
"text": "Output:"
},
{
"code": null,
"e": 3126,
"s": 3097,
"text": "Code : Input and Output data"
},
{
"code": "X = np.array(df.iloc[:, 1:])y = np.array(df['diagnosis'])",
"e": 3184,
"s": 3126,
"text": null
},
{
"code": null,
"e": 3230,
"s": 3184,
"text": "Code : Splitting data to training and testing"
},
{
"code": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.33, random_state = 42)",
"e": 3381,
"s": 3230,
"text": null
},
{
"code": null,
"e": 3402,
"s": 3381,
"text": "Code : Using Sklearn"
},
{
"code": "knn = KNeighborsClassifier(n_neighbors = 13)knn.fit(X_train, y_train)",
"e": 3472,
"s": 3402,
"text": null
},
{
"code": null,
"e": 3480,
"s": 3472,
"text": "Output:"
},
{
"code": null,
"e": 3669,
"s": 3480,
"text": "KNeighborsClassifier(algorithm='auto', leaf_size=30, \n metric='minkowski', metric_params=None, \n n_jobs=None, n_neighbors=13, p=2, \n weights='uniform')\n"
},
{
"code": null,
"e": 3693,
"s": 3669,
"text": "Code : Prediction Score"
},
{
"code": "knn.score(X_test, y_test)",
"e": 3719,
"s": 3693,
"text": null
},
{
"code": null,
"e": 3727,
"s": 3719,
"text": "Output:"
},
{
"code": null,
"e": 3747,
"s": 3727,
"text": "0.9627659574468085\n"
},
{
"code": null,
"e": 3782,
"s": 3747,
"text": "Code : Performing Cross Validation"
},
{
"code": "neighbors = []cv_scores = [] from sklearn.model_selection import cross_val_score# perform 10 fold cross validationfor k in range(1, 51, 2): neighbors.append(k) knn = KNeighborsClassifier(n_neighbors = k) scores = cross_val_score( knn, X_train, y_train, cv = 10, scoring = 'accuracy') cv_scores.append(scores.mean())",
"e": 4118,
"s": 3782,
"text": null
},
{
"code": null,
"e": 4158,
"s": 4118,
"text": "Code : Misclassification error versus k"
},
{
"code": "MSE = [1-x for x in cv_scores] # determining the best koptimal_k = neighbors[MSE.index(min(MSE))]print('The optimal number of neighbors is % d ' % optimal_k) # plot misclassification error versus kplt.figure(figsize = (10, 6))plt.plot(neighbors, MSE)plt.xlabel('Number of neighbors')plt.ylabel('Misclassification Error')plt.show()",
"e": 4491,
"s": 4158,
"text": null
},
{
"code": null,
"e": 4499,
"s": 4491,
"text": "Output:"
},
{
"code": null,
"e": 4539,
"s": 4499,
"text": "The optimal number of neighbors is 13 \n"
},
{
"code": null,
"e": 4556,
"s": 4539,
"text": "Machine Learning"
},
{
"code": null,
"e": 4563,
"s": 4556,
"text": "Python"
},
{
"code": null,
"e": 4580,
"s": 4563,
"text": "Machine Learning"
},
{
"code": null,
"e": 4678,
"s": 4580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4701,
"s": 4678,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 4738,
"s": 4701,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 4778,
"s": 4738,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4802,
"s": 4778,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4840,
"s": 4802,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4868,
"s": 4840,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4890,
"s": 4868,
"text": "Python map() function"
},
{
"code": null,
"e": 4940,
"s": 4890,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4958,
"s": 4940,
"text": "Python Dictionary"
}
] |
Different Ways to Convert Char Array to String in C# | 28 May, 2020
We have given a character array arr and the task is to convert char array to string str in C#.
Input: arr = [s, t, r, i, n, g]
Output: string
Input: arr = [G, e, e, k, s, F, o, r, G, e, e, k, s]
Output: GeeksForGeeks
In order to do this task, we have the following methods:
Using string() Method: The String class has several overloaded constructors which take an array of characters or bytes. Thus it can be used to create a new string from the character array.
Syntax:
string str = new string(character_array);
Example:
C#
// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // string() is a used to // convert the char array // to string string s = new string(arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}
Output:
GeeksForGeeks
Using Join() Method: This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. Thus it can be used to create a new string from the character array.
Syntax:
string str = string.Join("", character_array);
Example:
C#
// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // String.Join() is a used to // convert the char array // to string string s = string.Join("", arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}
Output:
GeeksForGeeks
Using Concat() Method: This method is used to concatenate one or more instances of String or the String representations of the values of one or more instances of Object. Thus it can be used to create a new string from the character array.
Syntax:
string str = string.Concat(character_array);
Example:
C#
// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // String.Concat() is a used to // convert the char array // to string string s = string.Concat(arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}
Output:
GeeksForGeeks
CSharp-Arrays
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "We have given a character array arr and the task is to convert char array to string str in C#. "
},
{
"code": null,
"e": 276,
"s": 148,
"text": "Input: arr = [s, t, r, i, n, g] \nOutput: string\n \nInput: arr = [G, e, e, k, s, F, o, r, G, e, e, k, s]\nOutput: GeeksForGeeks\n"
},
{
"code": null,
"e": 333,
"s": 276,
"text": "In order to do this task, we have the following methods:"
},
{
"code": null,
"e": 522,
"s": 333,
"text": "Using string() Method: The String class has several overloaded constructors which take an array of characters or bytes. Thus it can be used to create a new string from the character array."
},
{
"code": null,
"e": 530,
"s": 522,
"text": "Syntax:"
},
{
"code": null,
"e": 573,
"s": 530,
"text": "string str = new string(character_array);\n"
},
{
"code": null,
"e": 582,
"s": 573,
"text": "Example:"
},
{
"code": null,
"e": 585,
"s": 582,
"text": "C#"
},
{
"code": "// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // string() is a used to // convert the char array // to string string s = new string(arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}",
"e": 1217,
"s": 585,
"text": null
},
{
"code": null,
"e": 1225,
"s": 1217,
"text": "Output:"
},
{
"code": null,
"e": 1240,
"s": 1225,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 1496,
"s": 1240,
"text": "Using Join() Method: This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. Thus it can be used to create a new string from the character array."
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "Syntax:"
},
{
"code": null,
"e": 1552,
"s": 1504,
"text": "string str = string.Join(\"\", character_array);\n"
},
{
"code": null,
"e": 1561,
"s": 1552,
"text": "Example:"
},
{
"code": null,
"e": 1564,
"s": 1561,
"text": "C#"
},
{
"code": "// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // String.Join() is a used to // convert the char array // to string string s = string.Join(\"\", arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}",
"e": 2206,
"s": 1564,
"text": null
},
{
"code": null,
"e": 2214,
"s": 2206,
"text": "Output:"
},
{
"code": null,
"e": 2229,
"s": 2214,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 2468,
"s": 2229,
"text": "Using Concat() Method: This method is used to concatenate one or more instances of String or the String representations of the values of one or more instances of Object. Thus it can be used to create a new string from the character array."
},
{
"code": null,
"e": 2476,
"s": 2468,
"text": "Syntax:"
},
{
"code": null,
"e": 2522,
"s": 2476,
"text": "string str = string.Concat(character_array);\n"
},
{
"code": null,
"e": 2531,
"s": 2522,
"text": "Example:"
},
{
"code": null,
"e": 2534,
"s": 2531,
"text": "C#"
},
{
"code": "// C# program to convert the// char array to stringusing System;using System.Text; public class GFG{ static string getString(char[] arr) { // String.Concat() is a used to // convert the char array // to string string s = string.Concat(arr); return s; } static void Main(string[] args) { // given character array char[] arr = {'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; // function calling string str = getString(arr); // printing output Console.WriteLine(str); }}",
"e": 3176,
"s": 2534,
"text": null
},
{
"code": null,
"e": 3184,
"s": 3176,
"text": "Output:"
},
{
"code": null,
"e": 3199,
"s": 3184,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 3213,
"s": 3199,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 3227,
"s": 3213,
"text": "CSharp-string"
},
{
"code": null,
"e": 3230,
"s": 3227,
"text": "C#"
}
] |
Python Program for BogoSort or Permutation Sort | 08 Jun, 2021
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted.
PseudoCode:
while not Sorted(list) do
shuffle (list)
done
Python3
# Python program for implementation of Bogo Sortimport random # Sorts array a[0..n-1] using Bogo sortdef bogoSort(a): n = len(a) while (is_sorted(a)== False): shuffle(a) # To check if array is sorted or notdef is_sorted(a): n = len(a) for i in range(0, n-1): if (a[i] > a[i+1] ): return False return True # To generate permutation of the arraydef shuffle(a): n = len(a) for i in range (0,n): r = random.randint(0,n-1) a[i], a[r] = a[r], a[i] # Driver code to test abovea = [3, 2, 4, 1, 0, 5]bogoSort(a)print("Sorted array :")for i in range(len(a)): print ("%d" %a[i]),
Output:
Sorted array :
0
1
2
3
4
5
Please refer complete article on BogoSort or Permutation Sort for more details!
anikaseth98
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert string dictionary to dictionary
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 554,
"s": 28,
"text": "BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted. "
},
{
"code": null,
"e": 568,
"s": 554,
"text": "PseudoCode: "
},
{
"code": null,
"e": 618,
"s": 568,
"text": "while not Sorted(list) do\n shuffle (list)\ndone"
},
{
"code": null,
"e": 628,
"s": 620,
"text": "Python3"
},
{
"code": "# Python program for implementation of Bogo Sortimport random # Sorts array a[0..n-1] using Bogo sortdef bogoSort(a): n = len(a) while (is_sorted(a)== False): shuffle(a) # To check if array is sorted or notdef is_sorted(a): n = len(a) for i in range(0, n-1): if (a[i] > a[i+1] ): return False return True # To generate permutation of the arraydef shuffle(a): n = len(a) for i in range (0,n): r = random.randint(0,n-1) a[i], a[r] = a[r], a[i] # Driver code to test abovea = [3, 2, 4, 1, 0, 5]bogoSort(a)print(\"Sorted array :\")for i in range(len(a)): print (\"%d\" %a[i]),",
"e": 1260,
"s": 628,
"text": null
},
{
"code": null,
"e": 1270,
"s": 1260,
"text": "Output: "
},
{
"code": null,
"e": 1297,
"s": 1270,
"text": "Sorted array :\n0\n1\n2\n3\n4\n5"
},
{
"code": null,
"e": 1378,
"s": 1297,
"text": "Please refer complete article on BogoSort or Permutation Sort for more details! "
},
{
"code": null,
"e": 1390,
"s": 1378,
"text": "anikaseth98"
},
{
"code": null,
"e": 1415,
"s": 1390,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 1431,
"s": 1415,
"text": "Python Programs"
},
{
"code": null,
"e": 1529,
"s": 1431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1578,
"s": 1529,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 1612,
"s": 1578,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 1653,
"s": 1612,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 1708,
"s": 1653,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 1754,
"s": 1708,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 1787,
"s": 1754,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 1851,
"s": 1787,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 1890,
"s": 1851,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 1927,
"s": 1890,
"text": "Python | Convert a list into a tuple"
}
] |
Basic Slicing and Advanced Indexing in NumPy Python | 05 Aug, 2021
Prerequisites : Numpy in Python IntroductionNumPy or Numeric Python is a package for computation on homogeneous n-dimensional arrays. In numpy dimensions are called as axes.
Why do we need NumPy ?
A question arises that why do we need NumPy when python lists are already there. The answer to it is we cannot perform operations on all the elements of two list directly. For example we cannot multiply two lists directly we will have to do it element wise. This is where the role of NumPy comes into play.
Python
# Python program to demonstrate a need of NumPy list1 = [1, 2, 3, 4 ,5, 6]list2 = [10, 9, 8, 7, 6, 5] # Multiplying both lists directly would give an error.print(list1*list2)
Output :
TypeError: can't multiply sequence by non-int of type 'list'
Where as this can easily be done with NumPy arrays.
Another example,
Python
# Python program to demonstrate the use of NumPy arraysimport numpy as np list1 = [1, 2, 3, 4, 5, 6]list2 = [10, 9, 8, 7, 6, 5] # Convert list1 into a NumPy arraya1 = np.array(list1) # Convert list2 into a NumPy arraya2 = np.array(list2) print(a1*a2)
Output :
array([10, 18, 24, 28, 30, 30])
This article will help you get acquainted with indexing in NumPy in detail. Numpy package of python has a great power of indexing in different ways.
Indexing using index arrays
Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on.
Python
# Python program to demonstrate# the use of index arrays.import numpy as np # Create a sequence of integers from 10 to 1 with a step of -2a = np.arrange(10, 1, -2)print("\n A sequential array with a negative step: \n",a) # Indexes are specified inside the np.array method.newarr = a[np.array([3, 1, 2 ])]print("\n Elements at these indices are:\n",newarr)
Output :
A sequential array with a negative step:
[10 8 6 4 2]
Elements at these indices are:
[4 8 6]
Another example,
Python
import numpy as np # NumPy array with elements from 1 to 9x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Index values can be negative.arr = x[np.array([1, 3, -3])]print("\n Elements are : \n",arr)
Output :
Elements are:
[2 4 7]
Types of Indexing
There are two types of indexing :
1. Basic Slicing and indexing : Consider the syntax x[obj] where x is the array and obj is the index. Slice object is the index in case of basic slicing. Basic slicing occurs when obj is :
a slice object that is of the form start : stop : stepan integeror a tuple of slice objects and integers
a slice object that is of the form start : stop : step
an integer
or a tuple of slice objects and integers
All arrays generated by basic slicing are always view of the original array.
Python
# Python program for basic slicing.import numpy as np # Arrange elements from 0 to 19a = np.arrange(20)print("\n Array is:\n ",a) # a[start:stop:step]print("\n a[-8:17:1] = ",a[-8:17:1]) # The : operator means all elements till the end.print("\n a[10:] = ",a[10:])
Output :
Array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[-8:17:1] = [12 13 14 15 16]
a[10:] = [10 11 12 13 14 15 16 17 18 19]
Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array.
Python
# Python program for indexing using basic slicing with ellipsisimport numpy as np # A 3 dimensional array.b = np.array([[[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10, 11, 12]]]) print(b[...,1]) #Equivalent to b[: ,: ,1 ]
Output :
[[ 2 5]
[ 8 11]]
2. Advanced indexing : Advanced indexing is triggered when obj is :
an ndarray of type integer or Boolean
or a tuple with at least one sequence object
is a non tuple sequence object
Advanced indexing returns a copy of data rather than a view of it. Advanced indexing is of two types integer and Boolean.
Purely integer indexing : When integers are used for indexing. Each element of first dimension is paired with the element of the second dimension. So the index of the elements in this case are (0,0),(1,0),(2,1) and the corresponding elements are selected.
Python
# Python program showing advanced indexingimport numpy as np a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])print(a[[0 ,1 ,2 ],[0 ,0 ,1]])
Output :
[1 3 6]
Boolean Indexing This indexing has some boolean expression as the index. Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values.
Python
# You may wish to select numbers greater than 50import numpy as np a = np.array([10, 40, 80, 50, 100])print(a[a>50])
Output :
[80 100]
Python
# You may wish to square the multiples of 40import numpy as np a = np.array([10, 40, 80, 50, 100])print(a[a%40==0]**2)
Output :
[1600 6400])
Python
# You may wish to select those elements whose# sum of row is a multiple of 10.import numpy as np b = np.array([[5, 5],[4, 5],[16, 4]])sumrow = b.sum(-1)print(b[sumrow%10==0])
Output :
array([[ 5, 5], [16, 4]])
Reference : SciPy.orgThis article is contributed by Ayushi Asthana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ruhelaa48
gabaa406
saurabh1990aror
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python map() function
Rotate axis tick labels in Seaborn and Matplotlib
Read JSON file using Python
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Queue in Python
Print lists in Python (5 Different Ways)
Stack in Python
sum() function in Python
Iterate over a list in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 228,
"s": 54,
"text": "Prerequisites : Numpy in Python IntroductionNumPy or Numeric Python is a package for computation on homogeneous n-dimensional arrays. In numpy dimensions are called as axes."
},
{
"code": null,
"e": 251,
"s": 228,
"text": "Why do we need NumPy ?"
},
{
"code": null,
"e": 558,
"s": 251,
"text": "A question arises that why do we need NumPy when python lists are already there. The answer to it is we cannot perform operations on all the elements of two list directly. For example we cannot multiply two lists directly we will have to do it element wise. This is where the role of NumPy comes into play."
},
{
"code": null,
"e": 565,
"s": 558,
"text": "Python"
},
{
"code": "# Python program to demonstrate a need of NumPy list1 = [1, 2, 3, 4 ,5, 6]list2 = [10, 9, 8, 7, 6, 5] # Multiplying both lists directly would give an error.print(list1*list2)",
"e": 740,
"s": 565,
"text": null
},
{
"code": null,
"e": 750,
"s": 740,
"text": "Output : "
},
{
"code": null,
"e": 811,
"s": 750,
"text": "TypeError: can't multiply sequence by non-int of type 'list'"
},
{
"code": null,
"e": 863,
"s": 811,
"text": "Where as this can easily be done with NumPy arrays."
},
{
"code": null,
"e": 880,
"s": 863,
"text": "Another example,"
},
{
"code": null,
"e": 887,
"s": 880,
"text": "Python"
},
{
"code": "# Python program to demonstrate the use of NumPy arraysimport numpy as np list1 = [1, 2, 3, 4, 5, 6]list2 = [10, 9, 8, 7, 6, 5] # Convert list1 into a NumPy arraya1 = np.array(list1) # Convert list2 into a NumPy arraya2 = np.array(list2) print(a1*a2)",
"e": 1138,
"s": 887,
"text": null
},
{
"code": null,
"e": 1148,
"s": 1138,
"text": "Output : "
},
{
"code": null,
"e": 1180,
"s": 1148,
"text": "array([10, 18, 24, 28, 30, 30])"
},
{
"code": null,
"e": 1330,
"s": 1180,
"text": "This article will help you get acquainted with indexing in NumPy in detail. Numpy package of python has a great power of indexing in different ways. "
},
{
"code": null,
"e": 1358,
"s": 1330,
"text": "Indexing using index arrays"
},
{
"code": null,
"e": 1707,
"s": 1358,
"text": "Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples. The last element is indexed by -1 second last by -2 and so on."
},
{
"code": null,
"e": 1714,
"s": 1707,
"text": "Python"
},
{
"code": "# Python program to demonstrate# the use of index arrays.import numpy as np # Create a sequence of integers from 10 to 1 with a step of -2a = np.arrange(10, 1, -2)print(\"\\n A sequential array with a negative step: \\n\",a) # Indexes are specified inside the np.array method.newarr = a[np.array([3, 1, 2 ])]print(\"\\n Elements at these indices are:\\n\",newarr)",
"e": 2070,
"s": 1714,
"text": null
},
{
"code": null,
"e": 2080,
"s": 2070,
"text": "Output : "
},
{
"code": null,
"e": 2178,
"s": 2080,
"text": "A sequential array with a negative step:\n[10 8 6 4 2]\n\nElements at these indices are:\n[4 8 6]"
},
{
"code": null,
"e": 2195,
"s": 2178,
"text": "Another example,"
},
{
"code": null,
"e": 2202,
"s": 2195,
"text": "Python"
},
{
"code": "import numpy as np # NumPy array with elements from 1 to 9x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Index values can be negative.arr = x[np.array([1, 3, -3])]print(\"\\n Elements are : \\n\",arr)",
"e": 2396,
"s": 2202,
"text": null
},
{
"code": null,
"e": 2406,
"s": 2396,
"text": "Output : "
},
{
"code": null,
"e": 2428,
"s": 2406,
"text": "Elements are:\n[2 4 7]"
},
{
"code": null,
"e": 2446,
"s": 2428,
"text": "Types of Indexing"
},
{
"code": null,
"e": 2480,
"s": 2446,
"text": "There are two types of indexing :"
},
{
"code": null,
"e": 2669,
"s": 2480,
"text": "1. Basic Slicing and indexing : Consider the syntax x[obj] where x is the array and obj is the index. Slice object is the index in case of basic slicing. Basic slicing occurs when obj is :"
},
{
"code": null,
"e": 2774,
"s": 2669,
"text": "a slice object that is of the form start : stop : stepan integeror a tuple of slice objects and integers"
},
{
"code": null,
"e": 2829,
"s": 2774,
"text": "a slice object that is of the form start : stop : step"
},
{
"code": null,
"e": 2840,
"s": 2829,
"text": "an integer"
},
{
"code": null,
"e": 2881,
"s": 2840,
"text": "or a tuple of slice objects and integers"
},
{
"code": null,
"e": 2958,
"s": 2881,
"text": "All arrays generated by basic slicing are always view of the original array."
},
{
"code": null,
"e": 2965,
"s": 2958,
"text": "Python"
},
{
"code": "# Python program for basic slicing.import numpy as np # Arrange elements from 0 to 19a = np.arrange(20)print(\"\\n Array is:\\n \",a) # a[start:stop:step]print(\"\\n a[-8:17:1] = \",a[-8:17:1]) # The : operator means all elements till the end.print(\"\\n a[10:] = \",a[10:])",
"e": 3230,
"s": 2965,
"text": null
},
{
"code": null,
"e": 3239,
"s": 3230,
"text": "Output :"
},
{
"code": null,
"e": 3387,
"s": 3239,
"text": "Array is:\n[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\n\na[-8:17:1] = [12 13 14 15 16]\n\na[10:] = [10 11 12 13 14 15 16 17 18 19] "
},
{
"code": null,
"e": 3565,
"s": 3387,
"text": "Ellipsis can also be used along with basic slicing. Ellipsis (...) is the number of : objects needed to make a selection tuple of the same length as the dimensions of the array."
},
{
"code": null,
"e": 3572,
"s": 3565,
"text": "Python"
},
{
"code": "# Python program for indexing using basic slicing with ellipsisimport numpy as np # A 3 dimensional array.b = np.array([[[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10, 11, 12]]]) print(b[...,1]) #Equivalent to b[: ,: ,1 ]",
"e": 3796,
"s": 3572,
"text": null
},
{
"code": null,
"e": 3805,
"s": 3796,
"text": "Output :"
},
{
"code": null,
"e": 3824,
"s": 3805,
"text": "[[ 2 5]\n [ 8 11]]"
},
{
"code": null,
"e": 3893,
"s": 3824,
"text": "2. Advanced indexing : Advanced indexing is triggered when obj is : "
},
{
"code": null,
"e": 3931,
"s": 3893,
"text": "an ndarray of type integer or Boolean"
},
{
"code": null,
"e": 3976,
"s": 3931,
"text": "or a tuple with at least one sequence object"
},
{
"code": null,
"e": 4007,
"s": 3976,
"text": "is a non tuple sequence object"
},
{
"code": null,
"e": 4129,
"s": 4007,
"text": "Advanced indexing returns a copy of data rather than a view of it. Advanced indexing is of two types integer and Boolean."
},
{
"code": null,
"e": 4385,
"s": 4129,
"text": "Purely integer indexing : When integers are used for indexing. Each element of first dimension is paired with the element of the second dimension. So the index of the elements in this case are (0,0),(1,0),(2,1) and the corresponding elements are selected."
},
{
"code": null,
"e": 4392,
"s": 4385,
"text": "Python"
},
{
"code": "# Python program showing advanced indexingimport numpy as np a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])print(a[[0 ,1 ,2 ],[0 ,0 ,1]])",
"e": 4523,
"s": 4392,
"text": null
},
{
"code": null,
"e": 4533,
"s": 4523,
"text": "Output : "
},
{
"code": null,
"e": 4541,
"s": 4533,
"text": "[1 3 6]"
},
{
"code": null,
"e": 4734,
"s": 4541,
"text": "Boolean Indexing This indexing has some boolean expression as the index. Those elements are returned which satisfy that Boolean expression. It is used for filtering the desired element values."
},
{
"code": null,
"e": 4741,
"s": 4734,
"text": "Python"
},
{
"code": "# You may wish to select numbers greater than 50import numpy as np a = np.array([10, 40, 80, 50, 100])print(a[a>50])",
"e": 4858,
"s": 4741,
"text": null
},
{
"code": null,
"e": 4868,
"s": 4858,
"text": "Output : "
},
{
"code": null,
"e": 4877,
"s": 4868,
"text": "[80 100]"
},
{
"code": null,
"e": 4884,
"s": 4877,
"text": "Python"
},
{
"code": "# You may wish to square the multiples of 40import numpy as np a = np.array([10, 40, 80, 50, 100])print(a[a%40==0]**2)",
"e": 5003,
"s": 4884,
"text": null
},
{
"code": null,
"e": 5013,
"s": 5003,
"text": "Output : "
},
{
"code": null,
"e": 5026,
"s": 5013,
"text": "[1600 6400])"
},
{
"code": null,
"e": 5033,
"s": 5026,
"text": "Python"
},
{
"code": "# You may wish to select those elements whose# sum of row is a multiple of 10.import numpy as np b = np.array([[5, 5],[4, 5],[16, 4]])sumrow = b.sum(-1)print(b[sumrow%10==0])",
"e": 5208,
"s": 5033,
"text": null
},
{
"code": null,
"e": 5218,
"s": 5208,
"text": "Output : "
},
{
"code": null,
"e": 5244,
"s": 5218,
"text": "array([[ 5, 5], [16, 4]])"
},
{
"code": null,
"e": 5688,
"s": 5244,
"text": "Reference : SciPy.orgThis article is contributed by Ayushi Asthana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5698,
"s": 5688,
"text": "ruhelaa48"
},
{
"code": null,
"e": 5707,
"s": 5698,
"text": "gabaa406"
},
{
"code": null,
"e": 5723,
"s": 5707,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 5745,
"s": 5723,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 5758,
"s": 5745,
"text": "Python-numpy"
},
{
"code": null,
"e": 5765,
"s": 5758,
"text": "Python"
},
{
"code": null,
"e": 5863,
"s": 5765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5885,
"s": 5863,
"text": "Python map() function"
},
{
"code": null,
"e": 5935,
"s": 5885,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 5963,
"s": 5935,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5985,
"s": 5963,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6035,
"s": 5985,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6051,
"s": 6035,
"text": "Queue in Python"
},
{
"code": null,
"e": 6092,
"s": 6051,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 6108,
"s": 6092,
"text": "Stack in Python"
},
{
"code": null,
"e": 6133,
"s": 6108,
"text": "sum() function in Python"
}
] |
N-Queen Problem | Practice | GeeksforGeeks | The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other.
Given an integer n, find all distinct solutions to the n-queens puzzle. Each solution contains distinct board configurations of the n-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For eg below figure represents a chessboard [3 1 4 2].
Example 1:
Input:
1
Output:
[1]
Explaination:
Only one queen can be placed
in the single cell available.
Example 2:
Input:
4
Output:
[2 4 1 3 ] [3 1 4 2 ]
Explaination:
These are the 2 possible solutions.
Your Task:
You do not need to read input or print anything. Your task is to complete the function nQueen() which takes n as input parameter and returns a list containing all the possible chessboard configurations in sorted order. Return an empty list if no solution exists.
Expected Time Complexity: O(n!)
Expected Auxiliary Space: O(n2)
Constraints:
1 ≤ n ≤ 10
0
bensonpx119817 hours ago
Using Unordered Set:
void backtrack(int col, int n, vector<vector<int>> &ans,vector<int> &temp, unordered_set<int> &rowSt, unordered_set<int> &posDiag, unordered_set<int> &negDiag)
{
if(col == n){
ans.push_back(temp);
return;
}
for(int row =0;row<n;row++){
if(rowSt.find(row) == rowSt.end() && posDiag.find(col+row) == posDiag.end() &&
negDiag.find(col-row) == negDiag.end()){
rowSt.insert(row);
posDiag.insert(col+row);
negDiag.insert(col-row);
temp.push_back(row+1);
backtrack(col+1,n,ans,temp,rowSt,posDiag,negDiag);
temp.pop_back();
rowSt.erase(row);
posDiag.erase(col+row);
negDiag.erase(col-row);
}
}
}
vector<vector<int>> nQueen(int n)
{
unordered_set<int> rowSt;
unordered_set<int> posDiag;
unordered_set<int> negDiag;
vector<vector<int>> ans;
vector<int> temp;
backtrack(0,n,ans,temp,rowSt,posDiag,negDiag);
return ans;
}
0
insanelion3 days ago
class Solution{
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<ArrayList<Integer>> nQueen(int n) {
// code here
boolean col[] = new boolean[n];
boolean ld[] = new boolean[2*n-1];
boolean rd[] = new boolean[2*n-1];
ArrayList<Integer> list = new ArrayList<>();
fill(0,col,n,list,ld,rd);
return ans;
}
void fill(int x,boolean col[],int n,ArrayList<Integer> list,
boolean ld[],boolean rd[]) {
if(x==n) {
ans.add(new ArrayList<>(list));
return;
}
for(int i=0;i<n;i++) {
if(col[i])
continue;
int left = i-x;
int right = i+x;
if(left<0)
left = Math.abs(left)+n-1;
if(ld[left] || rd[right])
continue;
ld[left] = true;
rd[right] = true;
col[i] = true;
list.add(i+1);
fill(x+1,col,n,list,ld,rd);
list.remove(list.size()-1);
col[i] = false;
ld[left] = false;
rd[right] = false;
}
}
}
0
insanelion3 days ago
class Solution{
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<ArrayList<Integer>> nQueen(int n) {
// code here
boolean col[] = new boolean[n];
boolean visited[][] = new boolean[n][n];
ArrayList<Integer> list = new ArrayList<>();
fill(0,visited,col,n,list);
return ans;
}
void fill(int x,boolean visited[][],boolean col[],int n,ArrayList<Integer> list) {
if(x==n) {
ans.add(new ArrayList<>(list));
return;
}
for(int i=0;i<n;i++) {
if(col[i])
continue;
boolean test = diagonal(visited,x,i,n);
if(test)
continue;
visited[x][i] = true;
col[i] = true;
list.add(i+1);
fill(x+1,visited,col,n,list);
list.remove(list.size()-1);
visited[x][i] = false;
col[i] = false;
}
}
boolean diagonal(boolean visited[][],int x,int y,int n) {
boolean left = false;
boolean right = false;
for(int i=x,j=y;i>=0&&j>=0;i--,j--)
left = left||visited[i][j];
for(int i=x,j=y;i>=0&&j<n;i--,j++)
right = right||visited[i][j];
return right||left;
}
}
+1
rp214 days ago
Concise approach, have a look at this!!
class Solution {
int n;
bool row[12], d1[22], d2[22];
vector<vector<int>> res;
vector<int> v;
public:
vector<vector<int>> nQueen(int n) {
this -> n = n;
memset(row, 0, 12);
memset(d1, 0, 22);
memset(d2, 0, 22);
res.clear();
recur(1);
return res;
}
void recur(int c) {
if(c > n) {
res.push_back(v);
return;
}
for(int r = 1; r <= n; r++) {
if(row[r] || d1[r + c] || d2[r - c + n]) continue;
row[r] = d1[r + c] = d2[r - c + n] = 1;
v.emplace_back(r);
recur(c + 1);
row[r] = d1[r + c] = d2[r - c + n] = 0;
v.pop_back();
}
}
};
0
riturajmishra4514 days ago
class Solution{public:
bool isSafe(int row,int col,int n,vector<vector<int>> &board){ //leftwards int drow=row,dcol=col; while(col>=0){ if(board[row][col]==1) return false; col--; } //Upwards Left Diagonal row=drow;col=dcol; while(col>=0 and row>=0){ if(board[row][col]==1) return false; col--; row--; } //Downwards Left Diagonal row=drow;col=dcol; while(col>=0 and row<n){ if(board[row][col]==1) return false; col--; row++; } return true; }
void nqueenHelper(int col,vector<vector<int>> &ans,vector<int> &arr,int n, vector<vector<int>> &board){ if(col == n){ ans.push_back(arr); return; } for(int row=0;row<n;row++){ if(isSafe(row,col,n,board) and board[row][col]==0){ arr.push_back(row+1); board[row][col] = 1; nqueenHelper(col+1,ans,arr,n,board); board[row][col] = 0; arr.pop_back(); } } }
vector<vector<int>> nQueen(int n) { vector<vector<int>> board(n,vector<int>(n,0)); vector<vector<int>> ans; vector<int> arr; nqueenHelper(0,ans,arr,n,board); return ans; }};
0
rohankr200215 days ago
#User function Template for python3
def black(i,j,notpos,n):
#black all positions below i,j
for ii in range(i,n):
notpos[ii][j] += 1
#black diagonally down and right
for ii in range(j,n):
if i + ii - j < n:
notpos[i + ii - j][ii] += 1
#black diagonally down and left
for ii in range(j):
if i + j - ii < n:
notpos[i + j - ii][ii] += 1
def unblack(i,j,notpos,n):
for ii in range(i,n):
notpos[ii][j] -= 1
for ii in range(j,n):
if i + ii - j < n:
notpos[i + ii - j][ii] -= 1
for ii in range(j):
if i + j - ii < n:
notpos[i + j - ii][ii] -= 1
def solve(level,pattern,notpos,ans,n):
if level == n:
ans.append(pattern)
return
for i in range(n):
if notpos[level][i] == 0:
black(level,i,notpos,n)
solve(level + 1,pattern + [i + 1],notpos,ans,n)
unblack(level,i,notpos,n)
class Solution:
def nQueen(self, n):
notpos = [[0]*n for _ in range(n)]
ans = []
solve(0,[],notpos,ans,n)
return ans
0
namantyagi63375 days ago
EASY TO UNDERSTAND BACKTRACKING SOLUTION
class Solution{public: bool is_safe(int row,int col,vector<vector<int>>& ch,int n) { for(int i=0;i<col;i++) { if(ch[row][i]) return false; } for(int i=row,j=col;i>=0 && j>=0;i--,j--) { if(ch[i][j]) return false; } for(int i=row,j=col;i<n && j>=0;i++,j--) { if(ch[i][j]) return false; } return true; } void solve(int col,int n,vector<vector<int>>& ch,vector<vector<int>>& fin_ans) { if(col==n) { vector<int> ans; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(ch[i][j]==1) { ans.push_back(j+1); break; } } } fin_ans.push_back(ans); return; } for(int i=0;i<n;i++) { if(is_safe(i,col,ch,n)) { ch[i][col]=1; solve(col+1,n,ch,fin_ans); ch[i][col]=0; } } return; } vector<vector<int>> nQueen(int n) { vector<vector<int>> ch(n,vector<int>(n,0)); int col=0; vector<vector<int>> fin_ans; solve(col,n,ch,fin_ans); sort(fin_ans.begin(),fin_ans.end()); return fin_ans; }};
+2
alekhyag06082 weeks ago
Java Solution
very easy to understand
With comments
class Solution{
static ArrayList<ArrayList<Integer>> nQueen(int n) {
// to store answer
ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
boolean[][] board=new boolean[n][n];
helper(board,ans,0);
return ans;
}
private static void helper(boolean[][] board,ArrayList<ArrayList<Integer>> ans,int row){
if(row==board.length){
//a solution is found
//add it to our list
add(board,ans);
return;
}
for(int col=0;col<board.length;col++){
//checking whether the queen will be placed safely or not
if(isSafe(board,row,col)){
board[row][col]=true;
helper(board,ans,row+1);
//backtracking
board[row][col]=false;
}
}
}
private static boolean isSafe(boolean[][] board,int row,int col){
//check the above rows for queens
for(int i=0;i<row;i++){
if(board[i][col]){
return false;
}
}
//to check left diagonal
int maxLeft=Math.min(row,col);
for(int i=1;i<=maxLeft;i++){
if(board[row-i][col-i]){
return false;
}
}
//to check right diagonal
int maxRight=Math.min(row,board.length-col-1);
for(int i=1;i<=maxRight;i++){
if(board[row-i][col+i]){
return false;
}
}
return true;
}
private static void add(boolean[][] board,ArrayList<ArrayList<Integer>> ans){
//this function adds solutions to the final answer
ArrayList<Integer> sub=new ArrayList<Integer>();
for(int row=0;row<board.length;row++){
for(int col=0;col<board.length;col++){
if(board[row][col]){
sub.add(col+1);
}
}
}
ans.add(sub);
}
}
0
avinashsoni2 weeks ago
most optimal solution :
class Solution{public: int ld[30]={0}; int rd[30]={0}; int cr[30]={0}; bool f(vector<vector<int>>&ans , vector<vector<int>>&board , int col , int n){ if(col >= n){ vector<int>temp; for(int i = 0 ; i < n ; ++i){ for(int j = 0 ; j < n ; ++j){ if(board[i][j] == 1) temp.push_back(j + 1); } } ans.push_back(temp); return true; } bool flag = false; for(int i = 0 ; i < n ; ++i){ if(ld[i - col + n - 1 ]!=1 && rd[i + col]!=1 && cr[i]!=1){ board[i][col] = 1; ld[i - col + n - 1] = rd[i + col ] = cr[i] = 1; flag = f(ans , board , col + 1 , n) || flag; board[i][col] = 0; ld[i - col + n - 1] = rd[i + col ] = cr[i] = 0; } } return flag; } vector<vector<int>> nQueen(int n) { vector<vector<int>>ans; vector<vector<int>>board(n,vector<int>(n,0)); f(ans,board,0,n); sort(ans.begin(),ans.end()); return ans; }};
+1
ambuj60092 weeks ago
class Solution{public: bool issafe(int r,int j, int n, vector<int> temp) { for(auto x:temp) //to check in col queen { if(x==j) return false; } for(int i=0;i<temp.size();i++) //to check diag queen { if((r-i-1)==abs(j-temp[i])) return false; } return true; } void solve(int r,int n, vector<int> &temp , vector<vector<int>> &ans) { if(r>n)//if ans is achieved { ans.push_back(temp); return; } for(int c=1;c<=n;c++) //checking for all columns { if(issafe(r,c,n,temp)) //checking if curr position is safe { temp.push_back(c); solve(r+1,n,temp,ans); //callin for forward positons temp.pop_back(); //backtrack } } } vector<vector<int>> nQueen(int n) { // code here vector<vector<int>> ans; vector<int> temp; solve(1,n,temp,ans); return ans; }};
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 751,
"s": 238,
"text": "The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other.\nGiven an integer n, find all distinct solutions to the n-queens puzzle. Each solution contains distinct board configurations of the n-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For eg below figure represents a chessboard [3 1 4 2].\n\n"
},
{
"code": null,
"e": 764,
"s": 753,
"text": "Example 1:"
},
{
"code": null,
"e": 859,
"s": 764,
"text": "Input:\n1\nOutput:\n[1]\nExplaination:\nOnly one queen can be placed \nin the single cell available."
},
{
"code": null,
"e": 870,
"s": 859,
"text": "Example 2:"
},
{
"code": null,
"e": 959,
"s": 870,
"text": "Input:\n4\nOutput:\n[2 4 1 3 ] [3 1 4 2 ]\nExplaination:\nThese are the 2 possible solutions."
},
{
"code": null,
"e": 1235,
"s": 961,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function nQueen() which takes n as input parameter and returns a list containing all the possible chessboard configurations in sorted order. Return an empty list if no solution exists."
},
{
"code": null,
"e": 1302,
"s": 1237,
"text": "Expected Time Complexity: O(n!)\nExpected Auxiliary Space: O(n2) "
},
{
"code": null,
"e": 1329,
"s": 1304,
"text": "Constraints:\n1 ≤ n ≤ 10 "
},
{
"code": null,
"e": 1331,
"s": 1329,
"text": "0"
},
{
"code": null,
"e": 1356,
"s": 1331,
"text": "bensonpx119817 hours ago"
},
{
"code": null,
"e": 1377,
"s": 1356,
"text": "Using Unordered Set:"
},
{
"code": null,
"e": 2546,
"s": 1377,
"text": "void backtrack(int col, int n, vector<vector<int>> &ans,vector<int> &temp, unordered_set<int> &rowSt, unordered_set<int> &posDiag, unordered_set<int> &negDiag)\n {\n if(col == n){\n ans.push_back(temp);\n return;\n }\n\n for(int row =0;row<n;row++){\n if(rowSt.find(row) == rowSt.end() && posDiag.find(col+row) == posDiag.end() &&\n negDiag.find(col-row) == negDiag.end()){\n rowSt.insert(row);\n posDiag.insert(col+row);\n negDiag.insert(col-row);\n temp.push_back(row+1);\n backtrack(col+1,n,ans,temp,rowSt,posDiag,negDiag);\n temp.pop_back();\n rowSt.erase(row);\n posDiag.erase(col+row);\n negDiag.erase(col-row);\n }\n }\n }\n\n vector<vector<int>> nQueen(int n)\n {\n unordered_set<int> rowSt;\n unordered_set<int> posDiag;\n unordered_set<int> negDiag;\n vector<vector<int>> ans;\n vector<int> temp;\n\n backtrack(0,n,ans,temp,rowSt,posDiag,negDiag);\n return ans;\n }"
},
{
"code": null,
"e": 2548,
"s": 2546,
"text": "0"
},
{
"code": null,
"e": 2569,
"s": 2548,
"text": "insanelion3 days ago"
},
{
"code": null,
"e": 3701,
"s": 2569,
"text": "class Solution{\n ArrayList<ArrayList<Integer>> ans = new ArrayList<>();\n ArrayList<ArrayList<Integer>> nQueen(int n) {\n // code here\n boolean col[] = new boolean[n];\n boolean ld[] = new boolean[2*n-1];\n boolean rd[] = new boolean[2*n-1];\n ArrayList<Integer> list = new ArrayList<>();\n fill(0,col,n,list,ld,rd);\n return ans;\n }\n void fill(int x,boolean col[],int n,ArrayList<Integer> list,\n boolean ld[],boolean rd[]) {\n if(x==n) {\n ans.add(new ArrayList<>(list));\n return;\n }\n for(int i=0;i<n;i++) {\n if(col[i])\n continue;\n int left = i-x;\n int right = i+x;\n if(left<0)\n left = Math.abs(left)+n-1;\n if(ld[left] || rd[right])\n continue;\n ld[left] = true;\n rd[right] = true;\n col[i] = true;\n list.add(i+1);\n fill(x+1,col,n,list,ld,rd);\n list.remove(list.size()-1);\n col[i] = false;\n ld[left] = false;\n rd[right] = false;\n }\n }\n}"
},
{
"code": null,
"e": 3703,
"s": 3701,
"text": "0"
},
{
"code": null,
"e": 3724,
"s": 3703,
"text": "insanelion3 days ago"
},
{
"code": null,
"e": 5022,
"s": 3724,
"text": "class Solution{\n ArrayList<ArrayList<Integer>> ans = new ArrayList<>();\n ArrayList<ArrayList<Integer>> nQueen(int n) {\n // code here\n boolean col[] = new boolean[n];\n boolean visited[][] = new boolean[n][n];\n ArrayList<Integer> list = new ArrayList<>();\n fill(0,visited,col,n,list);\n return ans;\n }\n void fill(int x,boolean visited[][],boolean col[],int n,ArrayList<Integer> list) {\n if(x==n) {\n ans.add(new ArrayList<>(list));\n return;\n }\n for(int i=0;i<n;i++) {\n if(col[i])\n continue;\n boolean test = diagonal(visited,x,i,n);\n if(test)\n continue;\n visited[x][i] = true;\n col[i] = true;\n list.add(i+1);\n fill(x+1,visited,col,n,list);\n list.remove(list.size()-1);\n visited[x][i] = false;\n col[i] = false;\n }\n }\n boolean diagonal(boolean visited[][],int x,int y,int n) {\n boolean left = false;\n boolean right = false;\n \n for(int i=x,j=y;i>=0&&j>=0;i--,j--)\n left = left||visited[i][j];\n \n for(int i=x,j=y;i>=0&&j<n;i--,j++)\n right = right||visited[i][j];\n \n return right||left;\n }\n}"
},
{
"code": null,
"e": 5025,
"s": 5022,
"text": "+1"
},
{
"code": null,
"e": 5040,
"s": 5025,
"text": "rp214 days ago"
},
{
"code": null,
"e": 5080,
"s": 5040,
"text": "Concise approach, have a look at this!!"
},
{
"code": null,
"e": 5833,
"s": 5080,
"text": "class Solution {\n int n;\n bool row[12], d1[22], d2[22];\n vector<vector<int>> res;\n vector<int> v;\npublic:\n vector<vector<int>> nQueen(int n) {\n this -> n = n;\n memset(row, 0, 12);\n memset(d1, 0, 22);\n memset(d2, 0, 22);\n res.clear();\n recur(1);\n return res;\n }\n \n void recur(int c) {\n if(c > n) {\n res.push_back(v);\n return;\n }\n \n for(int r = 1; r <= n; r++) {\n if(row[r] || d1[r + c] || d2[r - c + n]) continue;\n row[r] = d1[r + c] = d2[r - c + n] = 1;\n v.emplace_back(r);\n recur(c + 1);\n row[r] = d1[r + c] = d2[r - c + n] = 0;\n v.pop_back();\n }\n }\n};"
},
{
"code": null,
"e": 5835,
"s": 5833,
"text": "0"
},
{
"code": null,
"e": 5862,
"s": 5835,
"text": "riturajmishra4514 days ago"
},
{
"code": null,
"e": 5885,
"s": 5862,
"text": "class Solution{public:"
},
{
"code": null,
"e": 6495,
"s": 5885,
"text": " bool isSafe(int row,int col,int n,vector<vector<int>> &board){ //leftwards int drow=row,dcol=col; while(col>=0){ if(board[row][col]==1) return false; col--; } //Upwards Left Diagonal row=drow;col=dcol; while(col>=0 and row>=0){ if(board[row][col]==1) return false; col--; row--; } //Downwards Left Diagonal row=drow;col=dcol; while(col>=0 and row<n){ if(board[row][col]==1) return false; col--; row++; } return true; }"
},
{
"code": null,
"e": 7042,
"s": 6495,
"text": " void nqueenHelper(int col,vector<vector<int>> &ans,vector<int> &arr,int n, vector<vector<int>> &board){ if(col == n){ ans.push_back(arr); return; } for(int row=0;row<n;row++){ if(isSafe(row,col,n,board) and board[row][col]==0){ arr.push_back(row+1); board[row][col] = 1; nqueenHelper(col+1,ans,arr,n,board); board[row][col] = 0; arr.pop_back(); } } }"
},
{
"code": null,
"e": 7251,
"s": 7042,
"text": " vector<vector<int>> nQueen(int n) { vector<vector<int>> board(n,vector<int>(n,0)); vector<vector<int>> ans; vector<int> arr; nqueenHelper(0,ans,arr,n,board); return ans; }};"
},
{
"code": null,
"e": 7253,
"s": 7251,
"text": "0"
},
{
"code": null,
"e": 7276,
"s": 7253,
"text": "rohankr200215 days ago"
},
{
"code": null,
"e": 8468,
"s": 7276,
"text": "#User function Template for python3\ndef black(i,j,notpos,n):\n #black all positions below i,j\n for ii in range(i,n):\n notpos[ii][j] += 1\n #black diagonally down and right\n for ii in range(j,n):\n if i + ii - j < n:\n notpos[i + ii - j][ii] += 1\n #black diagonally down and left \n for ii in range(j):\n if i + j - ii < n:\n notpos[i + j - ii][ii] += 1\n \n \ndef unblack(i,j,notpos,n):\n for ii in range(i,n):\n notpos[ii][j] -= 1\n for ii in range(j,n):\n if i + ii - j < n:\n notpos[i + ii - j][ii] -= 1\n for ii in range(j):\n if i + j - ii < n:\n notpos[i + j - ii][ii] -= 1 \n \n\n\ndef solve(level,pattern,notpos,ans,n):\n if level == n:\n ans.append(pattern)\n return \n \n for i in range(n):\n if notpos[level][i] == 0:\n black(level,i,notpos,n)\n solve(level + 1,pattern + [i + 1],notpos,ans,n)\n unblack(level,i,notpos,n)\n \n\n\nclass Solution:\n def nQueen(self, n):\n notpos = [[0]*n for _ in range(n)]\n ans = []\n solve(0,[],notpos,ans,n)\n return ans \n "
},
{
"code": null,
"e": 8470,
"s": 8468,
"text": "0"
},
{
"code": null,
"e": 8495,
"s": 8470,
"text": "namantyagi63375 days ago"
},
{
"code": null,
"e": 8536,
"s": 8495,
"text": "EASY TO UNDERSTAND BACKTRACKING SOLUTION"
},
{
"code": null,
"e": 9903,
"s": 8538,
"text": "class Solution{public: bool is_safe(int row,int col,vector<vector<int>>& ch,int n) { for(int i=0;i<col;i++) { if(ch[row][i]) return false; } for(int i=row,j=col;i>=0 && j>=0;i--,j--) { if(ch[i][j]) return false; } for(int i=row,j=col;i<n && j>=0;i++,j--) { if(ch[i][j]) return false; } return true; } void solve(int col,int n,vector<vector<int>>& ch,vector<vector<int>>& fin_ans) { if(col==n) { vector<int> ans; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(ch[i][j]==1) { ans.push_back(j+1); break; } } } fin_ans.push_back(ans); return; } for(int i=0;i<n;i++) { if(is_safe(i,col,ch,n)) { ch[i][col]=1; solve(col+1,n,ch,fin_ans); ch[i][col]=0; } } return; } vector<vector<int>> nQueen(int n) { vector<vector<int>> ch(n,vector<int>(n,0)); int col=0; vector<vector<int>> fin_ans; solve(col,n,ch,fin_ans); sort(fin_ans.begin(),fin_ans.end()); return fin_ans; }}; "
},
{
"code": null,
"e": 9906,
"s": 9903,
"text": "+2"
},
{
"code": null,
"e": 9930,
"s": 9906,
"text": "alekhyag06082 weeks ago"
},
{
"code": null,
"e": 9944,
"s": 9930,
"text": "Java Solution"
},
{
"code": null,
"e": 9968,
"s": 9944,
"text": "very easy to understand"
},
{
"code": null,
"e": 9982,
"s": 9968,
"text": "With comments"
},
{
"code": null,
"e": 11979,
"s": 9982,
"text": "class Solution{\n static ArrayList<ArrayList<Integer>> nQueen(int n) {\n // to store answer\n ArrayList<ArrayList<Integer>> ans=new ArrayList<>();\n boolean[][] board=new boolean[n][n];\n helper(board,ans,0);\n return ans;\n \n }\n private static void helper(boolean[][] board,ArrayList<ArrayList<Integer>> ans,int row){\n if(row==board.length){\n //a solution is found\n //add it to our list\n add(board,ans);\n return;\n }\n \n for(int col=0;col<board.length;col++){\n //checking whether the queen will be placed safely or not\n if(isSafe(board,row,col)){\n board[row][col]=true;\n helper(board,ans,row+1);\n //backtracking\n board[row][col]=false;\n }\n }\n }\n private static boolean isSafe(boolean[][] board,int row,int col){\n //check the above rows for queens\n for(int i=0;i<row;i++){\n if(board[i][col]){\n return false;\n }\n }\n //to check left diagonal\n int maxLeft=Math.min(row,col);\n for(int i=1;i<=maxLeft;i++){\n if(board[row-i][col-i]){\n return false;\n }\n }\n //to check right diagonal\n int maxRight=Math.min(row,board.length-col-1);\n for(int i=1;i<=maxRight;i++){\n if(board[row-i][col+i]){\n return false;\n }\n }\n return true;\n }\n \n private static void add(boolean[][] board,ArrayList<ArrayList<Integer>> ans){\n //this function adds solutions to the final answer\n ArrayList<Integer> sub=new ArrayList<Integer>();\n for(int row=0;row<board.length;row++){\n \n for(int col=0;col<board.length;col++){\n if(board[row][col]){\n sub.add(col+1);\n }\n }\n }\n ans.add(sub);\n }\n}\n"
},
{
"code": null,
"e": 11981,
"s": 11979,
"text": "0"
},
{
"code": null,
"e": 12004,
"s": 11981,
"text": "avinashsoni2 weeks ago"
},
{
"code": null,
"e": 12029,
"s": 12004,
"text": "most optimal solution : "
},
{
"code": null,
"e": 13359,
"s": 12031,
"text": "class Solution{public: int ld[30]={0}; int rd[30]={0}; int cr[30]={0}; bool f(vector<vector<int>>&ans , vector<vector<int>>&board , int col , int n){ if(col >= n){ vector<int>temp; for(int i = 0 ; i < n ; ++i){ for(int j = 0 ; j < n ; ++j){ if(board[i][j] == 1) temp.push_back(j + 1); } } ans.push_back(temp); return true; } bool flag = false; for(int i = 0 ; i < n ; ++i){ if(ld[i - col + n - 1 ]!=1 && rd[i + col]!=1 && cr[i]!=1){ board[i][col] = 1; ld[i - col + n - 1] = rd[i + col ] = cr[i] = 1; flag = f(ans , board , col + 1 , n) || flag; board[i][col] = 0; ld[i - col + n - 1] = rd[i + col ] = cr[i] = 0; } } return flag; } vector<vector<int>> nQueen(int n) { vector<vector<int>>ans; vector<vector<int>>board(n,vector<int>(n,0)); f(ans,board,0,n); sort(ans.begin(),ans.end()); return ans; }};"
},
{
"code": null,
"e": 13362,
"s": 13359,
"text": "+1"
},
{
"code": null,
"e": 13383,
"s": 13362,
"text": "ambuj60092 weeks ago"
},
{
"code": null,
"e": 14385,
"s": 13383,
"text": "class Solution{public: bool issafe(int r,int j, int n, vector<int> temp) { for(auto x:temp) //to check in col queen { if(x==j) return false; } for(int i=0;i<temp.size();i++) //to check diag queen { if((r-i-1)==abs(j-temp[i])) return false; } return true; } void solve(int r,int n, vector<int> &temp , vector<vector<int>> &ans) { if(r>n)//if ans is achieved { ans.push_back(temp); return; } for(int c=1;c<=n;c++) //checking for all columns { if(issafe(r,c,n,temp)) //checking if curr position is safe { temp.push_back(c); solve(r+1,n,temp,ans); //callin for forward positons temp.pop_back(); //backtrack } } } vector<vector<int>> nQueen(int n) { // code here vector<vector<int>> ans; vector<int> temp; solve(1,n,temp,ans); return ans; }};"
},
{
"code": null,
"e": 14531,
"s": 14385,
"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": 14567,
"s": 14531,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 14577,
"s": 14567,
"text": "\nProblem\n"
},
{
"code": null,
"e": 14587,
"s": 14577,
"text": "\nContest\n"
},
{
"code": null,
"e": 14650,
"s": 14587,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 14835,
"s": 14650,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 15119,
"s": 14835,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 15265,
"s": 15119,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 15342,
"s": 15265,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 15383,
"s": 15342,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 15411,
"s": 15383,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 15482,
"s": 15411,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 15669,
"s": 15482,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Replace every element of the array by product of all other elements | 12 May, 2021
Given an array of integers. Replace every element by the product of all other elements of the array.Examples:
Input : arr[] = { 2, 3, 3, 5, 7 }
Output : 315 210 210 126 90
Approach :
First, take the product of all the element of the array.
Now replace each element by the product divided by that element.
Print the modified array.
Below is the implementation of above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to Replace every element// by the product of all other elements#include "iostream"using namespace std; void ReplaceElements(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} int main(){ int arr[] = { 2, 3, 3, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } return 0;}
// Java program to Replace every element// by the product of all other elements class GFG{static void ReplaceElements(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} public static void main(String[] args){ int arr[] = { 2, 3, 3, 5, 7 }; int n = arr.length; ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { System.out.print(arr[i]+" "); } System.out.println(""); }}// This code is contributed by mits
# Python 3 program to Replace every# element by the product of all# other elements def ReplaceElements(arr, n): prod = 1 # Calculate the product of # all the elements for i in range(n): prod *= arr[i] # Replace every element product # of all other elements for i in range(n) : arr[i] = prod // arr[i] # Driver Codeif __name__ == "__main__": arr = [ 2, 3, 3, 5, 7 ] n = len(arr) ReplaceElements(arr, n) # Print the modified array. for i in range( n): print(arr[i], end = " ") # This code is contributed# by ChitraNayal
// C# program to Replace every element// by the product of all other elementsusing System; class GFG{static void ReplaceElements(int []arr, int n){ int prod = 1; // Calculate the product of // all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} // Driver Codestatic public void Main (){ int []arr = { 2, 3, 3, 5, 7 }; int n = arr.Length; ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { Console.Write(arr[i]+" "); } Console.WriteLine("");}} // This code is contributed by ajit
<?php// PHP program to Replace every element// by the product of all other elements function ReplaceElements($arr, $n){ $prod = 1; // Calculate the product of all // the elements for ($i = 0; $i < $n; ++$i) { $prod *= $arr[$i]; } // Replace every element product // of all other elements for ($i = 0; $i < $n; ++$i) { $arr[$i] = (int)($prod / $arr[$i]); } return $arr;} // Driver Code$arr = array( 2, 3, 3, 5, 7 );$n = sizeof($arr); $arr1 = ReplaceElements($arr, $n); // Print the modified array.for ($i = 0; $i < $n; ++$i){ echo $arr1[$i] . " ";} // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to Replace every element // by the product of all other elements function ReplaceElements(arr, n) { let prod = 1; // Calculate the product of // all the elements for (let i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (let i = 0; i < n; ++i) { arr[i] = parseInt(prod / arr[i], 10); } } let arr = [ 2, 3, 3, 5, 7 ]; let n = arr.length; ReplaceElements(arr, n); // Print the modified array. for (let i = 0; i < n; ++i) { document.write(arr[i]+" "); } </script>
Output :
315 210 210 126 90
Time Complexity – O(N)
ukasp
Mithun Kumar
jit_t
Akanksha_Rai
surajdubey5
suresh07
Technical Scripter 2018
Arrays
Mathematical
Technical Scripter
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 164,
"s": 52,
"text": "Given an array of integers. Replace every element by the product of all other elements of the array.Examples: "
},
{
"code": null,
"e": 227,
"s": 164,
"text": "Input : arr[] = { 2, 3, 3, 5, 7 } \nOutput : 315 210 210 126 90"
},
{
"code": null,
"e": 240,
"s": 227,
"text": "Approach : "
},
{
"code": null,
"e": 297,
"s": 240,
"text": "First, take the product of all the element of the array."
},
{
"code": null,
"e": 362,
"s": 297,
"text": "Now replace each element by the product divided by that element."
},
{
"code": null,
"e": 388,
"s": 362,
"text": "Print the modified array."
},
{
"code": null,
"e": 436,
"s": 388,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 440,
"s": 436,
"text": "C++"
},
{
"code": null,
"e": 445,
"s": 440,
"text": "Java"
},
{
"code": null,
"e": 454,
"s": 445,
"text": "Python 3"
},
{
"code": null,
"e": 457,
"s": 454,
"text": "C#"
},
{
"code": null,
"e": 461,
"s": 457,
"text": "PHP"
},
{
"code": null,
"e": 472,
"s": 461,
"text": "Javascript"
},
{
"code": "// C++ program to Replace every element// by the product of all other elements#include \"iostream\"using namespace std; void ReplaceElements(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} int main(){ int arr[] = { 2, 3, 3, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { cout << arr[i] << \" \"; } return 0;}",
"e": 1123,
"s": 472,
"text": null
},
{
"code": "// Java program to Replace every element// by the product of all other elements class GFG{static void ReplaceElements(int arr[], int n){ int prod = 1; // Calculate the product of all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} public static void main(String[] args){ int arr[] = { 2, 3, 3, 5, 7 }; int n = arr.length; ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { System.out.print(arr[i]+\" \"); } System.out.println(\"\"); }}// This code is contributed by mits",
"e": 1821,
"s": 1123,
"text": null
},
{
"code": "# Python 3 program to Replace every# element by the product of all# other elements def ReplaceElements(arr, n): prod = 1 # Calculate the product of # all the elements for i in range(n): prod *= arr[i] # Replace every element product # of all other elements for i in range(n) : arr[i] = prod // arr[i] # Driver Codeif __name__ == \"__main__\": arr = [ 2, 3, 3, 5, 7 ] n = len(arr) ReplaceElements(arr, n) # Print the modified array. for i in range( n): print(arr[i], end = \" \") # This code is contributed# by ChitraNayal",
"e": 2400,
"s": 1821,
"text": null
},
{
"code": "// C# program to Replace every element// by the product of all other elementsusing System; class GFG{static void ReplaceElements(int []arr, int n){ int prod = 1; // Calculate the product of // all the elements for (int i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (int i = 0; i < n; ++i) { arr[i] = prod / arr[i]; }} // Driver Codestatic public void Main (){ int []arr = { 2, 3, 3, 5, 7 }; int n = arr.Length; ReplaceElements(arr, n); // Print the modified array. for (int i = 0; i < n; ++i) { Console.Write(arr[i]+\" \"); } Console.WriteLine(\"\");}} // This code is contributed by ajit",
"e": 3130,
"s": 2400,
"text": null
},
{
"code": "<?php// PHP program to Replace every element// by the product of all other elements function ReplaceElements($arr, $n){ $prod = 1; // Calculate the product of all // the elements for ($i = 0; $i < $n; ++$i) { $prod *= $arr[$i]; } // Replace every element product // of all other elements for ($i = 0; $i < $n; ++$i) { $arr[$i] = (int)($prod / $arr[$i]); } return $arr;} // Driver Code$arr = array( 2, 3, 3, 5, 7 );$n = sizeof($arr); $arr1 = ReplaceElements($arr, $n); // Print the modified array.for ($i = 0; $i < $n; ++$i){ echo $arr1[$i] . \" \";} // This code is contributed// by Akanksha Rai?>",
"e": 3781,
"s": 3130,
"text": null
},
{
"code": "<script> // Javascript program to Replace every element // by the product of all other elements function ReplaceElements(arr, n) { let prod = 1; // Calculate the product of // all the elements for (let i = 0; i < n; ++i) { prod *= arr[i]; } // Replace every element product // of all other elements for (let i = 0; i < n; ++i) { arr[i] = parseInt(prod / arr[i], 10); } } let arr = [ 2, 3, 3, 5, 7 ]; let n = arr.length; ReplaceElements(arr, n); // Print the modified array. for (let i = 0; i < n; ++i) { document.write(arr[i]+\" \"); } </script>",
"e": 4493,
"s": 3781,
"text": null
},
{
"code": null,
"e": 4504,
"s": 4493,
"text": "Output : "
},
{
"code": null,
"e": 4523,
"s": 4504,
"text": "315 210 210 126 90"
},
{
"code": null,
"e": 4547,
"s": 4523,
"text": "Time Complexity – O(N) "
},
{
"code": null,
"e": 4553,
"s": 4547,
"text": "ukasp"
},
{
"code": null,
"e": 4566,
"s": 4553,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 4572,
"s": 4566,
"text": "jit_t"
},
{
"code": null,
"e": 4585,
"s": 4572,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4597,
"s": 4585,
"text": "surajdubey5"
},
{
"code": null,
"e": 4606,
"s": 4597,
"text": "suresh07"
},
{
"code": null,
"e": 4630,
"s": 4606,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4637,
"s": 4630,
"text": "Arrays"
},
{
"code": null,
"e": 4650,
"s": 4637,
"text": "Mathematical"
},
{
"code": null,
"e": 4669,
"s": 4650,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4676,
"s": 4669,
"text": "Arrays"
},
{
"code": null,
"e": 4689,
"s": 4676,
"text": "Mathematical"
}
] |
XML Parsing in Android using XmlPullParser | 23 Feb, 2021
In android, the XMLPullParser interface provides the functionality to parse the XML files in android applications. The XMLPullParser is a simple and efficient parser method to parse the XML data when compared to other parser methods such as DOM Parser and SAX Parser. The XMLPullParser has a method next() that provides access to high-level parsing events. The next() method will advance the parser to the next event. The following are the series of events available in XMLPullParser, which will be seen by the next() method.
START_DOCUMENT: The parser starts processing the XML document.START_TAG: In this event, we can get the start tag in XML.TEXT: In this event, we can read the text content using the getText() method.END_TAG: An end tag was read.END_DOCUMENT: No more events are available.
START_DOCUMENT: The parser starts processing the XML document.
START_TAG: In this event, we can get the start tag in XML.
TEXT: In this event, we can read the text content using the getText() method.
END_TAG: An end tag was read.
END_DOCUMENT: No more events are available.
Note that we are going to implement this project using the Kotlin language. One may also perform XML Parsing in another two ways. Please refer to the below articles:
XML Parsing in Android using DOM Parser
XML Parsing in Android using SAX Parser
XMLPullParser scrutinizes an XML file with a series of events, such as START_DOCUMENT, START_TAG, TEXT, END_TAG, and END_DOCUMENT to parse the XML document. To read and parse XML files using XMLPullParser in android, one needs to create an instance of XMLPullParserFactory, and XMLPullParser.
To parse an XML file using a DOM parser in Android, we follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Create an assets folder
Create an assets folder under the main folder in the Project Layout. Create an Android Resource File in this folder, where we shall put the information in the form of XML. Name this file as userdetails.xml. For doing so refer to the following steps:
Click on Project as shown on the left side of the below image.
Expand until you find the main folder, right-click on it, go to New > Folder > Assets Folder
Then just click on the Finish button.
Now the asset folder is created successfully. Right-Click on the Assets Folder > New > Android Resource FIle
Give it name Information, change type to XML, and finish.
Note: Sometimes, right-clicking on the Assets folder and creating an Android Resource File creates a file in the res folder. If this happens, cut our file and paste it directly into the assets folder. This happens due to some internal settings.
Paste this information which is in the form of XML, that is to be displayed in the userdetails.xml file. Below is the code for the userdetails.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><users> <user> <name>Tom</name> <designation>Actor and Producer</designation> </user> <user> <name>Danny</name> <designation>Music Director</designation> </user> <user> <name>Christopher</name> <designation>Writer</designation> </user></users>
Step 3: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!--Display the list from list_row file--> <ListView android:id="@+id/user_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" /> </LinearLayout>
Step 4: Create another layout file
Go to app > res > layout > right-click > New > Layout Resource File and name the file as list_row. list_row.xml file is used to show the data in the ListView. Below is the code for the list_row.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip"> <!--TextView to display the name from the userdetails file--> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="17dp" android:textStyle="bold" /> <!--TextView to display the designation from the userdetails file--> <TextView android:id="@+id/designation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_marginTop="7dp" android:textColor="#343434" android:textSize="14dp" /> </RelativeLayout>
Step 5: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport android.widget.ListAdapterimport android.widget.ListViewimport android.widget.SimpleAdapterimport androidx.appcompat.app.AppCompatActivityimport org.xmlpull.v1.XmlPullParserimport org.xmlpull.v1.XmlPullParserExceptionimport org.xmlpull.v1.XmlPullParserFactoryimport java.io.IOExceptionimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) try { // creating a user list string hash map arraylist val userList = ArrayList<HashMap<String, String?>>() // creating a user string hashmap var user = HashMap<String, String?>() // declaring the list view from the layout file val lv = findViewById<ListView>(R.id.user_list) // input stream the userdetails.xml file val istream = assets.open("userdetails.xml") //creating a XmlPull parse Factory instance val parserFactory = XmlPullParserFactory.newInstance() val parser = parserFactory.newPullParser() // setting the namespaces feature to false parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) // setting the input to the parser parser.setInput(istream, null) // working with the input stream var tag: String? = "" var text: String? = "" var event = parser.eventType while (event != XmlPullParser.END_DOCUMENT) { tag = parser.name when (event) { XmlPullParser.START_TAG -> if (tag == "user") user = HashMap() XmlPullParser.TEXT -> text = parser.text XmlPullParser.END_TAG -> when (tag) { "name" -> user["name"] = text "designation" -> user["designation"] = text "user" -> userList.add(user) } } event = parser.next() } // List Adapter to broadcast the information to the list_rows.xml file val adapter: ListAdapter = SimpleAdapter(this, userList, R.layout.list_row, arrayOf("name", "designation"), intArrayOf(R.id.name, R.id.designation) ) lv.adapter = adapter } catch (e: IOException) { e.printStackTrace() } catch (e: XmlPullParserException) { e.printStackTrace() } }}
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 554,
"s": 28,
"text": "In android, the XMLPullParser interface provides the functionality to parse the XML files in android applications. The XMLPullParser is a simple and efficient parser method to parse the XML data when compared to other parser methods such as DOM Parser and SAX Parser. The XMLPullParser has a method next() that provides access to high-level parsing events. The next() method will advance the parser to the next event. The following are the series of events available in XMLPullParser, which will be seen by the next() method."
},
{
"code": null,
"e": 824,
"s": 554,
"text": "START_DOCUMENT: The parser starts processing the XML document.START_TAG: In this event, we can get the start tag in XML.TEXT: In this event, we can read the text content using the getText() method.END_TAG: An end tag was read.END_DOCUMENT: No more events are available."
},
{
"code": null,
"e": 887,
"s": 824,
"text": "START_DOCUMENT: The parser starts processing the XML document."
},
{
"code": null,
"e": 946,
"s": 887,
"text": "START_TAG: In this event, we can get the start tag in XML."
},
{
"code": null,
"e": 1024,
"s": 946,
"text": "TEXT: In this event, we can read the text content using the getText() method."
},
{
"code": null,
"e": 1054,
"s": 1024,
"text": "END_TAG: An end tag was read."
},
{
"code": null,
"e": 1098,
"s": 1054,
"text": "END_DOCUMENT: No more events are available."
},
{
"code": null,
"e": 1264,
"s": 1098,
"text": "Note that we are going to implement this project using the Kotlin language. One may also perform XML Parsing in another two ways. Please refer to the below articles:"
},
{
"code": null,
"e": 1304,
"s": 1264,
"text": "XML Parsing in Android using DOM Parser"
},
{
"code": null,
"e": 1344,
"s": 1304,
"text": "XML Parsing in Android using SAX Parser"
},
{
"code": null,
"e": 1637,
"s": 1344,
"text": "XMLPullParser scrutinizes an XML file with a series of events, such as START_DOCUMENT, START_TAG, TEXT, END_TAG, and END_DOCUMENT to parse the XML document. To read and parse XML files using XMLPullParser in android, one needs to create an instance of XMLPullParserFactory, and XMLPullParser."
},
{
"code": null,
"e": 1720,
"s": 1637,
"text": "To parse an XML file using a DOM parser in Android, we follow the following steps:"
},
{
"code": null,
"e": 1749,
"s": 1720,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1913,
"s": 1749,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 1945,
"s": 1913,
"text": "Step 2: Create an assets folder"
},
{
"code": null,
"e": 2195,
"s": 1945,
"text": "Create an assets folder under the main folder in the Project Layout. Create an Android Resource File in this folder, where we shall put the information in the form of XML. Name this file as userdetails.xml. For doing so refer to the following steps:"
},
{
"code": null,
"e": 2259,
"s": 2195,
"text": "Click on Project as shown on the left side of the below image. "
},
{
"code": null,
"e": 2352,
"s": 2259,
"text": "Expand until you find the main folder, right-click on it, go to New > Folder > Assets Folder"
},
{
"code": null,
"e": 2390,
"s": 2352,
"text": "Then just click on the Finish button."
},
{
"code": null,
"e": 2500,
"s": 2390,
"text": "Now the asset folder is created successfully. Right-Click on the Assets Folder > New > Android Resource FIle "
},
{
"code": null,
"e": 2558,
"s": 2500,
"text": "Give it name Information, change type to XML, and finish."
},
{
"code": null,
"e": 2803,
"s": 2558,
"text": "Note: Sometimes, right-clicking on the Assets folder and creating an Android Resource File creates a file in the res folder. If this happens, cut our file and paste it directly into the assets folder. This happens due to some internal settings."
},
{
"code": null,
"e": 2956,
"s": 2803,
"text": "Paste this information which is in the form of XML, that is to be displayed in the userdetails.xml file. Below is the code for the userdetails.xml file."
},
{
"code": null,
"e": 2960,
"s": 2956,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><users> <user> <name>Tom</name> <designation>Actor and Producer</designation> </user> <user> <name>Danny</name> <designation>Music Director</designation> </user> <user> <name>Christopher</name> <designation>Writer</designation> </user></users>",
"e": 3302,
"s": 2960,
"text": null
},
{
"code": null,
"e": 3350,
"s": 3302,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3509,
"s": 3350,
"text": "Now go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 3513,
"s": 3509,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:orientation=\"vertical\" > <!--Display the list from list_row file--> <ListView android:id=\"@+id/user_list\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:dividerHeight=\"1dp\" /> </LinearLayout>",
"e": 3980,
"s": 3513,
"text": null
},
{
"code": null,
"e": 4016,
"s": 3980,
"text": " Step 4: Create another layout file"
},
{
"code": null,
"e": 4220,
"s": 4016,
"text": "Go to app > res > layout > right-click > New > Layout Resource File and name the file as list_row. list_row.xml file is used to show the data in the ListView. Below is the code for the list_row.xml file."
},
{
"code": null,
"e": 4224,
"s": 4220,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:padding=\"5dip\"> <!--TextView to display the name from the userdetails file--> <TextView android:id=\"@+id/name\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"17dp\" android:textStyle=\"bold\" /> <!--TextView to display the designation from the userdetails file--> <TextView android:id=\"@+id/designation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/name\" android:layout_marginTop=\"7dp\" android:textColor=\"#343434\" android:textSize=\"14dp\" /> </RelativeLayout>",
"e": 5137,
"s": 4224,
"text": null
},
{
"code": null,
"e": 5183,
"s": 5137,
"text": "Step 5: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 5379,
"s": 5183,
"text": "Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5386,
"s": 5379,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.widget.ListAdapterimport android.widget.ListViewimport android.widget.SimpleAdapterimport androidx.appcompat.app.AppCompatActivityimport org.xmlpull.v1.XmlPullParserimport org.xmlpull.v1.XmlPullParserExceptionimport org.xmlpull.v1.XmlPullParserFactoryimport java.io.IOExceptionimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) try { // creating a user list string hash map arraylist val userList = ArrayList<HashMap<String, String?>>() // creating a user string hashmap var user = HashMap<String, String?>() // declaring the list view from the layout file val lv = findViewById<ListView>(R.id.user_list) // input stream the userdetails.xml file val istream = assets.open(\"userdetails.xml\") //creating a XmlPull parse Factory instance val parserFactory = XmlPullParserFactory.newInstance() val parser = parserFactory.newPullParser() // setting the namespaces feature to false parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) // setting the input to the parser parser.setInput(istream, null) // working with the input stream var tag: String? = \"\" var text: String? = \"\" var event = parser.eventType while (event != XmlPullParser.END_DOCUMENT) { tag = parser.name when (event) { XmlPullParser.START_TAG -> if (tag == \"user\") user = HashMap() XmlPullParser.TEXT -> text = parser.text XmlPullParser.END_TAG -> when (tag) { \"name\" -> user[\"name\"] = text \"designation\" -> user[\"designation\"] = text \"user\" -> userList.add(user) } } event = parser.next() } // List Adapter to broadcast the information to the list_rows.xml file val adapter: ListAdapter = SimpleAdapter(this, userList, R.layout.list_row, arrayOf(\"name\", \"designation\"), intArrayOf(R.id.name, R.id.designation) ) lv.adapter = adapter } catch (e: IOException) { e.printStackTrace() } catch (e: XmlPullParserException) { e.printStackTrace() } }}",
"e": 7979,
"s": 5386,
"text": null
},
{
"code": null,
"e": 7992,
"s": 7979,
"text": "Android-Misc"
},
{
"code": null,
"e": 8000,
"s": 7992,
"text": "Android"
},
{
"code": null,
"e": 8007,
"s": 8000,
"text": "Kotlin"
},
{
"code": null,
"e": 8015,
"s": 8007,
"text": "Android"
},
{
"code": null,
"e": 8113,
"s": 8015,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8182,
"s": 8113,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8214,
"s": 8182,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8253,
"s": 8214,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8302,
"s": 8253,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8344,
"s": 8302,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 8413,
"s": 8344,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8432,
"s": 8413,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 8445,
"s": 8432,
"text": "Kotlin Array"
},
{
"code": null,
"e": 8494,
"s": 8445,
"text": "How to Communicate Between Fragments in Android?"
}
] |
numpy.flatnonzero() in Python | 28 Nov, 2018
numpy.flatnonzero()function is used to Compute indices that are non-zero in the flattened version of arr.
Syntax : numpy.flatnonzero(arr)
Parameters :arr : [array_like] Input array.
Return : ndarrayOutput array, containing the indices of the elements of arr.ravel() that are non-zero.
Code #1 : Working
# Python program explaining# flatnonzero() function import numpy as geekarr = geek.arange(-3, 4) print ("Input array : ", arr) out_arr = geek.flatnonzero(arr)print ("Indices of non zero elements : ", out_arr)
Output :
Input array : [-3 -2 -1 0 1 2 3]
Indices of non zero elements : [0 1 2 4 5 6]
Code #2 : Using the indices of the non-zero elements as an index array.
# Python program using the indices of the non-zero # elements as an index array to extract these elements out_arr = arr.ravel()[geek.flatnonzero(arr)] print ("Output array of non-zero number: ", out_arr)
Output :
Output array of non-zero number: [-3 -2 -1 1 2 3]
Python numpy-Sorting Searching
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "numpy.flatnonzero()function is used to Compute indices that are non-zero in the flattened version of arr."
},
{
"code": null,
"e": 166,
"s": 134,
"text": "Syntax : numpy.flatnonzero(arr)"
},
{
"code": null,
"e": 210,
"s": 166,
"text": "Parameters :arr : [array_like] Input array."
},
{
"code": null,
"e": 313,
"s": 210,
"text": "Return : ndarrayOutput array, containing the indices of the elements of arr.ravel() that are non-zero."
},
{
"code": null,
"e": 331,
"s": 313,
"text": "Code #1 : Working"
},
{
"code": "# Python program explaining# flatnonzero() function import numpy as geekarr = geek.arange(-3, 4) print (\"Input array : \", arr) out_arr = geek.flatnonzero(arr)print (\"Indices of non zero elements : \", out_arr) ",
"e": 547,
"s": 331,
"text": null
},
{
"code": null,
"e": 556,
"s": 547,
"text": "Output :"
},
{
"code": null,
"e": 642,
"s": 556,
"text": "Input array : [-3 -2 -1 0 1 2 3]\nIndices of non zero elements : [0 1 2 4 5 6]\n"
},
{
"code": null,
"e": 715,
"s": 642,
"text": " Code #2 : Using the indices of the non-zero elements as an index array."
},
{
"code": "# Python program using the indices of the non-zero # elements as an index array to extract these elements out_arr = arr.ravel()[geek.flatnonzero(arr)] print (\"Output array of non-zero number: \", out_arr) ",
"e": 922,
"s": 715,
"text": null
},
{
"code": null,
"e": 931,
"s": 922,
"text": "Output :"
},
{
"code": null,
"e": 986,
"s": 931,
"text": "Output array of non-zero number: [-3 -2 -1 1 2 3]\n"
},
{
"code": null,
"e": 1017,
"s": 986,
"text": "Python numpy-Sorting Searching"
},
{
"code": null,
"e": 1030,
"s": 1017,
"text": "Python-numpy"
},
{
"code": null,
"e": 1037,
"s": 1030,
"text": "Python"
},
{
"code": null,
"e": 1135,
"s": 1037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1153,
"s": 1135,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1195,
"s": 1153,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1217,
"s": 1195,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1243,
"s": 1217,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1275,
"s": 1243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1304,
"s": 1275,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1331,
"s": 1304,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1361,
"s": 1331,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1382,
"s": 1361,
"text": "Python OOPs Concepts"
}
] |
Difference between Direct and Immediate Addressing Modes | 29 Jun, 2022
Prerequisite – Addressing Modes
1. Direct Addressing Mode: In direct addressing mode, the address field contains the address of the operand.
Effective Address (EA) = address field of operand
Example: Add the contents of register 1303 to the accumulator.
Add (1303)
Only a single memory reference is required to access data. So no additional calculations are required to work out the effective address.
2. Immediate Addressing Mode: In immediate addressing mode, the operand is a part of the instruction.
Here the Operand = Address Field
Example: Add 3 to the accumulator.
ADD 3
No memory reference is required to fetch data. So no additional calculations are required to work out the effective address. It is a fast method. But the downside is that it has a limited range. Now let’s compare Direct and Immediate addressing modes.
annieahujaweb2020
Picked
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 61,
"s": 28,
"text": "Prerequisite – Addressing Modes "
},
{
"code": null,
"e": 170,
"s": 61,
"text": "1. Direct Addressing Mode: In direct addressing mode, the address field contains the address of the operand."
},
{
"code": null,
"e": 221,
"s": 170,
"text": "Effective Address (EA) = address field of operand "
},
{
"code": null,
"e": 286,
"s": 223,
"text": "Example: Add the contents of register 1303 to the accumulator."
},
{
"code": null,
"e": 298,
"s": 286,
"text": "Add (1303) "
},
{
"code": null,
"e": 436,
"s": 298,
"text": "Only a single memory reference is required to access data. So no additional calculations are required to work out the effective address. "
},
{
"code": null,
"e": 538,
"s": 436,
"text": "2. Immediate Addressing Mode: In immediate addressing mode, the operand is a part of the instruction."
},
{
"code": null,
"e": 572,
"s": 538,
"text": "Here the Operand = Address Field "
},
{
"code": null,
"e": 609,
"s": 574,
"text": "Example: Add 3 to the accumulator."
},
{
"code": null,
"e": 615,
"s": 609,
"text": "ADD 3"
},
{
"code": null,
"e": 867,
"s": 615,
"text": "No memory reference is required to fetch data. So no additional calculations are required to work out the effective address. It is a fast method. But the downside is that it has a limited range. Now let’s compare Direct and Immediate addressing modes."
},
{
"code": null,
"e": 885,
"s": 867,
"text": "annieahujaweb2020"
},
{
"code": null,
"e": 892,
"s": 885,
"text": "Picked"
},
{
"code": null,
"e": 929,
"s": 892,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 948,
"s": 929,
"text": "Difference Between"
},
{
"code": null,
"e": 956,
"s": 948,
"text": "GATE CS"
}
] |
PyQt5 QDockWidget – Setting Floating Property | 28 Jul, 2020
In this article, we will see how we can set floating property to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). This property holds whether the dock widget is floating.A floating dock widget is presented to the user as an independent window “on top” of its parent QMainWindow, instead of being docked in the QMainWindow.
In order to do this we will use setFloating method with the dock widget object.
Syntax : dock.setFloating(True)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget("GeeksforGeeks", self) # push button push = QPushButton("Press", self) # setting widget to the dock dock.setWidget(push) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # setting floating property dock.setFloating(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 543,
"s": 28,
"text": "In this article, we will see how we can set floating property to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). This property holds whether the dock widget is floating.A floating dock widget is presented to the user as an independent window “on top” of its parent QMainWindow, instead of being docked in the QMainWindow."
},
{
"code": null,
"e": 623,
"s": 543,
"text": "In order to do this we will use setFloating method with the dock widget object."
},
{
"code": null,
"e": 655,
"s": 623,
"text": "Syntax : dock.setFloating(True)"
},
{
"code": null,
"e": 692,
"s": 655,
"text": "Argument : It takes bool as argument"
},
{
"code": null,
"e": 717,
"s": 692,
"text": "Return : It returns None"
},
{
"code": null,
"e": 745,
"s": 717,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(\"GeeksforGeeks\", self) # push button push = QPushButton(\"Press\", self) # setting widget to the dock dock.setWidget(push) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # setting floating property dock.setFloating(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2005,
"s": 745,
"text": null
},
{
"code": null,
"e": 2014,
"s": 2005,
"text": "Output :"
},
{
"code": null,
"e": 2038,
"s": 2014,
"text": "Python PyQt-QDockWidget"
},
{
"code": null,
"e": 2049,
"s": 2038,
"text": "Python-gui"
},
{
"code": null,
"e": 2061,
"s": 2049,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2068,
"s": 2061,
"text": "Python"
}
] |
Non-Repeating Element | Practice | GeeksforGeeks | Find the first non-repeating element in a given array arr of N integers.
Note: Array consists of only positive and negative integers and not zero.
Example 1:
Input : arr[] = {-1, 2, -1, 3, 2}
Output : 3
Explanation:
-1 and 2 are repeating whereas 3 is
the only number occuring once.
Hence, the output is 3.
Example 2:
Input : arr[] = {1, 1, 1}
Output : 0
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function firstNonRepeating() that takes an array (arr), sizeOfArray (n), and returns the first non-repeating element. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= N <= 107
-1016 <= Ai <= 1016
{Ai !=0 }
0
ayushkumarmin203 days ago
unordered_map<int,int>m;
for( int i=0;i<n;i++){
m[arr[i]]++;
}
for( int i=0;i<n;i++){
if( m[arr[i]]==1)return arr[i];
}
// Complete the function
return 0;
0
harayanbas85 days ago
nice
0
chamanlal971961 week ago
int firstNonRepeating(int arr[], int n) {
unordered_map<int,int>mp;
for(int i=0; i<n; i++) mp[arr[i]]++;
for(int i=0; i<n; i++){
if(mp[arr[i]]==1) return arr[i];
}
return 0;
}
0
niteshkmr3661 week ago
firstNonRepeating(arr,n){
var i = 0;
var bkp = [...arr];
var map = new Map();
while(arr.length>0){
var current = arr.shift();
if(map.has(bkp[i])){
map.set(bkp[i],map.get(bkp[i])+1);
}else{
// console.log(bkp[i],'for index',i,'when arr was',arr)
map.set(bkp[i],1);
}
// if(map.get(bkp[i]) == Math.min(...map.values())){ return bkp[i]}
i++;
}
for (const [key, value] of (map)) {
if(value == Math.min(...map.values())){ return key}
}
return 0;
}
-3
jainvidhushi292 weeks ago
int res=arr[0]; for(int i=1;i<arr.length;i++) { res=res^arr[i]; } return res;
+1
viveksharma733 weeks ago
unordered_map<int,int >m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(int i=0;i<n;i++){ if(m[arr[i]]==1){ return arr[i]; } } return -1; }
0
raunakscarlet3 weeks ago
#include<unordered_map>class Solution{ public: int firstNonRepeating(int arr[], int n) { // Complete the function unordered_map<int,int>umap; for(int i=0;i<n;i++){ int temp=arr[i]; //umap.insert(temp); umap[temp]++; } for(int i=0;i<n;i++){ auto key=umap.find(arr[i]); if(key->second==1){ return key->first; } } } ;
0
raunakscarlet3 weeks ago
#include<unordered_map>class Solution{ public: int firstNonRepeating(int arr[], int n) { // Complete the function unordered_map<int,int>umap; for(int i=0;i<n;i++){ int temp=arr[i]; umap[temp]++; } for(int i=0;i<n;i++){ if(umap[arr[i]]==1){ return arr[i]; } } } };
0
chaitankhilar3 weeks ago
JAVA SOLUTION BY USING HASHMAP class Check{ public int firstNonRepeating(int arr[], int n) { HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<n;i++){ if(!hm.containsKey(arr[i])){ hm.put(arr[i],1); } else{ hm.put(arr[i],hm.get(arr[i])+1); } } for(int i=0;i<n;i++){ if(hm.get(arr[i])==1){ return arr[i]; } } return 0; } }
0
swarupcodes1 month ago
class Check{
public int firstNonRepeating(int arr[], int n)
{
Map<Integer,Integer> map = new LinkedHashMap<>();
for(Integer x : arr) {
if(!map.containsKey(x)) {
map.put(x, 1);
} else {
map.put(x, map.get(x)+1);
}
}
for(Map.Entry<Integer,Integer> entry : map.entrySet()) {
if(entry.getValue() == 1) return entry.getKey();
}
return 0;
}
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 385,
"s": 238,
"text": "Find the first non-repeating element in a given array arr of N integers.\nNote: Array consists of only positive and negative integers and not zero."
},
{
"code": null,
"e": 396,
"s": 385,
"text": "Example 1:"
},
{
"code": null,
"e": 547,
"s": 396,
"text": "Input : arr[] = {-1, 2, -1, 3, 2}\nOutput : 3\nExplanation:\n-1 and 2 are repeating whereas 3 is \nthe only number occuring once.\nHence, the output is 3. "
},
{
"code": null,
"e": 560,
"s": 549,
"text": "Example 2:"
},
{
"code": null,
"e": 598,
"s": 560,
"text": "Input : arr[] = {1, 1, 1}\nOutput : 0\n"
},
{
"code": null,
"e": 885,
"s": 598,
"text": "\nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function firstNonRepeating() that takes an array (arr), sizeOfArray (n), and returns the first non-repeating element. The driver code takes care of the printing."
},
{
"code": null,
"e": 949,
"s": 885,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 1006,
"s": 949,
"text": "Constraints:\n1 <= N <= 107\n-1016 <= Ai <= 1016\n{Ai !=0 }"
},
{
"code": null,
"e": 1010,
"s": 1008,
"text": "0"
},
{
"code": null,
"e": 1036,
"s": 1010,
"text": "ayushkumarmin203 days ago"
},
{
"code": null,
"e": 1238,
"s": 1036,
"text": "unordered_map<int,int>m;\n for( int i=0;i<n;i++){\n m[arr[i]]++;\n }\n for( int i=0;i<n;i++){\n if( m[arr[i]]==1)return arr[i];\n }\n // Complete the function\n return 0; "
},
{
"code": null,
"e": 1240,
"s": 1238,
"text": "0"
},
{
"code": null,
"e": 1262,
"s": 1240,
"text": "harayanbas85 days ago"
},
{
"code": null,
"e": 1267,
"s": 1262,
"text": "nice"
},
{
"code": null,
"e": 1269,
"s": 1267,
"text": "0"
},
{
"code": null,
"e": 1294,
"s": 1269,
"text": "chamanlal971961 week ago"
},
{
"code": null,
"e": 1530,
"s": 1294,
"text": "int firstNonRepeating(int arr[], int n) {\n unordered_map<int,int>mp;\n for(int i=0; i<n; i++) mp[arr[i]]++;\n for(int i=0; i<n; i++){\n if(mp[arr[i]]==1) return arr[i];\n }\n return 0;\n } \n "
},
{
"code": null,
"e": 1532,
"s": 1530,
"text": "0"
},
{
"code": null,
"e": 1555,
"s": 1532,
"text": "niteshkmr3661 week ago"
},
{
"code": null,
"e": 2144,
"s": 1555,
"text": " firstNonRepeating(arr,n){\n var i = 0;\n var bkp = [...arr];\n var map = new Map();\n while(arr.length>0){\n var current = arr.shift();\n if(map.has(bkp[i])){\n map.set(bkp[i],map.get(bkp[i])+1);\n }else{\n // console.log(bkp[i],'for index',i,'when arr was',arr)\n map.set(bkp[i],1);\n }\n // if(map.get(bkp[i]) == Math.min(...map.values())){ return bkp[i]}\n i++;\n }\n for (const [key, value] of (map)) {\n if(value == Math.min(...map.values())){ return key}\n }\n return 0;\n }"
},
{
"code": null,
"e": 2147,
"s": 2144,
"text": "-3"
},
{
"code": null,
"e": 2173,
"s": 2147,
"text": "jainvidhushi292 weeks ago"
},
{
"code": null,
"e": 2290,
"s": 2173,
"text": "int res=arr[0]; for(int i=1;i<arr.length;i++) { res=res^arr[i]; } return res;"
},
{
"code": null,
"e": 2295,
"s": 2292,
"text": "+1"
},
{
"code": null,
"e": 2320,
"s": 2295,
"text": "viveksharma733 weeks ago"
},
{
"code": null,
"e": 2554,
"s": 2320,
"text": " unordered_map<int,int >m; for(int i=0;i<n;i++){ m[arr[i]]++; } for(int i=0;i<n;i++){ if(m[arr[i]]==1){ return arr[i]; } } return -1; } "
},
{
"code": null,
"e": 2556,
"s": 2554,
"text": "0"
},
{
"code": null,
"e": 2581,
"s": 2556,
"text": "raunakscarlet3 weeks ago"
},
{
"code": null,
"e": 3053,
"s": 2581,
"text": "#include<unordered_map>class Solution{ public: int firstNonRepeating(int arr[], int n) { // Complete the function unordered_map<int,int>umap; for(int i=0;i<n;i++){ int temp=arr[i]; //umap.insert(temp); umap[temp]++; } for(int i=0;i<n;i++){ auto key=umap.find(arr[i]); if(key->second==1){ return key->first; } } } ;"
},
{
"code": null,
"e": 3055,
"s": 3053,
"text": "0"
},
{
"code": null,
"e": 3080,
"s": 3055,
"text": "raunakscarlet3 weeks ago"
},
{
"code": null,
"e": 3465,
"s": 3080,
"text": "#include<unordered_map>class Solution{ public: int firstNonRepeating(int arr[], int n) { // Complete the function unordered_map<int,int>umap; for(int i=0;i<n;i++){ int temp=arr[i]; umap[temp]++; } for(int i=0;i<n;i++){ if(umap[arr[i]]==1){ return arr[i]; } } } };"
},
{
"code": null,
"e": 3467,
"s": 3465,
"text": "0"
},
{
"code": null,
"e": 3492,
"s": 3467,
"text": "chaitankhilar3 weeks ago"
},
{
"code": null,
"e": 3951,
"s": 3492,
"text": "JAVA SOLUTION BY USING HASHMAP class Check{ public int firstNonRepeating(int arr[], int n) { HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<n;i++){ if(!hm.containsKey(arr[i])){ hm.put(arr[i],1); } else{ hm.put(arr[i],hm.get(arr[i])+1); } } for(int i=0;i<n;i++){ if(hm.get(arr[i])==1){ return arr[i]; } } return 0; } }"
},
{
"code": null,
"e": 3953,
"s": 3951,
"text": "0"
},
{
"code": null,
"e": 3976,
"s": 3953,
"text": "swarupcodes1 month ago"
},
{
"code": null,
"e": 4462,
"s": 3976,
"text": "class Check{\n \n public int firstNonRepeating(int arr[], int n) \n { \n Map<Integer,Integer> map = new LinkedHashMap<>();\n for(Integer x : arr) {\n if(!map.containsKey(x)) {\n map.put(x, 1);\n } else {\n map.put(x, map.get(x)+1);\n }\n }\n for(Map.Entry<Integer,Integer> entry : map.entrySet()) {\n if(entry.getValue() == 1) return entry.getKey();\n }\n return 0;\n } \n}"
},
{
"code": null,
"e": 4608,
"s": 4462,
"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": 4644,
"s": 4608,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4654,
"s": 4644,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4664,
"s": 4654,
"text": "\nContest\n"
},
{
"code": null,
"e": 4727,
"s": 4664,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4912,
"s": 4727,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5196,
"s": 4912,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 5342,
"s": 5196,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 5419,
"s": 5342,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5460,
"s": 5419,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5488,
"s": 5460,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5559,
"s": 5488,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5746,
"s": 5559,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
turtle.tilt() function in Python | 26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to rotate the turtleshape by the angle from its current tilt-angle, but do NOT change the turtle’s heading (direction of movement).
Syntax :
turtle.tilt(angle)
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # set turtle screensc=turtle.Screen()sc.setup(500,300) # set turtleturtle.speed(1)turtle.up()turtle.setpos(-200,0)turtle.down()turtle.shape("square")turtle.width(2) # motionturtle.forward(200) # tilt turtleshape by 45turtle.tilt(45) # motionturtle.forward(200)
Output :
Example 2 :
Python3
# import packageimport turtle # set screensc=turtle.Screen()sc.setup(500,350) # set turtleturtle.speed(1)turtle.up()turtle.setpos(-50,100)turtle.down()turtle.shape("turtle")turtle.width(2) # loop for patternfor i in range(6): # motion turtle.forward(100) # tilt turtleshpae by 180 turtle.tilt(180) # print turtleshape turtle.stamp() # move to right by 60 turtle.right(60) # hide the turtleturtle.ht()
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 399,
"s": 245,
"text": "This function is used to rotate the turtleshape by the angle from its current tilt-angle, but do NOT change the turtle’s heading (direction of movement)."
},
{
"code": null,
"e": 408,
"s": 399,
"text": "Syntax :"
},
{
"code": null,
"e": 428,
"s": 408,
"text": "turtle.tilt(angle)\n"
},
{
"code": null,
"e": 497,
"s": 428,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 509,
"s": 497,
"text": "Example 1 :"
},
{
"code": null,
"e": 517,
"s": 509,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set turtle screensc=turtle.Screen()sc.setup(500,300) # set turtleturtle.speed(1)turtle.up()turtle.setpos(-200,0)turtle.down()turtle.shape(\"square\")turtle.width(2) # motionturtle.forward(200) # tilt turtleshape by 45turtle.tilt(45) # motionturtle.forward(200)",
"e": 813,
"s": 517,
"text": null
},
{
"code": null,
"e": 822,
"s": 813,
"text": "Output :"
},
{
"code": null,
"e": 834,
"s": 822,
"text": "Example 2 :"
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Python3"
},
{
"code": "# import packageimport turtle # set screensc=turtle.Screen()sc.setup(500,350) # set turtleturtle.speed(1)turtle.up()turtle.setpos(-50,100)turtle.down()turtle.shape(\"turtle\")turtle.width(2) # loop for patternfor i in range(6): # motion turtle.forward(100) # tilt turtleshpae by 180 turtle.tilt(180) # print turtleshape turtle.stamp() # move to right by 60 turtle.right(60) # hide the turtleturtle.ht()",
"e": 1297,
"s": 842,
"text": null
},
{
"code": null,
"e": 1306,
"s": 1297,
"text": "Output :"
},
{
"code": null,
"e": 1320,
"s": 1306,
"text": "Python-turtle"
},
{
"code": null,
"e": 1327,
"s": 1320,
"text": "Python"
},
{
"code": null,
"e": 1425,
"s": 1327,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1457,
"s": 1425,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1484,
"s": 1457,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1505,
"s": 1484,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1528,
"s": 1505,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1559,
"s": 1528,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1615,
"s": 1559,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1657,
"s": 1615,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1699,
"s": 1657,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1738,
"s": 1699,
"text": "Python | datetime.timedelta() function"
}
] |
How to echo HTML in PHP ? | 31 Jul, 2021
While making a web application with PHP, we often need to print or echo few results in form of HTML. We can do this task in many different ways. Some of methods are described here:
Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.Example 1: This example uses PHP echo to display the result.<?php $name = "GeeksforGeeks"; echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>Output:Example 2: This example uses PHP print to display the result.<?php $name = "GeeksforGeeks"; print "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>Output :Using echo shorthand or separating HTML: PHP echo shorthand can be used to display the result of any expression, value of any variable or HTML markup.Example 1: This example uses PHP echo shorthand to display the result.<?php $name = "GeeksforGeeks";?> <?= "<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>" ?>Output:Example 2: Separating HTML from PHP<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>Output:Using heredoc: We can use <<< heredoc to print the html. <<< must be followed by an identifier and line break. The same identifier is used to close the body of heredoc.Syntax:<<<GFG
// HTML Markup
GFG;
Note: The ending identifier must not be indented.Example:<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>Output:
Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.Example 1: This example uses PHP echo to display the result.<?php $name = "GeeksforGeeks"; echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>Output:Example 2: This example uses PHP print to display the result.<?php $name = "GeeksforGeeks"; print "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>Output :
Example 1: This example uses PHP echo to display the result.
<?php $name = "GeeksforGeeks"; echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>
Output:
Example 2: This example uses PHP print to display the result.
<?php $name = "GeeksforGeeks"; print "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";?>
Output :
Using echo shorthand or separating HTML: PHP echo shorthand can be used to display the result of any expression, value of any variable or HTML markup.Example 1: This example uses PHP echo shorthand to display the result.<?php $name = "GeeksforGeeks";?> <?= "<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>" ?>Output:Example 2: Separating HTML from PHP<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>Output:
Example 1: This example uses PHP echo shorthand to display the result.
<?php $name = "GeeksforGeeks";?> <?= "<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>" ?>
Output:
Example 2: Separating HTML from PHP
<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>
Output:
Using heredoc: We can use <<< heredoc to print the html. <<< must be followed by an identifier and line break. The same identifier is used to close the body of heredoc.Syntax:<<<GFG
// HTML Markup
GFG;
Note: The ending identifier must not be indented.Example:<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>Output:
Syntax:
<<<GFG
// HTML Markup
GFG;
Note: The ending identifier must not be indented.
Example:
<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>
Output:
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
shubham_singh
PHP-basics
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "While making a web application with PHP, we often need to print or echo few results in form of HTML. We can do this task in many different ways. Some of methods are described here:"
},
{
"code": null,
"e": 1513,
"s": 209,
"text": "Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.Example 1: This example uses PHP echo to display the result.<?php $name = \"GeeksforGeeks\"; echo \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>Output:Example 2: This example uses PHP print to display the result.<?php $name = \"GeeksforGeeks\"; print \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>Output :Using echo shorthand or separating HTML: PHP echo shorthand can be used to display the result of any expression, value of any variable or HTML markup.Example 1: This example uses PHP echo shorthand to display the result.<?php $name = \"GeeksforGeeks\";?> <?= \"<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>\" ?>Output:Example 2: Separating HTML from PHP<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>Output:Using heredoc: We can use <<< heredoc to print the html. <<< must be followed by an identifier and line break. The same identifier is used to close the body of heredoc.Syntax:<<<GFG\n// HTML Markup\nGFG;\nNote: The ending identifier must not be indented.Example:<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>Output:"
},
{
"code": null,
"e": 1946,
"s": 1513,
"text": "Using echo or print: PHP echo or print can be used to display HTML markup, javascript, text or variables.Example 1: This example uses PHP echo to display the result.<?php $name = \"GeeksforGeeks\"; echo \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>Output:Example 2: This example uses PHP print to display the result.<?php $name = \"GeeksforGeeks\"; print \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>Output :"
},
{
"code": null,
"e": 2007,
"s": 1946,
"text": "Example 1: This example uses PHP echo to display the result."
},
{
"code": "<?php $name = \"GeeksforGeeks\"; echo \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>",
"e": 2103,
"s": 2007,
"text": null
},
{
"code": null,
"e": 2111,
"s": 2103,
"text": "Output:"
},
{
"code": null,
"e": 2173,
"s": 2111,
"text": "Example 2: This example uses PHP print to display the result."
},
{
"code": "<?php $name = \"GeeksforGeeks\"; print \"<h1>Hello User, </h1> <p>Welcome to {$name}</p>\";?>",
"e": 2270,
"s": 2173,
"text": null
},
{
"code": null,
"e": 2279,
"s": 2270,
"text": "Output :"
},
{
"code": null,
"e": 2783,
"s": 2279,
"text": "Using echo shorthand or separating HTML: PHP echo shorthand can be used to display the result of any expression, value of any variable or HTML markup.Example 1: This example uses PHP echo shorthand to display the result.<?php $name = \"GeeksforGeeks\";?> <?= \"<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>\" ?>Output:Example 2: Separating HTML from PHP<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>Output:"
},
{
"code": null,
"e": 2854,
"s": 2783,
"text": "Example 1: This example uses PHP echo shorthand to display the result."
},
{
"code": "<?php $name = \"GeeksforGeeks\";?> <?= \"<h1>Hello User,</h1> <h1>{$name} welcomes you</h1>\" ?>",
"e": 2956,
"s": 2854,
"text": null
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "Output:"
},
{
"code": null,
"e": 3000,
"s": 2964,
"text": "Example 2: Separating HTML from PHP"
},
{
"code": "<?php $num = 2; for ($i = 1; $i <= 10; $i++) { ?> <p><?= $num ?> * <?= $i ?> = <?= $num * $i ?></p> <?php }?>",
"e": 3134,
"s": 3000,
"text": null
},
{
"code": null,
"e": 3142,
"s": 3134,
"text": "Output:"
},
{
"code": null,
"e": 3511,
"s": 3142,
"text": "Using heredoc: We can use <<< heredoc to print the html. <<< must be followed by an identifier and line break. The same identifier is used to close the body of heredoc.Syntax:<<<GFG\n// HTML Markup\nGFG;\nNote: The ending identifier must not be indented.Example:<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>Output:"
},
{
"code": null,
"e": 3519,
"s": 3511,
"text": "Syntax:"
},
{
"code": null,
"e": 3547,
"s": 3519,
"text": "<<<GFG\n// HTML Markup\nGFG;\n"
},
{
"code": null,
"e": 3597,
"s": 3547,
"text": "Note: The ending identifier must not be indented."
},
{
"code": null,
"e": 3606,
"s": 3597,
"text": "Example:"
},
{
"code": "<?php echo <<<GFG <h1>GeeksforGeeks</h1> <p>I am in heredoc with identifier 'GFG' .</p>GFG; ?>",
"e": 3709,
"s": 3606,
"text": null
},
{
"code": null,
"e": 3717,
"s": 3709,
"text": "Output:"
},
{
"code": null,
"e": 3886,
"s": 3717,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 3900,
"s": 3886,
"text": "shubham_singh"
},
{
"code": null,
"e": 3911,
"s": 3900,
"text": "PHP-basics"
},
{
"code": null,
"e": 3918,
"s": 3911,
"text": "Picked"
},
{
"code": null,
"e": 3922,
"s": 3918,
"text": "PHP"
},
{
"code": null,
"e": 3935,
"s": 3922,
"text": "PHP Programs"
},
{
"code": null,
"e": 3952,
"s": 3935,
"text": "Web Technologies"
},
{
"code": null,
"e": 3979,
"s": 3952,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3983,
"s": 3979,
"text": "PHP"
}
] |
Python Data Structures | 19 May, 2022
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages.
In this article, we will discuss the Data Structures in the Python Programming Language and how they are related to some specific Python Data Types. We will discuss all the in-built data structures like list tuples, dictionaries, etc. as well as some advanced data structures like trees, graphs, etc.
Python Lists are just like the arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.
The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full.
We can create a list in python as shown below.
Python3
List = [1, 2, 3, "GFG", 2.3]print(List)
[1, 2, 3, 'GFG', 2.3]
List elements can be accessed by the assigned index. In python starting index of the list, sequence is 0 and the ending index is (if N elements are there) N-1.
Python3
# Creating a List with # the use of multiple values List = ["Geeks", "For", "Geeks"] print("\nList containing multiple values: ") print(List) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List2 = [['Geeks', 'For'], ['Geeks']] print("\nMulti-Dimensional List: ") print(List2) # accessing a element from the # list using index number print("Accessing element from the list") print(List[0]) print(List[2]) # accessing a element using # negative indexing print("Accessing element using negative indexing") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3])
List containing multiple values:
['Geeks', 'For', 'Geeks']
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Python dictionary is like hash tables in any other language with the time complexity of O(1). It is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized.
Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension.
Python3
# Creating a DictionaryDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print("Creating Dictionary: ")print(Dict) # accessing a element using key print("Accessing a element using key:") print(Dict['Name']) # accessing a element using get() # method print("Accessing a element using get:") print(Dict.get(1)) # creation using Dictionary comprehensionmyDict = {x: x**2 for x in [1,2,3,4,5]}print(myDict)
Creating Dictionary:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Accessing a element using key:
Geeks
Accessing a element using get:
[1, 2, 3, 4]
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain elements of various types.
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Python3
# Creating a Tuple with# the use of StringsTuple = ('Geeks', 'For')print("\nTuple with the use of String: ")print(Tuple) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print("\nTuple using List: ")Tuple = tuple(list1) # Accessing element using indexingprint("First element of tuple")print(Tuple[0]) # Accessing element from last# negative indexingprint("\nLast element of tuple")print(Tuple[-1]) print("\nThird last element of tuple")print(Tuple[-3])
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
First element of tuple
1
Last element of tuple
6
Third last element of tuple
4
Python Set is an ordered collection of data that is mutable and does not allow any duplicate element. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average.
If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity.
Set Implementation:
Sets with Numerous operations on a single HashTable:
Python3
# Creating a Set with # a mixed type of values # (Having numbers and strings) Set = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\nSet with the use of Mixed Values") print(Set) # Accessing element using # for loop print("\nElements of set: ") for i in Set: print(i, end =" ") print() # Checking the element # using in keyword print("Geeks" in Set)
Set with the use of Mixed Values
{1, 2, 'Geeks', 4, 6, 'For'}
Elements of set:
1 2 Geeks 4 6 For
True
Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
If no parameters are passed, it returns an empty frozenset.
Python3
# Same as {"a", "b","c"}normal_set = set(["a", "b","c"]) print("Normal Set")print(normal_set) # A frozen setfrozen_set = frozenset(["e", "f", "g"]) print("\nFrozen Set")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add("h")
Normal Set
{'a', 'c', 'b'}
Frozen Set
frozenset({'g', 'e', 'f'})
Python Strings are arrays of bytes representing Unicode characters. In simpler terms, a string is an immutable array of characters. Python does not have a character data type, a single character is simply a string with a length of 1.
Note: As strings are immutable, modifying a string will result in creating a new copy.
Python3
String = "Welcome to GeeksForGeeks"print("Creating String: ") print(String) # Printing First character print("\nFirst character of String is: ") print(String[0]) # Printing Last character print("\nLast character of String is: ") print(String[-1])
Creating String:
Welcome to GeeksForGeeks
First character of String is:
W
Last character of String is:
s
Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256.
Python3
# Creating bytearraya = bytearray((12, 8, 25, 2))print("Creating Bytearray:")print(a) # accessing elementsprint("\nAccessing Elements:", a[1]) # modifying elements a[1] = 3print("\nAfter Modifying:")print(a) # Appending elementsa.append(30)print("\nAfter Adding Elements:")print(a)
Creating Bytearray:
bytearray(b'\x0c\x08\x19\x02')
Accessing Elements: 8
After Modifying:
bytearray(b'\x0c\x03\x19\x02')
After Adding Elements:
bytearray(b'\x0c\x03\x19\x02\x1e')
Till now we have studied all the data structures that come built-in into core Python. Now let dive more deep into Python and see the collections module that provides some containers that are useful in many cases and provide more features than the above-defined functions.
Python collection module was introduced to improve the functionality of the built-in datatypes. It provides various containers let’s see each one of them in detail.
A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable. This is equivalent to a bag or multiset of other languages.
Python3
from collections import Counter # With sequence of items print(Counter(['B','B','A','B','C','A','B','B','A','C'])) # with dictionarycount = Counter({'A':3, 'B':5, 'C':2})print(count) count.update(['A', 1])print(count)
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 3, 'C': 2})
Counter({'B': 5, 'A': 4, 'C': 2, 1: 1})
An OrderedDict is also a sub-class of dictionary but unlike a dictionary, it remembers the order in which the keys were inserted.
Python3
from collections import OrderedDict print("Before deleting:\n")od = OrderedDict()od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 for key, value in od.items(): print(key, value) print("\nAfter deleting:\n")od.pop('c')for key, value in od.items(): print(key, value) print("\nAfter re-inserting:\n")od['c'] = 3for key, value in od.items(): print(key, value)
Before deleting:
a 1
b 2
c 3
d 4
After deleting:
a 1
b 2
d 4
After re-inserting:
a 1
b 2
d 4
c 3
DefaultDict is used to provide some default values for the key that does not exist and never raises a KeyError. Its objects can be initialized using DefaultDict() method by passing the data type as an argument.
Note: default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised.
Python3
from collections import defaultdict # Defining the dictd = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list# for keeping the countfor i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d)
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries. When a key is needed to be found then all the dictionaries are searched one by one until the key is found.
Python3
from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmapc = ChainMap(d1, d2, d3)print(c) print(c['a'])print(c['g'])
Output
ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})
1
KeyError: 'g'
A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.
Python3
from collections import namedtuple # Declaring namedtuple()Student = namedtuple('Student',['name','age','DOB']) # Adding valuesS = Student('Nandini','19','2541997') # Access using indexprint ("The Student age using index is : ",end ="")print (S[1]) # Access using nameprint ("The Student name using keyname is : ",end ="")print (S.name)
The Student age using index is : 19
The Student name using keyname is : Nandini
Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to the list with O(n) time complexity.
Python Deque is implemented using doubly linked lists therefore the performance for randomly accessing the elements is O(n).
Python3
# importing "collections" for deque operationsimport collections # initializing dequede = collections.deque([1,2,3]) # using append() to insert element at right end# inserts 4 at the end of dequede.append(4) # printing modified dequeprint("The deque after appending at right is : ")print(de) # using appendleft() to insert element at left end# inserts 6 at the beginning of dequede.appendleft(6) # printing modified dequeprint("The deque after appending at left is : ")print(de) # using pop() to delete element from right end# deletes 4 from the right end of dequede.pop() # printing modified dequeprint("The deque after deleting from right is : ")print(de) # using popleft() to delete element from left end# deletes 6 from the left end of dequede.popleft() # printing modified dequeprint("The deque after deleting from left is : ")print(de)
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality.
Python3
from collections import UserDict # Creating a Dictionary where# deletion is not allowedclass MyDict(UserDict): # Function to stop deletion # from dictionary def __del__(self): raise RuntimeError("Deletion not allowed") # Function to stop pop from # dictionary def pop(self, s = None): raise RuntimeError("Deletion not allowed") # Function to stop popitem # from Dictionary def popitem(self, s = None): raise RuntimeError("Deletion not allowed") # Driver's coded = MyDict({'a':1, 'b': 2, 'c': 3}) print("Original Dictionary")print(d) d.pop(1)
Output
Original Dictionary
{'a': 1, 'b': 2, 'c': 3}
RuntimeError: Deletion not allowed
UserList is a list-like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality.
Python3
# Python program to demonstrate# userlist from collections import UserList # Creating a List where# deletion is not allowedclass MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError("Deletion not allowed") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError("Deletion not allowed") # Driver's codeL = MyList([1, 2, 3, 4]) print("Original List")print(L) # Inserting to List"L.append(5)print("After Insertion")print(L) # Deleting From ListL.remove()
Output
Original List
[1, 2, 3, 4]
After Insertion
[1, 2, 3, 4, 5]
RuntimeError: Deletion not allowed
UserString is a string-like container and just like UserDict and UserList, it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality.
Python3
from collections import UserString # Creating a Mutable Stringclass Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, "") # Driver's codes1 = Mystring("Geeks")print("Original String:", s1.data) # Appending to strings1.append("s")print("String After Appending:", s1.data) # Removing from strings1.remove("e")print("String after Removing:", s1.data)
Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss
Now after studying all the data structures let’s see some advanced data structures such as stack, queue, graph, linked list, etc. that can be used in Python Language.
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts:
Data
Pointer (Or Reference) to the next node
Python3
# Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize # next as null # Linked List classclass LinkedList: # Function to initialize the Linked # List object def __init__(self): self.head = None
Let us create a simple linked list with 3 nodes.
Python3
# A simple Python program to introduce a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ '''
In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list.
Python3
# A simple Python program for traversal of a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print (temp.data) temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second; # Link first node with second second.next = third; # Link second node with the third node llist.printList()
1
2
3
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Implementation using List
Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order.
Python3
stack = [] # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty
Initial stack
['g', 'f', 'g']
Elements popped from stack:
g
f
g
Stack after elements are popped:
[]
Implementation using collections.deque:
Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
Python3
from collections import deque stack = deque() # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack:')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty
Initial stack:
deque(['g', 'f', 'g'])
Elements popped from stack:
g
f
g
Stack after elements are popped:
deque([])
Implementation using queue module
The queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue.
Python3
from queue import LifoQueue # Initializing a stackstack = LifoQueue(maxsize = 3) # qsize() show the number of elements# in the stackprint(stack.qsize()) # put() function to push# element in the stackstack.put('g')stack.put('f')stack.put('g') print("Full: ", stack.full())print("Size: ", stack.qsize()) # get() function to pop# element from stack in# LIFO orderprint('\nElements popped from the stack')print(stack.get())print(stack.get())print(stack.get()) print("\nEmpty: ", stack.empty())
0
Full: True
Size: 3
Elements popped from the stack
g
f
g
Empty: True
As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first.
Operations associated with queue are:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)
Front: Get the front item from queue – Time Complexity: O(1)
Rear: Get the last item from queue – Time Complexity: O(1)
Queue in Python can be implemented in the following ways:
list
collections.deque
queue.Queue
Implementation using list
Instead of enqueue() and dequeue(), append() and pop() function is used.
Python3
# Initializing a queuequeue = [] # Adding elements to the queuequeue.append('g')queue.append('f')queue.append('g') print("Initial queue")print(queue) # Removing elements from the queueprint("\nElements dequeued from queue")print(queue.pop(0))print(queue.pop(0))print(queue.pop(0)) print("\nQueue after removing elements")print(queue) # Uncommenting print(queue.pop(0))# will raise and IndexError# as the queue is now empty
Initial queue
['g', 'f', 'g']
Elements dequeued from queue
g
f
g
Queue after removing elements
[]
Implementation using collections.deque
Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
Python3
from collections import deque # Initializing a queueq = deque() # Adding elements to a queueq.append('g')q.append('f')q.append('g') print("Initial queue")print(q) # Removing elements from a queueprint("\nElements dequeued from the queue")print(q.popleft())print(q.popleft())print(q.popleft()) print("\nQueue after removing elements")print(q) # Uncommenting q.popleft()# will raise an IndexError# as queue is now empty
Initial queue
deque(['g', 'f', 'g'])
Elements dequeued from the queue
g
f
g
Queue after removing elements
deque([])
Implementation using the queue.Queue
queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means an infinite queue. This Queue follows the FIFO rule.
Python3
from queue import Queue # Initializing a queueq = Queue(maxsize = 3) # qsize() give the maxsize# of the Queueprint(q.qsize()) # Adding of element to queueq.put('g')q.put('f')q.put('g') # Return Boolean for Full# Queueprint("\nFull: ", q.full()) # Removing element from queueprint("\nElements dequeued from the queue")print(q.get())print(q.get())print(q.get()) # Return Boolean for Empty# Queueprint("\nEmpty: ", q.empty()) q.put(1)print("\nEmpty: ", q.empty())print("Full: ", q.full()) # This would result into Infinite# Loop as the Queue is empty.# print(q.get())
0
Full: True
Elements dequeued from the queue
g
f
g
Empty: True
Empty: False
Full: False
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties.
An element with high priority is dequeued before an element with low priority.
If two elements have the same priority, they are served according to their order in the queue.
Python3
# A simple implementation of Priority Queue# using Queue.class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() if __name__ == '__main__': myQueue = PriorityQueue() myQueue.insert(12) myQueue.insert(1) myQueue.insert(14) myQueue.insert(7) print(myQueue) while not myQueue.isEmpty(): print(myQueue.delete())
12 1 14 7
14
12
7
1
heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap). Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time.
It supports the extraction and insertion of the smallest element in the O(log n) times.
Python3
# importing "heapq" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint ("The created heap is : ",end="")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint ("The modified heap after push is : ",end="")print (list(li)) # using heappop() to pop smallest elementprint ("The popped and smallest element is : ",end="")print (heapq.heappop(li))
The created heap is : [1, 3, 9, 7, 5]
The modified heap after push is : [1, 3, 4, 7, 5, 9]
The popped and smallest element is : 1
A tree is a hierarchical data structure that looks like the below figure –
tree
----
j <-- root
/ \
f k
/ \ \
a h z <-- leaves
The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent.
A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts.
Data
Pointer to left child
Pointer to the right child
Python3
# A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key
Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below –
tree
----
1 <-- root
/ \
2 3
/
4
Python3
# Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \ 2 3 / \ / \None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \ 2 3 / \ / \4 None None None/ \None None'''
Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree –
tree
----
1 <-- root
/ \
2 3
/ \
4 5
Depth First Traversals:
Inorder (Left, Root, Right) : 4 2 5 1 3
Preorder (Root, Left, Right) : 1 2 4 5 3
Postorder (Left, Right, Root) : 4 5 2 3 1
Algorithm Inorder(tree)
Traverse the left subtree, i.e., call Inorder(left-subtree)
Visit the root.
Traverse the right subtree, i.e., call Inorder(right-subtree)
Algorithm Preorder(tree)
Visit the root.
Traverse the left subtree, i.e., call Preorder(left-subtree)
Traverse the right subtree, i.e., call Preorder(right-subtree)
Algorithm Postorder(tree)
Traverse the left subtree, i.e., call Postorder(left-subtree)
Traverse the right subtree, i.e., call Postorder(right-subtree)
Visit the root.
Python3
# Python program to for tree traversals # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversaldef printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversaldef printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversaldef printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print("Preorder traversal of binary tree is")printPreorder(root) print("\nInorder traversal of binary tree is")printInorder(root) print("\nPostorder traversal of binary tree is")printPostorder(root)
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1
Time Complexity – O(n)
Breadth-First or Level Order Traversal
Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5.
For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same –
Create an empty queue q
temp_node = root /*start from root*/
Loop while temp_node is not NULLprint temp_node->data.Enqueue temp_node’s children (first left then right children) to qDequeue a node from q
print temp_node->data.
Enqueue temp_node’s children (first left then right children) to q
Dequeue a node from q
Python3
# Python program to print level# order traversal using Queue # A node structureclass Node: # A utility function to create a new node def __init__(self ,key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary treedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print (queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print ("Level Order Traversal of binary tree is -")printLevelOrder(root)
Level Order Traversal of binary tree is -
1
2
3
4
5
Time Complexity: O(n)
A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.
In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
The following two are the most commonly used representations of a graph.
Adjacency Matrix
Adjacency List
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
Python3
# A simple representation of graph using Adjacency Matrixclass Graph: def __init__(self,numvertex): self.adjMatrix = [[-1]*numvertex for x in range(numvertex)] self.numvertex = numvertex self.vertices = {} self.verticeslist =[0]*numvertex def set_vertex(self,vtx,id): if 0<=vtx<=self.numvertex: self.vertices[id] = vtx self.verticeslist[vtx] = id def set_edge(self,frm,to,cost=0): frm = self.vertices[frm] to = self.vertices[to] self.adjMatrix[frm][to] = cost # for directed graph do not add this self.adjMatrix[to][frm] = cost def get_vertex(self): return self.verticeslist def get_edges(self): edges=[] for i in range (self.numvertex): for j in range (self.numvertex): if (self.adjMatrix[i][j]!=-1): edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j])) return edges def get_matrix(self): return self.adjMatrix G =Graph(6)G.set_vertex(0,'a')G.set_vertex(1,'b')G.set_vertex(2,'c')G.set_vertex(3,'d')G.set_vertex(4,'e')G.set_vertex(5,'f')G.set_edge('a','e',10)G.set_edge('a','c',20)G.set_edge('c','b',30)G.set_edge('b','e',40)G.set_edge('e','d',50)G.set_edge('f','e',60) print("Vertices of Graph")print(G.get_vertex()) print("Edges of Graph")print(G.get_edges()) print("Adjacency Matrix of Graph")print(G.get_matrix())
Output
Vertices of Graph
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
Edges of Graph
[(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)]
Adjacency Matrix of Graph
[[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]]
An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph.
Python3
# A class to represent the adjacency list of the nodeclass AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices "V"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print("Adjacency list of vertex {}\n head".format(i), end="") temp = self.graph[i] while temp: print(" -> {}".format(temp.vertex), end="") temp = temp.next print(" \n") # Driver program to the above graph classif __name__ == "__main__": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph()
Adjacency list of vertex 0
head -> 4 -> 1
Adjacency list of vertex 1
head -> 4 -> 3 -> 2 -> 0
Adjacency list of vertex 2
head -> 3 -> 1
Adjacency list of vertex 3
head -> 4 -> 2 -> 1
Adjacency list of vertex 4
head -> 3 -> 1 -> 0
Breadth-First Search or BFS
Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1.
Python3
# Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = " ") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print ("Following is Breadth First Traversal" " (starting from vertex 2)")g.BFS(2) # This code is contributed by Neelam Yadav
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph.
Depth First Search or DFS
Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array.
Algorithm:
Create a recursive function that takes the index of the node and a visited array.
Mark the current node as visited and print the node.
Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
Python3
# Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print("Following is DFS from (starting from vertex 2)")g.DFS(2)
Following is DFS from (starting from vertex 2)
2 0 1 3
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
punamsingh628700
aadityappagar
sagartomar9927
Python-Data-Structures
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 389,
"s": 52,
"text": "Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages."
},
{
"code": null,
"e": 690,
"s": 389,
"text": "In this article, we will discuss the Data Structures in the Python Programming Language and how they are related to some specific Python Data Types. We will discuss all the in-built data structures like list tuples, dictionaries, etc. as well as some advanced data structures like trees, graphs, etc."
},
{
"code": null,
"e": 876,
"s": 690,
"text": "Python Lists are just like the arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type."
},
{
"code": null,
"e": 1221,
"s": 876,
"text": "The implementation of Python List is similar to Vectors in C++ or ArrayList in JAVA. The costly operation is inserting or deleting the element from the beginning of the List as all the elements are needed to be shifted. Insertion and deletion at the end of the list can also become costly in the case where the preallocated memory becomes full."
},
{
"code": null,
"e": 1268,
"s": 1221,
"text": "We can create a list in python as shown below."
},
{
"code": null,
"e": 1276,
"s": 1268,
"text": "Python3"
},
{
"code": "List = [1, 2, 3, \"GFG\", 2.3]print(List)",
"e": 1317,
"s": 1276,
"text": null
},
{
"code": null,
"e": 1339,
"s": 1317,
"text": "[1, 2, 3, 'GFG', 2.3]"
},
{
"code": null,
"e": 1499,
"s": 1339,
"text": "List elements can be accessed by the assigned index. In python starting index of the list, sequence is 0 and the ending index is (if N elements are there) N-1."
},
{
"code": null,
"e": 1507,
"s": 1499,
"text": "Python3"
},
{
"code": "# Creating a List with # the use of multiple values List = [\"Geeks\", \"For\", \"Geeks\"] print(\"\\nList containing multiple values: \") print(List) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List2 = [['Geeks', 'For'], ['Geeks']] print(\"\\nMulti-Dimensional List: \") print(List2) # accessing a element from the # list using index number print(\"Accessing element from the list\") print(List[0]) print(List[2]) # accessing a element using # negative indexing print(\"Accessing element using negative indexing\") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3])",
"e": 2159,
"s": 1507,
"text": null
},
{
"code": null,
"e": 2373,
"s": 2159,
"text": "List containing multiple values: \n['Geeks', 'For', 'Geeks']\n\nMulti-Dimensional List: \n[['Geeks', 'For'], ['Geeks']]\nAccessing element from the list\nGeeks\nGeeks\nAccessing element using negative indexing\nGeeks\nGeeks"
},
{
"code": null,
"e": 2732,
"s": 2373,
"text": "Python dictionary is like hash tables in any other language with the time complexity of O(1). It is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized. "
},
{
"code": null,
"e": 2981,
"s": 2732,
"text": "Indexing of Python Dictionary is done with the help of keys. These are of any hashable type i.e. an object whose can never change like strings, numbers, tuples, etc. We can create a dictionary by using curly braces ({}) or dictionary comprehension."
},
{
"code": null,
"e": 2989,
"s": 2981,
"text": "Python3"
},
{
"code": "# Creating a DictionaryDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print(\"Creating Dictionary: \")print(Dict) # accessing a element using key print(\"Accessing a element using key:\") print(Dict['Name']) # accessing a element using get() # method print(\"Accessing a element using get:\") print(Dict.get(1)) # creation using Dictionary comprehensionmyDict = {x: x**2 for x in [1,2,3,4,5]}print(myDict)",
"e": 3388,
"s": 2989,
"text": null
},
{
"code": null,
"e": 3559,
"s": 3388,
"text": "Creating Dictionary: \n{'Name': 'Geeks', 1: [1, 2, 3, 4]}\nAccessing a element using key:\nGeeks\nAccessing a element using get:\n[1, 2, 3, 4]\n{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}"
},
{
"code": null,
"e": 3800,
"s": 3559,
"text": "Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain elements of various types."
},
{
"code": null,
"e": 3957,
"s": 3800,
"text": "In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence."
},
{
"code": null,
"e": 4147,
"s": 3957,
"text": "Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple."
},
{
"code": null,
"e": 4155,
"s": 4147,
"text": "Python3"
},
{
"code": "# Creating a Tuple with# the use of StringsTuple = ('Geeks', 'For')print(\"\\nTuple with the use of String: \")print(Tuple) # Creating a Tuple with# the use of listlist1 = [1, 2, 4, 5, 6]print(\"\\nTuple using List: \")Tuple = tuple(list1) # Accessing element using indexingprint(\"First element of tuple\")print(Tuple[0]) # Accessing element from last# negative indexingprint(\"\\nLast element of tuple\")print(Tuple[-1]) print(\"\\nThird last element of tuple\")print(Tuple[-3])",
"e": 4632,
"s": 4155,
"text": null
},
{
"code": null,
"e": 4781,
"s": 4632,
"text": "Tuple with the use of String: \n('Geeks', 'For')\n\nTuple using List: \nFirst element of tuple\n1\n\nLast element of tuple\n6\n\nThird last element of tuple\n4"
},
{
"code": null,
"e": 5103,
"s": 4781,
"text": "Python Set is an ordered collection of data that is mutable and does not allow any duplicate element. Sets are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion, and traversal in O(1) on average. "
},
{
"code": null,
"e": 5394,
"s": 5103,
"text": "If Multiple values are present at the same index position, then the value is appended to that index position, to form a Linked List. In, CPython Sets are implemented using a dictionary with dummy variables, where key beings the members set with greater optimizations to the time complexity."
},
{
"code": null,
"e": 5414,
"s": 5394,
"text": "Set Implementation:"
},
{
"code": null,
"e": 5467,
"s": 5414,
"text": "Sets with Numerous operations on a single HashTable:"
},
{
"code": null,
"e": 5475,
"s": 5467,
"text": "Python3"
},
{
"code": "# Creating a Set with # a mixed type of values # (Having numbers and strings) Set = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print(\"\\nSet with the use of Mixed Values\") print(Set) # Accessing element using # for loop print(\"\\nElements of set: \") for i in Set: print(i, end =\" \") print() # Checking the element # using in keyword print(\"Geeks\" in Set)",
"e": 5836,
"s": 5475,
"text": null
},
{
"code": null,
"e": 5941,
"s": 5836,
"text": "Set with the use of Mixed Values\n{1, 2, 'Geeks', 4, 6, 'For'}\n\nElements of set: \n1 2 Geeks 4 6 For \nTrue"
},
{
"code": null,
"e": 6227,
"s": 5941,
"text": "Frozen sets in Python are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation."
},
{
"code": null,
"e": 6287,
"s": 6227,
"text": "If no parameters are passed, it returns an empty frozenset."
},
{
"code": null,
"e": 6295,
"s": 6287,
"text": "Python3"
},
{
"code": "# Same as {\"a\", \"b\",\"c\"}normal_set = set([\"a\", \"b\",\"c\"]) print(\"Normal Set\")print(normal_set) # A frozen setfrozen_set = frozenset([\"e\", \"f\", \"g\"]) print(\"\\nFrozen Set\")print(frozen_set) # Uncommenting below line would cause error as# we are trying to add element to a frozen set# frozen_set.add(\"h\")",
"e": 6600,
"s": 6295,
"text": null
},
{
"code": null,
"e": 6666,
"s": 6600,
"text": "Normal Set\n{'a', 'c', 'b'}\n\nFrozen Set\nfrozenset({'g', 'e', 'f'})"
},
{
"code": null,
"e": 6900,
"s": 6666,
"text": "Python Strings are arrays of bytes representing Unicode characters. In simpler terms, a string is an immutable array of characters. Python does not have a character data type, a single character is simply a string with a length of 1."
},
{
"code": null,
"e": 6987,
"s": 6900,
"text": "Note: As strings are immutable, modifying a string will result in creating a new copy."
},
{
"code": null,
"e": 6995,
"s": 6987,
"text": "Python3"
},
{
"code": "String = \"Welcome to GeeksForGeeks\"print(\"Creating String: \") print(String) # Printing First character print(\"\\nFirst character of String is: \") print(String[0]) # Printing Last character print(\"\\nLast character of String is: \") print(String[-1])",
"e": 7254,
"s": 6995,
"text": null
},
{
"code": null,
"e": 7364,
"s": 7254,
"text": "Creating String: \nWelcome to GeeksForGeeks\n\nFirst character of String is: \nW\n\nLast character of String is: \ns"
},
{
"code": null,
"e": 7445,
"s": 7364,
"text": "Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256."
},
{
"code": null,
"e": 7453,
"s": 7445,
"text": "Python3"
},
{
"code": "# Creating bytearraya = bytearray((12, 8, 25, 2))print(\"Creating Bytearray:\")print(a) # accessing elementsprint(\"\\nAccessing Elements:\", a[1]) # modifying elements a[1] = 3print(\"\\nAfter Modifying:\")print(a) # Appending elementsa.append(30)print(\"\\nAfter Adding Elements:\")print(a)",
"e": 7738,
"s": 7453,
"text": null
},
{
"code": null,
"e": 7920,
"s": 7738,
"text": "Creating Bytearray:\nbytearray(b'\\x0c\\x08\\x19\\x02')\n\nAccessing Elements: 8\n\nAfter Modifying:\nbytearray(b'\\x0c\\x03\\x19\\x02')\n\nAfter Adding Elements:\nbytearray(b'\\x0c\\x03\\x19\\x02\\x1e')"
},
{
"code": null,
"e": 8192,
"s": 7920,
"text": "Till now we have studied all the data structures that come built-in into core Python. Now let dive more deep into Python and see the collections module that provides some containers that are useful in many cases and provide more features than the above-defined functions."
},
{
"code": null,
"e": 8357,
"s": 8192,
"text": "Python collection module was introduced to improve the functionality of the built-in datatypes. It provides various containers let’s see each one of them in detail."
},
{
"code": null,
"e": 8677,
"s": 8357,
"text": "A counter is a sub-class of the dictionary. It is used to keep the count of the elements in an iterable in the form of an unordered dictionary where the key represents the element in the iterable and value represents the count of that element in the iterable. This is equivalent to a bag or multiset of other languages."
},
{
"code": null,
"e": 8685,
"s": 8677,
"text": "Python3"
},
{
"code": "from collections import Counter # With sequence of items print(Counter(['B','B','A','B','C','A','B','B','A','C'])) # with dictionarycount = Counter({'A':3, 'B':5, 'C':2})print(count) count.update(['A', 1])print(count)",
"e": 8910,
"s": 8685,
"text": null
},
{
"code": null,
"e": 9018,
"s": 8910,
"text": "Counter({'B': 5, 'A': 3, 'C': 2})\nCounter({'B': 5, 'A': 3, 'C': 2})\nCounter({'B': 5, 'A': 4, 'C': 2, 1: 1})"
},
{
"code": null,
"e": 9149,
"s": 9018,
"text": "An OrderedDict is also a sub-class of dictionary but unlike a dictionary, it remembers the order in which the keys were inserted. "
},
{
"code": null,
"e": 9157,
"s": 9149,
"text": "Python3"
},
{
"code": "from collections import OrderedDict print(\"Before deleting:\\n\")od = OrderedDict()od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 for key, value in od.items(): print(key, value) print(\"\\nAfter deleting:\\n\")od.pop('c')for key, value in od.items(): print(key, value) print(\"\\nAfter re-inserting:\\n\")od['c'] = 3for key, value in od.items(): print(key, value)",
"e": 9522,
"s": 9157,
"text": null
},
{
"code": null,
"e": 9624,
"s": 9522,
"text": "Before deleting:\n\na 1\nb 2\nc 3\nd 4\n\nAfter deleting:\n\na 1\nb 2\nd 4\n\nAfter re-inserting:\n\na 1\nb 2\nd 4\nc 3"
},
{
"code": null,
"e": 9835,
"s": 9624,
"text": "DefaultDict is used to provide some default values for the key that does not exist and never raises a KeyError. Its objects can be initialized using DefaultDict() method by passing the data type as an argument."
},
{
"code": null,
"e": 9988,
"s": 9835,
"text": "Note: default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised."
},
{
"code": null,
"e": 9996,
"s": 9988,
"text": "Python3"
},
{
"code": "from collections import defaultdict # Defining the dictd = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list# for keeping the countfor i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d)",
"e": 10301,
"s": 9996,
"text": null
},
{
"code": null,
"e": 10354,
"s": 10301,
"text": "defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})"
},
{
"code": null,
"e": 10558,
"s": 10354,
"text": "A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries. When a key is needed to be found then all the dictionaries are searched one by one until the key is found."
},
{
"code": null,
"e": 10566,
"s": 10558,
"text": "Python3"
},
{
"code": "from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmapc = ChainMap(d1, d2, d3)print(c) print(c['a'])print(c['g'])",
"e": 10763,
"s": 10566,
"text": null
},
{
"code": null,
"e": 10770,
"s": 10763,
"text": "Output"
},
{
"code": null,
"e": 10835,
"s": 10770,
"text": "ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})\n1"
},
{
"code": null,
"e": 10849,
"s": 10835,
"text": "KeyError: 'g'"
},
{
"code": null,
"e": 11337,
"s": 10849,
"text": "A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple."
},
{
"code": null,
"e": 11345,
"s": 11337,
"text": "Python3"
},
{
"code": "from collections import namedtuple # Declaring namedtuple()Student = namedtuple('Student',['name','age','DOB']) # Adding valuesS = Student('Nandini','19','2541997') # Access using indexprint (\"The Student age using index is : \",end =\"\")print (S[1]) # Access using nameprint (\"The Student name using keyname is : \",end =\"\")print (S.name)",
"e": 11702,
"s": 11345,
"text": null
},
{
"code": null,
"e": 11782,
"s": 11702,
"text": "The Student age using index is : 19\nThe Student name using keyname is : Nandini"
},
{
"code": null,
"e": 12017,
"s": 11782,
"text": "Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to the list with O(n) time complexity."
},
{
"code": null,
"e": 12142,
"s": 12017,
"text": "Python Deque is implemented using doubly linked lists therefore the performance for randomly accessing the elements is O(n)."
},
{
"code": null,
"e": 12150,
"s": 12142,
"text": "Python3"
},
{
"code": "# importing \"collections\" for deque operationsimport collections # initializing dequede = collections.deque([1,2,3]) # using append() to insert element at right end# inserts 4 at the end of dequede.append(4) # printing modified dequeprint(\"The deque after appending at right is : \")print(de) # using appendleft() to insert element at left end# inserts 6 at the beginning of dequede.appendleft(6) # printing modified dequeprint(\"The deque after appending at left is : \")print(de) # using pop() to delete element from right end# deletes 4 from the right end of dequede.pop() # printing modified dequeprint(\"The deque after deleting from right is : \")print(de) # using popleft() to delete element from left end# deletes 6 from the left end of dequede.popleft() # printing modified dequeprint(\"The deque after deleting from left is : \")print(de)",
"e": 13001,
"s": 12150,
"text": null
},
{
"code": null,
"e": 13245,
"s": 13001,
"text": "The deque after appending at right is : \ndeque([1, 2, 3, 4])\nThe deque after appending at left is : \ndeque([6, 1, 2, 3, 4])\nThe deque after deleting from right is : \ndeque([6, 1, 2, 3])\nThe deque after deleting from left is : \ndeque([1, 2, 3])"
},
{
"code": null,
"e": 13454,
"s": 13245,
"text": "UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality. "
},
{
"code": null,
"e": 13462,
"s": 13454,
"text": "Python3"
},
{
"code": "from collections import UserDict # Creating a Dictionary where# deletion is not allowedclass MyDict(UserDict): # Function to stop deletion # from dictionary def __del__(self): raise RuntimeError(\"Deletion not allowed\") # Function to stop pop from # dictionary def pop(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Function to stop popitem # from Dictionary def popitem(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Driver's coded = MyDict({'a':1, 'b': 2, 'c': 3}) print(\"Original Dictionary\")print(d) d.pop(1)",
"e": 14092,
"s": 13462,
"text": null
},
{
"code": null,
"e": 14099,
"s": 14092,
"text": "Output"
},
{
"code": null,
"e": 14144,
"s": 14099,
"text": "Original Dictionary\n{'a': 1, 'b': 2, 'c': 3}"
},
{
"code": null,
"e": 14179,
"s": 14144,
"text": "RuntimeError: Deletion not allowed"
},
{
"code": null,
"e": 14368,
"s": 14179,
"text": "UserList is a list-like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality."
},
{
"code": null,
"e": 14376,
"s": 14368,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# userlist from collections import UserList # Creating a List where# deletion is not allowedclass MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Driver's codeL = MyList([1, 2, 3, 4]) print(\"Original List\")print(L) # Inserting to List\"L.append(5)print(\"After Insertion\")print(L) # Deleting From ListL.remove()",
"e": 14965,
"s": 14376,
"text": null
},
{
"code": null,
"e": 14972,
"s": 14965,
"text": "Output"
},
{
"code": null,
"e": 15031,
"s": 14972,
"text": "Original List\n[1, 2, 3, 4]\nAfter Insertion\n[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 15066,
"s": 15031,
"text": "RuntimeError: Deletion not allowed"
},
{
"code": null,
"e": 15292,
"s": 15066,
"text": "UserString is a string-like container and just like UserDict and UserList, it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality. "
},
{
"code": null,
"e": 15300,
"s": 15292,
"text": "Python3"
},
{
"code": "from collections import UserString # Creating a Mutable Stringclass Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, \"\") # Driver's codes1 = Mystring(\"Geeks\")print(\"Original String:\", s1.data) # Appending to strings1.append(\"s\")print(\"String After Appending:\", s1.data) # Removing from strings1.remove(\"e\")print(\"String after Removing:\", s1.data)",
"e": 15834,
"s": 15300,
"text": null
},
{
"code": null,
"e": 15916,
"s": 15834,
"text": "Original String: Geeks\nString After Appending: Geekss\nString after Removing: Gkss"
},
{
"code": null,
"e": 16083,
"s": 15916,
"text": "Now after studying all the data structures let’s see some advanced data structures such as stack, queue, graph, linked list, etc. that can be used in Python Language."
},
{
"code": null,
"e": 16279,
"s": 16083,
"text": "A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:"
},
{
"code": null,
"e": 16511,
"s": 16279,
"text": "A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head is NULL. Each node in a list consists of at least two parts:"
},
{
"code": null,
"e": 16516,
"s": 16511,
"text": "Data"
},
{
"code": null,
"e": 16556,
"s": 16516,
"text": "Pointer (Or Reference) to the next node"
},
{
"code": null,
"e": 16564,
"s": 16556,
"text": "Python3"
},
{
"code": "# Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize # next as null # Linked List classclass LinkedList: # Function to initialize the Linked # List object def __init__(self): self.head = None",
"e": 16923,
"s": 16564,
"text": null
},
{
"code": null,
"e": 16972,
"s": 16923,
"text": "Let us create a simple linked list with 3 nodes."
},
{
"code": null,
"e": 16980,
"s": 16972,
"text": "Python3"
},
{
"code": "# A simple Python program to introduce a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ '''",
"e": 18821,
"s": 16980,
"text": null
},
{
"code": null,
"e": 19062,
"s": 18821,
"text": "In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList() that prints any given list."
},
{
"code": null,
"e": 19070,
"s": 19062,
"text": "Python3"
},
{
"code": "# A simple Python program for traversal of a linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def printList(self): temp = self.head while (temp): print (temp.data) temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second; # Link first node with second second.next = third; # Link second node with the third node llist.printList()",
"e": 19987,
"s": 19070,
"text": null
},
{
"code": null,
"e": 19993,
"s": 19987,
"text": "1\n2\n3"
},
{
"code": null,
"e": 20266,
"s": 19993,
"text": "A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop."
},
{
"code": null,
"e": 20307,
"s": 20266,
"text": "The functions associated with stack are:"
},
{
"code": null,
"e": 20376,
"s": 20307,
"text": "empty() – Returns whether the stack is empty – Time Complexity: O(1)"
},
{
"code": null,
"e": 20439,
"s": 20376,
"text": "size() – Returns the size of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 20527,
"s": 20439,
"text": "top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 20609,
"s": 20527,
"text": "push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 20682,
"s": 20609,
"text": "pop() – Deletes the topmost element of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 20743,
"s": 20682,
"text": "Stack in Python can be implemented using the following ways:"
},
{
"code": null,
"e": 20748,
"s": 20743,
"text": "list"
},
{
"code": null,
"e": 20766,
"s": 20748,
"text": "Collections.deque"
},
{
"code": null,
"e": 20782,
"s": 20766,
"text": "queue.LifoQueue"
},
{
"code": null,
"e": 20808,
"s": 20782,
"text": "Implementation using List"
},
{
"code": null,
"e": 20994,
"s": 20808,
"text": "Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order. "
},
{
"code": null,
"e": 21002,
"s": 20994,
"text": "Python3"
},
{
"code": "stack = [] # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty",
"e": 21448,
"s": 21002,
"text": null
},
{
"code": null,
"e": 21550,
"s": 21448,
"text": "Initial stack\n['g', 'f', 'g']\n\nElements popped from stack:\ng\nf\ng\n\nStack after elements are popped:\n[]"
},
{
"code": null,
"e": 21590,
"s": 21550,
"text": "Implementation using collections.deque:"
},
{
"code": null,
"e": 21934,
"s": 21590,
"text": "Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. "
},
{
"code": null,
"e": 21942,
"s": 21934,
"text": "Python3"
},
{
"code": "from collections import deque stack = deque() # append() function to push# element in the stackstack.append('g')stack.append('f')stack.append('g') print('Initial stack:')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty",
"e": 22425,
"s": 21942,
"text": null
},
{
"code": null,
"e": 22542,
"s": 22425,
"text": "Initial stack:\ndeque(['g', 'f', 'g'])\n\nElements popped from stack:\ng\nf\ng\n\nStack after elements are popped:\ndeque([])"
},
{
"code": null,
"e": 22576,
"s": 22542,
"text": "Implementation using queue module"
},
{
"code": null,
"e": 22739,
"s": 22576,
"text": "The queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue. "
},
{
"code": null,
"e": 22747,
"s": 22739,
"text": "Python3"
},
{
"code": "from queue import LifoQueue # Initializing a stackstack = LifoQueue(maxsize = 3) # qsize() show the number of elements# in the stackprint(stack.qsize()) # put() function to push# element in the stackstack.put('g')stack.put('f')stack.put('g') print(\"Full: \", stack.full())print(\"Size: \", stack.qsize()) # get() function to pop# element from stack in# LIFO orderprint('\\nElements popped from the stack')print(stack.get())print(stack.get())print(stack.get()) print(\"\\nEmpty: \", stack.empty())",
"e": 23243,
"s": 22747,
"text": null
},
{
"code": null,
"e": 23318,
"s": 23243,
"text": "0\nFull: True\nSize: 3\n\nElements popped from the stack\ng\nf\ng\n\nEmpty: True"
},
{
"code": null,
"e": 23607,
"s": 23318,
"text": "As a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of the queue is any queue of consumers for a resource where the consumer that came first is served first."
},
{
"code": null,
"e": 23645,
"s": 23607,
"text": "Operations associated with queue are:"
},
{
"code": null,
"e": 23771,
"s": 23645,
"text": "Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)"
},
{
"code": null,
"e": 23969,
"s": 23771,
"text": "Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)"
},
{
"code": null,
"e": 24030,
"s": 23969,
"text": "Front: Get the front item from queue – Time Complexity: O(1)"
},
{
"code": null,
"e": 24089,
"s": 24030,
"text": "Rear: Get the last item from queue – Time Complexity: O(1)"
},
{
"code": null,
"e": 24147,
"s": 24089,
"text": "Queue in Python can be implemented in the following ways:"
},
{
"code": null,
"e": 24152,
"s": 24147,
"text": "list"
},
{
"code": null,
"e": 24170,
"s": 24152,
"text": "collections.deque"
},
{
"code": null,
"e": 24182,
"s": 24170,
"text": "queue.Queue"
},
{
"code": null,
"e": 24208,
"s": 24182,
"text": "Implementation using list"
},
{
"code": null,
"e": 24281,
"s": 24208,
"text": "Instead of enqueue() and dequeue(), append() and pop() function is used."
},
{
"code": null,
"e": 24289,
"s": 24281,
"text": "Python3"
},
{
"code": "# Initializing a queuequeue = [] # Adding elements to the queuequeue.append('g')queue.append('f')queue.append('g') print(\"Initial queue\")print(queue) # Removing elements from the queueprint(\"\\nElements dequeued from queue\")print(queue.pop(0))print(queue.pop(0))print(queue.pop(0)) print(\"\\nQueue after removing elements\")print(queue) # Uncommenting print(queue.pop(0))# will raise and IndexError# as the queue is now empty",
"e": 24717,
"s": 24289,
"text": null
},
{
"code": null,
"e": 24817,
"s": 24717,
"text": "Initial queue\n['g', 'f', 'g']\n\nElements dequeued from queue\ng\nf\ng\n\nQueue after removing elements\n[]"
},
{
"code": null,
"e": 24856,
"s": 24817,
"text": "Implementation using collections.deque"
},
{
"code": null,
"e": 25116,
"s": 24856,
"text": "Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity."
},
{
"code": null,
"e": 25124,
"s": 25116,
"text": "Python3"
},
{
"code": "from collections import deque # Initializing a queueq = deque() # Adding elements to a queueq.append('g')q.append('f')q.append('g') print(\"Initial queue\")print(q) # Removing elements from a queueprint(\"\\nElements dequeued from the queue\")print(q.popleft())print(q.popleft())print(q.popleft()) print(\"\\nQueue after removing elements\")print(q) # Uncommenting q.popleft()# will raise an IndexError# as queue is now empty",
"e": 25548,
"s": 25124,
"text": null
},
{
"code": null,
"e": 25666,
"s": 25548,
"text": "Initial queue\ndeque(['g', 'f', 'g'])\n\nElements dequeued from the queue\ng\nf\ng\n\nQueue after removing elements\ndeque([])"
},
{
"code": null,
"e": 25703,
"s": 25666,
"text": "Implementation using the queue.Queue"
},
{
"code": null,
"e": 25859,
"s": 25703,
"text": "queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means an infinite queue. This Queue follows the FIFO rule. "
},
{
"code": null,
"e": 25867,
"s": 25859,
"text": "Python3"
},
{
"code": "from queue import Queue # Initializing a queueq = Queue(maxsize = 3) # qsize() give the maxsize# of the Queueprint(q.qsize()) # Adding of element to queueq.put('g')q.put('f')q.put('g') # Return Boolean for Full# Queueprint(\"\\nFull: \", q.full()) # Removing element from queueprint(\"\\nElements dequeued from the queue\")print(q.get())print(q.get())print(q.get()) # Return Boolean for Empty# Queueprint(\"\\nEmpty: \", q.empty()) q.put(1)print(\"\\nEmpty: \", q.empty())print(\"Full: \", q.full()) # This would result into Infinite# Loop as the Queue is empty.# print(q.get())",
"e": 26440,
"s": 25867,
"text": null
},
{
"code": null,
"e": 26537,
"s": 26440,
"text": "0\n\nFull: True\n\nElements dequeued from the queue\ng\nf\ng\n\nEmpty: True\n\nEmpty: False\nFull: False"
},
{
"code": null,
"e": 26824,
"s": 26537,
"text": "Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties."
},
{
"code": null,
"e": 26903,
"s": 26824,
"text": "An element with high priority is dequeued before an element with low priority."
},
{
"code": null,
"e": 26998,
"s": 26903,
"text": "If two elements have the same priority, they are served according to their order in the queue."
},
{
"code": null,
"e": 27006,
"s": 26998,
"text": "Python3"
},
{
"code": "# A simple implementation of Priority Queue# using Queue.class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: max = 0 for i in range(len(self.queue)): if self.queue[i] > self.queue[max]: max = i item = self.queue[max] del self.queue[max] return item except IndexError: print() exit() if __name__ == '__main__': myQueue = PriorityQueue() myQueue.insert(12) myQueue.insert(1) myQueue.insert(14) myQueue.insert(7) print(myQueue) while not myQueue.isEmpty(): print(myQueue.delete())",
"e": 28026,
"s": 27006,
"text": null
},
{
"code": null,
"e": 28046,
"s": 28026,
"text": "12 1 14 7\n14\n12\n7\n1"
},
{
"code": null,
"e": 28400,
"s": 28046,
"text": "heapq module in Python provides the heap data structure that is mainly used to represent a priority queue. The property of this data structure in Python is that each time the smallest heap element is popped(min-heap). Whenever elements are pushed or popped, heap structure is maintained. The heap[0] element also returns the smallest element each time. "
},
{
"code": null,
"e": 28488,
"s": 28400,
"text": "It supports the extraction and insertion of the smallest element in the O(log n) times."
},
{
"code": null,
"e": 28496,
"s": 28488,
"text": "Python3"
},
{
"code": "# importing \"heapq\" to implement heap queueimport heapq # initializing listli = [5, 7, 9, 1, 3] # using heapify to convert list into heapheapq.heapify(li) # printing created heapprint (\"The created heap is : \",end=\"\")print (list(li)) # using heappush() to push elements into heap# pushes 4heapq.heappush(li,4) # printing modified heapprint (\"The modified heap after push is : \",end=\"\")print (list(li)) # using heappop() to pop smallest elementprint (\"The popped and smallest element is : \",end=\"\")print (heapq.heappop(li))",
"e": 29025,
"s": 28496,
"text": null
},
{
"code": null,
"e": 29155,
"s": 29025,
"text": "The created heap is : [1, 3, 9, 7, 5]\nThe modified heap after push is : [1, 3, 4, 7, 5, 9]\nThe popped and smallest element is : 1"
},
{
"code": null,
"e": 29232,
"s": 29155,
"text": "A tree is a hierarchical data structure that looks like the below figure – "
},
{
"code": null,
"e": 29340,
"s": 29232,
"text": " tree\n ----\n j <-- root\n / \\\n f k \n / \\ \\\na h z <-- leaves"
},
{
"code": null,
"e": 29610,
"s": 29340,
"text": "The topmost node of the tree is called the root whereas the bottommost nodes or the nodes with no children are called the leaf nodes. The nodes that are directly under a node are called its children and the nodes that are directly above something are called its parent."
},
{
"code": null,
"e": 29842,
"s": 29610,
"text": "A binary tree is a tree whose elements can have almost two children. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. A Binary Tree node contains the following parts."
},
{
"code": null,
"e": 29847,
"s": 29842,
"text": "Data"
},
{
"code": null,
"e": 29869,
"s": 29847,
"text": "Pointer to left child"
},
{
"code": null,
"e": 29896,
"s": 29869,
"text": "Pointer to the right child"
},
{
"code": null,
"e": 29904,
"s": 29896,
"text": "Python3"
},
{
"code": "# A Python class that represents an individual node# in a Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key",
"e": 30083,
"s": 29904,
"text": null
},
{
"code": null,
"e": 30183,
"s": 30083,
"text": "Now let’s create a tree with 4 nodes in Python. Let’s assume the tree structure looks like below – "
},
{
"code": null,
"e": 30256,
"s": 30183,
"text": " tree\n ----\n 1 <-- root\n / \\\n 2 3 \n / \n 4"
},
{
"code": null,
"e": 30264,
"s": 30256,
"text": "Python3"
},
{
"code": "# Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self,key): self.left = None self.right = None self.val = key # create rootroot = Node(1)''' following is the tree after above statement 1 / \\ None None''' root.left = Node(2);root.right = Node(3); ''' 2 and 3 become left and right children of 1 1 / \\ 2 3 / \\ / \\None None None None''' root.left.left = Node(4);'''4 becomes left child of 2 1 / \\ 2 3 / \\ / \\4 None None None/ \\None None'''",
"e": 30895,
"s": 30264,
"text": null
},
{
"code": null,
"e": 31031,
"s": 30895,
"text": "Trees can be traversed in different ways. Following are the generally used ways for traversing trees. Let us consider the below tree – "
},
{
"code": null,
"e": 31108,
"s": 31031,
"text": " tree\n ----\n 1 <-- root\n / \\\n 2 3 \n / \\\n 4 5"
},
{
"code": null,
"e": 31132,
"s": 31108,
"text": "Depth First Traversals:"
},
{
"code": null,
"e": 31172,
"s": 31132,
"text": "Inorder (Left, Root, Right) : 4 2 5 1 3"
},
{
"code": null,
"e": 31213,
"s": 31172,
"text": "Preorder (Root, Left, Right) : 1 2 4 5 3"
},
{
"code": null,
"e": 31255,
"s": 31213,
"text": "Postorder (Left, Right, Root) : 4 5 2 3 1"
},
{
"code": null,
"e": 31279,
"s": 31255,
"text": "Algorithm Inorder(tree)"
},
{
"code": null,
"e": 31339,
"s": 31279,
"text": "Traverse the left subtree, i.e., call Inorder(left-subtree)"
},
{
"code": null,
"e": 31355,
"s": 31339,
"text": "Visit the root."
},
{
"code": null,
"e": 31417,
"s": 31355,
"text": "Traverse the right subtree, i.e., call Inorder(right-subtree)"
},
{
"code": null,
"e": 31442,
"s": 31417,
"text": "Algorithm Preorder(tree)"
},
{
"code": null,
"e": 31458,
"s": 31442,
"text": "Visit the root."
},
{
"code": null,
"e": 31519,
"s": 31458,
"text": "Traverse the left subtree, i.e., call Preorder(left-subtree)"
},
{
"code": null,
"e": 31582,
"s": 31519,
"text": "Traverse the right subtree, i.e., call Preorder(right-subtree)"
},
{
"code": null,
"e": 31608,
"s": 31582,
"text": "Algorithm Postorder(tree)"
},
{
"code": null,
"e": 31670,
"s": 31608,
"text": "Traverse the left subtree, i.e., call Postorder(left-subtree)"
},
{
"code": null,
"e": 31734,
"s": 31670,
"text": "Traverse the right subtree, i.e., call Postorder(right-subtree)"
},
{
"code": null,
"e": 31750,
"s": 31734,
"text": "Visit the root."
},
{
"code": null,
"e": 31758,
"s": 31750,
"text": "Python3"
},
{
"code": "# Python program to for tree traversals # A class that represents an individual node in a# Binary Treeclass Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversaldef printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversaldef printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversaldef printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)print(\"Preorder traversal of binary tree is\")printPreorder(root) print(\"\\nInorder traversal of binary tree is\")printInorder(root) print(\"\\nPostorder traversal of binary tree is\")printPostorder(root)",
"e": 33149,
"s": 31758,
"text": null
},
{
"code": null,
"e": 33292,
"s": 33149,
"text": "Preorder traversal of binary tree is\n1\n2\n4\n5\n3\n\nInorder traversal of binary tree is\n4\n2\n5\n1\n3\n\nPostorder traversal of binary tree is\n4\n5\n2\n3\n1"
},
{
"code": null,
"e": 33317,
"s": 33292,
"text": "Time Complexity – O(n) "
},
{
"code": null,
"e": 33356,
"s": 33317,
"text": "Breadth-First or Level Order Traversal"
},
{
"code": null,
"e": 33487,
"s": 33356,
"text": "Level order traversal of a tree is breadth-first traversal for the tree. The level order traversal of the above tree is 1 2 3 4 5."
},
{
"code": null,
"e": 33618,
"s": 33487,
"text": "For each node, first, the node is visited and then its child nodes are put in a FIFO queue. Below is the algorithm for the same – "
},
{
"code": null,
"e": 33642,
"s": 33618,
"text": "Create an empty queue q"
},
{
"code": null,
"e": 33679,
"s": 33642,
"text": "temp_node = root /*start from root*/"
},
{
"code": null,
"e": 33821,
"s": 33679,
"text": "Loop while temp_node is not NULLprint temp_node->data.Enqueue temp_node’s children (first left then right children) to qDequeue a node from q"
},
{
"code": null,
"e": 33844,
"s": 33821,
"text": "print temp_node->data."
},
{
"code": null,
"e": 33911,
"s": 33844,
"text": "Enqueue temp_node’s children (first left then right children) to q"
},
{
"code": null,
"e": 33933,
"s": 33911,
"text": "Dequeue a node from q"
},
{
"code": null,
"e": 33941,
"s": 33933,
"text": "Python3"
},
{
"code": "# Python program to print level# order traversal using Queue # A node structureclass Node: # A utility function to create a new node def __init__(self ,key): self.data = key self.left = None self.right = None # Iterative Method to print the# height of a binary treedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue # for level order traversal queue = [] # Enqueue Root and initialize height queue.append(root) while(len(queue) > 0): # Print front of queue and # remove it from queue print (queue[0].data) node = queue.pop(0) # Enqueue left child if node.left is not None: queue.append(node.left) # Enqueue right child if node.right is not None: queue.append(node.right) # Driver Program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5) print (\"Level Order Traversal of binary tree is -\")printLevelOrder(root)",
"e": 35031,
"s": 33941,
"text": null
},
{
"code": null,
"e": 35083,
"s": 35031,
"text": "Level Order Traversal of binary tree is -\n1\n2\n3\n4\n5"
},
{
"code": null,
"e": 35106,
"s": 35083,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 35447,
"s": 35106,
"text": "A graph is a nonlinear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as a Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes."
},
{
"code": null,
"e": 35558,
"s": 35447,
"text": "In the above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}."
},
{
"code": null,
"e": 35631,
"s": 35558,
"text": "The following two are the most commonly used representations of a graph."
},
{
"code": null,
"e": 35648,
"s": 35631,
"text": "Adjacency Matrix"
},
{
"code": null,
"e": 35663,
"s": 35648,
"text": "Adjacency List"
},
{
"code": null,
"e": 36071,
"s": 35663,
"text": "Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. The adjacency matrix for an undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w. "
},
{
"code": null,
"e": 36079,
"s": 36071,
"text": "Python3"
},
{
"code": "# A simple representation of graph using Adjacency Matrixclass Graph: def __init__(self,numvertex): self.adjMatrix = [[-1]*numvertex for x in range(numvertex)] self.numvertex = numvertex self.vertices = {} self.verticeslist =[0]*numvertex def set_vertex(self,vtx,id): if 0<=vtx<=self.numvertex: self.vertices[id] = vtx self.verticeslist[vtx] = id def set_edge(self,frm,to,cost=0): frm = self.vertices[frm] to = self.vertices[to] self.adjMatrix[frm][to] = cost # for directed graph do not add this self.adjMatrix[to][frm] = cost def get_vertex(self): return self.verticeslist def get_edges(self): edges=[] for i in range (self.numvertex): for j in range (self.numvertex): if (self.adjMatrix[i][j]!=-1): edges.append((self.verticeslist[i],self.verticeslist[j],self.adjMatrix[i][j])) return edges def get_matrix(self): return self.adjMatrix G =Graph(6)G.set_vertex(0,'a')G.set_vertex(1,'b')G.set_vertex(2,'c')G.set_vertex(3,'d')G.set_vertex(4,'e')G.set_vertex(5,'f')G.set_edge('a','e',10)G.set_edge('a','c',20)G.set_edge('c','b',30)G.set_edge('b','e',40)G.set_edge('e','d',50)G.set_edge('f','e',60) print(\"Vertices of Graph\")print(G.get_vertex()) print(\"Edges of Graph\")print(G.get_edges()) print(\"Adjacency Matrix of Graph\")print(G.get_matrix())",
"e": 37545,
"s": 36079,
"text": null
},
{
"code": null,
"e": 37552,
"s": 37545,
"text": "Output"
},
{
"code": null,
"e": 37570,
"s": 37552,
"text": "Vertices of Graph"
},
{
"code": null,
"e": 37601,
"s": 37570,
"text": "[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]"
},
{
"code": null,
"e": 37616,
"s": 37601,
"text": "Edges of Graph"
},
{
"code": null,
"e": 37809,
"s": 37616,
"text": "[(‘a’, ‘c’, 20), (‘a’, ‘e’, 10), (‘b’, ‘c’, 30), (‘b’, ‘e’, 40), (‘c’, ‘a’, 20), (‘c’, ‘b’, 30), (‘d’, ‘e’, 50), (‘e’, ‘a’, 10), (‘e’, ‘b’, 40), (‘e’, ‘d’, 50), (‘e’, ‘f’, 60), (‘f’, ‘e’, 60)]"
},
{
"code": null,
"e": 37835,
"s": 37809,
"text": "Adjacency Matrix of Graph"
},
{
"code": null,
"e": 37992,
"s": 37835,
"text": "[[-1, -1, 20, -1, 10, -1], [-1, -1, 30, -1, 40, -1], [20, 30, -1, -1, -1, -1], [-1, -1, -1, -1, 50, -1], [10, 40, -1, 50, -1, 60], [-1, -1, -1, -1, 60, -1]]"
},
{
"code": null,
"e": 38379,
"s": 37992,
"text": "An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation of the above graph. "
},
{
"code": null,
"e": 38389,
"s": 38381,
"text": "Python3"
},
{
"code": "# A class to represent the adjacency list of the nodeclass AdjNode: def __init__(self, data): self.vertex = data self.next = None # A class to represent a graph. A graph# is the list of the adjacency lists.# Size of the array will be the no. of the# vertices \"V\"class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V # Function to add an edge in an undirected graph def add_edge(self, src, dest): # Adding the node to the source node node = AdjNode(dest) node.next = self.graph[src] self.graph[src] = node # Adding the source node to the destination as # it is the undirected graph node = AdjNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function to print the graph def print_graph(self): for i in range(self.V): print(\"Adjacency list of vertex {}\\n head\".format(i), end=\"\") temp = self.graph[i] while temp: print(\" -> {}\".format(temp.vertex), end=\"\") temp = temp.next print(\" \\n\") # Driver program to the above graph classif __name__ == \"__main__\": V = 5 graph = Graph(V) graph.add_edge(0, 1) graph.add_edge(0, 4) graph.add_edge(1, 2) graph.add_edge(1, 3) graph.add_edge(1, 4) graph.add_edge(2, 3) graph.add_edge(3, 4) graph.print_graph()",
"e": 39825,
"s": 38389,
"text": null
},
{
"code": null,
"e": 40069,
"s": 39825,
"text": "Adjacency list of vertex 0\n head -> 4 -> 1 \n\nAdjacency list of vertex 1\n head -> 4 -> 3 -> 2 -> 0 \n\nAdjacency list of vertex 2\n head -> 3 -> 1 \n\nAdjacency list of vertex 3\n head -> 4 -> 2 -> 1 \n\nAdjacency list of vertex 4\n head -> 3 -> 1 -> 0 "
},
{
"code": null,
"e": 40097,
"s": 40069,
"text": "Breadth-First Search or BFS"
},
{
"code": null,
"e": 40449,
"s": 40097,
"text": "Breadth-First Traversal for a graph is similar to Breadth-First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex."
},
{
"code": null,
"e": 40798,
"s": 40449,
"text": "For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth-First Traversal of the following graph is 2, 0, 3, 1."
},
{
"code": null,
"e": 40808,
"s": 40800,
"text": "Python3"
},
{
"code": "# Python3 Program to print BFS traversal# from a given source vertex. BFS(int s)# traverses vertices reachable from s.from collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Function to print a BFS of graph def BFS(self, s): # Mark all the vertices as not visited visited = [False] * (max(self.graph) + 1) # Create a queue for BFS queue = [] # Mark the source node as # visited and enqueue it queue.append(s) visited[s] = True while queue: # Dequeue a vertex from # queue and print it s = queue.pop(0) print (s, end = \" \") # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in self.graph[s]: if visited[i] == False: queue.append(i) visited[i] = True # Driver code # Create a graph given in# the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print (\"Following is Breadth First Traversal\" \" (starting from vertex 2)\")g.BFS(2) # This code is contributed by Neelam Yadav",
"e": 42380,
"s": 40808,
"text": null
},
{
"code": null,
"e": 42451,
"s": 42380,
"text": "Following is Breadth First Traversal (starting from vertex 2)\n2 0 3 1 "
},
{
"code": null,
"e": 42565,
"s": 42451,
"text": "Time Complexity: O(V+E) where V is the number of vertices in the graph and E is the number of edges in the graph."
},
{
"code": null,
"e": 42591,
"s": 42565,
"text": "Depth First Search or DFS"
},
{
"code": null,
"e": 42838,
"s": 42591,
"text": "Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, a node may be visited twice. To avoid processing a node more than once, use a boolean visited array."
},
{
"code": null,
"e": 42849,
"s": 42838,
"text": "Algorithm:"
},
{
"code": null,
"e": 42931,
"s": 42849,
"text": "Create a recursive function that takes the index of the node and a visited array."
},
{
"code": null,
"e": 42984,
"s": 42931,
"text": "Mark the current node as visited and print the node."
},
{
"code": null,
"e": 43098,
"s": 42984,
"text": "Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node."
},
{
"code": null,
"e": 43106,
"s": 43098,
"text": "Python3"
},
{
"code": "# Python3 program to print DFS traversal# from a given graphfrom collections import defaultdict # This class represents a directed graph using# adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self, v, visited): # Mark the current node as visited # and print it visited.add(v) print(v, end=' ') # Recur for all the vertices # adjacent to this vertex for neighbour in self.graph[v]: if neighbour not in visited: self.DFSUtil(neighbour, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self, v): # Create a set to store visited vertices visited = set() # Call the recursive helper function # to print DFS traversal self.DFSUtil(v, visited) # Driver code # Create a graph given# in the above diagramg = Graph()g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) print(\"Following is DFS from (starting from vertex 2)\")g.DFS(2)",
"e": 44403,
"s": 43106,
"text": null
},
{
"code": null,
"e": 44459,
"s": 44403,
"text": "Following is DFS from (starting from vertex 2)\n2 0 1 3 "
},
{
"code": null,
"e": 44563,
"s": 44459,
"text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph."
},
{
"code": null,
"e": 44580,
"s": 44563,
"text": "punamsingh628700"
},
{
"code": null,
"e": 44594,
"s": 44580,
"text": "aadityappagar"
},
{
"code": null,
"e": 44609,
"s": 44594,
"text": "sagartomar9927"
},
{
"code": null,
"e": 44632,
"s": 44609,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 44639,
"s": 44632,
"text": "Python"
}
] |
Python – Summation of Unique elements | 27 Feb, 2020
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence it’s knowledge is good to have.
Method 1 : Naive method + sum()In naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element. The task of summation is performed using sum().
# Python 3 code to demonstrate # Summation of Unique elements# using naive methods + sum() # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print ("The original list is : " + str(test_list)) # using naive method + sum()# Summation of Unique elements# from list res = []for i in test_list: if i not in res: res.append(i)res = sum(res) # printing list after removal print ("The unique elements summation : " + str(res))
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The unique elements summation : 15
Method 2 : Using set() + sum()This is the most popular way by which the duplicated are removed from the list. After that the summation of list can be performed using sum().
# Python 3 code to demonstrate # Summation of Unique elements# using set() + sum() # initializing listtest_list = [1, 5, 3, 6, 3, 5, 6, 1]print ("The original list is : " + str(test_list)) # using set() + sum()# Summation of Unique elements# from list res = sum(list(set(test_list))) # Summation of Unique elements# using set() + sum()print ("The unique elements summation : " + str(res))
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The unique elements summation : 15
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence it’s knowledge is good to have."
},
{
"code": null,
"e": 514,
"s": 266,
"text": "Method 1 : Naive method + sum()In naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element. The task of summation is performed using sum()."
},
{
"code": "# Python 3 code to demonstrate # Summation of Unique elements# using naive methods + sum() # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print (\"The original list is : \" + str(test_list)) # using naive method + sum()# Summation of Unique elements# from list res = []for i in test_list: if i not in res: res.append(i)res = sum(res) # printing list after removal print (\"The unique elements summation : \" + str(res))",
"e": 951,
"s": 514,
"text": null
},
{
"code": null,
"e": 1035,
"s": 951,
"text": "The original list is : [1, 3, 5, 6, 3, 5, 6, 1]\nThe unique elements summation : 15\n"
},
{
"code": null,
"e": 1210,
"s": 1037,
"text": "Method 2 : Using set() + sum()This is the most popular way by which the duplicated are removed from the list. After that the summation of list can be performed using sum()."
},
{
"code": "# Python 3 code to demonstrate # Summation of Unique elements# using set() + sum() # initializing listtest_list = [1, 5, 3, 6, 3, 5, 6, 1]print (\"The original list is : \" + str(test_list)) # using set() + sum()# Summation of Unique elements# from list res = sum(list(set(test_list))) # Summation of Unique elements# using set() + sum()print (\"The unique elements summation : \" + str(res))",
"e": 1602,
"s": 1210,
"text": null
},
{
"code": null,
"e": 1686,
"s": 1602,
"text": "The original list is : [1, 3, 5, 6, 3, 5, 6, 1]\nThe unique elements summation : 15\n"
},
{
"code": null,
"e": 1707,
"s": 1686,
"text": "Python list-programs"
},
{
"code": null,
"e": 1714,
"s": 1707,
"text": "Python"
},
{
"code": null,
"e": 1730,
"s": 1714,
"text": "Python Programs"
}
] |
How to customize Django forms using Django Widget Tweaks ? | 04 Jan, 2021
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn’t easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id to individual fields in forms.
Let’s say, we are having a simple Django form that will have four fields:
First Name
Last Name
Username (available default)
Password (available default)
Confirm Password (available default)
We are not going to discuss how we create this form but rather than we are going to see how to customize the frontend of Django forms. To create a form in Django you can check out – How to create a form using Django Forms ?
The initial Django forms (available default looks like)
The default Django form
which will have a simple code like
HTML
{{form}} <input type="submit" value="submit">
Of course, there are many default methods that Django provide us by default like using form.as_p which looks like
Django form using as_p
that will have a simple code like
HTML
{{form.as_p}}<input type="submit" value="submit">
But we need to add custom classes and CSS to forms.
So, Let’s see how to make it look good like this
Django form input form customized
So we are going to implement it using Django Widget Tweaks. Let’s install django-widget-tweaks using pip
pip install django-widget-tweaks
Now go to the INSTALLED_APPS in settings.pyand add widget_tweaks in INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.auth',
#...........(some more apps already here maybe)......
'widget_tweaks',
#...........(some more apps already here maybe)......
]
So Now we have Django widget tweaks installed let’s import it in the HTML file in which we are workingwrite this
{% load widget_tweaks %}
in the top of your HTML page and we have to simply change Every field:
HTML
{% load widget_tweaks %} <div class="form-group"> // first_name is the name by which first name is created in django forms {% render_field form.first_name class="form-control" placeholder="First Name" type="text" %}</div> <div class="form-group"> // last_name is the name by which last name is created in django forms {% render_field form.last_name type="text" class="form-control" placeholder="Last Name" %}</div> <div class="form-group"> // username is the default name of username in django forms {% render_field form.username type="text" class="form-control" id="exampleInputUsername" placeholder="Username" %}</div> <div class="form-group"> // password1 is the default name of password in django forms {% render_field form.password1 type="password" class="form-control" id="exampleInputPassword" placeholder="Password" %}</div> <div class="form-group"> // password2 is the default name of confirm password in django forms {% render_field form.password2 type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password" %}</div> <div> <button type="submit" value="Submit" > Register </button></div>
Each field’s name has been explained in “// ” in code. In the CSS file, we will have all our code for customizing each filed by class or id.
So let’s see how Django tweaks help us See in each of the fields, we have our class because of which we can add any CSS by our choice. So, we have to just design the HTML with css, and use it in Django by just replacing the input tag with render_field and form.field_name with {% %} at the end and design it with our choice.
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 434,
"s": 52,
"text": "Django forms are a great feature to create usable forms with just few lines of code. But Django doesn’t easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id to individual fields in forms."
},
{
"code": null,
"e": 508,
"s": 434,
"text": "Let’s say, we are having a simple Django form that will have four fields:"
},
{
"code": null,
"e": 519,
"s": 508,
"text": "First Name"
},
{
"code": null,
"e": 529,
"s": 519,
"text": "Last Name"
},
{
"code": null,
"e": 558,
"s": 529,
"text": "Username (available default)"
},
{
"code": null,
"e": 587,
"s": 558,
"text": "Password (available default)"
},
{
"code": null,
"e": 624,
"s": 587,
"text": "Confirm Password (available default)"
},
{
"code": null,
"e": 848,
"s": 624,
"text": "We are not going to discuss how we create this form but rather than we are going to see how to customize the frontend of Django forms. To create a form in Django you can check out – How to create a form using Django Forms ?"
},
{
"code": null,
"e": 904,
"s": 848,
"text": "The initial Django forms (available default looks like)"
},
{
"code": null,
"e": 928,
"s": 904,
"text": "The default Django form"
},
{
"code": null,
"e": 963,
"s": 928,
"text": "which will have a simple code like"
},
{
"code": null,
"e": 968,
"s": 963,
"text": "HTML"
},
{
"code": "{{form}} <input type=\"submit\" value=\"submit\">",
"e": 1014,
"s": 968,
"text": null
},
{
"code": null,
"e": 1129,
"s": 1014,
"text": "Of course, there are many default methods that Django provide us by default like using form.as_p which looks like"
},
{
"code": null,
"e": 1153,
"s": 1129,
"text": "Django form using as_p "
},
{
"code": null,
"e": 1187,
"s": 1153,
"text": "that will have a simple code like"
},
{
"code": null,
"e": 1192,
"s": 1187,
"text": "HTML"
},
{
"code": "{{form.as_p}}<input type=\"submit\" value=\"submit\">",
"e": 1242,
"s": 1192,
"text": null
},
{
"code": null,
"e": 1295,
"s": 1242,
"text": "But we need to add custom classes and CSS to forms. "
},
{
"code": null,
"e": 1344,
"s": 1295,
"text": "So, Let’s see how to make it look good like this"
},
{
"code": null,
"e": 1378,
"s": 1344,
"text": "Django form input form customized"
},
{
"code": null,
"e": 1483,
"s": 1378,
"text": "So we are going to implement it using Django Widget Tweaks. Let’s install django-widget-tweaks using pip"
},
{
"code": null,
"e": 1517,
"s": 1483,
"text": "pip install django-widget-tweaks\n"
},
{
"code": null,
"e": 1600,
"s": 1517,
"text": "Now go to the INSTALLED_APPS in settings.pyand add widget_tweaks in INSTALLED_APPS"
},
{
"code": null,
"e": 1779,
"s": 1600,
"text": "INSTALLED_APPS = [\n 'django.contrib.auth',\n\n#...........(some more apps already here maybe)......\n \n'widget_tweaks',\n\n#...........(some more apps already here maybe)......\n]\n"
},
{
"code": null,
"e": 1892,
"s": 1779,
"text": "So Now we have Django widget tweaks installed let’s import it in the HTML file in which we are workingwrite this"
},
{
"code": null,
"e": 1917,
"s": 1892,
"text": "{% load widget_tweaks %}"
},
{
"code": null,
"e": 1988,
"s": 1917,
"text": "in the top of your HTML page and we have to simply change Every field:"
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "HTML"
},
{
"code": "{% load widget_tweaks %} <div class=\"form-group\"> // first_name is the name by which first name is created in django forms {% render_field form.first_name class=\"form-control\" placeholder=\"First Name\" type=\"text\" %}</div> <div class=\"form-group\"> // last_name is the name by which last name is created in django forms {% render_field form.last_name type=\"text\" class=\"form-control\" placeholder=\"Last Name\" %}</div> <div class=\"form-group\"> // username is the default name of username in django forms {% render_field form.username type=\"text\" class=\"form-control\" id=\"exampleInputUsername\" placeholder=\"Username\" %}</div> <div class=\"form-group\"> // password1 is the default name of password in django forms {% render_field form.password1 type=\"password\" class=\"form-control\" id=\"exampleInputPassword\" placeholder=\"Password\" %}</div> <div class=\"form-group\"> // password2 is the default name of confirm password in django forms {% render_field form.password2 type=\"password\" class=\"form-control\" id=\"exampleInputPassword1\" placeholder=\"Confirm Password\" %}</div> <div> <button type=\"submit\" value=\"Submit\" > Register </button></div>",
"e": 3146,
"s": 1993,
"text": null
},
{
"code": null,
"e": 3287,
"s": 3146,
"text": "Each field’s name has been explained in “// ” in code. In the CSS file, we will have all our code for customizing each filed by class or id."
},
{
"code": null,
"e": 3612,
"s": 3287,
"text": "So let’s see how Django tweaks help us See in each of the fields, we have our class because of which we can add any CSS by our choice. So, we have to just design the HTML with css, and use it in Django by just replacing the input tag with render_field and form.field_name with {% %} at the end and design it with our choice."
},
{
"code": null,
"e": 3626,
"s": 3612,
"text": "Python Django"
},
{
"code": null,
"e": 3633,
"s": 3626,
"text": "Python"
}
] |
Unified Modeling Language (UML) | Object Diagrams | 13 Feb, 2018
An Object Diagram can be referred to as a screenshot of the instances in a system and the relationship that exists between them. Since object diagrams depict behaviour when objects have been instantiated, we are able to study the behavior of the system at a particular instant. Object diagrams are vital to portray and understand functional requirements of a system.In other words, “An object diagram in the Unified Modeling Language (UML), is a diagram that shows a complete or partial view of the structure of a modeled system at a specific time.”
Difference between an Object and a Class Diagram –An object diagram is similar to a class diagram except it shows the instances of classes in the system. We depict actual classifiers and their relationships making the use of class diagrams. On the other hand, an Object Diagram represents specific instances of classes and relationships between them at a point of time.
What is a classifier?
In UML a classifier refers to a group of elements that have some common features like methods, attributes and operations. A classifier can be thought of as an abstract metaclass which draws a boundary for a group of instances having common static and dynamic features. For example, we refer a class, an object, a component, or a deployment node as classifiers in UML since they define a common set of properties.
An Object Diagram is a structural diagram which uses notation similar to that of class diagrams. We are able to design object diagrams by instantiating classifiers.
Object Diagrams use real world examples to depict the nature and structure of the system at a particular point in time. Since we are able to use data available within objects, Object diagrams provide a clearer view of the relationships that exist between objects.
Figure – a class and its corresponding object
Objects or Instance specifications – When we instantiate a classifier in a system, the object we create represents an entity which exists in the system.We can represent the changes in object over time by creating multiple instance specifications. We use a rectangle to represent an object in an Object Diagram. An object is generally linked to other objects in an object diagram.Figure – notation for an ObjectFor example – In the figure below, two objects of class Student are linked to an object of class College.Figure – an object diagram using a link and 3 objectsLinks – We use a link to represent a relationship between two objects.Figure – notation for a linkWe represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects.NotationMeaning0..1Zero or one1One only0..*Zero or more*Zero or more1..*One or more7Seven only0..2Zero or two4..7Four to sevenDependency Relationships – We use a dependency relationship to show when one element depends on another element.Figure – notation for dependency relationshipClass diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”).Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class.Figure – an object diagram using a dependency relationshipAssociation – Association is a reference relationship between two objects (or classes).Figure – notation for associationWhenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class.Figure – an object diagram using associationAggregation – Aggregation represents a “has a” relationship.Figure – notation for aggregationAggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects.Figure – an object diagram using aggregationFor example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object.Composition – Composition is a type of association where the child cannot exist independent of the other.Figure – notation for compositionComposition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object.Figure – an object diagram using compositionFor Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank.Figure – a bank is composed of accounts
Objects or Instance specifications – When we instantiate a classifier in a system, the object we create represents an entity which exists in the system.We can represent the changes in object over time by creating multiple instance specifications. We use a rectangle to represent an object in an Object Diagram. An object is generally linked to other objects in an object diagram.Figure – notation for an ObjectFor example – In the figure below, two objects of class Student are linked to an object of class College.Figure – an object diagram using a link and 3 objects
Figure – notation for an Object
For example – In the figure below, two objects of class Student are linked to an object of class College.
Figure – an object diagram using a link and 3 objects
Links – We use a link to represent a relationship between two objects.Figure – notation for a linkWe represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects.NotationMeaning0..1Zero or one1One only0..*Zero or more*Zero or more1..*One or more7Seven only0..2Zero or two4..7Four to seven
Figure – notation for a link
We represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects.
Dependency Relationships – We use a dependency relationship to show when one element depends on another element.Figure – notation for dependency relationshipClass diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”).Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class.Figure – an object diagram using a dependency relationship
Figure – notation for dependency relationship
Class diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”).
Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class.
Figure – an object diagram using a dependency relationship
Association – Association is a reference relationship between two objects (or classes).Figure – notation for associationWhenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class.Figure – an object diagram using association
Figure – notation for association
Whenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class.
Figure – an object diagram using association
Aggregation – Aggregation represents a “has a” relationship.Figure – notation for aggregationAggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects.Figure – an object diagram using aggregationFor example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object.
Figure – notation for aggregation
Aggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects.
Figure – an object diagram using aggregation
For example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object.
Composition – Composition is a type of association where the child cannot exist independent of the other.Figure – notation for compositionComposition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object.Figure – an object diagram using compositionFor Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank.Figure – a bank is composed of accounts
Figure – notation for composition
Composition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object.
Figure – an object diagram using composition
For Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank.
Figure – a bank is composed of accounts
Association and dependency are often confused in their usage. A source of confusion was the use of transient links in UML 1. Meta-models are now handled differently in UML 2 and the issue has been resolved.
There are a large number of dependencies in a system. We only represent the ones which are essential to convey for understanding the system. We need to understand that every association implies a dependency itself. We , however, prefer not to draw it separately. An association implies a dependency similar to a way in which generalization does.
Draw all the necessary class diagrams for the system.Identify the crucial points in time where a system snapshot is needed.Identify the objects which cover crucial functionality of the system.Identify the relationship between objects drawn.
Draw all the necessary class diagrams for the system.
Identify the crucial points in time where a system snapshot is needed.
Identify the objects which cover crucial functionality of the system.
Identify the relationship between objects drawn.
Model the static design(similar to class diagrams ) or structure of a system using prototypical instances and real data.
Helps us to understand the functionalities that the system should deliver to the users.
Understand relationships between objects.
Visualise, document, construct and design a static frame showing instances of objects and their relationships in the dynamic story of life of a system.
Verify the class diagrams for completeness and accuracy by using Object Diagrams as specific test cases.
Discover facts and dependencies between specific instances and depicting specific examples of classifiers.
This article is contributed by Ankit Jain . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
UML
Design Pattern
UML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Feb, 2018"
},
{
"code": null,
"e": 602,
"s": 52,
"text": "An Object Diagram can be referred to as a screenshot of the instances in a system and the relationship that exists between them. Since object diagrams depict behaviour when objects have been instantiated, we are able to study the behavior of the system at a particular instant. Object diagrams are vital to portray and understand functional requirements of a system.In other words, “An object diagram in the Unified Modeling Language (UML), is a diagram that shows a complete or partial view of the structure of a modeled system at a specific time.”"
},
{
"code": null,
"e": 972,
"s": 602,
"text": "Difference between an Object and a Class Diagram –An object diagram is similar to a class diagram except it shows the instances of classes in the system. We depict actual classifiers and their relationships making the use of class diagrams. On the other hand, an Object Diagram represents specific instances of classes and relationships between them at a point of time."
},
{
"code": null,
"e": 994,
"s": 972,
"text": "What is a classifier?"
},
{
"code": null,
"e": 1407,
"s": 994,
"text": "In UML a classifier refers to a group of elements that have some common features like methods, attributes and operations. A classifier can be thought of as an abstract metaclass which draws a boundary for a group of instances having common static and dynamic features. For example, we refer a class, an object, a component, or a deployment node as classifiers in UML since they define a common set of properties."
},
{
"code": null,
"e": 1572,
"s": 1407,
"text": "An Object Diagram is a structural diagram which uses notation similar to that of class diagrams. We are able to design object diagrams by instantiating classifiers."
},
{
"code": null,
"e": 1836,
"s": 1572,
"text": "Object Diagrams use real world examples to depict the nature and structure of the system at a particular point in time. Since we are able to use data available within objects, Object diagrams provide a clearer view of the relationships that exist between objects."
},
{
"code": null,
"e": 1882,
"s": 1836,
"text": "Figure – a class and its corresponding object"
},
{
"code": null,
"e": 6157,
"s": 1882,
"text": "Objects or Instance specifications – When we instantiate a classifier in a system, the object we create represents an entity which exists in the system.We can represent the changes in object over time by creating multiple instance specifications. We use a rectangle to represent an object in an Object Diagram. An object is generally linked to other objects in an object diagram.Figure – notation for an ObjectFor example – In the figure below, two objects of class Student are linked to an object of class College.Figure – an object diagram using a link and 3 objectsLinks – We use a link to represent a relationship between two objects.Figure – notation for a linkWe represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects.NotationMeaning0..1Zero or one1One only0..*Zero or more*Zero or more1..*One or more7Seven only0..2Zero or two4..7Four to sevenDependency Relationships – We use a dependency relationship to show when one element depends on another element.Figure – notation for dependency relationshipClass diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”).Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class.Figure – an object diagram using a dependency relationshipAssociation – Association is a reference relationship between two objects (or classes).Figure – notation for associationWhenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class.Figure – an object diagram using associationAggregation – Aggregation represents a “has a” relationship.Figure – notation for aggregationAggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects.Figure – an object diagram using aggregationFor example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object.Composition – Composition is a type of association where the child cannot exist independent of the other.Figure – notation for compositionComposition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object.Figure – an object diagram using compositionFor Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank.Figure – a bank is composed of accounts"
},
{
"code": null,
"e": 6726,
"s": 6157,
"text": "Objects or Instance specifications – When we instantiate a classifier in a system, the object we create represents an entity which exists in the system.We can represent the changes in object over time by creating multiple instance specifications. We use a rectangle to represent an object in an Object Diagram. An object is generally linked to other objects in an object diagram.Figure – notation for an ObjectFor example – In the figure below, two objects of class Student are linked to an object of class College.Figure – an object diagram using a link and 3 objects"
},
{
"code": null,
"e": 6758,
"s": 6726,
"text": "Figure – notation for an Object"
},
{
"code": null,
"e": 6864,
"s": 6758,
"text": "For example – In the figure below, two objects of class Student are linked to an object of class College."
},
{
"code": null,
"e": 6918,
"s": 6864,
"text": "Figure – an object diagram using a link and 3 objects"
},
{
"code": null,
"e": 7449,
"s": 6918,
"text": "Links – We use a link to represent a relationship between two objects.Figure – notation for a linkWe represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects.NotationMeaning0..1Zero or one1One only0..*Zero or more*Zero or more1..*One or more7Seven only0..2Zero or two4..7Four to seven"
},
{
"code": null,
"e": 7478,
"s": 7449,
"text": "Figure – notation for a link"
},
{
"code": null,
"e": 7785,
"s": 7478,
"text": "We represent the number of participants on the link for each end of the link. We use the term association for a relationship between two classifiers. The term link is used to specify a relationship between two instance specifications or objects. We use a solid line to represent a link between two objects."
},
{
"code": null,
"e": 8683,
"s": 7785,
"text": "Dependency Relationships – We use a dependency relationship to show when one element depends on another element.Figure – notation for dependency relationshipClass diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”).Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class.Figure – an object diagram using a dependency relationship"
},
{
"code": null,
"e": 8729,
"s": 8683,
"text": "Figure – notation for dependency relationship"
},
{
"code": null,
"e": 9194,
"s": 8729,
"text": "Class diagrams, component diagrams, deployment and object diagrams use dependency relationships. A dependency is used to depict the relationship between dependent and independent entities in the system.Any change in the definition or structure of one element may cause changes to the other. This is a unidirectional kind of relationship between two objects.Dependency relationships are of various types specified with keywords (sometimes within angular brackets”)."
},
{
"code": null,
"e": 9413,
"s": 9194,
"text": "Abstraction,Binding, Realization, Substitution and Usage are the types of dependency relationships used in UML.For example – In the figure below, an object of Player class is dependent (or uses) an object of Bat class."
},
{
"code": null,
"e": 9472,
"s": 9413,
"text": "Figure – an object diagram using a dependency relationship"
},
{
"code": null,
"e": 9954,
"s": 9472,
"text": "Association – Association is a reference relationship between two objects (or classes).Figure – notation for associationWhenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class.Figure – an object diagram using association"
},
{
"code": null,
"e": 9988,
"s": 9954,
"text": "Figure – notation for association"
},
{
"code": null,
"e": 10306,
"s": 9988,
"text": "Whenever an object uses another it is called an association.We use association when one object references members of the other object. Association can be uni-directional or bi-directional. We use an arrow to represent association.For example – The object of Order class is associated with an object of Customer class."
},
{
"code": null,
"e": 10351,
"s": 10306,
"text": "Figure – an object diagram using association"
},
{
"code": null,
"e": 11259,
"s": 10351,
"text": "Aggregation – Aggregation represents a “has a” relationship.Figure – notation for aggregationAggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects.Figure – an object diagram using aggregationFor example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object."
},
{
"code": null,
"e": 11293,
"s": 11259,
"text": "Figure – notation for aggregation"
},
{
"code": null,
"e": 11687,
"s": 11293,
"text": "Aggregation is a specific form of association.on relationship; aggregation is more specific than ordinary association. It is an association that represents a part-whole or part-of relationship. It is a kind of parent -child relationship however it isn’t inheritance. Aggregation occurs when the lifecycle of the contained objects does not strongly depend on the lifecycle of container objects."
},
{
"code": null,
"e": 11732,
"s": 11687,
"text": "Figure – an object diagram using aggregation"
},
{
"code": null,
"e": 12110,
"s": 11732,
"text": "For example – A library has an aggregation relationship with books. Library has books or books are a part of library. The existence of books is independent of the existence of the library.While implementing, there isn’t a lot of difference between aggregation and association. We use a hollow diamond on the containing object with a line which joins it to the contained object."
},
{
"code": null,
"e": 13002,
"s": 12110,
"text": "Composition – Composition is a type of association where the child cannot exist independent of the other.Figure – notation for compositionComposition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object.Figure – an object diagram using compositionFor Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank.Figure – a bank is composed of accounts"
},
{
"code": null,
"e": 13036,
"s": 13002,
"text": "Figure – notation for composition"
},
{
"code": null,
"e": 13584,
"s": 13036,
"text": "Composition is also a special type of association. It is also a kind of parent child relationship but it is not inheritance. Consider the example of a boy Gurkaran: Gurkaran is composed of legs and arms. Here Gurkaran has a composition relationship with his legs and arms. Here legs and arms cant exist without the existence of their parent object. So whenever independent existence of the child is not possible we use a composition relationship. We use a filled diamond on the containing object with a line which joins it to the contained object."
},
{
"code": null,
"e": 13629,
"s": 13584,
"text": "Figure – an object diagram using composition"
},
{
"code": null,
"e": 13753,
"s": 13629,
"text": "For Example – In the figure below, consider the object Bank1. Here an account cannot exist without the existence of a bank."
},
{
"code": null,
"e": 13793,
"s": 13753,
"text": "Figure – a bank is composed of accounts"
},
{
"code": null,
"e": 14000,
"s": 13793,
"text": "Association and dependency are often confused in their usage. A source of confusion was the use of transient links in UML 1. Meta-models are now handled differently in UML 2 and the issue has been resolved."
},
{
"code": null,
"e": 14346,
"s": 14000,
"text": "There are a large number of dependencies in a system. We only represent the ones which are essential to convey for understanding the system. We need to understand that every association implies a dependency itself. We , however, prefer not to draw it separately. An association implies a dependency similar to a way in which generalization does."
},
{
"code": null,
"e": 14587,
"s": 14346,
"text": "Draw all the necessary class diagrams for the system.Identify the crucial points in time where a system snapshot is needed.Identify the objects which cover crucial functionality of the system.Identify the relationship between objects drawn."
},
{
"code": null,
"e": 14641,
"s": 14587,
"text": "Draw all the necessary class diagrams for the system."
},
{
"code": null,
"e": 14712,
"s": 14641,
"text": "Identify the crucial points in time where a system snapshot is needed."
},
{
"code": null,
"e": 14782,
"s": 14712,
"text": "Identify the objects which cover crucial functionality of the system."
},
{
"code": null,
"e": 14831,
"s": 14782,
"text": "Identify the relationship between objects drawn."
},
{
"code": null,
"e": 14952,
"s": 14831,
"text": "Model the static design(similar to class diagrams ) or structure of a system using prototypical instances and real data."
},
{
"code": null,
"e": 15040,
"s": 14952,
"text": "Helps us to understand the functionalities that the system should deliver to the users."
},
{
"code": null,
"e": 15082,
"s": 15040,
"text": "Understand relationships between objects."
},
{
"code": null,
"e": 15234,
"s": 15082,
"text": "Visualise, document, construct and design a static frame showing instances of objects and their relationships in the dynamic story of life of a system."
},
{
"code": null,
"e": 15339,
"s": 15234,
"text": "Verify the class diagrams for completeness and accuracy by using Object Diagrams as specific test cases."
},
{
"code": null,
"e": 15446,
"s": 15339,
"text": "Discover facts and dependencies between specific instances and depicting specific examples of classifiers."
},
{
"code": null,
"e": 15745,
"s": 15446,
"text": "This article is contributed by Ankit Jain . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 15870,
"s": 15745,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15874,
"s": 15870,
"text": "UML"
},
{
"code": null,
"e": 15889,
"s": 15874,
"text": "Design Pattern"
},
{
"code": null,
"e": 15893,
"s": 15889,
"text": "UML"
}
] |
std::to_wstring in c++ | 14 Sep, 2021
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function. In this function data type is being internally typecasted to the wstring data type and bypassing the numerical value as its parameter we can obtain a wstring type of string in return where the numerical value has been typecasted to the desired data type.
Syntax :
wstring to_wstring (int val);
wstring to_wstring (long long val);
wstring to_wstring (float val);
wstring to_wstring (double val);
Parameters :
val :This is the numerical value that is to be converted to the wide string.
Return Value :
It returns the passed numerical value into the wide string of data type wstring.
C++
// C++ code to convert numerical value// to wide string data type// using the to_wstring function // These header files contains wcout,// wstring and to_wstring#include <iostream>#include <string> using namespace std; //Driver codeint main (){ // Data types to be typecastedfloat x = 3.1415926;int a = 5 , b = 9;double y = 6.29; // numerical values being typecasted into wstringwstring pi = L"Pi is " + to_wstring(x);wstring perfect = to_wstring(a+b) + L" is a number";wstring num = to_wstring(y/x) + L"is division of two numbers"; // Printing the typecasted wstringwcout << pi << L'\n';wcout << perfect << L'\n';wcout << num <<L'\n';return 0;}
Output:
Pi is 3.141593
14 is a number
2.002169is division of two numbers
Applications : It can be used for calculation to be used in report statement such as average value so we need not write any statement for this purpose and we can directly use this function to convert numerical values.
Example: Suppose the HOD of a department is filing a report for number of sections in his department and he has to avoid data type casting so he can use to_wstring function to do this particular task.
Below is the implementation :
C++
// These header files contains wcout and wstring#include <iostream>#include <string> using namespace std; // Driver codeint main (){ // Data types to be typecastedint a = 600 , b = 150; // numerical values being typecasted into wstringwstring rep = L"Number of section = " + to_wstring(a/b);wstring sec_rep = to_wstring(b) + L" is the number of students in each section"; // Printing the typecasted wstringwcout << rep << L'\n';wcout << sec_rep << L'\n';return 0;}
Output:
Number of section = 4
150 is the number of students in each section
In the above example we need not typecast the data type every time but with the help of this function external typecasting is avoided which is beneficial for the system as external typecasting takes more time then the stl functions.
arorakashish0911
sweetyty
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 556,
"s": 28,
"text": "This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function. In this function data type is being internally typecasted to the wstring data type and bypassing the numerical value as its parameter we can obtain a wstring type of string in return where the numerical value has been typecasted to the desired data type. "
},
{
"code": null,
"e": 566,
"s": 556,
"text": "Syntax : "
},
{
"code": null,
"e": 884,
"s": 566,
"text": "wstring to_wstring (int val);\nwstring to_wstring (long long val);\nwstring to_wstring (float val);\nwstring to_wstring (double val);\nParameters :\nval :This is the numerical value that is to be converted to the wide string.\n\nReturn Value :\nIt returns the passed numerical value into the wide string of data type wstring."
},
{
"code": null,
"e": 888,
"s": 884,
"text": "C++"
},
{
"code": "// C++ code to convert numerical value// to wide string data type// using the to_wstring function // These header files contains wcout,// wstring and to_wstring#include <iostream>#include <string> using namespace std; //Driver codeint main (){ // Data types to be typecastedfloat x = 3.1415926;int a = 5 , b = 9;double y = 6.29; // numerical values being typecasted into wstringwstring pi = L\"Pi is \" + to_wstring(x);wstring perfect = to_wstring(a+b) + L\" is a number\";wstring num = to_wstring(y/x) + L\"is division of two numbers\"; // Printing the typecasted wstringwcout << pi << L'\\n';wcout << perfect << L'\\n';wcout << num <<L'\\n';return 0;}",
"e": 1574,
"s": 888,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1574,
"text": "Output: "
},
{
"code": null,
"e": 1648,
"s": 1583,
"text": "Pi is 3.141593\n14 is a number\n2.002169is division of two numbers"
},
{
"code": null,
"e": 1866,
"s": 1648,
"text": "Applications : It can be used for calculation to be used in report statement such as average value so we need not write any statement for this purpose and we can directly use this function to convert numerical values."
},
{
"code": null,
"e": 2068,
"s": 1866,
"text": "Example: Suppose the HOD of a department is filing a report for number of sections in his department and he has to avoid data type casting so he can use to_wstring function to do this particular task. "
},
{
"code": null,
"e": 2099,
"s": 2068,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 2103,
"s": 2099,
"text": "C++"
},
{
"code": "// These header files contains wcout and wstring#include <iostream>#include <string> using namespace std; // Driver codeint main (){ // Data types to be typecastedint a = 600 , b = 150; // numerical values being typecasted into wstringwstring rep = L\"Number of section = \" + to_wstring(a/b);wstring sec_rep = to_wstring(b) + L\" is the number of students in each section\"; // Printing the typecasted wstringwcout << rep << L'\\n';wcout << sec_rep << L'\\n';return 0;}",
"e": 2583,
"s": 2103,
"text": null
},
{
"code": null,
"e": 2592,
"s": 2583,
"text": "Output: "
},
{
"code": null,
"e": 2661,
"s": 2592,
"text": "Number of section = 4\n150 is the number of students in each section"
},
{
"code": null,
"e": 2896,
"s": 2661,
"text": "In the above example we need not typecast the data type every time but with the help of this function external typecasting is avoided which is beneficial for the system as external typecasting takes more time then the stl functions. "
},
{
"code": null,
"e": 2913,
"s": 2896,
"text": "arorakashish0911"
},
{
"code": null,
"e": 2922,
"s": 2913,
"text": "sweetyty"
},
{
"code": null,
"e": 2926,
"s": 2922,
"text": "STL"
},
{
"code": null,
"e": 2930,
"s": 2926,
"text": "C++"
},
{
"code": null,
"e": 2934,
"s": 2930,
"text": "STL"
},
{
"code": null,
"e": 2938,
"s": 2934,
"text": "CPP"
}
] |
How to Convert MySQL Table Field Type from BLOB to JSON? | 16 Dec, 2021
In this article, we would be learning a MySQL query to convert a field of BLOB Data Type to JSON Data Type in a table. To execute this query, we would need to alter the table and subsequently the field’s definition. We would first need to use the ALTER TABLE command to start making changes to the table.
ALTER TABLE: ALTER TABLE is a command used to add, delete, or modify fields in an existing table. It is also used to add and drop various constraints on an existing table. We have two commands for alter table, MODIFY and CHANGE.
Step 1: Database Creation
Creation of a Database is done by using the CREATE DATABASE command in MySQL.
Query:
CREATE DATABASE geek;
Step 2: Change Database in use, to one we created.
To use a particular database among multiple ones or to specify the database whose data we are interested in,we use the USE command in MySQL.
Query:
USE geek;
Step 3: MySQL Table creation
We are going to create a table in MySQL where one field has BLOB values. Please note you can do this with multiple fields in a table.
Query:
CREATE TABLE table1(ID INT,
DOCS BLOB,
REVIEW VARCHAR(100));
Step 4: Showing structure of the table
We will use the DESCRIBE table command to cross-check if our table has created a field with BLOB Data Type.
Query:
DESCRIBE table1;
Output:
Step 5: Changing field Data Type from BLOB to JSON. DOCS field would be changed as it is of the BLOB Data Type.
Method 1: USING MODIFY command
To change a field definition use MODIFY along with the ALTER command.
Query:
ALTER TABLE table1
MODIFY DOCS JSON;
Method 2: USING CHANGE
The syntax of the CHANGE command is different. After the CHANGE keyword, we name the field that has to be changed, then specify the new definition of the field, which includes the name of the changed field. Here we are changing the name of DOCS to DOCS_CHANGE.
Query:
ALTER TABLE table1 CHANGE
DOCS DOCS_CHANGE JSON;
Step 6: Use the DESCRIBE command to see the changes made for each of the commands : MODIFY and CHANGE.
DESCRIBE table1;
Output: Results after using MODIFY
Output: Results after using CHANGE
mysql
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 359,
"s": 54,
"text": "In this article, we would be learning a MySQL query to convert a field of BLOB Data Type to JSON Data Type in a table. To execute this query, we would need to alter the table and subsequently the field’s definition. We would first need to use the ALTER TABLE command to start making changes to the table."
},
{
"code": null,
"e": 588,
"s": 359,
"text": "ALTER TABLE: ALTER TABLE is a command used to add, delete, or modify fields in an existing table. It is also used to add and drop various constraints on an existing table. We have two commands for alter table, MODIFY and CHANGE."
},
{
"code": null,
"e": 614,
"s": 588,
"text": "Step 1: Database Creation"
},
{
"code": null,
"e": 692,
"s": 614,
"text": "Creation of a Database is done by using the CREATE DATABASE command in MySQL."
},
{
"code": null,
"e": 701,
"s": 692,
"text": "Query: "
},
{
"code": null,
"e": 723,
"s": 701,
"text": "CREATE DATABASE geek;"
},
{
"code": null,
"e": 774,
"s": 723,
"text": "Step 2: Change Database in use, to one we created."
},
{
"code": null,
"e": 915,
"s": 774,
"text": "To use a particular database among multiple ones or to specify the database whose data we are interested in,we use the USE command in MySQL."
},
{
"code": null,
"e": 923,
"s": 915,
"text": "Query: "
},
{
"code": null,
"e": 933,
"s": 923,
"text": "USE geek;"
},
{
"code": null,
"e": 962,
"s": 933,
"text": "Step 3: MySQL Table creation"
},
{
"code": null,
"e": 1096,
"s": 962,
"text": "We are going to create a table in MySQL where one field has BLOB values. Please note you can do this with multiple fields in a table."
},
{
"code": null,
"e": 1105,
"s": 1096,
"text": "Query: "
},
{
"code": null,
"e": 1166,
"s": 1105,
"text": "CREATE TABLE table1(ID INT,\nDOCS BLOB,\nREVIEW VARCHAR(100));"
},
{
"code": null,
"e": 1205,
"s": 1166,
"text": "Step 4: Showing structure of the table"
},
{
"code": null,
"e": 1313,
"s": 1205,
"text": "We will use the DESCRIBE table command to cross-check if our table has created a field with BLOB Data Type."
},
{
"code": null,
"e": 1320,
"s": 1313,
"text": "Query:"
},
{
"code": null,
"e": 1337,
"s": 1320,
"text": "DESCRIBE table1;"
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Output:"
},
{
"code": null,
"e": 1457,
"s": 1345,
"text": "Step 5: Changing field Data Type from BLOB to JSON. DOCS field would be changed as it is of the BLOB Data Type."
},
{
"code": null,
"e": 1488,
"s": 1457,
"text": "Method 1: USING MODIFY command"
},
{
"code": null,
"e": 1558,
"s": 1488,
"text": "To change a field definition use MODIFY along with the ALTER command."
},
{
"code": null,
"e": 1567,
"s": 1558,
"text": "Query: "
},
{
"code": null,
"e": 1604,
"s": 1567,
"text": "ALTER TABLE table1\nMODIFY DOCS JSON;"
},
{
"code": null,
"e": 1629,
"s": 1604,
"text": "Method 2: USING CHANGE "
},
{
"code": null,
"e": 1890,
"s": 1629,
"text": "The syntax of the CHANGE command is different. After the CHANGE keyword, we name the field that has to be changed, then specify the new definition of the field, which includes the name of the changed field. Here we are changing the name of DOCS to DOCS_CHANGE."
},
{
"code": null,
"e": 1899,
"s": 1890,
"text": "Query: "
},
{
"code": null,
"e": 1950,
"s": 1899,
"text": "ALTER TABLE table1 CHANGE \nDOCS DOCS_CHANGE JSON;"
},
{
"code": null,
"e": 2053,
"s": 1950,
"text": "Step 6: Use the DESCRIBE command to see the changes made for each of the commands : MODIFY and CHANGE."
},
{
"code": null,
"e": 2070,
"s": 2053,
"text": "DESCRIBE table1;"
},
{
"code": null,
"e": 2105,
"s": 2070,
"text": "Output: Results after using MODIFY"
},
{
"code": null,
"e": 2140,
"s": 2105,
"text": "Output: Results after using CHANGE"
},
{
"code": null,
"e": 2146,
"s": 2140,
"text": "mysql"
},
{
"code": null,
"e": 2153,
"s": 2146,
"text": "Picked"
},
{
"code": null,
"e": 2163,
"s": 2153,
"text": "SQL-Query"
},
{
"code": null,
"e": 2167,
"s": 2163,
"text": "SQL"
},
{
"code": null,
"e": 2171,
"s": 2167,
"text": "SQL"
}
] |
Find position of the given number among the numbers made of 4 and 7 | 08 Jun, 2022
Consider a series of numbers composed of only digits 4 and 7. The first few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number constructed by 4, 7 digits only, we need to find the position of this number in this series.Examples:
Input : 7
Output : pos = 2
Input : 444
Output : pos = 7
It is reverse of the following article : Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
""
/ \
1(4) 2(7)
/ \ / \
3(44) 4(47) 5(74) 6(77)
/ \ / \ / \ / \
The idea is based on the fact that all even positioned numbers have 7 as the last digit and all odd positioned numbers have 4 as the last digit.If the number is 4 then it is the left node of the tree, then it corresponds to (pos*2)+1. Else right child node(7) corresponds to (pos*2)+2.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find position of a number// in a series of numbers with 4 and 7 as the// only digits.#include <iostream>#include <algorithm>using namespace std; int findpos(string n){ int i = 0, pos = 0; while (n[i] != '\0') { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos;} // Driver codeint main(){ // given a number which is constructed // by 4 and 7 digit only string n = "774"; cout << findpos(n); return 0;}
// java program to find position of a number// in a series of numbers with 4 and 7 as the// only digits.import java.util.*; class GFG { static int findpos(String n) { int k = 0, pos = 0, i = 0; while (k != n.length()) { // check all digit position switch (n.charAt(i)) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; k++; } return pos; } // Driver code public static void main(String[] args) { // given a number which is constructed // by 4 and 7 digit only String n = "774"; System.out.println(findpos(n)); }} // This code is contributed by Sam007.
# python program to find position# of a number in a series of# numbers with 4 and 7 as the# only digits.def findpos(n): i = 0 j = len(n) pos = 0 while (i<j): # check all digit position # if number is left then # pos*2+1 if(n[i] == '4'): pos = pos * 2 + 1 # if number is right then # pos*2+2 if(n[i] == '7'): pos = pos * 2 + 2 i= i+1 return pos # Driver code# given a number which is constructed# by 4 and 7 digit onlyn = "774"print(findpos(n)) # This code is contributed by Sam007
// C# program to find position of// a number in a series of numbers// with 4 and 7 as the only digits.using System; class GFG{ static int findpos(String n) { int k = 0, pos = 0, i = 0; while (k != n.Length) { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; k++; } return pos; } // Driver code static void Main() { // given a number which is constructed // by 4 and 7 digit only String n = "774"; Console.Write(findpos(n)); } } // This code is contributed by Sam007
<?php// PHP program to find position of a number// in a series of numbers with 4 and 7 as the// only digits. function findpos($n){ $i = 0; $pos = 0; while($i < strlen($n)) { // check all digit position switch ($n[$i]) { // if number is left then pos*2+1 case '4': $pos = $pos * 2 + 1; break; // if number is right then pos*2+2 case '7': $pos = $pos * 2 + 2; break; } $i++; } return $pos;} // Driver code // given a number which // is constructed by 4 // and 7 digit only $n = "774"; echo findpos($n); // This code is contributed by Sam007?>
<script> // Javascript program to find position of a number// in a series of numbers with 4 and 7 as the// only digits. function findpos(n){ let i = 0; let pos = 0; while(i < n.length) { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos;} // Driver code // given a number which // is constructed by 4 // and 7 digit only let n = "774"; document.write(findpos(n)); // This code is contributed by _saurabh_jaiswal</script>
Output:
13
Time Complexity: O(n), where n represents the size of the given string.Auxiliary Space: O(1), no extra space is required, so it is a constant.
Find position of the given number among the numbers made of 4 and 7 | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind position of the given number among the numbers made of 4 and 7 | 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:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=R8r5Z4Ku1vw" 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 Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
byte_b
_saurabh_jaiswal
samim2000
series
Mathematical
Strings
Strings
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 310,
"s": 54,
"text": "Consider a series of numbers composed of only digits 4 and 7. The first few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number constructed by 4, 7 digits only, we need to find the position of this number in this series.Examples: "
},
{
"code": null,
"e": 368,
"s": 310,
"text": "Input : 7\nOutput : pos = 2 \n\nInput : 444\nOutput : pos = 7"
},
{
"code": null,
"e": 504,
"s": 370,
"text": "It is reverse of the following article : Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method) "
},
{
"code": null,
"e": 711,
"s": 504,
"text": " \"\"\n / \\\n 1(4) 2(7)\n / \\ / \\ \n 3(44) 4(47) 5(74) 6(77)\n / \\ / \\ / \\ / \\"
},
{
"code": null,
"e": 998,
"s": 711,
"text": "The idea is based on the fact that all even positioned numbers have 7 as the last digit and all odd positioned numbers have 4 as the last digit.If the number is 4 then it is the left node of the tree, then it corresponds to (pos*2)+1. Else right child node(7) corresponds to (pos*2)+2. "
},
{
"code": null,
"e": 1002,
"s": 998,
"text": "C++"
},
{
"code": null,
"e": 1007,
"s": 1002,
"text": "Java"
},
{
"code": null,
"e": 1015,
"s": 1007,
"text": "Python3"
},
{
"code": null,
"e": 1018,
"s": 1015,
"text": "C#"
},
{
"code": null,
"e": 1022,
"s": 1018,
"text": "PHP"
},
{
"code": null,
"e": 1033,
"s": 1022,
"text": "Javascript"
},
{
"code": "// C++ program to find position of a number// in a series of numbers with 4 and 7 as the// only digits.#include <iostream>#include <algorithm>using namespace std; int findpos(string n){ int i = 0, pos = 0; while (n[i] != '\\0') { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos;} // Driver codeint main(){ // given a number which is constructed // by 4 and 7 digit only string n = \"774\"; cout << findpos(n); return 0;}",
"e": 1745,
"s": 1033,
"text": null
},
{
"code": "// java program to find position of a number// in a series of numbers with 4 and 7 as the// only digits.import java.util.*; class GFG { static int findpos(String n) { int k = 0, pos = 0, i = 0; while (k != n.length()) { // check all digit position switch (n.charAt(i)) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; k++; } return pos; } // Driver code public static void main(String[] args) { // given a number which is constructed // by 4 and 7 digit only String n = \"774\"; System.out.println(findpos(n)); }} // This code is contributed by Sam007.",
"e": 2691,
"s": 1745,
"text": null
},
{
"code": "# python program to find position# of a number in a series of# numbers with 4 and 7 as the# only digits.def findpos(n): i = 0 j = len(n) pos = 0 while (i<j): # check all digit position # if number is left then # pos*2+1 if(n[i] == '4'): pos = pos * 2 + 1 # if number is right then # pos*2+2 if(n[i] == '7'): pos = pos * 2 + 2 i= i+1 return pos # Driver code# given a number which is constructed# by 4 and 7 digit onlyn = \"774\"print(findpos(n)) # This code is contributed by Sam007",
"e": 3302,
"s": 2691,
"text": null
},
{
"code": "// C# program to find position of// a number in a series of numbers// with 4 and 7 as the only digits.using System; class GFG{ static int findpos(String n) { int k = 0, pos = 0, i = 0; while (k != n.Length) { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; k++; } return pos; } // Driver code static void Main() { // given a number which is constructed // by 4 and 7 digit only String n = \"774\"; Console.Write(findpos(n)); } } // This code is contributed by Sam007",
"e": 4204,
"s": 3302,
"text": null
},
{
"code": "<?php// PHP program to find position of a number// in a series of numbers with 4 and 7 as the// only digits. function findpos($n){ $i = 0; $pos = 0; while($i < strlen($n)) { // check all digit position switch ($n[$i]) { // if number is left then pos*2+1 case '4': $pos = $pos * 2 + 1; break; // if number is right then pos*2+2 case '7': $pos = $pos * 2 + 2; break; } $i++; } return $pos;} // Driver code // given a number which // is constructed by 4 // and 7 digit only $n = \"774\"; echo findpos($n); // This code is contributed by Sam007?>",
"e": 4893,
"s": 4204,
"text": null
},
{
"code": "<script> // Javascript program to find position of a number// in a series of numbers with 4 and 7 as the// only digits. function findpos(n){ let i = 0; let pos = 0; while(i < n.length) { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos;} // Driver code // given a number which // is constructed by 4 // and 7 digit only let n = \"774\"; document.write(findpos(n)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 5632,
"s": 4893,
"text": null
},
{
"code": null,
"e": 5642,
"s": 5632,
"text": "Output: "
},
{
"code": null,
"e": 5645,
"s": 5642,
"text": "13"
},
{
"code": null,
"e": 5789,
"s": 5645,
"text": "Time Complexity: O(n), where n represents the size of the given string.Auxiliary Space: O(1), no extra space is required, so it is a constant. "
},
{
"code": null,
"e": 6741,
"s": 5789,
"text": "Find position of the given number among the numbers made of 4 and 7 | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind position of the given number among the numbers made of 4 and 7 | 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:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=R8r5Z4Ku1vw\" 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": 7166,
"s": 6741,
"text": "This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7173,
"s": 7166,
"text": "Sam007"
},
{
"code": null,
"e": 7180,
"s": 7173,
"text": "byte_b"
},
{
"code": null,
"e": 7197,
"s": 7180,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 7207,
"s": 7197,
"text": "samim2000"
},
{
"code": null,
"e": 7214,
"s": 7207,
"text": "series"
},
{
"code": null,
"e": 7227,
"s": 7214,
"text": "Mathematical"
},
{
"code": null,
"e": 7235,
"s": 7227,
"text": "Strings"
},
{
"code": null,
"e": 7243,
"s": 7235,
"text": "Strings"
},
{
"code": null,
"e": 7256,
"s": 7243,
"text": "Mathematical"
},
{
"code": null,
"e": 7263,
"s": 7256,
"text": "series"
}
] |
TIMESTAMPDIFF() function in MYSQL | 30 Dec, 2020
TIMESTAMPDIFF() :
This function in MySQL is used to return a value after subtracting a DateTime expression from another.
Syntax :
TIMESTAMPDIFF(unit,expr1,expr2)
Parameters :
It will accept three parameters.
unit – It denotes the unit for the result. It can be one of the following.MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR
expr1 – First date or DateTime expressions.
expr2 – Second date or DateTime expressions.
Returns :
It returns the DateTime expressions after subtraction.
Example 1 :
Getting the differences between two specified time values where the time is specified in the format of YYYY-MM-DD HH-MM-SS. Here expr2 is greater than expr1, so the return value is positive.
SELECT TIMESTAMPDIFF(SECOND, '2010-01-01 10:10:20', '2010-01-01 10:45:59') AS SECONDDIFFERENCE;
Output :
Example 2:
Getting the differences between two specified time values where the time is specified in the format of YYYY-MM-DD HH-MM-SS. Here expr2 is lesser than expr1, so the return value is negative.
SELECT TIMESTAMPDIFF(SECOND, '2010-01-01 10:10:20', '2010-01-01 09:45:59') AS SECONDDIFFERENCE;
Output:
Example 3:
Getting the differences between two specified date values in the month when the date is specified in the format of YYYY-MM-DD.
SELECT TIMESTAMPDIFF(MONTH, '2019-08-01', '2020-11-01') AS MONTHDIFFERENCE;
Output:
Example 4:
Calculating Total Work experience of an Employee using the TIMESTAMPDIFF function.
Creating an Employee table –
CREATE TABLE Employee(
id INT AUTO_INCREMENT PRIMARY KEY,
Full_Name VARCHAR(50) NOT NULL,
Joining_Date DATE NOT NULL
);
Inserting values into the table –
INSERT INTO Employee(Full_Name , Joining_Date )
VALUES('Riya Jana', '2000-01-01'),
('Sayan Ghosh', '2005-09-26'),
('Rinki Sharma', '2014-08-12'),
('Aniket Singh', '2019-11-05');
Now, we will use the TIMESTAMPDIFF to calculate the work experience of each employee in the year.
SELECT
id,
Full_Name,
Joining_Date ,
TIMESTAMPDIFF(YEAR, Joining_Date,'2020-11-26') AS WorkExperience
FROM
Employee ;
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
What is Temporary Table in SQL?
SQL using Python
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Convert Rows to Columns in SQL Server
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 46,
"s": 28,
"text": "TIMESTAMPDIFF() :"
},
{
"code": null,
"e": 149,
"s": 46,
"text": "This function in MySQL is used to return a value after subtracting a DateTime expression from another."
},
{
"code": null,
"e": 158,
"s": 149,
"text": "Syntax :"
},
{
"code": null,
"e": 190,
"s": 158,
"text": "TIMESTAMPDIFF(unit,expr1,expr2)"
},
{
"code": null,
"e": 204,
"s": 190,
"text": "Parameters : "
},
{
"code": null,
"e": 237,
"s": 204,
"text": "It will accept three parameters."
},
{
"code": null,
"e": 379,
"s": 237,
"text": "unit – It denotes the unit for the result. It can be one of the following.MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR "
},
{
"code": null,
"e": 424,
"s": 379,
"text": "expr1 – First date or DateTime expressions. "
},
{
"code": null,
"e": 469,
"s": 424,
"text": "expr2 – Second date or DateTime expressions."
},
{
"code": null,
"e": 479,
"s": 469,
"text": "Returns :"
},
{
"code": null,
"e": 534,
"s": 479,
"text": "It returns the DateTime expressions after subtraction."
},
{
"code": null,
"e": 546,
"s": 534,
"text": "Example 1 :"
},
{
"code": null,
"e": 737,
"s": 546,
"text": "Getting the differences between two specified time values where the time is specified in the format of YYYY-MM-DD HH-MM-SS. Here expr2 is greater than expr1, so the return value is positive."
},
{
"code": null,
"e": 833,
"s": 737,
"text": "SELECT TIMESTAMPDIFF(SECOND, '2010-01-01 10:10:20', '2010-01-01 10:45:59') AS SECONDDIFFERENCE;"
},
{
"code": null,
"e": 842,
"s": 833,
"text": "Output :"
},
{
"code": null,
"e": 853,
"s": 842,
"text": "Example 2:"
},
{
"code": null,
"e": 1043,
"s": 853,
"text": "Getting the differences between two specified time values where the time is specified in the format of YYYY-MM-DD HH-MM-SS. Here expr2 is lesser than expr1, so the return value is negative."
},
{
"code": null,
"e": 1139,
"s": 1043,
"text": "SELECT TIMESTAMPDIFF(SECOND, '2010-01-01 10:10:20', '2010-01-01 09:45:59') AS SECONDDIFFERENCE;"
},
{
"code": null,
"e": 1147,
"s": 1139,
"text": "Output:"
},
{
"code": null,
"e": 1158,
"s": 1147,
"text": "Example 3:"
},
{
"code": null,
"e": 1285,
"s": 1158,
"text": "Getting the differences between two specified date values in the month when the date is specified in the format of YYYY-MM-DD."
},
{
"code": null,
"e": 1361,
"s": 1285,
"text": "SELECT TIMESTAMPDIFF(MONTH, '2019-08-01', '2020-11-01') AS MONTHDIFFERENCE;"
},
{
"code": null,
"e": 1369,
"s": 1361,
"text": "Output:"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": "Example 4:"
},
{
"code": null,
"e": 1464,
"s": 1380,
"text": "Calculating Total Work experience of an Employee using the TIMESTAMPDIFF function. "
},
{
"code": null,
"e": 1493,
"s": 1464,
"text": "Creating an Employee table –"
},
{
"code": null,
"e": 1625,
"s": 1493,
"text": "CREATE TABLE Employee(\n id INT AUTO_INCREMENT PRIMARY KEY,\n Full_Name VARCHAR(50) NOT NULL,\n Joining_Date DATE NOT NULL\n);"
},
{
"code": null,
"e": 1659,
"s": 1625,
"text": "Inserting values into the table –"
},
{
"code": null,
"e": 1855,
"s": 1659,
"text": "INSERT INTO Employee(Full_Name , Joining_Date )\nVALUES('Riya Jana', '2000-01-01'),\n ('Sayan Ghosh', '2005-09-26'),\n ('Rinki Sharma', '2014-08-12'),\n ('Aniket Singh', '2019-11-05');"
},
{
"code": null,
"e": 1953,
"s": 1855,
"text": "Now, we will use the TIMESTAMPDIFF to calculate the work experience of each employee in the year."
},
{
"code": null,
"e": 2092,
"s": 1953,
"text": "SELECT \n id,\n Full_Name,\n Joining_Date ,\n TIMESTAMPDIFF(YEAR, Joining_Date,'2020-11-26') AS WorkExperience\nFROM\n Employee ;"
},
{
"code": null,
"e": 2101,
"s": 2092,
"text": "Output :"
},
{
"code": null,
"e": 2110,
"s": 2101,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2116,
"s": 2110,
"text": "mysql"
},
{
"code": null,
"e": 2120,
"s": 2116,
"text": "SQL"
},
{
"code": null,
"e": 2124,
"s": 2120,
"text": "SQL"
},
{
"code": null,
"e": 2222,
"s": 2124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2288,
"s": 2222,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2321,
"s": 2288,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2345,
"s": 2321,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2423,
"s": 2345,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2455,
"s": 2423,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2472,
"s": 2455,
"text": "SQL using Python"
},
{
"code": null,
"e": 2502,
"s": 2472,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2538,
"s": 2502,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2589,
"s": 2538,
"text": "SQL Query to Convert Rows to Columns in SQL Server"
}
] |
HTML | <meta> http-equiv Attribute | 06 Jun, 2022
The HTML <meta> http-equiv Attribute is used to provide header information or value of the content Attribute. It can be used to simulate an HTTP Header response. It can be used in meta Element.Syntax:
<meta http-equiv="content-type | default-style | refresh">
Example:
html
<!DOCTYPE html><html> <head> <title> HTML Meta http-equiv Attribute </title> <meta name="keywords about" content="Meta Tags, Metadata" /> <meta name="description" content="Learning about Meta Tags." /> <meta name="revised about" content="GeeksforGeeks" /> <meta http-equiv="refresh" content="8" /></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2> HTML Meta http-equiv Attribute </h2> </center></body> </html>
Output:
Supported Browsers: The browser supported by HTML Meta http-equiv attribute are listed below:
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 6 and above
Firefox 1 and above
Opera 12.1 and above
Safari 4 and above
arorakashish0911
hritikbhatnagar2182
kumargaurav97520
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The HTML <meta> http-equiv Attribute is used to provide header information or value of the content Attribute. It can be used to simulate an HTTP Header response. It can be used in meta Element.Syntax:"
},
{
"code": null,
"e": 288,
"s": 229,
"text": "<meta http-equiv=\"content-type | default-style | refresh\">"
},
{
"code": null,
"e": 299,
"s": 288,
"text": "Example: "
},
{
"code": null,
"e": 304,
"s": 299,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML Meta http-equiv Attribute </title> <meta name=\"keywords about\" content=\"Meta Tags, Metadata\" /> <meta name=\"description\" content=\"Learning about Meta Tags.\" /> <meta name=\"revised about\" content=\"GeeksforGeeks\" /> <meta http-equiv=\"refresh\" content=\"8\" /></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> HTML Meta http-equiv Attribute </h2> </center></body> </html> ",
"e": 863,
"s": 304,
"text": null
},
{
"code": null,
"e": 873,
"s": 863,
"text": "Output: "
},
{
"code": null,
"e": 969,
"s": 873,
"text": "Supported Browsers: The browser supported by HTML Meta http-equiv attribute are listed below: "
},
{
"code": null,
"e": 995,
"s": 969,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 1013,
"s": 995,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 1043,
"s": 1013,
"text": "Internet Explorer 6 and above"
},
{
"code": null,
"e": 1063,
"s": 1043,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 1084,
"s": 1063,
"text": "Opera 12.1 and above"
},
{
"code": null,
"e": 1103,
"s": 1084,
"text": "Safari 4 and above"
},
{
"code": null,
"e": 1122,
"s": 1105,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1142,
"s": 1122,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 1159,
"s": 1142,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 1175,
"s": 1159,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1180,
"s": 1175,
"text": "HTML"
},
{
"code": null,
"e": 1197,
"s": 1180,
"text": "Web Technologies"
},
{
"code": null,
"e": 1202,
"s": 1197,
"text": "HTML"
}
] |
Why 0.3 – 0.2 is not equal to 0.1 in Python? | 26 Nov, 2020
In this article, we will see why 0.3 – 0.2 is not equal to 0.1 in Python. The reason behind it is called “precision”, and it’s due to the fact that computers do not compute in Decimal, but in Binary. Computers do not use a base 10 system, they use a base 2 system (also called Binary code).
Below is the Implementation.
Python3
# codeprint(0.3 - 0.2)print(0.3 - 0.2 == 0.1)
0.09999999999999998
False
As you can see in the output, 0.3 – 0.2 does not give 0.1 but 0.09999999999999998. We do calculations using decimal (base 10), while computer does calculations using binary(base 2).
Let us consider 1 / 3 in decimal which is 0.3333333, 2 / 3 in decimal is 0.6666666, if we add both we will only get 0.9999999, which is not equal to 1. Similarly, 0.3, 0.2 cannot be represented accurately in binary no matter how many significant digits you use. Fractions with denominator in multiples of 5 and 2 can only be represented precisely in decimal, similarly fractions with denominator in multiples of 2 can only be represented precisely in binary. Floating-point numbers are stored internally using IEEE standard 754 which is correct only from 15-17 significant digits.
We can use inbuilt decimal module to change precision and get accurate results. getcontext().prec can be used to set precision of each decimal value. Default precision is 28 digits.
Python3
from decimal import * getcontext().prec = 6print(Decimal("0.3") - Decimal("0.2"))print(Decimal("0.3") - Decimal("0.2") == Decimal("0.1"))
0.1
True
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 345,
"s": 54,
"text": "In this article, we will see why 0.3 – 0.2 is not equal to 0.1 in Python. The reason behind it is called “precision”, and it’s due to the fact that computers do not compute in Decimal, but in Binary. Computers do not use a base 10 system, they use a base 2 system (also called Binary code)."
},
{
"code": null,
"e": 375,
"s": 345,
"text": "Below is the Implementation. "
},
{
"code": null,
"e": 383,
"s": 375,
"text": "Python3"
},
{
"code": "# codeprint(0.3 - 0.2)print(0.3 - 0.2 == 0.1)",
"e": 429,
"s": 383,
"text": null
},
{
"code": null,
"e": 456,
"s": 429,
"text": "0.09999999999999998\nFalse\n"
},
{
"code": null,
"e": 639,
"s": 456,
"text": "As you can see in the output, 0.3 – 0.2 does not give 0.1 but 0.09999999999999998. We do calculations using decimal (base 10), while computer does calculations using binary(base 2)."
},
{
"code": null,
"e": 1220,
"s": 639,
"text": "Let us consider 1 / 3 in decimal which is 0.3333333, 2 / 3 in decimal is 0.6666666, if we add both we will only get 0.9999999, which is not equal to 1. Similarly, 0.3, 0.2 cannot be represented accurately in binary no matter how many significant digits you use. Fractions with denominator in multiples of 5 and 2 can only be represented precisely in decimal, similarly fractions with denominator in multiples of 2 can only be represented precisely in binary. Floating-point numbers are stored internally using IEEE standard 754 which is correct only from 15-17 significant digits."
},
{
"code": null,
"e": 1402,
"s": 1220,
"text": "We can use inbuilt decimal module to change precision and get accurate results. getcontext().prec can be used to set precision of each decimal value. Default precision is 28 digits."
},
{
"code": null,
"e": 1410,
"s": 1402,
"text": "Python3"
},
{
"code": "from decimal import * getcontext().prec = 6print(Decimal(\"0.3\") - Decimal(\"0.2\"))print(Decimal(\"0.3\") - Decimal(\"0.2\") == Decimal(\"0.1\"))",
"e": 1551,
"s": 1410,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1551,
"text": "0.1\nTrue\n"
},
{
"code": null,
"e": 1568,
"s": 1561,
"text": "Python"
}
] |
C program to perform intersection operation on two arrays | If array 1 = { 1,2,3,4,6}
Array 2 = {1,2,5,6,7}
Then, intersection of array1 and array 2 is
Array1 ^ array 2 = {1,2,3,4,6} ^ {1,2,5,6,7}
= {1,2,6}
Set of common elements is called an intersection.
The logic for intersection is as follows −
k=0;
for(i=0;i<size1;i++){
for(j=0;j<size2;j++){
if(a[i]==b[j]){
intersection[k]=a[i];
k++;
}
}
}
Following is the C program to perform intersection operation on two arrays −
Live Demo
#include<stdio.h>
int removerepeated(int size,int a[]);
void sort(int size,int a[]);
main(){
int i,size1,size2,size,j=0,k,intersectionsize;
printf("Enter size of an array1\n");
scanf("%d",&size1);
printf("Enter size of an array2\n");
scanf("%d",&size2);
int a[size1],b[size2],uni[size1+size2];
if(size1<size2){
intersectionsize=size1;
}else if(size1>size2){
intersectionsize=size2;
}else{
intersectionsize=size1;
}
int intersection[intersectionsize];
printf("Enter numbers for array 1\n");
for(i=0;i<size1;i++){
scanf("%d",&a[i]);
}
printf("Enter numbers for array 2\n");
for(i=0;i<size2;i++){
scanf("%d",&b[i]);
}
//Intersection starts
k=0;
for(i=0;i<size1;i++){
for(j=0;j<size2;j++){
if(a[i]==b[j]){
intersection[k]=a[i];
k++;
}
}
}
//Sorting
sort(k,intersection);
//Removing
size=removerepeated(k,intersection);
printf("Array after intersection\n");
if(size>0){
for(i=0;i<size;i++){
printf("%d\n",intersection[i]);
}
}else{
printf("No intersection\n");
}
}
int removerepeated(int size,int a[]){
int i,j,k;
for(i=0;i<size;i++){
for(j=i+1;j<size;){
if(a[i]==a[j]){
for(k=j;k<size;k++){
a[k]=a[k+1];
}
size--;
}else{
j++;
}
}
}
return(size);
}
void sort(int size,int a[]){
int i,j,temp;
for(i=0;i<size;i++){
for(j=i+1;j<size;j++){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
When the above program is executed, it produces the following result −
Enter size of an array1
5
Enter size of an array2
2
Enter numbers for array 1
4
5
6
7
8
Enter numbers for array 2
4
1
Array after intersection
4 | [
{
"code": null,
"e": 1088,
"s": 1062,
"text": "If array 1 = { 1,2,3,4,6}"
},
{
"code": null,
"e": 1112,
"s": 1088,
"text": " Array 2 = {1,2,5,6,7}"
},
{
"code": null,
"e": 1156,
"s": 1112,
"text": "Then, intersection of array1 and array 2 is"
},
{
"code": null,
"e": 1228,
"s": 1156,
"text": "Array1 ^ array 2 = {1,2,3,4,6} ^ {1,2,5,6,7}\n = {1,2,6}"
},
{
"code": null,
"e": 1278,
"s": 1228,
"text": "Set of common elements is called an intersection."
},
{
"code": null,
"e": 1321,
"s": 1278,
"text": "The logic for intersection is as follows −"
},
{
"code": null,
"e": 1455,
"s": 1321,
"text": "k=0;\nfor(i=0;i<size1;i++){\n for(j=0;j<size2;j++){\n if(a[i]==b[j]){\n intersection[k]=a[i];\n k++;\n }\n }\n}"
},
{
"code": null,
"e": 1532,
"s": 1455,
"text": "Following is the C program to perform intersection operation on two arrays −"
},
{
"code": null,
"e": 1543,
"s": 1532,
"text": " Live Demo"
},
{
"code": null,
"e": 3217,
"s": 1543,
"text": "#include<stdio.h>\nint removerepeated(int size,int a[]);\nvoid sort(int size,int a[]);\nmain(){\n int i,size1,size2,size,j=0,k,intersectionsize;\n printf(\"Enter size of an array1\\n\");\n scanf(\"%d\",&size1);\n printf(\"Enter size of an array2\\n\");\n scanf(\"%d\",&size2);\n int a[size1],b[size2],uni[size1+size2];\n if(size1<size2){\n intersectionsize=size1;\n }else if(size1>size2){\n intersectionsize=size2;\n }else{\n intersectionsize=size1;\n }\n int intersection[intersectionsize];\n printf(\"Enter numbers for array 1\\n\");\n for(i=0;i<size1;i++){\n scanf(\"%d\",&a[i]);\n }\n printf(\"Enter numbers for array 2\\n\");\n for(i=0;i<size2;i++){\n scanf(\"%d\",&b[i]);\n }\n //Intersection starts\n k=0;\n for(i=0;i<size1;i++){\n for(j=0;j<size2;j++){\n if(a[i]==b[j]){\n intersection[k]=a[i];\n k++;\n }\n }\n }\n //Sorting\n sort(k,intersection);\n //Removing\n size=removerepeated(k,intersection);\n printf(\"Array after intersection\\n\");\n if(size>0){\n for(i=0;i<size;i++){\n printf(\"%d\\n\",intersection[i]);\n }\n }else{\n printf(\"No intersection\\n\");\n }\n}\nint removerepeated(int size,int a[]){\n int i,j,k;\n for(i=0;i<size;i++){\n for(j=i+1;j<size;){\n if(a[i]==a[j]){\n for(k=j;k<size;k++){\n a[k]=a[k+1];\n }\n size--;\n }else{\n j++;\n }\n }\n }\n return(size);\n}\nvoid sort(int size,int a[]){\n int i,j,temp;\n for(i=0;i<size;i++){\n for(j=i+1;j<size;j++){\n if(a[i]>a[j]){\n temp=a[i];\n a[i]=a[j];\n a[j]=temp;\n }\n }\n }\n}"
},
{
"code": null,
"e": 3288,
"s": 3217,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3433,
"s": 3288,
"text": "Enter size of an array1\n5\nEnter size of an array2\n2\nEnter numbers for array 1\n4\n5\n6\n7\n8\nEnter numbers for array 2\n4\n1\nArray after intersection\n4"
}
] |
5 things that make my job as a Data Scientist easier | by Shree Vandana | Towards Data Science | Time Series Data Processing with Pandas
Time Series Data Processing with Pandas
If you work with time series data, chances are you have spent a significant amount of time accounting for missing records or aggregating data at a particular temporal granularity either via SQL queries or writing custom functions. Pandas has a very efficient resample function that can help you process the data at a particular frequency by simply setting the DataFrame index to be the timestamp column.
I am going to use the room occupancy dataset to give an example of this function. You can find the dataset here. This dataset records observations at a minute level.
import pandas as pddata = pd.read_csv('occupancy_data/datatest.txt').reset_index(drop = True)data.head(5)
First, I show a simple aggregation one can do to get metrics at an hourly level.
data.index = pd.to_datetime(data['date'])pd.DataFrame(data.resample('H').agg({'Temperature':'mean', 'Humidity':'mean', 'Light':'last', 'CO2':'last', 'HumidityRatio' : 'mean', 'Occupancy' : 'mean'})).head(5)
Though this dataset is not sparse, in the real world one often encounters data which has missing records. It is important to account for those records since you might want to put in 0 values if there were no records or use the previous or next time steps for imputation. Below, I removed records for hour 15 to show how you can use the hour 14 timestamp to impute the missing value:
data = pd.read_csv('occupancy_data/datatest.txt').reset_index(drop = True)data_missing_records = data[~(pd.to_datetime(data.date).dt.hour == 15)].reset_index(drop = True)data_missing_records.index = pd.to_datetime(data_missing_records['date'])data_missing_records.resample('H', base = 1).agg({'Temperature':'mean', 'Humidity':'mean', 'Light':'last', 'CO2':'last', 'HumidityRatio' : 'mean', 'Occupancy' : 'mean'}).fillna(method = 'ffill').head(5)
2. Fast Visualization via Plotly Express
From analysis to model training to model reporting, visualizations are often required. Especially with time series graphs, I noticed I was spending a lot of time trying to customize the size and angle of my x-axis ticks in matplotlib. After I switched to using Plotly Express, I cut down the time I spent in making graphs looking cleaner/crisper by around 70%. And if I want to implement specific details in my visuals I can still do that by using Plotly Graph Objects. Additionally, Plotly offers a lot of easy options via Express like setting group colors in plots which results in more powerful visualizations.
import plotly.express as pxdata['Temp_Bands'] = np.round(data['Temperature'])fig = px.line(data, x = 'date', y = 'HumidityRatio', color = 'Temp_Bands', title = 'Humidity Ratio across dates as a function of Temperature Bands', labels = {'date' : 'Time Stamp', 'HumidityRatio' : 'Humidity Ratio', 'Temp_Bands' : 'Temperature Band'})fig.show()
Using the occupancy dataset mentioned above, I used Plotly Express to create line plots with color grouping. We can see how easy it to create these plots with just two functions.
3. Speed up pandas apply() via Swifter
I sometimes run into long wait times for processing pandas columns even with running code on a notebook with a large instance. Instead, there is an easy one word addition that can be used to speed up the apply functionality in a pandas DataFrame. One only has to import the library swifter.
def custom(num1, num2): if num1 > num2: if num1 < 0: return "Greater Negative" else: return "Greater Positive" elif num2 > num1: if num2 < 0: return "Less Negative" else: return "Less Positive" else: return "Rare Equal"import swifter import pandas as pdimport numpy as npdata_sample = pd.DataFrame(np.random.randint(-10000, 10000, size = (50000000, 2)), columns = list('XY'))
I created a 50 million rows DataFrame and compared the time taken to process it via swifter apply() vs the vanilla apply(). I also created a dummy function with simple if else conditions to test the two approaches on.
%%timeresults_arr = data_sample.apply(lambda x : custom(x['X'], x['Y']), axis = 1)
%%timeresults_arr = data_sample.swifter.apply(lambda x : custom(x['X'], x['Y']), axis = 1)
We are able to reduce the processing time by 64.4% from 7 minutes 53 seconds to 2 minutes 38 seconds.
4. Multiprocessing in Python
While we are on the topic of decreasing time complexity, I often end up dealing with datasets that I wish to process at multiple granularities. Using multiprocessing in python helps me save that time by utilizing multiple workers.
I demonstrate the effectiveness of multiprocessing using the same 50 million rows data frame I created above. Except this time I add a categorical variable which is a random value selected out of a set of vowels.
import pandas as pdimport numpy as npimport randomstring = 'AEIOU'data_sample = pd.DataFrame(np.random.randint(-10000, 10000, size = (50000000, 2)), columns = list('XY'))data_sample['random_char'] = random.choices(string, k = data_sample.shape[0])unique_char = data_sample['random_char'].unique()
I used a for loop vs the Process Pool executor from concurrent.futures to demonstrate the runtime reduction we can achieve.
%%timearr = []for i in range(len(data_sample)): num1 = data_sample.X.iloc[i] num2 = data_sample.Y.iloc[i] if num1 > num2: if num1 < 0: arr.append("Greater Negative") else: arr.append("Greater Positive") elif num2 > num1: if num2 < 0: arr.append("Less Negative") else: arr.append("Less Positive") else: arr.append("Rare Equal")
def custom_multiprocessing(i): sample = data_sample[data_sample['random_char'] == \ unique_char[i]] arr = [] for j in range(len(sample)): if num1 > num2: if num1 < 0: arr.append("Greater Negative") else: arr.append("Greater Positive") elif num2 > num1: if num2 < 0: arr.append("Less Negative") else: arr.append("Less Positive") else: arr.append("Rare Equal") sample['values'] = arr return sample
I created a function that allows me to process each vowel grouping separately:
%%time import concurrentdef main(): aggregated = pd.DataFrame() with concurrent.futures.ProcessPoolExecutor(max_workers = 5) as executor: results = executor.map(custom_multiprocessing, range(len(unique_char)))if __name__ == '__main__': main()
We see a reduction of CPU time by 99.3%. Though one must remember to use these methods carefully since they will not serialize the output therefore using them via grouping can be a good means to leverage this capability.
5. MASE as a metric
With the rise of using Machine Learning and Deep Learning approaches for time series forecasting, it is essential to use a metric NOT just based on the distance between predicted and actual value. A metric for a forecasting model should use errors from the temporal trend as well to evaluate how well a model is performing instead of just point in time error estimates. Enter Mean Absolute Scaled Error! This metric that takes into account the error we would get if we used a random walk approach where last timestamp’s value would be the forecast for the next timestamp. It compares the error from the model to the error from the naive forecast.
def MASE(y_train, y_test, pred): naive_error = np.sum(np.abs(np.diff(y_train)))/(len(y_train)-1) model_error = np.mean(np.abs(y_test - pred))return model_error/naive_error
If MASE > 1 then the model is performing worse than a random walk. The closer the MASE is to 0, the better the forecasting model.
In this article, we went through some of the tricks I often use to make my life easier as a Data Scientist. Comment to share some of your tips! I would love to learn more about tricks that other Data Scientists use in their work.
This is also my first Medium article and I feel like I am talking to nothingness so if you have any feedback to share then please feel free to critique and reach out :) | [
{
"code": null,
"e": 211,
"s": 171,
"text": "Time Series Data Processing with Pandas"
},
{
"code": null,
"e": 251,
"s": 211,
"text": "Time Series Data Processing with Pandas"
},
{
"code": null,
"e": 655,
"s": 251,
"text": "If you work with time series data, chances are you have spent a significant amount of time accounting for missing records or aggregating data at a particular temporal granularity either via SQL queries or writing custom functions. Pandas has a very efficient resample function that can help you process the data at a particular frequency by simply setting the DataFrame index to be the timestamp column."
},
{
"code": null,
"e": 821,
"s": 655,
"text": "I am going to use the room occupancy dataset to give an example of this function. You can find the dataset here. This dataset records observations at a minute level."
},
{
"code": null,
"e": 927,
"s": 821,
"text": "import pandas as pddata = pd.read_csv('occupancy_data/datatest.txt').reset_index(drop = True)data.head(5)"
},
{
"code": null,
"e": 1008,
"s": 927,
"text": "First, I show a simple aggregation one can do to get metrics at an hourly level."
},
{
"code": null,
"e": 1395,
"s": 1008,
"text": "data.index = pd.to_datetime(data['date'])pd.DataFrame(data.resample('H').agg({'Temperature':'mean', 'Humidity':'mean', 'Light':'last', 'CO2':'last', 'HumidityRatio' : 'mean', 'Occupancy' : 'mean'})).head(5)"
},
{
"code": null,
"e": 1778,
"s": 1395,
"text": "Though this dataset is not sparse, in the real world one often encounters data which has missing records. It is important to account for those records since you might want to put in 0 values if there were no records or use the previous or next time steps for imputation. Below, I removed records for hour 15 to show how you can use the hour 14 timestamp to impute the missing value:"
},
{
"code": null,
"e": 2261,
"s": 1778,
"text": "data = pd.read_csv('occupancy_data/datatest.txt').reset_index(drop = True)data_missing_records = data[~(pd.to_datetime(data.date).dt.hour == 15)].reset_index(drop = True)data_missing_records.index = pd.to_datetime(data_missing_records['date'])data_missing_records.resample('H', base = 1).agg({'Temperature':'mean', 'Humidity':'mean', 'Light':'last', 'CO2':'last', 'HumidityRatio' : 'mean', 'Occupancy' : 'mean'}).fillna(method = 'ffill').head(5)"
},
{
"code": null,
"e": 2302,
"s": 2261,
"text": "2. Fast Visualization via Plotly Express"
},
{
"code": null,
"e": 2916,
"s": 2302,
"text": "From analysis to model training to model reporting, visualizations are often required. Especially with time series graphs, I noticed I was spending a lot of time trying to customize the size and angle of my x-axis ticks in matplotlib. After I switched to using Plotly Express, I cut down the time I spent in making graphs looking cleaner/crisper by around 70%. And if I want to implement specific details in my visuals I can still do that by using Plotly Graph Objects. Additionally, Plotly offers a lot of easy options via Express like setting group colors in plots which results in more powerful visualizations."
},
{
"code": null,
"e": 3361,
"s": 2916,
"text": "import plotly.express as pxdata['Temp_Bands'] = np.round(data['Temperature'])fig = px.line(data, x = 'date', y = 'HumidityRatio', color = 'Temp_Bands', title = 'Humidity Ratio across dates as a function of Temperature Bands', labels = {'date' : 'Time Stamp', 'HumidityRatio' : 'Humidity Ratio', 'Temp_Bands' : 'Temperature Band'})fig.show()"
},
{
"code": null,
"e": 3540,
"s": 3361,
"text": "Using the occupancy dataset mentioned above, I used Plotly Express to create line plots with color grouping. We can see how easy it to create these plots with just two functions."
},
{
"code": null,
"e": 3579,
"s": 3540,
"text": "3. Speed up pandas apply() via Swifter"
},
{
"code": null,
"e": 3870,
"s": 3579,
"text": "I sometimes run into long wait times for processing pandas columns even with running code on a notebook with a large instance. Instead, there is an easy one word addition that can be used to speed up the apply functionality in a pandas DataFrame. One only has to import the library swifter."
},
{
"code": null,
"e": 4338,
"s": 3870,
"text": "def custom(num1, num2): if num1 > num2: if num1 < 0: return \"Greater Negative\" else: return \"Greater Positive\" elif num2 > num1: if num2 < 0: return \"Less Negative\" else: return \"Less Positive\" else: return \"Rare Equal\"import swifter import pandas as pdimport numpy as npdata_sample = pd.DataFrame(np.random.randint(-10000, 10000, size = (50000000, 2)), columns = list('XY'))"
},
{
"code": null,
"e": 4556,
"s": 4338,
"text": "I created a 50 million rows DataFrame and compared the time taken to process it via swifter apply() vs the vanilla apply(). I also created a dummy function with simple if else conditions to test the two approaches on."
},
{
"code": null,
"e": 4639,
"s": 4556,
"text": "%%timeresults_arr = data_sample.apply(lambda x : custom(x['X'], x['Y']), axis = 1)"
},
{
"code": null,
"e": 4730,
"s": 4639,
"text": "%%timeresults_arr = data_sample.swifter.apply(lambda x : custom(x['X'], x['Y']), axis = 1)"
},
{
"code": null,
"e": 4832,
"s": 4730,
"text": "We are able to reduce the processing time by 64.4% from 7 minutes 53 seconds to 2 minutes 38 seconds."
},
{
"code": null,
"e": 4861,
"s": 4832,
"text": "4. Multiprocessing in Python"
},
{
"code": null,
"e": 5092,
"s": 4861,
"text": "While we are on the topic of decreasing time complexity, I often end up dealing with datasets that I wish to process at multiple granularities. Using multiprocessing in python helps me save that time by utilizing multiple workers."
},
{
"code": null,
"e": 5305,
"s": 5092,
"text": "I demonstrate the effectiveness of multiprocessing using the same 50 million rows data frame I created above. Except this time I add a categorical variable which is a random value selected out of a set of vowels."
},
{
"code": null,
"e": 5603,
"s": 5305,
"text": "import pandas as pdimport numpy as npimport randomstring = 'AEIOU'data_sample = pd.DataFrame(np.random.randint(-10000, 10000, size = (50000000, 2)), columns = list('XY'))data_sample['random_char'] = random.choices(string, k = data_sample.shape[0])unique_char = data_sample['random_char'].unique()"
},
{
"code": null,
"e": 5727,
"s": 5603,
"text": "I used a for loop vs the Process Pool executor from concurrent.futures to demonstrate the runtime reduction we can achieve."
},
{
"code": null,
"e": 6156,
"s": 5727,
"text": "%%timearr = []for i in range(len(data_sample)): num1 = data_sample.X.iloc[i] num2 = data_sample.Y.iloc[i] if num1 > num2: if num1 < 0: arr.append(\"Greater Negative\") else: arr.append(\"Greater Positive\") elif num2 > num1: if num2 < 0: arr.append(\"Less Negative\") else: arr.append(\"Less Positive\") else: arr.append(\"Rare Equal\")"
},
{
"code": null,
"e": 6734,
"s": 6156,
"text": "def custom_multiprocessing(i): sample = data_sample[data_sample['random_char'] == \\ unique_char[i]] arr = [] for j in range(len(sample)): if num1 > num2: if num1 < 0: arr.append(\"Greater Negative\") else: arr.append(\"Greater Positive\") elif num2 > num1: if num2 < 0: arr.append(\"Less Negative\") else: arr.append(\"Less Positive\") else: arr.append(\"Rare Equal\") sample['values'] = arr return sample"
},
{
"code": null,
"e": 6813,
"s": 6734,
"text": "I created a function that allows me to process each vowel grouping separately:"
},
{
"code": null,
"e": 7076,
"s": 6813,
"text": "%%time import concurrentdef main(): aggregated = pd.DataFrame() with concurrent.futures.ProcessPoolExecutor(max_workers = 5) as executor: results = executor.map(custom_multiprocessing, range(len(unique_char)))if __name__ == '__main__': main()"
},
{
"code": null,
"e": 7297,
"s": 7076,
"text": "We see a reduction of CPU time by 99.3%. Though one must remember to use these methods carefully since they will not serialize the output therefore using them via grouping can be a good means to leverage this capability."
},
{
"code": null,
"e": 7317,
"s": 7297,
"text": "5. MASE as a metric"
},
{
"code": null,
"e": 7964,
"s": 7317,
"text": "With the rise of using Machine Learning and Deep Learning approaches for time series forecasting, it is essential to use a metric NOT just based on the distance between predicted and actual value. A metric for a forecasting model should use errors from the temporal trend as well to evaluate how well a model is performing instead of just point in time error estimates. Enter Mean Absolute Scaled Error! This metric that takes into account the error we would get if we used a random walk approach where last timestamp’s value would be the forecast for the next timestamp. It compares the error from the model to the error from the naive forecast."
},
{
"code": null,
"e": 8153,
"s": 7964,
"text": "def MASE(y_train, y_test, pred): naive_error = np.sum(np.abs(np.diff(y_train)))/(len(y_train)-1) model_error = np.mean(np.abs(y_test - pred))return model_error/naive_error"
},
{
"code": null,
"e": 8283,
"s": 8153,
"text": "If MASE > 1 then the model is performing worse than a random walk. The closer the MASE is to 0, the better the forecasting model."
},
{
"code": null,
"e": 8513,
"s": 8283,
"text": "In this article, we went through some of the tricks I often use to make my life easier as a Data Scientist. Comment to share some of your tips! I would love to learn more about tricks that other Data Scientists use in their work."
}
] |
Generating Python Scripts with OpenAi’s Github Copilot | by Lucas Soares | Towards Data Science | It’s been a while since I got access to the technical preview of OpenAi’s Github copilot. Since then, I kind of learned to enjoy asking it all sorts of questions in the form of function names and descriptions to see what kind of code it could come up with.
In this article, I will share how I used the Github Copilot extension for VS Code (technical preview) to generate Python scripts, from simple neural networks in Keras and data visualization scripts to remarks about the secrets of existence
When you trim all of the hype and apocalyptic-like talk about language models like GPT-3 and actually get to play with them a little bit, you realize the good, the bad and the ugly about the scope of such applications.
By demystifying a little bit their true potential, we get to assess this unbelievable tool that could potentially be useful for countless different problems (granted that valid concerns be addressed), as well as learn its technical limitations like its lack of true human-like contextual understanding of basic sentences.
Let’s start with a simple neural network in Keras. For this first script, all I gave to the model as input was:
def SimpleNeuralNetKeras(): pass
The output from the AI-generated autocompletion was this:
def SimpleNeuralNetKeras(): net_net = Sequential() net_net.add(Dense(units=1, input_dim=1)) net_net.compile(loss='mean_squared_error', optimizer='adam') net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5') net_net = load_model('my_model.h5') net_net.predict(x_test, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5') """....it goes on and on"""
Although it continued to suggest the retraining of the same model, if we trim the fat, this is what we get:
def SimpleNeuralNetKeras(): net_net = Sequential() net_net.add(Dense(units=1, input_dim=1)) net_net.compile(loss='mean_squared_error', optimizer='adam') net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5')
Honestly! Not bad at all! Let’s see what happens when I ask it to create a fake dataset to match this neural network set up:
My input here was simply:
x_train,
what I got back was:
x_train,y_train,x_test,y_test = get_data()
Interesting. Let’s see if the model could actually write out the get_data() function for us.
My input for that was:
def get_...
literally just that, and what I got completely automatically was:
def get_data(): """ This function is used to get the data for the neural network. """ # Load the data data = np.loadtxt('data.csv', delimiter=',') # Split the data x = data[:, :-1] y = data[:, -1] # Split the data x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) return x_train,y_train,x_test,y_test
It does look pretty neat, although the unpacking of x and y seems a bit odd among other minor details, however, it does look like a piece of code that could be run with just a few tweaks.
How about plotting? Could we get a nice plot of some synthetic data?
Again this was my input for the model:
def plotFakeData(): """ This function creates a fake dataset of some normally distributed data and plots the result of passing it through a sin function. """
This is what I got:
def plotFakeData(): """ This function creates a fake dataset of some normally distributed data and plots the result of passing it through a sin function. """ import numpy as np import matplotlib.pyplot as plt # Create some fake data x = np.linspace(0, 10, 100) y = np.sin(x) + np.random.normal(0, 0.1, 100) # Plot the data plt.plot(x, y) plt.show()
It looks pretty close! Shall we test it?
plotFakeData()
It actually runs! How cool is that?
Although the data created was not normally distributed, (I mean that was just something random that came up in my head), the model did add normally distributed noise to a sequence of data points after passing them through a sin function, after which it plotted the data successfully.
Now, how about writing tests for already defined functions?
Here my input was:
def sum_Square(a,b): return (a+b)**2def test_sum_Square(): pass
What I got:
def test_sum_Square(): assert sum_Square(2,3) == 25 assert sum_Square(3,5) == 55 assert sum_Square(3,5) != 56test_sum_Square()# Output (from running it on a jupyter notebook)AssertionError Traceback (most recent call last)<ipython-input-94-b8fb676bf724> in <module>----> 1 test_sum_Square()<ipython-input-93-bf52191596f9> in test_sum_Square() 1 def test_sum_Square(): 2 assert sum_Square(2,3) == 25----> 3 assert sum_Square(3,5) == 55 4 assert sum_Square(3,5) != 56AssertionError:
Not bad! Actually the first and third tests were correct, the second not so much because for 3 and 5 the expected result would be 64. Nevertheless, it is really impressive that the model can actually do this kind of stuff out of the box just from a simple function definition.
After playing with potentially useful applications for the model, I decided, just for fun, to ask some random pseudo-philosophical questions to see what kind of answers the model would come up with.
My input:
def writeArticleAboutSecretOfExistence(): pass
What I got:
def writeArticleAboutSecretOfExistence(): """ The secret of existence is to be one. """
That is one short article but at least as a sentence, it does make some sense. I can definitely picture an old philosopher or monk giving this advice to a traveler seeking knowledge somewhere in a hypothetical mountain of wisdom.
Granted, the functions are supposed to be code, but I was just having some nerd fun ;).
Another one:
def writeArticleAboutHowToSolveAnyProblem(): pass
I got:
def writeArticleAboutHowToSolveAnyProblem(): """ The secret of solving any problem is to think about it in another way. """ pass
All right, now you know, think about your problem in another way and boom! You solved it!
I think the future of AI-assisted programming looks bright, although there are issues that must be addressed for this to be a real-world solution.
As models like this understand more and more about a programmer’s intention regarding code, the amount of time needed to write good code will likely decrease a lot, which I think could have amazing benefits, allowing coders to focus on more important big picture issues.
If you want to get started playing around with github copilot, sign up for their waitlist to get access to the technical preview.
If you liked this post, follow me on Medium, subscribe to my newsletter, connect with me on Twitter, LinkedIn, Instagram, and join Medium! Thanks and see you next time! :) | [
{
"code": null,
"e": 429,
"s": 172,
"text": "It’s been a while since I got access to the technical preview of OpenAi’s Github copilot. Since then, I kind of learned to enjoy asking it all sorts of questions in the form of function names and descriptions to see what kind of code it could come up with."
},
{
"code": null,
"e": 669,
"s": 429,
"text": "In this article, I will share how I used the Github Copilot extension for VS Code (technical preview) to generate Python scripts, from simple neural networks in Keras and data visualization scripts to remarks about the secrets of existence"
},
{
"code": null,
"e": 888,
"s": 669,
"text": "When you trim all of the hype and apocalyptic-like talk about language models like GPT-3 and actually get to play with them a little bit, you realize the good, the bad and the ugly about the scope of such applications."
},
{
"code": null,
"e": 1210,
"s": 888,
"text": "By demystifying a little bit their true potential, we get to assess this unbelievable tool that could potentially be useful for countless different problems (granted that valid concerns be addressed), as well as learn its technical limitations like its lack of true human-like contextual understanding of basic sentences."
},
{
"code": null,
"e": 1322,
"s": 1210,
"text": "Let’s start with a simple neural network in Keras. For this first script, all I gave to the model as input was:"
},
{
"code": null,
"e": 1358,
"s": 1322,
"text": "def SimpleNeuralNetKeras(): pass"
},
{
"code": null,
"e": 1416,
"s": 1358,
"text": "The output from the AI-generated autocompletion was this:"
},
{
"code": null,
"e": 2189,
"s": 1416,
"text": "def SimpleNeuralNetKeras(): net_net = Sequential() net_net.add(Dense(units=1, input_dim=1)) net_net.compile(loss='mean_squared_error', optimizer='adam') net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5') net_net = load_model('my_model.h5') net_net.predict(x_test, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5') \"\"\"....it goes on and on\"\"\""
},
{
"code": null,
"e": 2297,
"s": 2189,
"text": "Although it continued to suggest the retraining of the same model, if we trim the fat, this is what we get:"
},
{
"code": null,
"e": 2673,
"s": 2297,
"text": "def SimpleNeuralNetKeras(): net_net = Sequential() net_net.add(Dense(units=1, input_dim=1)) net_net.compile(loss='mean_squared_error', optimizer='adam') net_net.fit(x_train, y_train, epochs=100, batch_size=1, verbose=0) net_net.evaluate(x_test, y_test, batch_size=1, verbose=0) net_net.predict(x_test, batch_size=1, verbose=0) net_net.save('my_model.h5')"
},
{
"code": null,
"e": 2798,
"s": 2673,
"text": "Honestly! Not bad at all! Let’s see what happens when I ask it to create a fake dataset to match this neural network set up:"
},
{
"code": null,
"e": 2824,
"s": 2798,
"text": "My input here was simply:"
},
{
"code": null,
"e": 2833,
"s": 2824,
"text": "x_train,"
},
{
"code": null,
"e": 2854,
"s": 2833,
"text": "what I got back was:"
},
{
"code": null,
"e": 2897,
"s": 2854,
"text": "x_train,y_train,x_test,y_test = get_data()"
},
{
"code": null,
"e": 2990,
"s": 2897,
"text": "Interesting. Let’s see if the model could actually write out the get_data() function for us."
},
{
"code": null,
"e": 3013,
"s": 2990,
"text": "My input for that was:"
},
{
"code": null,
"e": 3025,
"s": 3013,
"text": "def get_..."
},
{
"code": null,
"e": 3091,
"s": 3025,
"text": "literally just that, and what I got completely automatically was:"
},
{
"code": null,
"e": 3465,
"s": 3091,
"text": "def get_data(): \"\"\" This function is used to get the data for the neural network. \"\"\" # Load the data data = np.loadtxt('data.csv', delimiter=',') # Split the data x = data[:, :-1] y = data[:, -1] # Split the data x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) return x_train,y_train,x_test,y_test"
},
{
"code": null,
"e": 3653,
"s": 3465,
"text": "It does look pretty neat, although the unpacking of x and y seems a bit odd among other minor details, however, it does look like a piece of code that could be run with just a few tweaks."
},
{
"code": null,
"e": 3722,
"s": 3653,
"text": "How about plotting? Could we get a nice plot of some synthetic data?"
},
{
"code": null,
"e": 3761,
"s": 3722,
"text": "Again this was my input for the model:"
},
{
"code": null,
"e": 3935,
"s": 3761,
"text": "def plotFakeData(): \"\"\" This function creates a fake dataset of some normally distributed data and plots the result of passing it through a sin function. \"\"\""
},
{
"code": null,
"e": 3955,
"s": 3935,
"text": "This is what I got:"
},
{
"code": null,
"e": 4344,
"s": 3955,
"text": "def plotFakeData(): \"\"\" This function creates a fake dataset of some normally distributed data and plots the result of passing it through a sin function. \"\"\" import numpy as np import matplotlib.pyplot as plt # Create some fake data x = np.linspace(0, 10, 100) y = np.sin(x) + np.random.normal(0, 0.1, 100) # Plot the data plt.plot(x, y) plt.show()"
},
{
"code": null,
"e": 4385,
"s": 4344,
"text": "It looks pretty close! Shall we test it?"
},
{
"code": null,
"e": 4400,
"s": 4385,
"text": "plotFakeData()"
},
{
"code": null,
"e": 4436,
"s": 4400,
"text": "It actually runs! How cool is that?"
},
{
"code": null,
"e": 4720,
"s": 4436,
"text": "Although the data created was not normally distributed, (I mean that was just something random that came up in my head), the model did add normally distributed noise to a sequence of data points after passing them through a sin function, after which it plotted the data successfully."
},
{
"code": null,
"e": 4780,
"s": 4720,
"text": "Now, how about writing tests for already defined functions?"
},
{
"code": null,
"e": 4799,
"s": 4780,
"text": "Here my input was:"
},
{
"code": null,
"e": 4869,
"s": 4799,
"text": "def sum_Square(a,b): return (a+b)**2def test_sum_Square(): pass"
},
{
"code": null,
"e": 4881,
"s": 4869,
"text": "What I got:"
},
{
"code": null,
"e": 5426,
"s": 4881,
"text": "def test_sum_Square(): assert sum_Square(2,3) == 25 assert sum_Square(3,5) == 55 assert sum_Square(3,5) != 56test_sum_Square()# Output (from running it on a jupyter notebook)AssertionError Traceback (most recent call last)<ipython-input-94-b8fb676bf724> in <module>----> 1 test_sum_Square()<ipython-input-93-bf52191596f9> in test_sum_Square() 1 def test_sum_Square(): 2 assert sum_Square(2,3) == 25----> 3 assert sum_Square(3,5) == 55 4 assert sum_Square(3,5) != 56AssertionError: "
},
{
"code": null,
"e": 5703,
"s": 5426,
"text": "Not bad! Actually the first and third tests were correct, the second not so much because for 3 and 5 the expected result would be 64. Nevertheless, it is really impressive that the model can actually do this kind of stuff out of the box just from a simple function definition."
},
{
"code": null,
"e": 5902,
"s": 5703,
"text": "After playing with potentially useful applications for the model, I decided, just for fun, to ask some random pseudo-philosophical questions to see what kind of answers the model would come up with."
},
{
"code": null,
"e": 5912,
"s": 5902,
"text": "My input:"
},
{
"code": null,
"e": 5962,
"s": 5912,
"text": "def writeArticleAboutSecretOfExistence(): pass"
},
{
"code": null,
"e": 5974,
"s": 5962,
"text": "What I got:"
},
{
"code": null,
"e": 6071,
"s": 5974,
"text": "def writeArticleAboutSecretOfExistence(): \"\"\" The secret of existence is to be one. \"\"\""
},
{
"code": null,
"e": 6301,
"s": 6071,
"text": "That is one short article but at least as a sentence, it does make some sense. I can definitely picture an old philosopher or monk giving this advice to a traveler seeking knowledge somewhere in a hypothetical mountain of wisdom."
},
{
"code": null,
"e": 6389,
"s": 6301,
"text": "Granted, the functions are supposed to be code, but I was just having some nerd fun ;)."
},
{
"code": null,
"e": 6402,
"s": 6389,
"text": "Another one:"
},
{
"code": null,
"e": 6455,
"s": 6402,
"text": "def writeArticleAboutHowToSolveAnyProblem(): pass"
},
{
"code": null,
"e": 6462,
"s": 6455,
"text": "I got:"
},
{
"code": null,
"e": 6603,
"s": 6462,
"text": "def writeArticleAboutHowToSolveAnyProblem(): \"\"\" The secret of solving any problem is to think about it in another way. \"\"\" pass"
},
{
"code": null,
"e": 6693,
"s": 6603,
"text": "All right, now you know, think about your problem in another way and boom! You solved it!"
},
{
"code": null,
"e": 6840,
"s": 6693,
"text": "I think the future of AI-assisted programming looks bright, although there are issues that must be addressed for this to be a real-world solution."
},
{
"code": null,
"e": 7111,
"s": 6840,
"text": "As models like this understand more and more about a programmer’s intention regarding code, the amount of time needed to write good code will likely decrease a lot, which I think could have amazing benefits, allowing coders to focus on more important big picture issues."
},
{
"code": null,
"e": 7241,
"s": 7111,
"text": "If you want to get started playing around with github copilot, sign up for their waitlist to get access to the technical preview."
}
] |
PySpark debugging — 6 common issues | by Maria Karanasou | Towards Data Science | Debugging a spark application can range from a fun to a very (and I mean very) frustrating experience.
I’ve started gathering the issues I’ve come across from time to time to compile a list of the most common problems and their solutions.
This is the first part of this list. I hope you find it useful and it saves you some time. Most of them are very simple to resolve but their stacktrace can be cryptic and not very helpful.
When you add a column to a dataframe using a udf but the result is Null: the udf return datatype is different than what was defined
For example, if you define a udf function that takes as input two numbers a and b and returns a / b , this udf function will return a float (in Python 3). If the udf is defined as:
udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.BooleanType())# or udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.DoubleType())
instead of:
udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.FloatType())
then the outcome of using the udf will be something like this:
df = df.withColumn('a_b_ratio', udf_ratio_calculation('a', 'b'))df.show() +---+---+---------+| a| b|a_b_ratio|+---+---+---------+| 1| 0| null|| 10| 3| null|+---+---+---------+
Full example:
This exception usually happens when you are trying to connect your application to an external system, e.g. a database. The stacktrace below is from an attempt to save a dataframe in Postgres.
This means that spark cannot find the necessary jar driver to connect to the database. We need to provide our application with the correct jars either in the spark configuration when instantiating the session
from pyspark import SparkConffrom pyspark.sql import SparkSessionconf = SparkConf()conf.set('spark.jars', '/full/path/to/postgres.jar,/full/path/to/other/jar')spark_session = SparkSession.builder \ .config(conf=conf) \ .appName('test') \ .getOrCreate()
or as a command line argument — depending on how we run our application.
spark-submit --jars /full/path/to/postgres.jar,/full/path/to/other/jar ...
Note 1: It is very important that the jars are accessible to all nodes and not local to the driver.
Note 2: This error might also mean a spark version mismatch between the cluster components. There other more common telltales, like AttributeError. More on this here.
Note 3: Make sure there is no space between the commas in the list of jars.
Spark driver memory and spark executor memory are set by default to 1g. It is in general very useful to take a look at the many configuration parameters and their defaults, because there are many things there that can influence your spark application.
spark.apache.org
When spark is running locally, you should adjust the spark.driver.memory to something that’s reasonable for your system, e.g. 8g and when running on a cluster, you might also want to tweak the spark.executor.memory also, even though that depends on your kind of cluster and its configuration.
Again as in #2, all the necessary files/ jars should be located somewhere accessible to all of the components of your cluster, e.g. an FTP server or a common mounted drive.
spark-submit --master yarn --deploy-mode cluster http://somewhere/accessible/to/master/and/workers/test.py
Or if the error happens while trying to save to a database, you’ll get a java.lang.NullPointerException :
This usually means that we forgot to set the driver , e.g. org.postgresql.Driver for Postgres:
df = spark.read.format('jdbc').options( url= 'db_url', driver='org.postgresql.Driver', # <-- here dbtable='table_name', user='user', password='password').load()
Please, also make sure you check #2 so that the driver jars are properly set.
You might get the following horrible stacktrace for various reasons.
Two of the most common are:
You are using pyspark functions without having an active spark session
from pyspark.sql import SparkSession, functions as Fclass A(object): def __init__(self): self.calculations = F.col('a') / F.col('b')...a = A() # instantiating A without an active spark session will give you this error
Or you are using pyspark functions within a udf:
from pyspark import SparkConffrom pyspark.sql import SparkSession, functions as F, types as Tconf = SparkConf()spark_session = SparkSession.builder \ .config(conf=conf) \ .appName('test') \ .getOrCreate()# create a dataframedata = [{'a': 1, 'b': 0}, {'a': 10, 'b': 3}]df = spark_session.createDataFrame(data)df.show()# +---+---+# | a| b|# +---+---+# | 1| 0|# | 10| 3|# +---+---+# define a simple function that returns a / b# we *cannot* use pyspark functions inside a udf# udfs operate on a row per row basis while pyspark functions on a column basisdef calculate_a_b_max(a, b): return F.max([a, b])# and a udf for this function - notice the return datatypeudf_max_calculation = F.udf(calculate_a_b_ratio, T.FloatType())df = df.withColumn('a_b_max', udf_max_calculation('a', 'b'))df.show()
Both will give you this error.
In the last example F.max needs a column as an input and not a list, so the correct usage would be:
df = df.withColumn('a_max', F.max('a'))
Which would give us the maximum of column a — not what the udf is trying to do.
The correct way to set up a udf that calculates the maximum between two columns for each row would be:
def calculate_a_b_max(a, b): return max([a, b])
Assuming a and b are numbers. (There are other ways to do this of course without a udf.)
I hope this was helpful. I plan to continue with the list and in time go to more complex issues, like debugging a memory leak in a pyspark application.Any thoughts, questions, corrections and suggestions are very welcome :)
If you want to know a bit about how Spark works, take a look at: | [
{
"code": null,
"e": 275,
"s": 172,
"text": "Debugging a spark application can range from a fun to a very (and I mean very) frustrating experience."
},
{
"code": null,
"e": 411,
"s": 275,
"text": "I’ve started gathering the issues I’ve come across from time to time to compile a list of the most common problems and their solutions."
},
{
"code": null,
"e": 600,
"s": 411,
"text": "This is the first part of this list. I hope you find it useful and it saves you some time. Most of them are very simple to resolve but their stacktrace can be cryptic and not very helpful."
},
{
"code": null,
"e": 732,
"s": 600,
"text": "When you add a column to a dataframe using a udf but the result is Null: the udf return datatype is different than what was defined"
},
{
"code": null,
"e": 913,
"s": 732,
"text": "For example, if you define a udf function that takes as input two numbers a and b and returns a / b , this udf function will return a float (in Python 3). If the udf is defined as:"
},
{
"code": null,
"e": 1052,
"s": 913,
"text": "udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.BooleanType())# or udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.DoubleType())"
},
{
"code": null,
"e": 1064,
"s": 1052,
"text": "instead of:"
},
{
"code": null,
"e": 1130,
"s": 1064,
"text": "udf_ratio_calculation = F.udf(calculate_a_b_ratio, T.FloatType())"
},
{
"code": null,
"e": 1193,
"s": 1130,
"text": "then the outcome of using the udf will be something like this:"
},
{
"code": null,
"e": 1382,
"s": 1193,
"text": "df = df.withColumn('a_b_ratio', udf_ratio_calculation('a', 'b'))df.show() +---+---+---------+| a| b|a_b_ratio|+---+---+---------+| 1| 0| null|| 10| 3| null|+---+---+---------+"
},
{
"code": null,
"e": 1396,
"s": 1382,
"text": "Full example:"
},
{
"code": null,
"e": 1588,
"s": 1396,
"text": "This exception usually happens when you are trying to connect your application to an external system, e.g. a database. The stacktrace below is from an attempt to save a dataframe in Postgres."
},
{
"code": null,
"e": 1797,
"s": 1588,
"text": "This means that spark cannot find the necessary jar driver to connect to the database. We need to provide our application with the correct jars either in the spark configuration when instantiating the session"
},
{
"code": null,
"e": 2059,
"s": 1797,
"text": "from pyspark import SparkConffrom pyspark.sql import SparkSessionconf = SparkConf()conf.set('spark.jars', '/full/path/to/postgres.jar,/full/path/to/other/jar')spark_session = SparkSession.builder \\ .config(conf=conf) \\ .appName('test') \\ .getOrCreate()"
},
{
"code": null,
"e": 2132,
"s": 2059,
"text": "or as a command line argument — depending on how we run our application."
},
{
"code": null,
"e": 2207,
"s": 2132,
"text": "spark-submit --jars /full/path/to/postgres.jar,/full/path/to/other/jar ..."
},
{
"code": null,
"e": 2307,
"s": 2207,
"text": "Note 1: It is very important that the jars are accessible to all nodes and not local to the driver."
},
{
"code": null,
"e": 2474,
"s": 2307,
"text": "Note 2: This error might also mean a spark version mismatch between the cluster components. There other more common telltales, like AttributeError. More on this here."
},
{
"code": null,
"e": 2550,
"s": 2474,
"text": "Note 3: Make sure there is no space between the commas in the list of jars."
},
{
"code": null,
"e": 2802,
"s": 2550,
"text": "Spark driver memory and spark executor memory are set by default to 1g. It is in general very useful to take a look at the many configuration parameters and their defaults, because there are many things there that can influence your spark application."
},
{
"code": null,
"e": 2819,
"s": 2802,
"text": "spark.apache.org"
},
{
"code": null,
"e": 3112,
"s": 2819,
"text": "When spark is running locally, you should adjust the spark.driver.memory to something that’s reasonable for your system, e.g. 8g and when running on a cluster, you might also want to tweak the spark.executor.memory also, even though that depends on your kind of cluster and its configuration."
},
{
"code": null,
"e": 3285,
"s": 3112,
"text": "Again as in #2, all the necessary files/ jars should be located somewhere accessible to all of the components of your cluster, e.g. an FTP server or a common mounted drive."
},
{
"code": null,
"e": 3392,
"s": 3285,
"text": "spark-submit --master yarn --deploy-mode cluster http://somewhere/accessible/to/master/and/workers/test.py"
},
{
"code": null,
"e": 3498,
"s": 3392,
"text": "Or if the error happens while trying to save to a database, you’ll get a java.lang.NullPointerException :"
},
{
"code": null,
"e": 3593,
"s": 3498,
"text": "This usually means that we forgot to set the driver , e.g. org.postgresql.Driver for Postgres:"
},
{
"code": null,
"e": 3770,
"s": 3593,
"text": "df = spark.read.format('jdbc').options( url= 'db_url', driver='org.postgresql.Driver', # <-- here dbtable='table_name', user='user', password='password').load()"
},
{
"code": null,
"e": 3848,
"s": 3770,
"text": "Please, also make sure you check #2 so that the driver jars are properly set."
},
{
"code": null,
"e": 3917,
"s": 3848,
"text": "You might get the following horrible stacktrace for various reasons."
},
{
"code": null,
"e": 3945,
"s": 3917,
"text": "Two of the most common are:"
},
{
"code": null,
"e": 4016,
"s": 3945,
"text": "You are using pyspark functions without having an active spark session"
},
{
"code": null,
"e": 4245,
"s": 4016,
"text": "from pyspark.sql import SparkSession, functions as Fclass A(object): def __init__(self): self.calculations = F.col('a') / F.col('b')...a = A() # instantiating A without an active spark session will give you this error "
},
{
"code": null,
"e": 4294,
"s": 4245,
"text": "Or you are using pyspark functions within a udf:"
},
{
"code": null,
"e": 5101,
"s": 4294,
"text": "from pyspark import SparkConffrom pyspark.sql import SparkSession, functions as F, types as Tconf = SparkConf()spark_session = SparkSession.builder \\ .config(conf=conf) \\ .appName('test') \\ .getOrCreate()# create a dataframedata = [{'a': 1, 'b': 0}, {'a': 10, 'b': 3}]df = spark_session.createDataFrame(data)df.show()# +---+---+# | a| b|# +---+---+# | 1| 0|# | 10| 3|# +---+---+# define a simple function that returns a / b# we *cannot* use pyspark functions inside a udf# udfs operate on a row per row basis while pyspark functions on a column basisdef calculate_a_b_max(a, b): return F.max([a, b])# and a udf for this function - notice the return datatypeudf_max_calculation = F.udf(calculate_a_b_ratio, T.FloatType())df = df.withColumn('a_b_max', udf_max_calculation('a', 'b'))df.show()"
},
{
"code": null,
"e": 5132,
"s": 5101,
"text": "Both will give you this error."
},
{
"code": null,
"e": 5232,
"s": 5132,
"text": "In the last example F.max needs a column as an input and not a list, so the correct usage would be:"
},
{
"code": null,
"e": 5272,
"s": 5232,
"text": "df = df.withColumn('a_max', F.max('a'))"
},
{
"code": null,
"e": 5352,
"s": 5272,
"text": "Which would give us the maximum of column a — not what the udf is trying to do."
},
{
"code": null,
"e": 5455,
"s": 5352,
"text": "The correct way to set up a udf that calculates the maximum between two columns for each row would be:"
},
{
"code": null,
"e": 5507,
"s": 5455,
"text": "def calculate_a_b_max(a, b): return max([a, b]) "
},
{
"code": null,
"e": 5596,
"s": 5507,
"text": "Assuming a and b are numbers. (There are other ways to do this of course without a udf.)"
},
{
"code": null,
"e": 5820,
"s": 5596,
"text": "I hope this was helpful. I plan to continue with the list and in time go to more complex issues, like debugging a memory leak in a pyspark application.Any thoughts, questions, corrections and suggestions are very welcome :)"
}
] |
What is modulo % operator in Python? | The % symbol is defined in Python as modulo operator. It can also be called remainder operator. It returns remainder of division of two numeric operands (except complex numbers).
>>> a=10
>>> b=3
>>> a%b
1
>>> a=12.25
>>> b=4
>>> a%b
0.25
>>> a=-10
>>> b=6
>>> a%b
2
>>> a=1.55
>>> b=0.05
>>> a%b
0.04999999999999996 | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "The % symbol is defined in Python as modulo operator. It can also be called remainder operator. It returns remainder of division of two numeric operands (except complex numbers)."
},
{
"code": null,
"e": 1379,
"s": 1241,
"text": ">>> a=10\n>>> b=3\n>>> a%b\n1\n>>> a=12.25\n>>> b=4\n>>> a%b\n0.25\n>>> a=-10\n>>> b=6\n>>> a%b\n2\n>>> a=1.55\n>>> b=0.05\n>>> a%b\n0.04999999999999996"
}
] |
losetup - Unix, Linux Command | losetup: set up and control loop devices.
losetup loopdev
losetup -l [-a]
losetup -j file [-o offset]
Detach a loop device:
losetup -d loopdev...
Detach all associated loop devices:
losetup -D
Print the name of the first unused loop device:
losetup -f
Set up a loop device:
losetup [-o offset] [--sizelimit size]
[-Pr] [--show] -f|loopdev file
Resize a loop device:
losetup -c loopdev
losetup loopdev
losetup -l [-a]
losetup -j file [-o offset]
Detach a loop device:
losetup -d loopdev...
Detach all associated loop devices:
losetup -D
Print the name of the first unused loop device:
losetup -f
Set up a loop device:
losetup [-o offset] [--sizelimit size]
[-Pr] [--show] -f|loopdev file
Resize a loop device:
losetup -c loopdev
losetup is used to associate loop devices with regular files or block
devices, to detach loop devices and to query the status of a loop
device. If only the loop_device argument is given, the status of the
corresponding loop deviceis shown.
Example-1:
To detach file or device associated with loop device :
# losetup -e des /dev/loop0 /file
OR
# losetup -d /dev/loop0
Example-2:
The following commands can be used as an example of using the loop device.
# dd if=/dev/zero of=~/file.img bs=1MiB count=10
# losetup --find --show ~/file.img /dev/loop0
# mkfs -t ext2 /dev/loop0
# mount /dev/loop0 /mnt
...
# umount /dev/loop0
# losetup --detach /dev/loop0
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10619,
"s": 10577,
"text": "losetup: set up and control loop devices."
},
{
"code": null,
"e": 11096,
"s": 10619,
"text": " losetup loopdev\n\n losetup -l [-a]\n\n losetup -j file [-o offset]\n\n Detach a loop device:\n\n losetup -d loopdev...\n\n Detach all associated loop devices:\n\n losetup -D\n\n Print the name of the first unused loop device:\n\n losetup -f\n\n Set up a loop device:\n\n losetup [-o offset] [--sizelimit size]\n [-Pr] [--show] -f|loopdev file\n\n Resize a loop device:\n\n losetup -c loopdev\n "
},
{
"code": null,
"e": 11168,
"s": 11096,
"text": " losetup loopdev\n\n losetup -l [-a]\n\n losetup -j file [-o offset]\n"
},
{
"code": null,
"e": 11223,
"s": 11168,
"text": " Detach a loop device:\n\n losetup -d loopdev...\n"
},
{
"code": null,
"e": 11285,
"s": 11223,
"text": " Detach all associated loop devices:\n\n losetup -D\n"
},
{
"code": null,
"e": 11358,
"s": 11285,
"text": "Print the name of the first unused loop device:\n\n losetup -f\n"
},
{
"code": null,
"e": 11484,
"s": 11358,
"text": "Set up a loop device:\n\n losetup [-o offset] [--sizelimit size]\n [-Pr] [--show] -f|loopdev file\n"
},
{
"code": null,
"e": 11538,
"s": 11484,
"text": "Resize a loop device:\n\n losetup -c loopdev"
},
{
"code": null,
"e": 11811,
"s": 11538,
"text": "losetup is used to associate loop devices with regular files or block\n devices, to detach loop devices and to query the status of a loop\n device. If only the loop_device argument is given, the status of the\n corresponding loop deviceis shown.\n"
},
{
"code": null,
"e": 11822,
"s": 11811,
"text": "Example-1:"
},
{
"code": null,
"e": 11877,
"s": 11822,
"text": "To detach file or device associated with loop device :"
},
{
"code": null,
"e": 11911,
"s": 11877,
"text": "# losetup -e des /dev/loop0 /file"
},
{
"code": null,
"e": 11914,
"s": 11911,
"text": "OR"
},
{
"code": null,
"e": 11938,
"s": 11914,
"text": "# losetup -d /dev/loop0"
},
{
"code": null,
"e": 11949,
"s": 11938,
"text": "Example-2:"
},
{
"code": null,
"e": 12024,
"s": 11949,
"text": "The following commands can be used as an example of using the loop device."
},
{
"code": null,
"e": 12235,
"s": 12024,
"text": " # dd if=/dev/zero of=~/file.img bs=1MiB count=10\n # losetup --find --show ~/file.img /dev/loop0\n # mkfs -t ext2 /dev/loop0\n # mount /dev/loop0 /mnt\n ...\n # umount /dev/loop0\n # losetup --detach /dev/loop0 \n\t "
},
{
"code": null,
"e": 12270,
"s": 12235,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12298,
"s": 12270,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12332,
"s": 12298,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12349,
"s": 12332,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12382,
"s": 12349,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12393,
"s": 12382,
"text": " Pradeep D"
},
{
"code": null,
"e": 12428,
"s": 12393,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12444,
"s": 12428,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12477,
"s": 12444,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12489,
"s": 12477,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12521,
"s": 12489,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12529,
"s": 12521,
"text": " Uplatz"
},
{
"code": null,
"e": 12536,
"s": 12529,
"text": " Print"
},
{
"code": null,
"e": 12547,
"s": 12536,
"text": " Add Notes"
}
] |
Python - How to Group Pandas DataFrame by Days? | We will group Pandas DataFrame using the groupby(). Select the column to be used using the grouper function. We will group day-wise and calculate sum of Registration Price with day interval for our example shown below for Car Sale Records.
Set the frequency as an interval of days in the groupby() grouper method, that means, if the freq is 7D, that would mean data grouped by interval of 7 days of every month till the last date given in the date column.
At first, let’s say the following is our Pandas DataFrame with three columns −
import pandas as pd
# dataframe with one of the columns as Date_of_Purchase
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
pd.Timestamp("2021-01-22"),
pd.Timestamp("2021-01-06"),
pd.Timestamp("2021-01-04"),
pd.Timestamp("2021-05-09")
],
"Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
}
)
Next, use the Grouper to select Date_of_Purchase column within groupby function. The frequency is set 7D i.e. interval of 7 Days grouped till the last date mentioned in the column −
print"\nGroup Dataframe by 7 days...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7D')).sum()
Following is the code −
import pandas as pd
# dataframe with one of the columns as Date_of_Purchase
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
pd.Timestamp("2021-01-22"),
pd.Timestamp("2021-01-06"),
pd.Timestamp("2021-01-04"),
pd.Timestamp("2021-05-09")
],
"Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
}
)
print"DataFrame...\n",dataFrame
# Grouper to select Date_of_Purchase column within groupby function
print("\nGroup Dataframe by 7 days...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7D')).sum()
)
This will produce the following output −
DataFrame...
Car Date_of_Purchase Reg_Price
0 Audi 2021-06-10 1000
1 Lexus 2021-07-11 1400
2 Tesla 2021-06-25 1100
3 Mercedes 2021-06-29 900
4 BMW 2021-03-20 1700
5 Toyota 2021-01-22 1800
6 Nissan 2021-01-06 1300
7 Bentley 2021-01-04 1150
8 Mustang 2021-05-09 1350
Group Dataframe by 7 days...
Reg_Price
Date_of_Purchase
2021-01-04 2450.0
2021-01-11 NaN
2021-01-18 1800.0
2021-01-25 NaN
2021-02-01 NaN
2021-02-08 NaN
2021-02-15 NaN
2021-02-22 NaN
2021-03-01 NaN
2021-03-08 NaN
2021-03-15 1700.0
2021-03-22 NaN
2021-03-29 NaN
2021-04-05 NaN
2021-04-12 NaN
2021-04-19 NaN
2021-04-26 NaN
2021-05-03 1350.0
2021-05-10 NaN
2021-05-17 NaN
2021-05-24 NaN
2021-05-31 NaN
2021-06-07 1000.0
2021-06-14 NaN
2021-06-21 1100.0
2021-06-28 900.0
2021-07-05 1400.0 | [
{
"code": null,
"e": 1302,
"s": 1062,
"text": "We will group Pandas DataFrame using the groupby(). Select the column to be used using the grouper function. We will group day-wise and calculate sum of Registration Price with day interval for our example shown below for Car Sale Records."
},
{
"code": null,
"e": 1518,
"s": 1302,
"text": "Set the frequency as an interval of days in the groupby() grouper method, that means, if the freq is 7D, that would mean data grouped by interval of 7 days of every month till the last date given in the date column."
},
{
"code": null,
"e": 1597,
"s": 1518,
"text": "At first, let’s say the following is our Pandas DataFrame with three columns −"
},
{
"code": null,
"e": 2258,
"s": 1597,
"text": "import pandas as pd\n\n# dataframe with one of the columns as Date_of_Purchase\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\", \"Toyota\", \"Nissan\", \"Bentley\", \"Mustang\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n pd.Timestamp(\"2021-01-22\"),\n pd.Timestamp(\"2021-01-06\"),\n pd.Timestamp(\"2021-01-04\"),\n pd.Timestamp(\"2021-05-09\")\n ],\n\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)"
},
{
"code": null,
"e": 2440,
"s": 2258,
"text": "Next, use the Grouper to select Date_of_Purchase column within groupby function. The frequency is set 7D i.e. interval of 7 Days grouped till the last date mentioned in the column −"
},
{
"code": null,
"e": 2559,
"s": 2440,
"text": "print\"\\nGroup Dataframe by 7 days...\\n\",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7D')).sum()"
},
{
"code": null,
"e": 2583,
"s": 2559,
"text": "Following is the code −"
},
{
"code": null,
"e": 3470,
"s": 2583,
"text": "import pandas as pd\n\n# dataframe with one of the columns as Date_of_Purchase\ndataFrame = pd.DataFrame(\n {\n \"Car\": [\"Audi\", \"Lexus\", \"Tesla\", \"Mercedes\", \"BMW\", \"Toyota\", \"Nissan\", \"Bentley\", \"Mustang\"],\n\n \"Date_of_Purchase\": [\n pd.Timestamp(\"2021-06-10\"),\n pd.Timestamp(\"2021-07-11\"),\n pd.Timestamp(\"2021-06-25\"),\n pd.Timestamp(\"2021-06-29\"),\n pd.Timestamp(\"2021-03-20\"),\n pd.Timestamp(\"2021-01-22\"),\n pd.Timestamp(\"2021-01-06\"),\n pd.Timestamp(\"2021-01-04\"),\n pd.Timestamp(\"2021-05-09\")\n ],\n \"Reg_Price\": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]\n }\n)\n\nprint\"DataFrame...\\n\",dataFrame\n\n# Grouper to select Date_of_Purchase column within groupby function\nprint(\"\\nGroup Dataframe by 7 days...\\n\",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='7D')).sum()\n)"
},
{
"code": null,
"e": 3511,
"s": 3470,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4723,
"s": 3511,
"text": "DataFrame...\n Car Date_of_Purchase Reg_Price\n0 Audi 2021-06-10 1000\n1 Lexus 2021-07-11 1400\n2 Tesla 2021-06-25 1100\n3 Mercedes 2021-06-29 900\n4 BMW 2021-03-20 1700\n5 Toyota 2021-01-22 1800\n6 Nissan 2021-01-06 1300\n7 Bentley 2021-01-04 1150\n8 Mustang 2021-05-09 1350\n\nGroup Dataframe by 7 days...\n Reg_Price\nDate_of_Purchase\n2021-01-04 2450.0\n2021-01-11 NaN\n2021-01-18 1800.0\n2021-01-25 NaN\n2021-02-01 NaN\n2021-02-08 NaN\n2021-02-15 NaN\n2021-02-22 NaN\n2021-03-01 NaN\n2021-03-08 NaN\n2021-03-15 1700.0\n2021-03-22 NaN\n2021-03-29 NaN\n2021-04-05 NaN\n2021-04-12 NaN\n2021-04-19 NaN\n2021-04-26 NaN\n2021-05-03 1350.0\n2021-05-10 NaN\n2021-05-17 NaN\n2021-05-24 NaN\n2021-05-31 NaN\n2021-06-07 1000.0\n2021-06-14 NaN\n2021-06-21 1100.0\n2021-06-28 900.0\n2021-07-05 1400.0"
}
] |
Java - String matches() Method | This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).
Here is the syntax of this method −
public boolean matches(String regex)
Here is the detail of parameters −
regex − the regular expression to which this string is to be matched.
regex − the regular expression to which this string is to be matched.
This method returns true if, and only if, this string matches the given regular expression.
This method returns true if, and only if, this string matches the given regular expression.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.matches("(.*)Tutorials(.*)"));
System.out.print("Return Value :" );
System.out.println(Str.matches("Tutorials"));
System.out.print("Return Value :" );
System.out.println(Str.matches("Welcome(.*)"));
}
}
This will produce the following result −
Return Value :true
Return Value :false
Return Value :true
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2598,
"s": 2377,
"text": "This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str)."
},
{
"code": null,
"e": 2634,
"s": 2598,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2672,
"s": 2634,
"text": "public boolean matches(String regex)\n"
},
{
"code": null,
"e": 2707,
"s": 2672,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2777,
"s": 2707,
"text": "regex − the regular expression to which this string is to be matched."
},
{
"code": null,
"e": 2847,
"s": 2777,
"text": "regex − the regular expression to which this string is to be matched."
},
{
"code": null,
"e": 2939,
"s": 2847,
"text": "This method returns true if, and only if, this string matches the given regular expression."
},
{
"code": null,
"e": 3031,
"s": 2939,
"text": "This method returns true if, and only if, this string matches the given regular expression."
},
{
"code": null,
"e": 3483,
"s": 3031,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.matches(\"(.*)Tutorials(.*)\"));\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.matches(\"Tutorials\"));\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.matches(\"Welcome(.*)\"));\n }\n}"
},
{
"code": null,
"e": 3524,
"s": 3483,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3583,
"s": 3524,
"text": "Return Value :true\nReturn Value :false\nReturn Value :true\n"
},
{
"code": null,
"e": 3616,
"s": 3583,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3632,
"s": 3616,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3665,
"s": 3632,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3681,
"s": 3665,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3716,
"s": 3681,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3730,
"s": 3716,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3764,
"s": 3730,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3778,
"s": 3764,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3815,
"s": 3778,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3830,
"s": 3815,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3863,
"s": 3830,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3863,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3889,
"s": 3882,
"text": " Print"
},
{
"code": null,
"e": 3900,
"s": 3889,
"text": " Add Notes"
}
] |
Java - Arrays | Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
The following code snippets are examples of this syntax −
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
You can create an array by using the new operator with the following syntax −
arrayRefVar = new dataType[arraySize];
The above statement does two things −
It creates an array using new dataType[arraySize].
It creates an array using new dataType[arraySize].
It assigns the reference of the newly created array to the variable arrayRefVar.
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Here is a complete example showing how to create, initialize, and process arrays −
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This will produce the following result −
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
The following code displays all the elements in the array myList −
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This will produce the following result −
1.9
2.9
3.4
3.5
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 −
printArray(new int[]{3, 1, 2, 6, 4, 2});
A method may also return an array. For example, the following method returns an array that is the reversal of another array −
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)).
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)
public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.)
public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.)
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2642,
"s": 2377,
"text": "Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 2865,
"s": 2642,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables."
},
{
"code": null,
"e": 2981,
"s": 2865,
"text": "This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables."
},
{
"code": null,
"e": 3183,
"s": 2981,
"text": "To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −"
},
{
"code": null,
"e": 3288,
"s": 3183,
"text": "dataType[] arrayRefVar; // preferred way.\nor\ndataType arrayRefVar[]; // works but not preferred way.\n"
},
{
"code": null,
"e": 3463,
"s": 3288,
"text": "Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers."
},
{
"code": null,
"e": 3521,
"s": 3463,
"text": "The following code snippets are examples of this syntax −"
},
{
"code": null,
"e": 3612,
"s": 3521,
"text": "double[] myList; // preferred way.\nor\ndouble myList[]; // works but not preferred way."
},
{
"code": null,
"e": 3690,
"s": 3612,
"text": "You can create an array by using the new operator with the following syntax −"
},
{
"code": null,
"e": 3730,
"s": 3690,
"text": "arrayRefVar = new dataType[arraySize];\n"
},
{
"code": null,
"e": 3768,
"s": 3730,
"text": "The above statement does two things −"
},
{
"code": null,
"e": 3819,
"s": 3768,
"text": "It creates an array using new dataType[arraySize]."
},
{
"code": null,
"e": 3870,
"s": 3819,
"text": "It creates an array using new dataType[arraySize]."
},
{
"code": null,
"e": 3951,
"s": 3870,
"text": "It assigns the reference of the newly created array to the variable arrayRefVar."
},
{
"code": null,
"e": 4032,
"s": 3951,
"text": "It assigns the reference of the newly created array to the variable arrayRefVar."
},
{
"code": null,
"e": 4188,
"s": 4032,
"text": "Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −"
},
{
"code": null,
"e": 4239,
"s": 4188,
"text": "dataType[] arrayRefVar = new dataType[arraySize];\n"
},
{
"code": null,
"e": 4288,
"s": 4239,
"text": "Alternatively you can create arrays as follows −"
},
{
"code": null,
"e": 4345,
"s": 4288,
"text": "dataType[] arrayRefVar = {value0, value1, ..., valuek};\n"
},
{
"code": null,
"e": 4475,
"s": 4345,
"text": "The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1."
},
{
"code": null,
"e": 4616,
"s": 4475,
"text": "Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −"
},
{
"code": null,
"e": 4650,
"s": 4616,
"text": "double[] myList = new double[10];"
},
{
"code": null,
"e": 4763,
"s": 4650,
"text": "Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9."
},
{
"code": null,
"e": 4937,
"s": 4763,
"text": "When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known."
},
{
"code": null,
"e": 5020,
"s": 4937,
"text": "Here is a complete example showing how to create, initialize, and process arrays −"
},
{
"code": null,
"e": 5698,
"s": 5020,
"text": "public class TestArray {\n\n public static void main(String[] args) {\n double[] myList = {1.9, 2.9, 3.4, 3.5};\n\n // Print all the array elements\n for (int i = 0; i < myList.length; i++) {\n System.out.println(myList[i] + \" \");\n }\n \n // Summing all elements\n double total = 0;\n for (int i = 0; i < myList.length; i++) {\n total += myList[i];\n }\n System.out.println(\"Total is \" + total);\n \n // Finding the largest element\n double max = myList[0];\n for (int i = 1; i < myList.length; i++) {\n if (myList[i] > max) max = myList[i];\n }\n System.out.println(\"Max is \" + max); \n }\n}"
},
{
"code": null,
"e": 5739,
"s": 5698,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5781,
"s": 5739,
"text": "1.9\n2.9\n3.4\n3.5\nTotal is 11.7\nMax is 3.5\n"
},
{
"code": null,
"e": 5954,
"s": 5781,
"text": "JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable."
},
{
"code": null,
"e": 6021,
"s": 5954,
"text": "The following code displays all the elements in the array myList −"
},
{
"code": null,
"e": 6266,
"s": 6021,
"text": "public class TestArray {\n\n public static void main(String[] args) {\n double[] myList = {1.9, 2.9, 3.4, 3.5};\n\n // Print all the array elements\n for (double element: myList) {\n System.out.println(element);\n }\n }\n}"
},
{
"code": null,
"e": 6307,
"s": 6266,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6324,
"s": 6307,
"text": "1.9\n2.9\n3.4\n3.5\n"
},
{
"code": null,
"e": 6490,
"s": 6324,
"text": "Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −"
},
{
"code": null,
"e": 6626,
"s": 6490,
"text": "public static void printArray(int[] array) {\n for (int i = 0; i < array.length; i++) {\n System.out.print(array[i] + \" \");\n }\n}"
},
{
"code": null,
"e": 6766,
"s": 6626,
"text": "You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2 −"
},
{
"code": null,
"e": 6807,
"s": 6766,
"text": "printArray(new int[]{3, 1, 2, 6, 4, 2});"
},
{
"code": null,
"e": 6933,
"s": 6807,
"text": "A method may also return an array. For example, the following method returns an array that is the reversal of another array −"
},
{
"code": null,
"e": 7139,
"s": 6933,
"text": "public static int[] reverse(int[] list) {\n int[] result = new int[list.length];\n\n for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {\n result[j] = list[i];\n }\n return result;\n}"
},
{
"code": null,
"e": 7332,
"s": 7139,
"text": "The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types."
},
{
"code": null,
"e": 7387,
"s": 7332,
"text": "public static int binarySearch(Object[] a, Object key)"
},
{
"code": null,
"e": 7685,
"s": 7387,
"text": "Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1))."
},
{
"code": null,
"e": 7735,
"s": 7685,
"text": "public static boolean equals(long[] a, long[] a2)"
},
{
"code": null,
"e": 8096,
"s": 7735,
"text": "Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)"
},
{
"code": null,
"e": 8138,
"s": 8096,
"text": "public static void fill(int[] a, int val)"
},
{
"code": null,
"e": 8307,
"s": 8138,
"text": "Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.)"
},
{
"code": null,
"e": 8343,
"s": 8307,
"text": "public static void sort(Object[] a)"
},
{
"code": null,
"e": 8546,
"s": 8343,
"text": "Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.)"
},
{
"code": null,
"e": 8579,
"s": 8546,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8595,
"s": 8579,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8628,
"s": 8595,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8644,
"s": 8628,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8679,
"s": 8644,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8693,
"s": 8679,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8727,
"s": 8693,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8741,
"s": 8727,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8778,
"s": 8741,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8793,
"s": 8778,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8826,
"s": 8793,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8845,
"s": 8826,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8852,
"s": 8845,
"text": " Print"
},
{
"code": null,
"e": 8863,
"s": 8852,
"text": " Add Notes"
}
] |
Image Classification using CNN. Classification of Marvel characters... | by Vishnu Bhaarath | Towards Data Science | Before diving in to the technicalities behind CNN let us talk about living beings . How do they recognize and perceive images. We see multiple images every second and we are able to process it and we are able to recognize it in the future. All this is capable due to Human brain, the most powerful machine in the world. Let us talk about how we perceive images to have a better understanding of CNN. Take a look at the below pictures
We are able to see two images
A man with a right face
A man facing towards us
Based on our focus on the image we see different views, our brain is too powerful ,it automatically recognizes the pattern and help us identify the object. This is the underlying principle behind CNN it searches for patterns and differentiate the images.
Consider the above image, we are able to identify A and B by looking at some patterns. We are able to do this because we have seen these images in the past and our brain has observed some patterns in them which helps us to differentiate it. If we ask to a child or to a person who in his lifetime haven’t seen a lion or dog. Will he be able to classify the above images? Definitely No.
The above illustration is not only applicable to CNN but to machine learning in general. Let us focus on CNN as the article is all about it. We send a bunch of images to CNN for training, CNN looks for patterns in it similar to how human beings does, so when we ask the CNN to identify the images it will be able to recognize the patterns in it. So if we send images to an untrained CNN it will fail as the case with human beings too.
How to make the machine read images ? is the common question that strikes most of us and this is the first step in image processing.
Machine read images by pixel value . Every image is a combination of pixel values, changing the pixel values alters the image. These pixel values has to processed before feeding in to CNN. The number of pixel values depends on the size of the image, so again a problem arises what if the size of the image is too large. A fully connected network will flatten the 2 D array of pixels in to 1 D array and identify the images based on the pixel values.
Convolution layer along with pooling comes to our rescue. It extracts certain features from the images and reduces the size of the image.
Our image of 6*6 matrix is converted in to 3*3 matrix . Our weight is initialized as 3*3 matrix. The weight matrix runs across our image and produce a convoluted output of 3*3 matrix. The weight covers all the pixel values in our image at least once and performs element wise multiplication.
When you look at the element wise multiplication to obtain the convolution layer, an another problem arises the pixel values at the edges are covered only once. This problem can be solved with the help of padding.
The size of the image is preserved when we apply padding. Weights are learned similar to MLP that is to minimize loss function or to help the model in correct prediction of images. We won’t use just a single filter in real world application , the usage of number of filter affects the depth of the convoluted layer. The depth of the convoluted output depends on the number of filters we use.
Every colour images can be represented as a combination of Red , Blue and Green. We split it in to three layers and follow the same procedure applied in case of grey scale images.
The sole purpose of pooling is to reduce the size of the images. Max pooling is preferred in most cases. Pooling operates independently on each layer so the depth of the convolution layer remains unchanged. You can observe that we are applying two strides at a time. The size decreases as the number of strides increases.
Our ultimate aim is to predict whether an image belongs to a particular class or not. But Convolution layer gives us a 3 D activation map and it is not easy to obtain the output class by using convolution layer, So we need to flatten it to produce the desired number of output classes. Forward and Back propagation are done to reduce the losses.
As we can observe we apply convolution at the start to extract useful features from it , followed it by max pooling to reduce the size of the images followed by flattening and finally the output predicts the probability of image belonging to a particular class.
Five Marvel characters were chosen Black Widow, Iron Man, Thor, Captain America and Hulk. Train and Testing set were divided in the ratio of 70: 30 and the performance was observed.
from zipfile import ZipFilefilename= "marvel.zip"with ZipFile(filename,'r')as zip:zip.extractall()
You can ignore the first three blocks as it deals with loading of images and importing dependencies. The zip file which consist of the 5 marvel characters is loaded and extracted in the above block of codes.
#Importingimport osimport numpy as npimport globimport shutilimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2Dfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorbase_dir = os.path.join(os.path.dirname(filename), 'marvel')
All the necessary dependencies are imported, If you get an error while importing these dependencies you have to install it. Using pip install (Jupyter notebook)
# Accessing the images and setting 0.7 of images for training and the rest for testingclasses=['Black Widow','Captain America','Hulk','Iron Man','Thor']for m in classes:img_path = os.path.join(base_dir, m)images = glob.glob(img_path + '/*.jpg')num_train = int(round(len(images)*0.7))train, val = images[:num_train], images[num_train:]# Creating separate directories for training datafor t in train:if not os.path.exists(os.path.join(base_dir, 'train', m)):os.makedirs(os.path.join(base_dir, 'train', m))shutil.move(t, os.path.join(base_dir, 'train', m))# Creating separate directories for validating datafor v in val:if not os.path.exists(os.path.join(base_dir, 'val', m)):os.makedirs(os.path.join(base_dir, 'val', m))shutil.move(v, os.path.join(base_dir, 'val', m))
In the above block of codes a separate directories for training and validation data is created. The train and validation data are divided in the ratio of 70:30. All the image extension are converted to jpg.
train_dir = os.path.join(base_dir, 'train')val_dir = os.path.join(base_dir, 'val')
Two directories are created for training and validation.
# Setting batch size and a constant image shapebatch_size = 130IMG_SHAPE = 150# Rescaling the images so all the values lie between 0 and 1 and applying horizontal flip and training the dataimage_gen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)train_data_gen = image_gen.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE,IMG_SHAPE))# Rescaling the images so all the values lie between 0 and 1 and rotating and training the dataimage_gen = ImageDataGenerator(rescale=1./255, rotation_range=45)train_data_gen = image_gen.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE, IMG_SHAPE))#Rescaling and zooming the dataimage_gen_train = ImageDataGenerator(rescale=1./255,rotation_range=45,width_shift_range=.15,height_shift_range=.15,horizontal_flip=True,zoom_range=0.5)train_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE,IMG_SHAPE),class_mode='sparse')
As the image collected will not be of same size, resizing of image is done. An image size of 150 * 150 is chosen. The pixel value of images ranges from 0 to 255, to provide better results pixel values are re-scaled so all the values lies between 0 and 1. Different techniques such as horizontal flip, zooming , rotation are performed on the existing set of images.
image_gen_val = ImageDataGenerator(rescale=1./255)val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,directory=val_dir,target_size=(IMG_SHAPE, IMG_SHAPE),class_mode='sparse')model = Sequential()model.add(Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_SHAPE,IMG_SHAPE, 3)))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(32, 3, padding='same', activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(64, 3, padding='same', activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))# Adding dropout to turn down some neuronsmodel.add(Flatten())model.add(Dropout(0.2))model.add(Dense(512, activation='relu'))model.add(Dropout(0.2))model.add(Dense(5, activation='softmax'))
Convolution and max pooling is applied to the data set, before sending it to the output layer the model is flattened. Dropout is applied to prevent overfitting of images.
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])epochs = 120history = model.fit_generator(train_data_gen,steps_per_epoch=int(np.ceil(train_data_gen.n / float(batch_size))),epochs=epochs,validation_data=val_data_gen,validation_steps=int(np.ceil(val_data_gen.n / float(batch_size))))
Model is compiled and the performance is observed. You can play with the hyper-parameter to obtain the optimum result.
The link to github(code) is attached below | [
{
"code": null,
"e": 606,
"s": 172,
"text": "Before diving in to the technicalities behind CNN let us talk about living beings . How do they recognize and perceive images. We see multiple images every second and we are able to process it and we are able to recognize it in the future. All this is capable due to Human brain, the most powerful machine in the world. Let us talk about how we perceive images to have a better understanding of CNN. Take a look at the below pictures"
},
{
"code": null,
"e": 636,
"s": 606,
"text": "We are able to see two images"
},
{
"code": null,
"e": 660,
"s": 636,
"text": "A man with a right face"
},
{
"code": null,
"e": 684,
"s": 660,
"text": "A man facing towards us"
},
{
"code": null,
"e": 939,
"s": 684,
"text": "Based on our focus on the image we see different views, our brain is too powerful ,it automatically recognizes the pattern and help us identify the object. This is the underlying principle behind CNN it searches for patterns and differentiate the images."
},
{
"code": null,
"e": 1325,
"s": 939,
"text": "Consider the above image, we are able to identify A and B by looking at some patterns. We are able to do this because we have seen these images in the past and our brain has observed some patterns in them which helps us to differentiate it. If we ask to a child or to a person who in his lifetime haven’t seen a lion or dog. Will he be able to classify the above images? Definitely No."
},
{
"code": null,
"e": 1760,
"s": 1325,
"text": "The above illustration is not only applicable to CNN but to machine learning in general. Let us focus on CNN as the article is all about it. We send a bunch of images to CNN for training, CNN looks for patterns in it similar to how human beings does, so when we ask the CNN to identify the images it will be able to recognize the patterns in it. So if we send images to an untrained CNN it will fail as the case with human beings too."
},
{
"code": null,
"e": 1893,
"s": 1760,
"text": "How to make the machine read images ? is the common question that strikes most of us and this is the first step in image processing."
},
{
"code": null,
"e": 2343,
"s": 1893,
"text": "Machine read images by pixel value . Every image is a combination of pixel values, changing the pixel values alters the image. These pixel values has to processed before feeding in to CNN. The number of pixel values depends on the size of the image, so again a problem arises what if the size of the image is too large. A fully connected network will flatten the 2 D array of pixels in to 1 D array and identify the images based on the pixel values."
},
{
"code": null,
"e": 2481,
"s": 2343,
"text": "Convolution layer along with pooling comes to our rescue. It extracts certain features from the images and reduces the size of the image."
},
{
"code": null,
"e": 2773,
"s": 2481,
"text": "Our image of 6*6 matrix is converted in to 3*3 matrix . Our weight is initialized as 3*3 matrix. The weight matrix runs across our image and produce a convoluted output of 3*3 matrix. The weight covers all the pixel values in our image at least once and performs element wise multiplication."
},
{
"code": null,
"e": 2987,
"s": 2773,
"text": "When you look at the element wise multiplication to obtain the convolution layer, an another problem arises the pixel values at the edges are covered only once. This problem can be solved with the help of padding."
},
{
"code": null,
"e": 3379,
"s": 2987,
"text": "The size of the image is preserved when we apply padding. Weights are learned similar to MLP that is to minimize loss function or to help the model in correct prediction of images. We won’t use just a single filter in real world application , the usage of number of filter affects the depth of the convoluted layer. The depth of the convoluted output depends on the number of filters we use."
},
{
"code": null,
"e": 3559,
"s": 3379,
"text": "Every colour images can be represented as a combination of Red , Blue and Green. We split it in to three layers and follow the same procedure applied in case of grey scale images."
},
{
"code": null,
"e": 3881,
"s": 3559,
"text": "The sole purpose of pooling is to reduce the size of the images. Max pooling is preferred in most cases. Pooling operates independently on each layer so the depth of the convolution layer remains unchanged. You can observe that we are applying two strides at a time. The size decreases as the number of strides increases."
},
{
"code": null,
"e": 4227,
"s": 3881,
"text": "Our ultimate aim is to predict whether an image belongs to a particular class or not. But Convolution layer gives us a 3 D activation map and it is not easy to obtain the output class by using convolution layer, So we need to flatten it to produce the desired number of output classes. Forward and Back propagation are done to reduce the losses."
},
{
"code": null,
"e": 4489,
"s": 4227,
"text": "As we can observe we apply convolution at the start to extract useful features from it , followed it by max pooling to reduce the size of the images followed by flattening and finally the output predicts the probability of image belonging to a particular class."
},
{
"code": null,
"e": 4671,
"s": 4489,
"text": "Five Marvel characters were chosen Black Widow, Iron Man, Thor, Captain America and Hulk. Train and Testing set were divided in the ratio of 70: 30 and the performance was observed."
},
{
"code": null,
"e": 4770,
"s": 4671,
"text": "from zipfile import ZipFilefilename= \"marvel.zip\"with ZipFile(filename,'r')as zip:zip.extractall()"
},
{
"code": null,
"e": 4978,
"s": 4770,
"text": "You can ignore the first three blocks as it deals with loading of images and importing dependencies. The zip file which consist of the 5 marvel characters is loaded and extracted in the above block of codes."
},
{
"code": null,
"e": 5348,
"s": 4978,
"text": "#Importingimport osimport numpy as npimport globimport shutilimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2Dfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorbase_dir = os.path.join(os.path.dirname(filename), 'marvel')"
},
{
"code": null,
"e": 5509,
"s": 5348,
"text": "All the necessary dependencies are imported, If you get an error while importing these dependencies you have to install it. Using pip install (Jupyter notebook)"
},
{
"code": null,
"e": 6276,
"s": 5509,
"text": "# Accessing the images and setting 0.7 of images for training and the rest for testingclasses=['Black Widow','Captain America','Hulk','Iron Man','Thor']for m in classes:img_path = os.path.join(base_dir, m)images = glob.glob(img_path + '/*.jpg')num_train = int(round(len(images)*0.7))train, val = images[:num_train], images[num_train:]# Creating separate directories for training datafor t in train:if not os.path.exists(os.path.join(base_dir, 'train', m)):os.makedirs(os.path.join(base_dir, 'train', m))shutil.move(t, os.path.join(base_dir, 'train', m))# Creating separate directories for validating datafor v in val:if not os.path.exists(os.path.join(base_dir, 'val', m)):os.makedirs(os.path.join(base_dir, 'val', m))shutil.move(v, os.path.join(base_dir, 'val', m))"
},
{
"code": null,
"e": 6483,
"s": 6276,
"text": "In the above block of codes a separate directories for training and validation data is created. The train and validation data are divided in the ratio of 70:30. All the image extension are converted to jpg."
},
{
"code": null,
"e": 6566,
"s": 6483,
"text": "train_dir = os.path.join(base_dir, 'train')val_dir = os.path.join(base_dir, 'val')"
},
{
"code": null,
"e": 6623,
"s": 6566,
"text": "Two directories are created for training and validation."
},
{
"code": null,
"e": 7658,
"s": 6623,
"text": "# Setting batch size and a constant image shapebatch_size = 130IMG_SHAPE = 150# Rescaling the images so all the values lie between 0 and 1 and applying horizontal flip and training the dataimage_gen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)train_data_gen = image_gen.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE,IMG_SHAPE))# Rescaling the images so all the values lie between 0 and 1 and rotating and training the dataimage_gen = ImageDataGenerator(rescale=1./255, rotation_range=45)train_data_gen = image_gen.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE, IMG_SHAPE))#Rescaling and zooming the dataimage_gen_train = ImageDataGenerator(rescale=1./255,rotation_range=45,width_shift_range=.15,height_shift_range=.15,horizontal_flip=True,zoom_range=0.5)train_data_gen = image_gen_train.flow_from_directory(batch_size=batch_size,directory=train_dir,shuffle=True,target_size=(IMG_SHAPE,IMG_SHAPE),class_mode='sparse')"
},
{
"code": null,
"e": 8023,
"s": 7658,
"text": "As the image collected will not be of same size, resizing of image is done. An image size of 150 * 150 is chosen. The pixel value of images ranges from 0 to 255, to provide better results pixel values are re-scaled so all the values lies between 0 and 1. Different techniques such as horizontal flip, zooming , rotation are performed on the existing set of images."
},
{
"code": null,
"e": 8765,
"s": 8023,
"text": "image_gen_val = ImageDataGenerator(rescale=1./255)val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,directory=val_dir,target_size=(IMG_SHAPE, IMG_SHAPE),class_mode='sparse')model = Sequential()model.add(Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_SHAPE,IMG_SHAPE, 3)))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(32, 3, padding='same', activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Conv2D(64, 3, padding='same', activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))# Adding dropout to turn down some neuronsmodel.add(Flatten())model.add(Dropout(0.2))model.add(Dense(512, activation='relu'))model.add(Dropout(0.2))model.add(Dense(5, activation='softmax'))"
},
{
"code": null,
"e": 8936,
"s": 8765,
"text": "Convolution and max pooling is applied to the data set, before sending it to the output layer the model is flattened. Dropout is applied to prevent overfitting of images."
},
{
"code": null,
"e": 9261,
"s": 8936,
"text": "model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])epochs = 120history = model.fit_generator(train_data_gen,steps_per_epoch=int(np.ceil(train_data_gen.n / float(batch_size))),epochs=epochs,validation_data=val_data_gen,validation_steps=int(np.ceil(val_data_gen.n / float(batch_size))))"
},
{
"code": null,
"e": 9380,
"s": 9261,
"text": "Model is compiled and the performance is observed. You can play with the hyper-parameter to obtain the optimum result."
}
] |
Classification in Imbalanced Data Sets. | by Ada kibet | Towards Data Science | Classification is a type of supervised learning in Machine Learning that deals with categorizing data into classes. Supervised learning implies models that take input with their matched output to train a model which can later make useful predictions on a new set of data with no output. Some examples of classification problems include: spam detection in mails, subscription analysis, hand written digit recognition, survival predictions et.c. They all involve the use of classifiers that utilize the train data to understand how the input variables relate to the output (target) variable.
Class imbalance refers to a problem in classification where the distribution of the classes are skewed. This can range from a slight to an extreme imbalance.
This is a problem because most classification algorithms will have a low prediction accuracy towards the minority class because they run with the assumption that there’s balance between the classes.
An example of class imbalance is in credit card fraud detection. The classes, in this case, are fraud and not fraud. Most of the transactions are not fraud, thus the fraud classes are the minority class. Having a low accuracy in the minority class predictions is problematic because it is the most important class.
This blog covers the steps involved in tackling a classification problem in imbalanced dataset. The Github repository containing all the code is available here.
Data used is from the UCI Machine Learning Repository. The data is related with marketing campaigns of a Portuguese banking institution. The classification goal is to predict if the client will subscribe to a term deposit (variable y).
An effective model can help increase campaign efficiency as more efforts can be directed towards customers with high subscription chances.
Sample of the data:
Visualizing the target variable(y) in order to observe the class imbalance:
The circles’ sizes represents the value counts of each class. Clearly there’s extreme class imbalance. This will be taken care of in the preprocessing section.
Preprocessing involves the following steps:
Missing values need to be handled because they can lead to wrong predictions and can also cause a high bias for any given model being used.
The categorical features will be imputed with the column mode, the discrete numerical features with the column median and the continuous numerical features with the column mean.
Outliers are a problem for many machine learning algorithms because they can cause missing of important insights or contort real results which eventually results to less accurate models.
The outliers will be clipped with the 10th and 90th percentiles.
Generating new features from already existing features adds new information to be accessible during the model training and therefore increasing model accuracy.
Standardizing numerical features with a StandardScaler to remove the differences brought about by different units of measurement.
Most Machine Learning and Neural Nets algorithms require numerical inputs, thus to make use of the categorical features, we have to remap them.
One hot encoding technique is applied. It takes a column which has categorical data then splits the column into multiple columns. The entries are replaced by zeros and ones, depending which column has what value.
Resampling involves creating a new version of our imbalanced dataset.
There are 2 main approaches for resampling:
Over sampling: Randomly duplicating entries in the minority class. Appropriate for small datasets.
Under sampling: Randomly deleting entries from the majority class. Appropriate for large datasets.
Our dataset has 41188 rows and 21 columns thus safe to use oversampling.
The Preprocessing class:
# calling the class and its methodsd = DataPrep()path = '/content/bank-additional-full.csv'data = d.read_data(path)data = d.treat_null(data)data = d.outlier_correcter(data)data = d.generate_features(data)data = d.scaler(data)print('After scaling:', data.shape)data = d.encoder(data)data = d.over_sample(data)data.head()
The output:
Notice the changes in the categorical and numerical columns.
Straight off from the preprocessing to making predictions, we begin by training and evaluating our models using the train and validation data. But first, we have to separate the target and predictor variables then split them into train, validation and test sets. The test set is not provided separately thus we retrieve it from our dataset.
# split the data to have the predictor and predicted variablesx = data.drop(['y'], axis = 1)y = data[['y']]# Encode labels in target df.encoder = LabelEncoder()y = encoder.fit_transform(y)# get the setsx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.10, random_state = 42)x_train, x_val, y_train, y_val = train_test_split(x_train ,y_train, test_size = 0.20, random_state = 42)
Algorithms to be explored:
XGBoost:
XGBoost classifier is tree-based ensemble learning algorithm that’s an implementation of gradient boosting machines.
It is optimized for speed and performance.
* Multilayer Perceptron:
A multilayer perceptron (MLP) is a class of feed-forward artificial neural network. It consists of at least three layers of nodes: an input layer, a hidden layer and an output layer.
Its ability to distinguish data that is not linearly separable is why we explore it.
* Logistic Regression:
Logistic regression is a simple and yet very effective classification algorithm that uses log odds ratio to predict group membership.
Its simplicity and use of log odds ratio in place for probabilities is why we explore it.
Cross-validation is a resampling procedure used to evaluate machine learning models on a limited data sample.
Techniques used:
K-fold: K-Fold CV is where a given data set is split into n number of folds where each fold is used as a testing set at some point and the rest as the training set.
Stratified K-fold: StratifiedKFold shuffles the data, then splits it into n number of folds then the folds are each used as a testing set. Stratification keeps the balance between targets of the dataset (each stratified fold keeps the same ratio of the target classes). This strategy is best in cases of imbalanced data.
The scoring metric by default in both techniques is the accuracy score (the number of correct predictions made divided by the total number of predictions made).
Implementation:
Now we observe our models performance on the train data using these techniques.
# using grid search to find optimal parametersregressor = LogisticRegression()grid_values = {'penalty': ['l1','l2'], 'C': [0.001,0.01,0.1,1,10,100,1000]}model = GridSearchCV(regressor, param_grid=grid_values)model.fit(x_train,y_train)print(model.best_score_)print(model.best_params_)
# using the optimal parametes printed outregressor = LogisticRegression(C = 1000, penalty= 'l2')regressor.fit(x_train, y_train)# using kfoldsprint('Logistic Regression mean accuracy score using kfold:', overall_score(regressor, x_train))# stratified KFoldprint('Logistic Regression mean accuracy score using Stratifiedkfold :', overall__stratified_score(regressor, x_train))
Output:
Logistic Regression mean accuracy score using kfold: 0.742437522099093Logistic Regression mean accuracy score using Stratifiedkfold : 0.7420879248958712
Repeating the same procedure for the XGBoost and the MLP.
xgb = XGBClassifier(silent = True,max_depth = 6, n_estimators = 200)xgb.fit(x_train, y_train)# using kfoldsprint('xgb mean score on the original dataset (kfold):', overall_score(xgb, x_train))# stratified KFoldprint('xgb mean score on the original dataset (stratified kfold):', overall__stratified_score(xgb, x_train))
mlp = MLPClassifier() # working with default parametersmlp.fit(x_train, y_train)# using kfoldsprint('mlp mean score on the original dataset (kfold):', overall_score(mlp, x_train))# stratified KFoldprint('mlp mean score on the original dataset (stratified kfold):', overall__stratified_score(mlp, x_train))
In all the 3 models, K-fold yields the highest accuracy although its variation with Stratified is so slight. Like mentioned earlier, Stratified is best for imbalanced data but we already resampled our data during preprocessing rendering it not so useful.
We can explore other accuracy metrics through our validation set.
ROC — ROC curve is a plot of the true positive rate (y-axis) against the false positive rate (x-axis) for a number of different candidate threshold values between 0.0 and 1.0.
PRECISION AND RECALL — Precision is the number of correctly identified positive results divided by the number of all positive results, including those not identified correctly and recall is the number of correctly identified positive results divided by the number of all samples that should have been identified as positive.
F1 SCORE — F1 score is a measure of a test’s accuracy. It is calculated from the precision and recall of the test.
ROC curves should be used when there are roughly equal numbers of observations for each class. Precision-Recall curves should be used when there is moderate to large class imbalance.
Since we resampled our data to be balanced, ROC is our best take.
ROC plots: Implementation :
The plots are implemented on other models: RandomForest, CatBoost and LGBM, they can be edited to fit whichever model. (Code available in the github link shared).
from sklearn.datasets import make_classificationfrom sklearn.metrics import roc_curvefrom sklearn.metrics import roc_auc_score#predict probabilitiesns_probs = [0 for _ in range(len(x_val))] # no skill classifierf_prob = forest.predict_proba(x_val)c_prob = cat.predict_proba(x_val)l_prob = lgbm.predict_proba(x_val)# keep probabilities for the positive outcome onlyf_prob = f_prob[:, 1]c_prob = c_prob[:, 1]l_prob = l_prob[:, 1]# calculate scores then print themf_auc = roc_auc_score(y_val, f_prob)c_auc = roc_auc_score(y_val, c_prob)l_auc = roc_auc_score(y_val, l_prob)ns_auc = roc_auc_score(y_val, ns_probs)print('RandomForest:', f_auc)print('CatBoost: ', c_auc)print('LGBM:', l_auc)# calculate roc curvesf_fpr, f_tpr, _ = roc_curve(y_val, f_prob)c_fpr, c_tpr, _ = roc_curve(y_val, c_prob)l_fpr, l_tpr, _ = roc_curve(y_val, l_prob)ns_fpr, ns_tpr, _ = roc_curve(y_val, ns_probs)# plot the roc curve for the modelplt.figure(figsize = (12,7))plt.plot(f_fpr, f_tpr, marker='.', label='random forest')plt.plot(l_fpr, l_tpr, marker='.', label='lgbm')plt.plot(c_fpr, c_tpr, marker='.', label='catboost')plt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')plt.legend()plt.title('ROC curves for different models')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')
Output:
The bigger the area under the curve, the higher the accuracy.
A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. (Our benchmark).
Using MLP, our best performer from the 3 initial models.
# mlppred = mlp.predict(x_test)pred_df = pd.DataFrame(pred)pred_df.columns = ['y']pred_df.to_csv('pred_df.csv') # export to a csv file
We could go on and on with our classification problem exploring distinct techniques like Dimensionality reduction solely in an attempt to achieve a better performing model. But for now, we know that having imbalanced data doesn’t hinder one from performing predictions, it simply beckons one to use the appropriate techniques to evade poor forecasts on the minority class.
PS: Respect to all my fellow learners and tutors at 10academy.org for their endless support.
How to Use ROC Curves and Precision-Recall Curves for Classification in Python.
How to Use ROC Curves and Precision-Recall Curves for Classification in Python.
2. Understanding AUC — ROC Curve.
3. XGBoost Algorithm: Long May She Reign!
4. Dealing with Imbalanced Data.
5. XGBoost Documentation.
6. Imbalanced Data : How to handle Imbalanced Classification Problems.
7. Why Is Imbalanced Classification Difficult? | [
{
"code": null,
"e": 762,
"s": 172,
"text": "Classification is a type of supervised learning in Machine Learning that deals with categorizing data into classes. Supervised learning implies models that take input with their matched output to train a model which can later make useful predictions on a new set of data with no output. Some examples of classification problems include: spam detection in mails, subscription analysis, hand written digit recognition, survival predictions et.c. They all involve the use of classifiers that utilize the train data to understand how the input variables relate to the output (target) variable."
},
{
"code": null,
"e": 920,
"s": 762,
"text": "Class imbalance refers to a problem in classification where the distribution of the classes are skewed. This can range from a slight to an extreme imbalance."
},
{
"code": null,
"e": 1119,
"s": 920,
"text": "This is a problem because most classification algorithms will have a low prediction accuracy towards the minority class because they run with the assumption that there’s balance between the classes."
},
{
"code": null,
"e": 1434,
"s": 1119,
"text": "An example of class imbalance is in credit card fraud detection. The classes, in this case, are fraud and not fraud. Most of the transactions are not fraud, thus the fraud classes are the minority class. Having a low accuracy in the minority class predictions is problematic because it is the most important class."
},
{
"code": null,
"e": 1595,
"s": 1434,
"text": "This blog covers the steps involved in tackling a classification problem in imbalanced dataset. The Github repository containing all the code is available here."
},
{
"code": null,
"e": 1831,
"s": 1595,
"text": "Data used is from the UCI Machine Learning Repository. The data is related with marketing campaigns of a Portuguese banking institution. The classification goal is to predict if the client will subscribe to a term deposit (variable y)."
},
{
"code": null,
"e": 1970,
"s": 1831,
"text": "An effective model can help increase campaign efficiency as more efforts can be directed towards customers with high subscription chances."
},
{
"code": null,
"e": 1990,
"s": 1970,
"text": "Sample of the data:"
},
{
"code": null,
"e": 2066,
"s": 1990,
"text": "Visualizing the target variable(y) in order to observe the class imbalance:"
},
{
"code": null,
"e": 2226,
"s": 2066,
"text": "The circles’ sizes represents the value counts of each class. Clearly there’s extreme class imbalance. This will be taken care of in the preprocessing section."
},
{
"code": null,
"e": 2270,
"s": 2226,
"text": "Preprocessing involves the following steps:"
},
{
"code": null,
"e": 2410,
"s": 2270,
"text": "Missing values need to be handled because they can lead to wrong predictions and can also cause a high bias for any given model being used."
},
{
"code": null,
"e": 2588,
"s": 2410,
"text": "The categorical features will be imputed with the column mode, the discrete numerical features with the column median and the continuous numerical features with the column mean."
},
{
"code": null,
"e": 2775,
"s": 2588,
"text": "Outliers are a problem for many machine learning algorithms because they can cause missing of important insights or contort real results which eventually results to less accurate models."
},
{
"code": null,
"e": 2840,
"s": 2775,
"text": "The outliers will be clipped with the 10th and 90th percentiles."
},
{
"code": null,
"e": 3000,
"s": 2840,
"text": "Generating new features from already existing features adds new information to be accessible during the model training and therefore increasing model accuracy."
},
{
"code": null,
"e": 3130,
"s": 3000,
"text": "Standardizing numerical features with a StandardScaler to remove the differences brought about by different units of measurement."
},
{
"code": null,
"e": 3274,
"s": 3130,
"text": "Most Machine Learning and Neural Nets algorithms require numerical inputs, thus to make use of the categorical features, we have to remap them."
},
{
"code": null,
"e": 3487,
"s": 3274,
"text": "One hot encoding technique is applied. It takes a column which has categorical data then splits the column into multiple columns. The entries are replaced by zeros and ones, depending which column has what value."
},
{
"code": null,
"e": 3557,
"s": 3487,
"text": "Resampling involves creating a new version of our imbalanced dataset."
},
{
"code": null,
"e": 3601,
"s": 3557,
"text": "There are 2 main approaches for resampling:"
},
{
"code": null,
"e": 3700,
"s": 3601,
"text": "Over sampling: Randomly duplicating entries in the minority class. Appropriate for small datasets."
},
{
"code": null,
"e": 3799,
"s": 3700,
"text": "Under sampling: Randomly deleting entries from the majority class. Appropriate for large datasets."
},
{
"code": null,
"e": 3872,
"s": 3799,
"text": "Our dataset has 41188 rows and 21 columns thus safe to use oversampling."
},
{
"code": null,
"e": 3897,
"s": 3872,
"text": "The Preprocessing class:"
},
{
"code": null,
"e": 4217,
"s": 3897,
"text": "# calling the class and its methodsd = DataPrep()path = '/content/bank-additional-full.csv'data = d.read_data(path)data = d.treat_null(data)data = d.outlier_correcter(data)data = d.generate_features(data)data = d.scaler(data)print('After scaling:', data.shape)data = d.encoder(data)data = d.over_sample(data)data.head()"
},
{
"code": null,
"e": 4229,
"s": 4217,
"text": "The output:"
},
{
"code": null,
"e": 4290,
"s": 4229,
"text": "Notice the changes in the categorical and numerical columns."
},
{
"code": null,
"e": 4631,
"s": 4290,
"text": "Straight off from the preprocessing to making predictions, we begin by training and evaluating our models using the train and validation data. But first, we have to separate the target and predictor variables then split them into train, validation and test sets. The test set is not provided separately thus we retrieve it from our dataset."
},
{
"code": null,
"e": 5032,
"s": 4631,
"text": "# split the data to have the predictor and predicted variablesx = data.drop(['y'], axis = 1)y = data[['y']]# Encode labels in target df.encoder = LabelEncoder()y = encoder.fit_transform(y)# get the setsx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.10, random_state = 42)x_train, x_val, y_train, y_val = train_test_split(x_train ,y_train, test_size = 0.20, random_state = 42)"
},
{
"code": null,
"e": 5059,
"s": 5032,
"text": "Algorithms to be explored:"
},
{
"code": null,
"e": 5068,
"s": 5059,
"text": "XGBoost:"
},
{
"code": null,
"e": 5185,
"s": 5068,
"text": "XGBoost classifier is tree-based ensemble learning algorithm that’s an implementation of gradient boosting machines."
},
{
"code": null,
"e": 5228,
"s": 5185,
"text": "It is optimized for speed and performance."
},
{
"code": null,
"e": 5253,
"s": 5228,
"text": "* Multilayer Perceptron:"
},
{
"code": null,
"e": 5436,
"s": 5253,
"text": "A multilayer perceptron (MLP) is a class of feed-forward artificial neural network. It consists of at least three layers of nodes: an input layer, a hidden layer and an output layer."
},
{
"code": null,
"e": 5521,
"s": 5436,
"text": "Its ability to distinguish data that is not linearly separable is why we explore it."
},
{
"code": null,
"e": 5544,
"s": 5521,
"text": "* Logistic Regression:"
},
{
"code": null,
"e": 5678,
"s": 5544,
"text": "Logistic regression is a simple and yet very effective classification algorithm that uses log odds ratio to predict group membership."
},
{
"code": null,
"e": 5768,
"s": 5678,
"text": "Its simplicity and use of log odds ratio in place for probabilities is why we explore it."
},
{
"code": null,
"e": 5878,
"s": 5768,
"text": "Cross-validation is a resampling procedure used to evaluate machine learning models on a limited data sample."
},
{
"code": null,
"e": 5895,
"s": 5878,
"text": "Techniques used:"
},
{
"code": null,
"e": 6060,
"s": 5895,
"text": "K-fold: K-Fold CV is where a given data set is split into n number of folds where each fold is used as a testing set at some point and the rest as the training set."
},
{
"code": null,
"e": 6381,
"s": 6060,
"text": "Stratified K-fold: StratifiedKFold shuffles the data, then splits it into n number of folds then the folds are each used as a testing set. Stratification keeps the balance between targets of the dataset (each stratified fold keeps the same ratio of the target classes). This strategy is best in cases of imbalanced data."
},
{
"code": null,
"e": 6542,
"s": 6381,
"text": "The scoring metric by default in both techniques is the accuracy score (the number of correct predictions made divided by the total number of predictions made)."
},
{
"code": null,
"e": 6558,
"s": 6542,
"text": "Implementation:"
},
{
"code": null,
"e": 6638,
"s": 6558,
"text": "Now we observe our models performance on the train data using these techniques."
},
{
"code": null,
"e": 6922,
"s": 6638,
"text": "# using grid search to find optimal parametersregressor = LogisticRegression()grid_values = {'penalty': ['l1','l2'], 'C': [0.001,0.01,0.1,1,10,100,1000]}model = GridSearchCV(regressor, param_grid=grid_values)model.fit(x_train,y_train)print(model.best_score_)print(model.best_params_)"
},
{
"code": null,
"e": 7297,
"s": 6922,
"text": "# using the optimal parametes printed outregressor = LogisticRegression(C = 1000, penalty= 'l2')regressor.fit(x_train, y_train)# using kfoldsprint('Logistic Regression mean accuracy score using kfold:', overall_score(regressor, x_train))# stratified KFoldprint('Logistic Regression mean accuracy score using Stratifiedkfold :', overall__stratified_score(regressor, x_train))"
},
{
"code": null,
"e": 7305,
"s": 7297,
"text": "Output:"
},
{
"code": null,
"e": 7458,
"s": 7305,
"text": "Logistic Regression mean accuracy score using kfold: 0.742437522099093Logistic Regression mean accuracy score using Stratifiedkfold : 0.7420879248958712"
},
{
"code": null,
"e": 7516,
"s": 7458,
"text": "Repeating the same procedure for the XGBoost and the MLP."
},
{
"code": null,
"e": 7835,
"s": 7516,
"text": "xgb = XGBClassifier(silent = True,max_depth = 6, n_estimators = 200)xgb.fit(x_train, y_train)# using kfoldsprint('xgb mean score on the original dataset (kfold):', overall_score(xgb, x_train))# stratified KFoldprint('xgb mean score on the original dataset (stratified kfold):', overall__stratified_score(xgb, x_train))"
},
{
"code": null,
"e": 8141,
"s": 7835,
"text": "mlp = MLPClassifier() # working with default parametersmlp.fit(x_train, y_train)# using kfoldsprint('mlp mean score on the original dataset (kfold):', overall_score(mlp, x_train))# stratified KFoldprint('mlp mean score on the original dataset (stratified kfold):', overall__stratified_score(mlp, x_train))"
},
{
"code": null,
"e": 8396,
"s": 8141,
"text": "In all the 3 models, K-fold yields the highest accuracy although its variation with Stratified is so slight. Like mentioned earlier, Stratified is best for imbalanced data but we already resampled our data during preprocessing rendering it not so useful."
},
{
"code": null,
"e": 8462,
"s": 8396,
"text": "We can explore other accuracy metrics through our validation set."
},
{
"code": null,
"e": 8638,
"s": 8462,
"text": "ROC — ROC curve is a plot of the true positive rate (y-axis) against the false positive rate (x-axis) for a number of different candidate threshold values between 0.0 and 1.0."
},
{
"code": null,
"e": 8963,
"s": 8638,
"text": "PRECISION AND RECALL — Precision is the number of correctly identified positive results divided by the number of all positive results, including those not identified correctly and recall is the number of correctly identified positive results divided by the number of all samples that should have been identified as positive."
},
{
"code": null,
"e": 9078,
"s": 8963,
"text": "F1 SCORE — F1 score is a measure of a test’s accuracy. It is calculated from the precision and recall of the test."
},
{
"code": null,
"e": 9261,
"s": 9078,
"text": "ROC curves should be used when there are roughly equal numbers of observations for each class. Precision-Recall curves should be used when there is moderate to large class imbalance."
},
{
"code": null,
"e": 9327,
"s": 9261,
"text": "Since we resampled our data to be balanced, ROC is our best take."
},
{
"code": null,
"e": 9355,
"s": 9327,
"text": "ROC plots: Implementation :"
},
{
"code": null,
"e": 9518,
"s": 9355,
"text": "The plots are implemented on other models: RandomForest, CatBoost and LGBM, they can be edited to fit whichever model. (Code available in the github link shared)."
},
{
"code": null,
"e": 10796,
"s": 9518,
"text": "from sklearn.datasets import make_classificationfrom sklearn.metrics import roc_curvefrom sklearn.metrics import roc_auc_score#predict probabilitiesns_probs = [0 for _ in range(len(x_val))] # no skill classifierf_prob = forest.predict_proba(x_val)c_prob = cat.predict_proba(x_val)l_prob = lgbm.predict_proba(x_val)# keep probabilities for the positive outcome onlyf_prob = f_prob[:, 1]c_prob = c_prob[:, 1]l_prob = l_prob[:, 1]# calculate scores then print themf_auc = roc_auc_score(y_val, f_prob)c_auc = roc_auc_score(y_val, c_prob)l_auc = roc_auc_score(y_val, l_prob)ns_auc = roc_auc_score(y_val, ns_probs)print('RandomForest:', f_auc)print('CatBoost: ', c_auc)print('LGBM:', l_auc)# calculate roc curvesf_fpr, f_tpr, _ = roc_curve(y_val, f_prob)c_fpr, c_tpr, _ = roc_curve(y_val, c_prob)l_fpr, l_tpr, _ = roc_curve(y_val, l_prob)ns_fpr, ns_tpr, _ = roc_curve(y_val, ns_probs)# plot the roc curve for the modelplt.figure(figsize = (12,7))plt.plot(f_fpr, f_tpr, marker='.', label='random forest')plt.plot(l_fpr, l_tpr, marker='.', label='lgbm')plt.plot(c_fpr, c_tpr, marker='.', label='catboost')plt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')plt.legend()plt.title('ROC curves for different models')plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')"
},
{
"code": null,
"e": 10804,
"s": 10796,
"text": "Output:"
},
{
"code": null,
"e": 10866,
"s": 10804,
"text": "The bigger the area under the curve, the higher the accuracy."
},
{
"code": null,
"e": 11024,
"s": 10866,
"text": "A no-skill classifier is one that cannot discriminate between the classes and would predict a random class or a constant class in all cases. (Our benchmark)."
},
{
"code": null,
"e": 11081,
"s": 11024,
"text": "Using MLP, our best performer from the 3 initial models."
},
{
"code": null,
"e": 11216,
"s": 11081,
"text": "# mlppred = mlp.predict(x_test)pred_df = pd.DataFrame(pred)pred_df.columns = ['y']pred_df.to_csv('pred_df.csv') # export to a csv file"
},
{
"code": null,
"e": 11589,
"s": 11216,
"text": "We could go on and on with our classification problem exploring distinct techniques like Dimensionality reduction solely in an attempt to achieve a better performing model. But for now, we know that having imbalanced data doesn’t hinder one from performing predictions, it simply beckons one to use the appropriate techniques to evade poor forecasts on the minority class."
},
{
"code": null,
"e": 11682,
"s": 11589,
"text": "PS: Respect to all my fellow learners and tutors at 10academy.org for their endless support."
},
{
"code": null,
"e": 11762,
"s": 11682,
"text": "How to Use ROC Curves and Precision-Recall Curves for Classification in Python."
},
{
"code": null,
"e": 11842,
"s": 11762,
"text": "How to Use ROC Curves and Precision-Recall Curves for Classification in Python."
},
{
"code": null,
"e": 11876,
"s": 11842,
"text": "2. Understanding AUC — ROC Curve."
},
{
"code": null,
"e": 11918,
"s": 11876,
"text": "3. XGBoost Algorithm: Long May She Reign!"
},
{
"code": null,
"e": 11951,
"s": 11918,
"text": "4. Dealing with Imbalanced Data."
},
{
"code": null,
"e": 11977,
"s": 11951,
"text": "5. XGBoost Documentation."
},
{
"code": null,
"e": 12048,
"s": 11977,
"text": "6. Imbalanced Data : How to handle Imbalanced Classification Problems."
}
] |
How to add git hooks for your python projects using the pre-commit framework | by Mathanraj Sharma | Towards Data Science | As a developer, we need to ensure readability, writability, and reliability of the program we are writing. If we take a git repo multiple contributors write or modify hundreds of lines of codes each day, new contributors come in as few go out. So to make the codebase consistent, we have to follow certain standards. For example certain code formatting styles (black) or linting style (flake8) etc. Usually, these sanity checks take place before submitting (commit) the code for review, also there can be actions that need to be done after submitting, something like maintaining an internal log.
Before deep dive let me tell you what we going to see today,
What is Git Hooks?What is pre-commit framework?How to use the pre-commit framework with python projects?
What is Git Hooks?
What is pre-commit framework?
How to use the pre-commit framework with python projects?
As I mentioned at the top there are certain actions (tasks) we need to perform when an event happens in the development workflow, which is known as hooks.
Git hooks are scripts that run automatically every time a particular event occurs in a git repository.
For example, running black formatting and flake8 linting before each commit. Literally, we can add hooks at various stages of the git events.
pre-commit:- run certain hook before commit, if fails abort the commit
pre-merge-commit:- run certain hook before the merge, if fails abort the merge
pre-push:- run certain hook before pushing to the remote repo, if fails abort push
post-commit:- hook to be run immediately after a successful commit
post-checkout:- hook to be run immediately after checkout from one branch
post-merge:- hook to be run immediately after a successful merge
etc
When we do git initit adds the most commonly used git hooks into .git/hooks/, we can write our own hooks using the most commonly used scripting languages. But today we going to see about a framework designed to ease this process.
It is a framework for managing and maintaining multi-language git hooks. You may have a question, why do we need a framework for hooks.
As we create more libraries and projects we might find that sharing our pre-commit hooks across projects is painful. We have to copy and paste unwieldy bash scripts from project to project and had to manually change the hooks to work for different project structures. And also sometimes some good linters or other testing tools we need, might be not written in the same language we using for our project.
Pre-commit is a multi-language package manager for pre-commit hooks. We can simply specify the list of hooks we want and pre-commit manages the installation and execution of any hook written in any language without any root permission.
Install pre-commit framework
Install pre-commit framework
pip install pre-commitorconda install -c conda-forge pre-commit
Add .pre-commit-config.yaml to your project’s root folder. In this example, I am going to show how to add black formatting and flake8 linting for each commit and push.
let us break down each component here,
default_stages:- a configuration-wide default for the stages property of hooks. This will only override individual hooks that do not set stages.
default_language_version:- default language version that should be used if language_version is not set for individual hooks.
repos:- list of repository mappings
repo:- the repository URL to git clone, the code for the hook will be taken from here.
rev:- which version of repo needs to be used (tag)
hooks:- A list of hook mappings, hook mapping lets the user select which hook needs to be used from the repo and allows customizations.
id: hook name from the repo.
args: command-line arguments need to be passed for that hook.
exclude:- regex for file/folder names to be excluded for that hook.
types:- file types to be considered for that hook.
There are many more components, to customize the hooks.
2. After adding the config file, run the below command to install hooks
pre-commit install --hook-type pre-commit hook-type pre-post
this will install the hooks that should be run before commits and push.
3. Modify any of the files in your project and try to commit them
here my hooks have failed due to some code reformatting and lint errors. Note, if any of the hooks failed then the commit will be aborted. Fix the issue and re-commit.
This will be the same if you have configured any pre-push hooks.
You can find the complete source code here, https://github.com/Mathanraj-Sharma/python_boilerplate
In conclusion, git hooks is simply any script that we wish to trigger during the occurrence of a git event. It helps use to automate the repetitive workload to maintain the consistency of the code being written. It may not seem effective at the early stage, but as the projects grows and more contributors comes in we can feel the benefits of git hooks. | [
{
"code": null,
"e": 768,
"s": 172,
"text": "As a developer, we need to ensure readability, writability, and reliability of the program we are writing. If we take a git repo multiple contributors write or modify hundreds of lines of codes each day, new contributors come in as few go out. So to make the codebase consistent, we have to follow certain standards. For example certain code formatting styles (black) or linting style (flake8) etc. Usually, these sanity checks take place before submitting (commit) the code for review, also there can be actions that need to be done after submitting, something like maintaining an internal log."
},
{
"code": null,
"e": 829,
"s": 768,
"text": "Before deep dive let me tell you what we going to see today,"
},
{
"code": null,
"e": 934,
"s": 829,
"text": "What is Git Hooks?What is pre-commit framework?How to use the pre-commit framework with python projects?"
},
{
"code": null,
"e": 953,
"s": 934,
"text": "What is Git Hooks?"
},
{
"code": null,
"e": 983,
"s": 953,
"text": "What is pre-commit framework?"
},
{
"code": null,
"e": 1041,
"s": 983,
"text": "How to use the pre-commit framework with python projects?"
},
{
"code": null,
"e": 1196,
"s": 1041,
"text": "As I mentioned at the top there are certain actions (tasks) we need to perform when an event happens in the development workflow, which is known as hooks."
},
{
"code": null,
"e": 1299,
"s": 1196,
"text": "Git hooks are scripts that run automatically every time a particular event occurs in a git repository."
},
{
"code": null,
"e": 1441,
"s": 1299,
"text": "For example, running black formatting and flake8 linting before each commit. Literally, we can add hooks at various stages of the git events."
},
{
"code": null,
"e": 1512,
"s": 1441,
"text": "pre-commit:- run certain hook before commit, if fails abort the commit"
},
{
"code": null,
"e": 1591,
"s": 1512,
"text": "pre-merge-commit:- run certain hook before the merge, if fails abort the merge"
},
{
"code": null,
"e": 1674,
"s": 1591,
"text": "pre-push:- run certain hook before pushing to the remote repo, if fails abort push"
},
{
"code": null,
"e": 1741,
"s": 1674,
"text": "post-commit:- hook to be run immediately after a successful commit"
},
{
"code": null,
"e": 1815,
"s": 1741,
"text": "post-checkout:- hook to be run immediately after checkout from one branch"
},
{
"code": null,
"e": 1880,
"s": 1815,
"text": "post-merge:- hook to be run immediately after a successful merge"
},
{
"code": null,
"e": 1884,
"s": 1880,
"text": "etc"
},
{
"code": null,
"e": 2114,
"s": 1884,
"text": "When we do git initit adds the most commonly used git hooks into .git/hooks/, we can write our own hooks using the most commonly used scripting languages. But today we going to see about a framework designed to ease this process."
},
{
"code": null,
"e": 2250,
"s": 2114,
"text": "It is a framework for managing and maintaining multi-language git hooks. You may have a question, why do we need a framework for hooks."
},
{
"code": null,
"e": 2655,
"s": 2250,
"text": "As we create more libraries and projects we might find that sharing our pre-commit hooks across projects is painful. We have to copy and paste unwieldy bash scripts from project to project and had to manually change the hooks to work for different project structures. And also sometimes some good linters or other testing tools we need, might be not written in the same language we using for our project."
},
{
"code": null,
"e": 2891,
"s": 2655,
"text": "Pre-commit is a multi-language package manager for pre-commit hooks. We can simply specify the list of hooks we want and pre-commit manages the installation and execution of any hook written in any language without any root permission."
},
{
"code": null,
"e": 2920,
"s": 2891,
"text": "Install pre-commit framework"
},
{
"code": null,
"e": 2949,
"s": 2920,
"text": "Install pre-commit framework"
},
{
"code": null,
"e": 3013,
"s": 2949,
"text": "pip install pre-commitorconda install -c conda-forge pre-commit"
},
{
"code": null,
"e": 3181,
"s": 3013,
"text": "Add .pre-commit-config.yaml to your project’s root folder. In this example, I am going to show how to add black formatting and flake8 linting for each commit and push."
},
{
"code": null,
"e": 3220,
"s": 3181,
"text": "let us break down each component here,"
},
{
"code": null,
"e": 3365,
"s": 3220,
"text": "default_stages:- a configuration-wide default for the stages property of hooks. This will only override individual hooks that do not set stages."
},
{
"code": null,
"e": 3490,
"s": 3365,
"text": "default_language_version:- default language version that should be used if language_version is not set for individual hooks."
},
{
"code": null,
"e": 3526,
"s": 3490,
"text": "repos:- list of repository mappings"
},
{
"code": null,
"e": 3613,
"s": 3526,
"text": "repo:- the repository URL to git clone, the code for the hook will be taken from here."
},
{
"code": null,
"e": 3664,
"s": 3613,
"text": "rev:- which version of repo needs to be used (tag)"
},
{
"code": null,
"e": 3800,
"s": 3664,
"text": "hooks:- A list of hook mappings, hook mapping lets the user select which hook needs to be used from the repo and allows customizations."
},
{
"code": null,
"e": 3829,
"s": 3800,
"text": "id: hook name from the repo."
},
{
"code": null,
"e": 3891,
"s": 3829,
"text": "args: command-line arguments need to be passed for that hook."
},
{
"code": null,
"e": 3959,
"s": 3891,
"text": "exclude:- regex for file/folder names to be excluded for that hook."
},
{
"code": null,
"e": 4010,
"s": 3959,
"text": "types:- file types to be considered for that hook."
},
{
"code": null,
"e": 4066,
"s": 4010,
"text": "There are many more components, to customize the hooks."
},
{
"code": null,
"e": 4138,
"s": 4066,
"text": "2. After adding the config file, run the below command to install hooks"
},
{
"code": null,
"e": 4199,
"s": 4138,
"text": "pre-commit install --hook-type pre-commit hook-type pre-post"
},
{
"code": null,
"e": 4271,
"s": 4199,
"text": "this will install the hooks that should be run before commits and push."
},
{
"code": null,
"e": 4337,
"s": 4271,
"text": "3. Modify any of the files in your project and try to commit them"
},
{
"code": null,
"e": 4505,
"s": 4337,
"text": "here my hooks have failed due to some code reformatting and lint errors. Note, if any of the hooks failed then the commit will be aborted. Fix the issue and re-commit."
},
{
"code": null,
"e": 4570,
"s": 4505,
"text": "This will be the same if you have configured any pre-push hooks."
},
{
"code": null,
"e": 4669,
"s": 4570,
"text": "You can find the complete source code here, https://github.com/Mathanraj-Sharma/python_boilerplate"
}
] |
How I would Learn Python for Data Science if I Had to Start Over | by Nicholas | Towards Data Science | I reached over to grab another sip of my red bull.
My eyes were bloodshot from staring at the screen for so long.
I was exhausted. But I needed to do this, I had to get my head around it.
So I flipped the page.
Then wrote a couple more lines in my notebook.
....And I did it again.
..................And again.
.......................Annnd again.
I’d been sitting in a dark corner in Building 11 at the University of Technology, Sydney for 9 HOURS now.
My MacBook in front of me.
Python Crash Course on my right.
And about 87 different tabs open in Chrome
Desperately trying to get a decent grasp of Python.
I wanted to get it so bad....and I wanted to learn it fast (admittedly faster than what was probably practical).
I was studying my Masters and trying to bring some ML to my clients at work....without really knowing what the hell I was doing. There was just so much to learn when it came to Data Science and ML, let alone Python.
There had to be a better way.
Unfortunately, back then, I didn’t know any better.
Fast forward three years, there’s a lot of stuff I would’ve done a HELLLUVA lot differently. In that time, I’ve managed to build a ton of models, start (and crash) a startup, as well as becoming a Data Scientist at IBM working with some amazing clients.
But I always think back to those weekends I spent grinding away teaching myself to code. Looking back now, yeah it was worth it...but I could’ve done it wayyyyy more efficiently.
That’s exactly what I want to talk to you about today.
The strategy I would use to learn Python for Machine Learning and Data Science again...if I had to start over.
If you’re more of a video person, I also made a 5ish hour crash course that distills all this down but stick with me, I’m hoping i can share some golden nuggets nonetheless.
There are 3 key components that I think it’s important to get your head around before kicking off your study.
The first is CRUD.
CRUD stands for Create, Read, Update and Delete. It’s a concept that’s commonly associated with SQL. It refers to the core actions that are necessary to work with database records.
However!
The same concept is useful when it comes to programming. If you can understand how to create, read, update and delete an object in Python, you’re well on your way to understanding that component. The only objection I have to this is that it’s also important to understand how to loop through components as well, so maybe CRUDL is a better initialism? I digress.
Understanding CRUD is important because it sets a foundation for the operations you should be able to apply to components in Python. Say for example you wanted to apply CRUD to lists.
We know that we can CREATE lists using sequences wrapped in square brackets.
# Creating a listnames = [‘neil armstrong’, ‘buzz aldrin’, ‘sally ride’, ‘yuri gagarin’, ‘elon musk’]
We can READ them using indexing or the print function
# Printing a listprint(names)# Reading the first valuenames[0]# Slicing a rangenames[1:3]
To UPDATE, you can reassign a value, use the insert method or append method.
# Update a single valuenames[-1] = 'nicholas renotte'# Update by adding to the end of the listnames.append('elon musk')# Update by inserting at the start of the listnames.insert(0, 'richard branson')
And last but certainly not least, it helps understanding how to DELETE.
# Delete components from a listdel names[-2]
Understanding CRUD sets up a mental framework for the components you should understand for each data type.
When I was starting out, there were a ton of IDE options when it came to coding in Python. But the one thing I’d wish I’d known is that Jupyter Notebooks are probably the best interface to use when starting out, especially when it comes to Data Science workloads.
Why?
They provide you with an interactive environment to build, explore and model your data. I’m going to go out on a limb here and say that nothing really comes close. There are other alternatives but Jupyter makes it ridiculously easy.
The easiest way I’ve found to have a stable operating environment for Jupyter is to use Anaconda.
There are a range of flavors when it comes to Jupyter as well, they all provide a similar working interface with a few pros and cons. For a FREE environment that allows you to use GPUs and TPUs. Take a look at Google Colab:
But, be prepared to flex as well when you finally land that sweet sweet Data Science gig. A lot of enterprise organisations are moving towards Data Science platforms. The one I use at work on a day to day basis is Watson Studio.
It’s so easy to fall into the TUTORIAL TRAP!
Doing tutorial, after tutorial and never really getting up and running with building stuff.
I’ve been there. You’ve been there. We’ve ALL been there!
The best way to break through that rut is to start making and breaking stuff with Python. Find an easy enough tutorial that’s just outside the boundary of your skill and give it a go.
I’ve always wanted to do something in the accessibility space and decided to try and tackle sign language recognition pretty early on in my journey.
I don’t think I’m quite there yet. That being said tackling something that’s just outside the boundary of your skillset will help you accelerate faster than anything else!
Alright, enough of the ‘tips’. Let’s get to the nitty gritty.
The code blocks below highlight the key components for each sub topic. They’re all explained in a ton of detail in the YouTube video as well and in this GitHub repo!
Think of variables as placeholders for values and data. They make it easy to refer to data or values that you might need repeatedly throughout your code.
There are a number of different data types in Python. Understanding their properties helps you 1) set the right data type and 2) navigate its properties and 3) leverage the attached methods.
Conditions are important, they allow you to run your data through gates and checks to determine if values meet certain conditions. Loops help you iterate through your sequences so you can perform certain actions repeatedly.
It’s useful to understand basic math operators, however note that a lot of the common packages that you’ll find yourself using e.g. Numpy and Pandas also have native mathematical operators.
Wrapping your code in a function allows you to make things modular, this means that you’re rewriting the same code less often. I found myself writing functions a ton, particularly when it comes to data preprocessing workflows.
To be perfectly honest, I haven’t had to use classes much in my day to day work. HOWEVER, I’ve found them being used just about everywhere when it comes to building custom neural network models and layers, particularly those which have multiple inputs and prediction heads.
Ah, modules and packages. These allow you to tap into the collective wisdom of Python developers around the world. Some of the most common packages you’ll find yourself using are Requests, Pandas, Numpy, Scikit-Learn, TensorFlow and NLTK.
Writing out to disc or saving your data to files is especially useful particularly when working in the Natural Language Processing space. Error Handling comes in handy just about everywhere but especially so when you’re writing production-grade code.
And that’s about it.
I’m crossing my fingers that you found this useful, and if you had any other tips on learning DS, ML or DL I’d love to hear them! The key thing to take away is to start, don’t be afraid to take that first step.
I’m posting a bunch of new ML and DS content each week on my YouTube channel, would love to connect with all of y’all. | [
{
"code": null,
"e": 223,
"s": 172,
"text": "I reached over to grab another sip of my red bull."
},
{
"code": null,
"e": 286,
"s": 223,
"text": "My eyes were bloodshot from staring at the screen for so long."
},
{
"code": null,
"e": 360,
"s": 286,
"text": "I was exhausted. But I needed to do this, I had to get my head around it."
},
{
"code": null,
"e": 383,
"s": 360,
"text": "So I flipped the page."
},
{
"code": null,
"e": 430,
"s": 383,
"text": "Then wrote a couple more lines in my notebook."
},
{
"code": null,
"e": 455,
"s": 430,
"text": "....And I did it again."
},
{
"code": null,
"e": 484,
"s": 455,
"text": "..................And again."
},
{
"code": null,
"e": 520,
"s": 484,
"text": ".......................Annnd again."
},
{
"code": null,
"e": 626,
"s": 520,
"text": "I’d been sitting in a dark corner in Building 11 at the University of Technology, Sydney for 9 HOURS now."
},
{
"code": null,
"e": 653,
"s": 626,
"text": "My MacBook in front of me."
},
{
"code": null,
"e": 686,
"s": 653,
"text": "Python Crash Course on my right."
},
{
"code": null,
"e": 729,
"s": 686,
"text": "And about 87 different tabs open in Chrome"
},
{
"code": null,
"e": 781,
"s": 729,
"text": "Desperately trying to get a decent grasp of Python."
},
{
"code": null,
"e": 894,
"s": 781,
"text": "I wanted to get it so bad....and I wanted to learn it fast (admittedly faster than what was probably practical)."
},
{
"code": null,
"e": 1110,
"s": 894,
"text": "I was studying my Masters and trying to bring some ML to my clients at work....without really knowing what the hell I was doing. There was just so much to learn when it came to Data Science and ML, let alone Python."
},
{
"code": null,
"e": 1140,
"s": 1110,
"text": "There had to be a better way."
},
{
"code": null,
"e": 1192,
"s": 1140,
"text": "Unfortunately, back then, I didn’t know any better."
},
{
"code": null,
"e": 1446,
"s": 1192,
"text": "Fast forward three years, there’s a lot of stuff I would’ve done a HELLLUVA lot differently. In that time, I’ve managed to build a ton of models, start (and crash) a startup, as well as becoming a Data Scientist at IBM working with some amazing clients."
},
{
"code": null,
"e": 1625,
"s": 1446,
"text": "But I always think back to those weekends I spent grinding away teaching myself to code. Looking back now, yeah it was worth it...but I could’ve done it wayyyyy more efficiently."
},
{
"code": null,
"e": 1680,
"s": 1625,
"text": "That’s exactly what I want to talk to you about today."
},
{
"code": null,
"e": 1791,
"s": 1680,
"text": "The strategy I would use to learn Python for Machine Learning and Data Science again...if I had to start over."
},
{
"code": null,
"e": 1965,
"s": 1791,
"text": "If you’re more of a video person, I also made a 5ish hour crash course that distills all this down but stick with me, I’m hoping i can share some golden nuggets nonetheless."
},
{
"code": null,
"e": 2075,
"s": 1965,
"text": "There are 3 key components that I think it’s important to get your head around before kicking off your study."
},
{
"code": null,
"e": 2094,
"s": 2075,
"text": "The first is CRUD."
},
{
"code": null,
"e": 2275,
"s": 2094,
"text": "CRUD stands for Create, Read, Update and Delete. It’s a concept that’s commonly associated with SQL. It refers to the core actions that are necessary to work with database records."
},
{
"code": null,
"e": 2284,
"s": 2275,
"text": "However!"
},
{
"code": null,
"e": 2646,
"s": 2284,
"text": "The same concept is useful when it comes to programming. If you can understand how to create, read, update and delete an object in Python, you’re well on your way to understanding that component. The only objection I have to this is that it’s also important to understand how to loop through components as well, so maybe CRUDL is a better initialism? I digress."
},
{
"code": null,
"e": 2830,
"s": 2646,
"text": "Understanding CRUD is important because it sets a foundation for the operations you should be able to apply to components in Python. Say for example you wanted to apply CRUD to lists."
},
{
"code": null,
"e": 2907,
"s": 2830,
"text": "We know that we can CREATE lists using sequences wrapped in square brackets."
},
{
"code": null,
"e": 3009,
"s": 2907,
"text": "# Creating a listnames = [‘neil armstrong’, ‘buzz aldrin’, ‘sally ride’, ‘yuri gagarin’, ‘elon musk’]"
},
{
"code": null,
"e": 3063,
"s": 3009,
"text": "We can READ them using indexing or the print function"
},
{
"code": null,
"e": 3153,
"s": 3063,
"text": "# Printing a listprint(names)# Reading the first valuenames[0]# Slicing a rangenames[1:3]"
},
{
"code": null,
"e": 3230,
"s": 3153,
"text": "To UPDATE, you can reassign a value, use the insert method or append method."
},
{
"code": null,
"e": 3430,
"s": 3230,
"text": "# Update a single valuenames[-1] = 'nicholas renotte'# Update by adding to the end of the listnames.append('elon musk')# Update by inserting at the start of the listnames.insert(0, 'richard branson')"
},
{
"code": null,
"e": 3502,
"s": 3430,
"text": "And last but certainly not least, it helps understanding how to DELETE."
},
{
"code": null,
"e": 3547,
"s": 3502,
"text": "# Delete components from a listdel names[-2]"
},
{
"code": null,
"e": 3654,
"s": 3547,
"text": "Understanding CRUD sets up a mental framework for the components you should understand for each data type."
},
{
"code": null,
"e": 3918,
"s": 3654,
"text": "When I was starting out, there were a ton of IDE options when it came to coding in Python. But the one thing I’d wish I’d known is that Jupyter Notebooks are probably the best interface to use when starting out, especially when it comes to Data Science workloads."
},
{
"code": null,
"e": 3923,
"s": 3918,
"text": "Why?"
},
{
"code": null,
"e": 4156,
"s": 3923,
"text": "They provide you with an interactive environment to build, explore and model your data. I’m going to go out on a limb here and say that nothing really comes close. There are other alternatives but Jupyter makes it ridiculously easy."
},
{
"code": null,
"e": 4254,
"s": 4156,
"text": "The easiest way I’ve found to have a stable operating environment for Jupyter is to use Anaconda."
},
{
"code": null,
"e": 4478,
"s": 4254,
"text": "There are a range of flavors when it comes to Jupyter as well, they all provide a similar working interface with a few pros and cons. For a FREE environment that allows you to use GPUs and TPUs. Take a look at Google Colab:"
},
{
"code": null,
"e": 4707,
"s": 4478,
"text": "But, be prepared to flex as well when you finally land that sweet sweet Data Science gig. A lot of enterprise organisations are moving towards Data Science platforms. The one I use at work on a day to day basis is Watson Studio."
},
{
"code": null,
"e": 4752,
"s": 4707,
"text": "It’s so easy to fall into the TUTORIAL TRAP!"
},
{
"code": null,
"e": 4844,
"s": 4752,
"text": "Doing tutorial, after tutorial and never really getting up and running with building stuff."
},
{
"code": null,
"e": 4902,
"s": 4844,
"text": "I’ve been there. You’ve been there. We’ve ALL been there!"
},
{
"code": null,
"e": 5086,
"s": 4902,
"text": "The best way to break through that rut is to start making and breaking stuff with Python. Find an easy enough tutorial that’s just outside the boundary of your skill and give it a go."
},
{
"code": null,
"e": 5235,
"s": 5086,
"text": "I’ve always wanted to do something in the accessibility space and decided to try and tackle sign language recognition pretty early on in my journey."
},
{
"code": null,
"e": 5407,
"s": 5235,
"text": "I don’t think I’m quite there yet. That being said tackling something that’s just outside the boundary of your skillset will help you accelerate faster than anything else!"
},
{
"code": null,
"e": 5469,
"s": 5407,
"text": "Alright, enough of the ‘tips’. Let’s get to the nitty gritty."
},
{
"code": null,
"e": 5635,
"s": 5469,
"text": "The code blocks below highlight the key components for each sub topic. They’re all explained in a ton of detail in the YouTube video as well and in this GitHub repo!"
},
{
"code": null,
"e": 5789,
"s": 5635,
"text": "Think of variables as placeholders for values and data. They make it easy to refer to data or values that you might need repeatedly throughout your code."
},
{
"code": null,
"e": 5980,
"s": 5789,
"text": "There are a number of different data types in Python. Understanding their properties helps you 1) set the right data type and 2) navigate its properties and 3) leverage the attached methods."
},
{
"code": null,
"e": 6204,
"s": 5980,
"text": "Conditions are important, they allow you to run your data through gates and checks to determine if values meet certain conditions. Loops help you iterate through your sequences so you can perform certain actions repeatedly."
},
{
"code": null,
"e": 6394,
"s": 6204,
"text": "It’s useful to understand basic math operators, however note that a lot of the common packages that you’ll find yourself using e.g. Numpy and Pandas also have native mathematical operators."
},
{
"code": null,
"e": 6621,
"s": 6394,
"text": "Wrapping your code in a function allows you to make things modular, this means that you’re rewriting the same code less often. I found myself writing functions a ton, particularly when it comes to data preprocessing workflows."
},
{
"code": null,
"e": 6895,
"s": 6621,
"text": "To be perfectly honest, I haven’t had to use classes much in my day to day work. HOWEVER, I’ve found them being used just about everywhere when it comes to building custom neural network models and layers, particularly those which have multiple inputs and prediction heads."
},
{
"code": null,
"e": 7134,
"s": 6895,
"text": "Ah, modules and packages. These allow you to tap into the collective wisdom of Python developers around the world. Some of the most common packages you’ll find yourself using are Requests, Pandas, Numpy, Scikit-Learn, TensorFlow and NLTK."
},
{
"code": null,
"e": 7385,
"s": 7134,
"text": "Writing out to disc or saving your data to files is especially useful particularly when working in the Natural Language Processing space. Error Handling comes in handy just about everywhere but especially so when you’re writing production-grade code."
},
{
"code": null,
"e": 7406,
"s": 7385,
"text": "And that’s about it."
},
{
"code": null,
"e": 7617,
"s": 7406,
"text": "I’m crossing my fingers that you found this useful, and if you had any other tips on learning DS, ML or DL I’d love to hear them! The key thing to take away is to start, don’t be afraid to take that first step."
}
] |
How to make a page redirect using jQuery? | To redirect to another webpage in jQuery, use attr(). You can try to run the following code to redirect to another webpage −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$(location).attr('href','http://qries.com');
});
</script>
</head>
<body>
</body>
</html> | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "To redirect to another webpage in jQuery, use attr(). You can try to run the following code to redirect to another webpage −"
},
{
"code": null,
"e": 1487,
"s": 1187,
"text": "<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n $(document).ready(function() {\n $(location).attr('href','http://qries.com');\n });\n </script>\n </head>\n <body>\n </body>\n</html>"
}
] |
Javascript | Window Blur() and Window Focus() Method - GeeksforGeeks | 22 Nov, 2021
Window.blur() MethodThe blur() method is used to remove focus from the current window. i.e, It send the new open Window to the background.
Syntax:
Window.blur()
Parameter: It does not require any parameters.
Return Value: It does not Return any value.
Window.focus() MethodThe focus() method is used to focus on the new open window. i.e bringing back the blur window to the foreground.
Syntax:
window.focus()
Parameter: It does not require any parameters.
Return Value: It does not Return any value.
Below example illustrates the window.blur() and window.focus() method in JavaScript:
Example:
<!DOCTYPE html><html> <head> <title> window Blur and Focus method </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } </style></head> <body> <div class="gfg">GeeksforGeeks</div> <h2>Blur and Focus</h2> <script> var Window; // Function that open the new Window function windowOpen() { Window = window.open( "https://www.geeksforgeeks.org/", "_blank", "width=400, height=450"); } // function that Closes the open Window function windowClose() { Window.close(); } //function that blur the open Window function windowBlur() { Window.blur(); } //function that focus on open Window function windowFocus() { Window.focus(); } </script> <button onclick="windowOpen()"> Open GeeksforGeeks </button> <button onclick="windowBlur()"> Blur GeeksforGeeks </button> <button onclick="windowFocus()"> Focus GeeksforGeeks </button> <button onclick="windowClose()"> Close GeeksforGeeks </button></body> </html>
Output: If click on blur GeeksforGeeks button then geeksforgeeks.org page will move to the background and if click on focus GeeksforGeeks button then the geeksforgeeks.oge windows will come to foreground.
Click on the Blur:
Click on the Focus:
Supported Browser: The browser supported by Window Blur() and Window Focus() Method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 12.1 and above
Safari 1 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to Open URL in New Tab using JavaScript ?
JavaScript | console.log() with Examples
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25922,
"s": 25894,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 26061,
"s": 25922,
"text": "Window.blur() MethodThe blur() method is used to remove focus from the current window. i.e, It send the new open Window to the background."
},
{
"code": null,
"e": 26069,
"s": 26061,
"text": "Syntax:"
},
{
"code": null,
"e": 26083,
"s": 26069,
"text": "Window.blur()"
},
{
"code": null,
"e": 26130,
"s": 26083,
"text": "Parameter: It does not require any parameters."
},
{
"code": null,
"e": 26174,
"s": 26130,
"text": "Return Value: It does not Return any value."
},
{
"code": null,
"e": 26308,
"s": 26174,
"text": "Window.focus() MethodThe focus() method is used to focus on the new open window. i.e bringing back the blur window to the foreground."
},
{
"code": null,
"e": 26316,
"s": 26308,
"text": "Syntax:"
},
{
"code": null,
"e": 26331,
"s": 26316,
"text": "window.focus()"
},
{
"code": null,
"e": 26378,
"s": 26331,
"text": "Parameter: It does not require any parameters."
},
{
"code": null,
"e": 26422,
"s": 26378,
"text": "Return Value: It does not Return any value."
},
{
"code": null,
"e": 26507,
"s": 26422,
"text": "Below example illustrates the window.blur() and window.focus() method in JavaScript:"
},
{
"code": null,
"e": 26516,
"s": 26507,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> window Blur and Focus method </title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } </style></head> <body> <div class=\"gfg\">GeeksforGeeks</div> <h2>Blur and Focus</h2> <script> var Window; // Function that open the new Window function windowOpen() { Window = window.open( \"https://www.geeksforgeeks.org/\", \"_blank\", \"width=400, height=450\"); } // function that Closes the open Window function windowClose() { Window.close(); } //function that blur the open Window function windowBlur() { Window.blur(); } //function that focus on open Window function windowFocus() { Window.focus(); } </script> <button onclick=\"windowOpen()\"> Open GeeksforGeeks </button> <button onclick=\"windowBlur()\"> Blur GeeksforGeeks </button> <button onclick=\"windowFocus()\"> Focus GeeksforGeeks </button> <button onclick=\"windowClose()\"> Close GeeksforGeeks </button></body> </html>",
"e": 27793,
"s": 26516,
"text": null
},
{
"code": null,
"e": 27998,
"s": 27793,
"text": "Output: If click on blur GeeksforGeeks button then geeksforgeeks.org page will move to the background and if click on focus GeeksforGeeks button then the geeksforgeeks.oge windows will come to foreground."
},
{
"code": null,
"e": 28017,
"s": 27998,
"text": "Click on the Blur:"
},
{
"code": null,
"e": 28037,
"s": 28017,
"text": "Click on the Focus:"
},
{
"code": null,
"e": 28139,
"s": 28037,
"text": "Supported Browser: The browser supported by Window Blur() and Window Focus() Method are listed below:"
},
{
"code": null,
"e": 28165,
"s": 28139,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 28183,
"s": 28165,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 28203,
"s": 28183,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 28233,
"s": 28203,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 28254,
"s": 28233,
"text": "Opera 12.1 and above"
},
{
"code": null,
"e": 28273,
"s": 28254,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 28285,
"s": 28273,
"text": "ysachin2314"
},
{
"code": null,
"e": 28306,
"s": 28285,
"text": "javascript-functions"
},
{
"code": null,
"e": 28317,
"s": 28306,
"text": "JavaScript"
},
{
"code": null,
"e": 28334,
"s": 28317,
"text": "Web Technologies"
},
{
"code": null,
"e": 28432,
"s": 28334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28441,
"s": 28432,
"text": "Comments"
},
{
"code": null,
"e": 28454,
"s": 28441,
"text": "Old Comments"
},
{
"code": null,
"e": 28499,
"s": 28454,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28571,
"s": 28499,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28632,
"s": 28571,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28678,
"s": 28632,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28719,
"s": 28678,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 28761,
"s": 28719,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28794,
"s": 28761,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28856,
"s": 28794,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28899,
"s": 28856,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Flex - Style with CSS | Flex supports the use of CSS syntax and styles to apply to its UI controls in the same way as CSS to HTML components.
You can refer to a style sheet available in the class path of the application. For example consider Style.css file in com/tutorialspoint/client folder where HelloWorld.mxml file also lies.
/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
...
.container {
cornerRadius :10;
horizontalCenter :0;
borderColor: #777777;
verticalCenter:0;
backgroundColor: #efefef;
}
Then css file can be referred by following code snippet
<fx:Style source = "/com/tutorialspoint/client/Style.css" />
Assign styles to UI component using styleName property
<s:BorderContainer width = "500" height = "500" id = "mainContainer"
styleName = "container">
...
</s:BorderContainer>
You can define styles within UI container component using <fx:Style> tag
<fx:Style>
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
/* class level selector */
.errorLabel {
color: red;
}
</fx:Style>
Assign styles to UI component using styleName property.
<s:Label id = "errorMsg" text = "This is an error message" styleName = "errorLabel" />
Style UI component using id selector.
<fx:Style>
/* id level selector */
#msgLabel {
color: gray;
}
</fx:Style>
<s:Label id = "msgLabel" text = "This is a normal message" />
Style one type of UI Component in one GO.
<fx:Style>
/* style applied on all buttons */
s|Button {
fontSize: 15;
color: #9933FF;
}
</fx:Style>
<s:Button label = "Click Me!" id = "btnClickMe"
click = "btnClickMe_clickHandler(event)" />
Let us follow the steps to check CSS styling of a Flex application by creating a test application −
Following is the content of the modified CSS file src/com.tutorialspoint/Style.css.
/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
.heading
{
fontFamily: Arial, Helvetica, sans-serif;
fontSize: 17px;
color: #9b1204;
textDecoration:none;
fontWeight:normal;
}
.button {
fontWeight: bold;
}
.container {
cornerRadius :10;
horizontalCenter :0;
borderColor: #777777;
verticalCenter:0;
backgroundColor: #efefef;
}
Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml.
<?xml version = "1.0" encoding = "utf-8"?>
<s:Application xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s = "library://ns.adobe.com/flex/spark"
xmlns:mx = "library://ns.adobe.com/flex/mx"
width = "100%" height = "100%" minWidth = "500" minHeight = "500"
initialize = "application_initializeHandler(event)">
<!--Add reference to style sheet -->
<fx:Style source = "/com/tutorialspoint/client/Style.css" />
<!--Using styles within mxml file -->
<fx:Style>
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
/* class level selector */
.errorLabel {
color: red;
}
/* id level selector */
#msgLabel {
color: gray;
}
/* style applied on all buttons */
s|Button {
fontSize: 15;
color: #9933FF;
}
</fx:Style>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
protected function btnClickMe_clickHandler(event:MouseEvent):void {
Alert.show("Hello World!");
}
protected function application_initializeHandler(event:FlexEvent):void {
lblHeader.text = "CSS Demonstrating Application";
}
]]>
</fx:Script>
<s:BorderContainer width = "560" height = "500" id = "mainContainer"
styleName = "container">
<s:VGroup width = "100%" height = "100%" gap = "50"
horizontalAlign = "center" verticalAlign = "middle">
<s:Label width = "100%" id = "lblHeader" fontSize = "40"
color = "0x777777" styleName = "heading" />
<s:Button label = "Click Me!" id = "btnClickMe"
click = "btnClickMe_clickHandler(event)" />
<s:Label id = "errorMsg"
text = "This is an error message" styleName = "errorLabel" />
<s:Label id = "msgLabel" text = "This is a normal message" />
</s:VGroup>
</s:BorderContainer>
</s:Application>
Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, this will produce following result: [ Try it online ]
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
12 Lectures
1 hours
Prof. Paul Cline, Ed.D
87 Lectures
11 hours
Code And Create
30 Lectures
1 hours
Faigy Liebermann
11 Lectures
1.5 hours
Prof Krishna N Sharma
32 Lectures
34 mins
Prof Krishna N Sharma
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2165,
"s": 2047,
"text": "Flex supports the use of CSS syntax and styles to apply to its UI controls in the same way as CSS to HTML components."
},
{
"code": null,
"e": 2354,
"s": 2165,
"text": "You can refer to a style sheet available in the class path of the application. For example consider Style.css file in com/tutorialspoint/client folder where HelloWorld.mxml file also lies."
},
{
"code": null,
"e": 2607,
"s": 2354,
"text": "/* CSS file */\n@namespace s \"library://ns.adobe.com/flex/spark\";\n@namespace mx \"library://ns.adobe.com/flex/mx\";\n...\n.container {\n cornerRadius :10;\n horizontalCenter :0;\t\n borderColor: #777777;\n verticalCenter:0;\n backgroundColor: #efefef;\n}"
},
{
"code": null,
"e": 2663,
"s": 2607,
"text": "Then css file can be referred by following code snippet"
},
{
"code": null,
"e": 2725,
"s": 2663,
"text": "<fx:Style source = \"/com/tutorialspoint/client/Style.css\" />\n"
},
{
"code": null,
"e": 2780,
"s": 2725,
"text": "Assign styles to UI component using styleName property"
},
{
"code": null,
"e": 2911,
"s": 2780,
"text": "<s:BorderContainer width = \"500\" height = \"500\" id = \"mainContainer\" \n styleName = \"container\"> \n ...\n</s:BorderContainer>\t\t "
},
{
"code": null,
"e": 2984,
"s": 2911,
"text": "You can define styles within UI container component using <fx:Style> tag"
},
{
"code": null,
"e": 3185,
"s": 2984,
"text": "<fx:Style>\n @namespace s \"library://ns.adobe.com/flex/spark\";\n @namespace mx \"library://ns.adobe.com/flex/mx\";\n\n /* class level selector */\n .errorLabel {\n color: red;\n }\t\t\n</fx:Style>"
},
{
"code": null,
"e": 3241,
"s": 3185,
"text": "Assign styles to UI component using styleName property."
},
{
"code": null,
"e": 3329,
"s": 3241,
"text": "<s:Label id = \"errorMsg\" text = \"This is an error message\" styleName = \"errorLabel\" />\n"
},
{
"code": null,
"e": 3367,
"s": 3329,
"text": "Style UI component using id selector."
},
{
"code": null,
"e": 3526,
"s": 3367,
"text": "<fx:Style> \n /* id level selector */ \n #msgLabel { \n color: gray; \n } \n</fx:Style>\n\n<s:Label id = \"msgLabel\" text = \"This is a normal message\" /> "
},
{
"code": null,
"e": 3568,
"s": 3526,
"text": "Style one type of UI Component in one GO."
},
{
"code": null,
"e": 3794,
"s": 3568,
"text": "<fx:Style> \n /* style applied on all buttons */ \n s|Button { \n fontSize: 15; \n color: #9933FF; \n } \n</fx:Style>\n\n<s:Button label = \"Click Me!\" id = \"btnClickMe\"\n click = \"btnClickMe_clickHandler(event)\" />"
},
{
"code": null,
"e": 3894,
"s": 3794,
"text": "Let us follow the steps to check CSS styling of a Flex application by creating a test application −"
},
{
"code": null,
"e": 3978,
"s": 3894,
"text": "Following is the content of the modified CSS file src/com.tutorialspoint/Style.css."
},
{
"code": null,
"e": 4408,
"s": 3978,
"text": "/* CSS file */\n@namespace s \"library://ns.adobe.com/flex/spark\";\n@namespace mx \"library://ns.adobe.com/flex/mx\";\n\n.heading\n{\n fontFamily: Arial, Helvetica, sans-serif;\n fontSize: 17px;\n color: #9b1204;\n textDecoration:none;\n fontWeight:normal;\n}\n\n.button {\n fontWeight: bold;\t\t\t\n}\n\n.container {\n cornerRadius :10;\n horizontalCenter :0;\t\n borderColor: #777777;\n verticalCenter:0;\n backgroundColor: #efefef;\n}"
},
{
"code": null,
"e": 4499,
"s": 4408,
"text": "Following is the content of the modified mxml file src/com.tutorialspoint/HelloWorld.mxml."
},
{
"code": null,
"e": 6505,
"s": 4499,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<s:Application xmlns:fx = \"http://ns.adobe.com/mxml/2009\"\n xmlns:s = \"library://ns.adobe.com/flex/spark\"\n xmlns:mx = \"library://ns.adobe.com/flex/mx\"\n width = \"100%\" height = \"100%\" minWidth = \"500\" minHeight = \"500\"\n initialize = \"application_initializeHandler(event)\">\n \n <!--Add reference to style sheet -->\n <fx:Style source = \"/com/tutorialspoint/client/Style.css\" />\n\n <!--Using styles within mxml file -->\n <fx:Style>\n @namespace s \"library://ns.adobe.com/flex/spark\";\n @namespace mx \"library://ns.adobe.com/flex/mx\";\n\n /* class level selector */\n .errorLabel {\n color: red;\n }\n\n /* id level selector */\n #msgLabel {\n color: gray;\n }\n\n /* style applied on all buttons */\n s|Button {\n fontSize: 15;\n color: #9933FF;\n }\n </fx:Style>\n\n <fx:Script>\n <![CDATA[\n import mx.controls.Alert;\n import mx.events.FlexEvent;\n protected function btnClickMe_clickHandler(event:MouseEvent):void {\n Alert.show(\"Hello World!\");\n }\n\n protected function application_initializeHandler(event:FlexEvent):void {\n lblHeader.text = \"CSS Demonstrating Application\";\n }\n ]]>\n </fx:Script>\n \n <s:BorderContainer width = \"560\" height = \"500\" id = \"mainContainer\"\n styleName = \"container\">\n <s:VGroup width = \"100%\" height = \"100%\" gap = \"50\"\n horizontalAlign = \"center\" verticalAlign = \"middle\">\n <s:Label width = \"100%\" id = \"lblHeader\" fontSize = \"40\"\n color = \"0x777777\" styleName = \"heading\" />\n <s:Button label = \"Click Me!\" id = \"btnClickMe\"\n click = \"btnClickMe_clickHandler(event)\" />\n <s:Label id = \"errorMsg\"\n text = \"This is an error message\" styleName = \"errorLabel\" />\n <s:Label id = \"msgLabel\" text = \"This is a normal message\" />\n </s:VGroup>\n </s:BorderContainer>\n</s:Application>"
},
{
"code": null,
"e": 6752,
"s": 6505,
"text": "Once you are ready with all the changes done, let us compile and run the application in normal mode as we did in Flex - Create Application chapter. If everything is fine with your application, this will produce following result: [ Try it online ]"
},
{
"code": null,
"e": 6787,
"s": 6752,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6818,
"s": 6787,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6851,
"s": 6818,
"text": "\n 12 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6875,
"s": 6851,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 6909,
"s": 6875,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6926,
"s": 6909,
"text": " Code And Create"
},
{
"code": null,
"e": 6959,
"s": 6926,
"text": "\n 30 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6977,
"s": 6959,
"text": " Faigy Liebermann"
},
{
"code": null,
"e": 7012,
"s": 6977,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7035,
"s": 7012,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 7067,
"s": 7035,
"text": "\n 32 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 7090,
"s": 7067,
"text": " Prof Krishna N Sharma"
},
{
"code": null,
"e": 7097,
"s": 7090,
"text": " Print"
},
{
"code": null,
"e": 7108,
"s": 7097,
"text": " Add Notes"
}
] |
Plus One | Practice | GeeksforGeeks | Given a non-negative number represented as a list of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is first element of array.
Example 1:
Input:
N = 3
arr[] = {1, 2, 4}
Output:
1 2 5
Explanation:
124+1 = 125, and so the Output
Example 2:
Input:
N = 3
arr[] = {9,9,9}
Output:
1 0 0 0
Explanation:
999+1 = 1000, and so the output
Your Task:
You don't need to read input or print anything. You only need to complete the function increment() that takes an integer N, and an array arr of size N as input and returns a list of integers denoting the new number which we get after adding one to the number denoted by the array arr.
Expected Time Complexity: O(N)
Expected Auxilliary Space: O(1)
Constraints:
1 <= N <= 105
0 <= arri <= 9
0
singhsourav02154 days ago
//Solution in java
static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) {
int i = N-1;
if(arr.get(arr.size()-1) < 9) {
arr.set(arr.size()-1, arr.get(N-1)+1);
return arr;
}
else {
while(i>=0 && arr.get(i) == 9) {
arr.set(i, 0);
if(i == 0)
arr.add(0,1);
i--;
}
}
//System.out.println(i);
if(i>-1)
arr.set(i, arr.get(i)+1);
return arr;
}
+1
mohittpattel2 weeks ago
class Solution {
public:
vector<int> increment(vector<int> arr ,int N) {
// code here
//Copying the whole array ot the ans
vector<int> ans(arr);
for(int i = N-1; i >= 0; i--)
{
if(ans[i] == 9)
ans[i] = 0;
else
{
ans[i]++;
return ans;
}
}
ans[0] = 1;
ans.push_back(0);
return ans;
}
};
0
joyrockok2 weeks ago
class Solution { static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) { // code here ArrayList<Integer> subRslt = new ArrayList<Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); boolean olim = false; for(int i=N-1; i>=0; i--) { int value = arr.get(i); if(i==N-1) { value += 1; } else if(olim) { value += 1; } if(value >= 10) { if(i==0) { subRslt.add(value%10); subRslt.add(1); } else { subRslt.add(value%10); olim = true; } } else { subRslt.add(value); olim = false; } } for(int i=subRslt.size()-1; i>=0; i--) { result.add(subRslt.get(i)); } return result; }};
+1
sagrikasoni3 weeks ago
EASY JAVA Solution using Array List .set function
class Solution {
static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) {
int j = arr.size()-1; boolean b = true;
while(j>= 0 && b == true ){
if(j== 0 && arr.get(j)==9){
arr.set(j,1);
arr.add(0);
j--;
}
else if(arr.get(j)==9){
arr.set(j,0);
j--;
}
else {
int temp = arr.get(j)+1;
arr. set(j,temp);
b = false;
}
}
return arr;
}
}
+1
eswar99933 weeks ago
Python Solution:
def increment(self, arr, N):
# code here
str1=""
if arr[-1]!=9:
arr[-1]=arr[-1]+1
return arr
else:
for i in arr:
str1+=str(i)
res=int(str1)+1
return str(res)
+1
swapniltayal4221 month ago
class Solution { public: vector<int> increment(vector<int> arr ,int N) { // code here int carry = 1; for (int i=N-1; i>-1; i--){ int s = arr[i] + carry; arr[i] = (s)%10; if (s > 10){ carry = arr[i] % 10; }else if (s == 10){ carry = 1; }else{ carry = 0; } } if(arr[0]==0){ arr.push_back(0); arr[0]=1; } return arr; }};
0
pacificngu11 month ago
vector<int> increment(vector<int> arr ,int N) { vector<int> number; int carry=0; for(int i=N-1;i>=0;i--) {
if(arr[i]==9&&i==N-1&&N!=1) { number.push_back(0); carry=1; } else if(arr[i]==9&&N==1) { number.push_back(0); number.push_back(1); } else if(arr[i]==9&&carry==1) { number.push_back(0); carry=1; } else if(i==N-1&&arr[i]!=9) { number.push_back(arr[i]+1); carry=0; } else if(carry==1) { number.push_back(arr[i]+1); carry=0; } else { number.push_back(arr[i]); } } if(carry==1) { number.push_back(1); } reverse(number.begin(),number.end()); return number; }
0
nandasobhan1 month ago
can anyone tell why my code is not running?
class Solution { public: vector<int> increment(vector<int> arr ,int N) { // code here int no=0; for(int i=0;i<N;i++){ no=no*10+arr[i]; } no=no+1; int p=N+1; vector<int> v(p); for(int i=p-1;i>=0;i--){ v.push_back(no%10); no=no/10; } arr=v; return arr ; } };
+1
abera25831 month ago
vector<int> increment(vector<int> arr ,int N) { // code here int n=arr.size(); for(int i=(n-1);i>=0;i--){ if(arr[i]!=9){ arr[i]=arr[i]+1; break; } else{ arr[i]=0; } } if(arr[0]==0){ arr.push_back(0); arr[0]=1; } return arr; }
0
raghav_maheshwari1 month ago
A very simple logic
class Solution {
public:
vector<int> increment(vector<int> a ,int N) {
a[N-1] +=1;
int carry =0 ;
if(a[N-1] > 9) {
a[N-1]%= 10;
++carry;
}
for(int i = N-2 ; i>=0 ; --i) {
if(a[i]+carry > 9) {
a[i] = (a[i] + carry)%10;
carry = 1;
}
else {
a[i] = a[i] + carry;
carry = 0;
break;
}
}
if(carry) {
a.insert(a.begin() , 1);
}
return a;
}
};
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": 458,
"s": 238,
"text": "Given a non-negative number represented as a list of digits, add 1 to the number (increment the number represented by the digits). The digits are stored such that the most significant digit is first element of array. \n "
},
{
"code": null,
"e": 469,
"s": 458,
"text": "Example 1:"
},
{
"code": null,
"e": 560,
"s": 469,
"text": "Input: \nN = 3\narr[] = {1, 2, 4}\nOutput: \n1 2 5\nExplanation:\n124+1 = 125, and so the Output"
},
{
"code": null,
"e": 571,
"s": 560,
"text": "Example 2:"
},
{
"code": null,
"e": 663,
"s": 571,
"text": "Input: \nN = 3\narr[] = {9,9,9}\nOutput: \n1 0 0 0\nExplanation:\n999+1 = 1000, and so the output"
},
{
"code": null,
"e": 960,
"s": 663,
"text": "\nYour Task:\nYou don't need to read input or print anything. You only need to complete the function increment() that takes an integer N, and an array arr of size N as input and returns a list of integers denoting the new number which we get after adding one to the number denoted by the array arr."
},
{
"code": null,
"e": 1027,
"s": 960,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxilliary Space: O(1)\n "
},
{
"code": null,
"e": 1069,
"s": 1027,
"text": "Constraints:\n1 <= N <= 105\n0 <= arri <= 9"
},
{
"code": null,
"e": 1071,
"s": 1069,
"text": "0"
},
{
"code": null,
"e": 1097,
"s": 1071,
"text": "singhsourav02154 days ago"
},
{
"code": null,
"e": 1509,
"s": 1097,
"text": "//Solution in java\n static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) {\n \tint i = N-1;\n\t\tif(arr.get(arr.size()-1) < 9) {\n\t\t\tarr.set(arr.size()-1, arr.get(N-1)+1);\n\t\t\treturn arr;\n\t\t}\n\t\telse {\n\t\t\twhile(i>=0 && arr.get(i) == 9) {\n\t\t\t\tarr.set(i, 0);\n\t\t\t\tif(i == 0)\n\t\t\t\t\tarr.add(0,1);\n\t\t\t\ti--;\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t//System.out.println(i);\n\t\tif(i>-1)\n\t\t\tarr.set(i, arr.get(i)+1);\n\t\treturn arr;\n\n }"
},
{
"code": null,
"e": 1512,
"s": 1509,
"text": "+1"
},
{
"code": null,
"e": 1536,
"s": 1512,
"text": "mohittpattel2 weeks ago"
},
{
"code": null,
"e": 2026,
"s": 1536,
"text": "class Solution {\n public:\n vector<int> increment(vector<int> arr ,int N) {\n // code here\n //Copying the whole array ot the ans\n vector<int> ans(arr);\n \n for(int i = N-1; i >= 0; i--)\n {\n if(ans[i] == 9)\n ans[i] = 0;\n else\n {\n ans[i]++;\n return ans;\n }\n }\n \n ans[0] = 1;\n ans.push_back(0);\n \n return ans;\n }\n};"
},
{
"code": null,
"e": 2028,
"s": 2026,
"text": "0"
},
{
"code": null,
"e": 2049,
"s": 2028,
"text": "joyrockok2 weeks ago"
},
{
"code": null,
"e": 2746,
"s": 2049,
"text": "class Solution { static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) { // code here ArrayList<Integer> subRslt = new ArrayList<Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); boolean olim = false; for(int i=N-1; i>=0; i--) { int value = arr.get(i); if(i==N-1) { value += 1; } else if(olim) { value += 1; } if(value >= 10) { if(i==0) { subRslt.add(value%10); subRslt.add(1); } else { subRslt.add(value%10); olim = true; } } else { subRslt.add(value); olim = false; } } for(int i=subRslt.size()-1; i>=0; i--) { result.add(subRslt.get(i)); } return result; }};"
},
{
"code": null,
"e": 2749,
"s": 2746,
"text": "+1"
},
{
"code": null,
"e": 2772,
"s": 2749,
"text": "sagrikasoni3 weeks ago"
},
{
"code": null,
"e": 2823,
"s": 2772,
"text": "EASY JAVA Solution using Array List .set function "
},
{
"code": null,
"e": 3371,
"s": 2823,
"text": "\nclass Solution {\n static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) {\n \n int j = arr.size()-1; boolean b = true;\n while(j>= 0 && b == true ){\n if(j== 0 && arr.get(j)==9){\n arr.set(j,1);\n arr.add(0);\n j--;\n }\n else if(arr.get(j)==9){\n arr.set(j,0);\n j--;\n }\n else {\n int temp = arr.get(j)+1;\n arr. set(j,temp);\n\n b = false;\n }\n \n }\n return arr;\n}\n}"
},
{
"code": null,
"e": 3376,
"s": 3373,
"text": "+1"
},
{
"code": null,
"e": 3397,
"s": 3376,
"text": "eswar99933 weeks ago"
},
{
"code": null,
"e": 3675,
"s": 3397,
"text": "Python Solution:\n\n def increment(self, arr, N):\n # code here\n str1=\"\"\n if arr[-1]!=9:\n arr[-1]=arr[-1]+1\n return arr\n else:\n for i in arr:\n str1+=str(i)\n res=int(str1)+1\n return str(res)"
},
{
"code": null,
"e": 3678,
"s": 3675,
"text": "+1"
},
{
"code": null,
"e": 3705,
"s": 3678,
"text": "swapniltayal4221 month ago"
},
{
"code": null,
"e": 4186,
"s": 3705,
"text": "class Solution { public: vector<int> increment(vector<int> arr ,int N) { // code here int carry = 1; for (int i=N-1; i>-1; i--){ int s = arr[i] + carry; arr[i] = (s)%10; if (s > 10){ carry = arr[i] % 10; }else if (s == 10){ carry = 1; }else{ carry = 0; } } if(arr[0]==0){ arr.push_back(0); arr[0]=1; } return arr; }};"
},
{
"code": null,
"e": 4188,
"s": 4186,
"text": "0"
},
{
"code": null,
"e": 4211,
"s": 4188,
"text": "pacificngu11 month ago"
},
{
"code": null,
"e": 4340,
"s": 4211,
"text": " vector<int> increment(vector<int> arr ,int N) { vector<int> number; int carry=0; for(int i=N-1;i>=0;i--) {"
},
{
"code": null,
"e": 5094,
"s": 4340,
"text": " if(arr[i]==9&&i==N-1&&N!=1) { number.push_back(0); carry=1; } else if(arr[i]==9&&N==1) { number.push_back(0); number.push_back(1); } else if(arr[i]==9&&carry==1) { number.push_back(0); carry=1; } else if(i==N-1&&arr[i]!=9) { number.push_back(arr[i]+1); carry=0; } else if(carry==1) { number.push_back(arr[i]+1); carry=0; } else { number.push_back(arr[i]); } } if(carry==1) { number.push_back(1); } reverse(number.begin(),number.end()); return number; }"
},
{
"code": null,
"e": 5096,
"s": 5094,
"text": "0"
},
{
"code": null,
"e": 5119,
"s": 5096,
"text": "nandasobhan1 month ago"
},
{
"code": null,
"e": 5163,
"s": 5119,
"text": "can anyone tell why my code is not running?"
},
{
"code": null,
"e": 5545,
"s": 5165,
"text": "class Solution { public: vector<int> increment(vector<int> arr ,int N) { // code here int no=0; for(int i=0;i<N;i++){ no=no*10+arr[i]; } no=no+1; int p=N+1; vector<int> v(p); for(int i=p-1;i>=0;i--){ v.push_back(no%10); no=no/10; } arr=v; return arr ; } };"
},
{
"code": null,
"e": 5548,
"s": 5545,
"text": "+1"
},
{
"code": null,
"e": 5569,
"s": 5548,
"text": "abera25831 month ago"
},
{
"code": null,
"e": 5949,
"s": 5569,
"text": " vector<int> increment(vector<int> arr ,int N) { // code here int n=arr.size(); for(int i=(n-1);i>=0;i--){ if(arr[i]!=9){ arr[i]=arr[i]+1; break; } else{ arr[i]=0; } } if(arr[0]==0){ arr.push_back(0); arr[0]=1; } return arr; }"
},
{
"code": null,
"e": 5951,
"s": 5949,
"text": "0"
},
{
"code": null,
"e": 5980,
"s": 5951,
"text": "raghav_maheshwari1 month ago"
},
{
"code": null,
"e": 6582,
"s": 5980,
"text": "A very simple logic \nclass Solution {\n public:\n vector<int> increment(vector<int> a ,int N) {\n a[N-1] +=1;\n int carry =0 ;\n if(a[N-1] > 9) {\n a[N-1]%= 10;\n ++carry;\n }\n for(int i = N-2 ; i>=0 ; --i) {\n if(a[i]+carry > 9) {\n a[i] = (a[i] + carry)%10;\n carry = 1;\n }\n else {\n a[i] = a[i] + carry;\n carry = 0;\n break;\n }\n }\n if(carry) {\n a.insert(a.begin() , 1);\n }\n return a;\n }\n};"
},
{
"code": null,
"e": 6728,
"s": 6582,
"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": 6764,
"s": 6728,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6774,
"s": 6764,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6784,
"s": 6774,
"text": "\nContest\n"
},
{
"code": null,
"e": 6847,
"s": 6784,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6995,
"s": 6847,
"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": 7203,
"s": 6995,
"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": 7309,
"s": 7203,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Spring AOP - Annotation Based Around Advice | @Around is an advice type, which ensures that an advice can run before and after the method execution. Following is the syntax of @Around advice.
@Pointcut("execution(* com.tutorialspoint.Student.getAge(..))")
private void selectGetName(){}
@Around("selectGetAge()")
public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
System.out.println("Around advice");
Object[] args = jp.getArgs();
if(args.length>0){
System.out.print("Arguments passed: " );
for (int i = 0; i < args.length; i++) {
System.out.print("arg "+(i+1)+": "+args[i]);
}
}
Object result = jp.proceed(args);
System.out.println("Returning " + result);
return result.toString();
}
Where,
@Pointcut − Mark a function as a Pointcut
@Pointcut − Mark a function as a Pointcut
execution( expression ) − Expression covering methods on which advice is to be applied.
execution( expression ) − Expression covering methods on which advice is to be applied.
@Around − Mark a function as an advice to be executed before method(s) covered by Pointcut.
@Around − Mark a function as an advice to be executed before method(s) covered by Pointcut.
To understand the above-mentioned concepts related to @Around Advice, let us write an example which will implement @Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class Logging {
/** Following is the definition for a Pointcut to select
* all the methods available. So advice will be called
* for all the methods.
*/
@Pointcut("execution(* com.tutorialspoint.Student.getAge(..))")
private void selectGetAge(){}
/**
* This is the method which I would like to execute
* around a selected method execution.
*/
@Around("selectGetAge()")
public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("Around advice");
Object[] args = proceedingJoinPoint.getArgs();
if(args.length>0){
System.out.print("Arguments passed: " );
for (int i = 0; i < args.length; i++) {
System.out.print("arg "+(i+1)+": "+args[i]);
}
}
Object result = proceedingJoinPoint.proceed(args);
System.out.println("Returning " + result);
}
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
student.getAge();
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy/>
<!-- Definition for student bean -->
<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Around advice
Age : 11
Returning 11
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2415,
"s": 2269,
"text": "@Around is an advice type, which ensures that an advice can run before and after the method execution. Following is the syntax of @Around advice."
},
{
"code": null,
"e": 2976,
"s": 2415,
"text": "@Pointcut(\"execution(* com.tutorialspoint.Student.getAge(..))\")\nprivate void selectGetName(){}\n\n@Around(\"selectGetAge()\")\npublic void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){\n System.out.println(\"Around advice\");\n Object[] args = jp.getArgs();\n if(args.length>0){\n System.out.print(\"Arguments passed: \" );\n for (int i = 0; i < args.length; i++) {\n System.out.print(\"arg \"+(i+1)+\": \"+args[i]);\n }\n }\n Object result = jp.proceed(args);\n System.out.println(\"Returning \" + result);\n return result.toString(); \n}"
},
{
"code": null,
"e": 2983,
"s": 2976,
"text": "Where,"
},
{
"code": null,
"e": 3025,
"s": 2983,
"text": "@Pointcut − Mark a function as a Pointcut"
},
{
"code": null,
"e": 3067,
"s": 3025,
"text": "@Pointcut − Mark a function as a Pointcut"
},
{
"code": null,
"e": 3155,
"s": 3067,
"text": "execution( expression ) − Expression covering methods on which advice is to be applied."
},
{
"code": null,
"e": 3243,
"s": 3155,
"text": "execution( expression ) − Expression covering methods on which advice is to be applied."
},
{
"code": null,
"e": 3335,
"s": 3243,
"text": "@Around − Mark a function as an advice to be executed before method(s) covered by Pointcut."
},
{
"code": null,
"e": 3427,
"s": 3335,
"text": "@Around − Mark a function as an advice to be executed before method(s) covered by Pointcut."
},
{
"code": null,
"e": 3701,
"s": 3427,
"text": "To understand the above-mentioned concepts related to @Around Advice, let us write an example which will implement @Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application −"
},
{
"code": null,
"e": 3850,
"s": 3701,
"text": "Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points."
},
{
"code": null,
"e": 4986,
"s": 3850,
"text": "package com.tutorialspoint;\n\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Pointcut;\nimport org.aspectj.lang.annotation.Around;\nimport org.aspectj.lang.ProceedingJoinPoint; \n\n@Aspect\npublic class Logging {\n /** Following is the definition for a Pointcut to select\n * all the methods available. So advice will be called\n * for all the methods.\n */\n @Pointcut(\"execution(* com.tutorialspoint.Student.getAge(..))\")\n private void selectGetAge(){}\n\n /** \n * This is the method which I would like to execute\n * around a selected method execution.\n */\n @Around(\"selectGetAge()\")\n public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{\n System.out.println(\"Around advice\");\n Object[] args = proceedingJoinPoint.getArgs();\n if(args.length>0){\n System.out.print(\"Arguments passed: \" );\n for (int i = 0; i < args.length; i++) {\n System.out.print(\"arg \"+(i+1)+\": \"+args[i]);\n }\n }\n Object result = proceedingJoinPoint.proceed(args);\n System.out.println(\"Returning \" + result);\n }\n}"
},
{
"code": null,
"e": 5037,
"s": 4986,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5600,
"s": 5037,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n \n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n System.out.println(\"Age : \" + age );\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n System.out.println(\"Name : \" + name );\n return name;\n }\n public void printThrowException(){\n System.out.println(\"Exception raised\");\n throw new IllegalArgumentException();\n }\n}"
},
{
"code": null,
"e": 5651,
"s": 5600,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 6061,
"s": 5651,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n Student student = (Student) context.getBean(\"student\");\n student.getAge(); \n }\n}"
},
{
"code": null,
"e": 6108,
"s": 6061,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 6948,
"s": 6108,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/aop \n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \">\n\n <aop:aspectj-autoproxy/>\n\n <!-- Definition for student bean -->\n <bean id = \"student\" class = \"com.tutorialspoint.Student\">\n <property name = \"name\" value = \"Zara\" />\n <property name = \"age\" value = \"11\"/> \n </bean>\n\n <!-- Definition for logging aspect -->\n <bean id = \"logging\" class = \"com.tutorialspoint.Logging\"/> \n \n</beans>"
},
{
"code": null,
"e": 7203,
"s": 6948,
"text": "Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 7240,
"s": 7203,
"text": "Around advice\nAge : 11\nReturning 11\n"
},
{
"code": null,
"e": 7247,
"s": 7240,
"text": " Print"
},
{
"code": null,
"e": 7258,
"s": 7247,
"text": " Add Notes"
}
] |
Construct a ∈-NFA for the language L = (a* + b*) | The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ
ε-NFA is defined in five-tuple representation
{Q, q0, Σ, δ, F}
Where,
δ − Q × (Σ∪ε)→2Q
δ − Q × (Σ∪ε)→2Q
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
NFA is defined in five tuple representation
{Q, q0, Σ, δ, F}
Where,
δ − Q X Σ→ 2Q
δ − Q X Σ→ 2Q
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
NFA and NFA with epsilon both are almost the same; the only difference is their transition function.
Let’s consider the given language L = (a*+b*)
Step 1 − NFA with epsilon for a* is as follows −
a* means there can be any number of ‘a’ in the expression, even 0 ( if the input symbol is null then also it is valid).
Step 2 − NFA with epsilon for b* is as follows −
b* means there can be any number of b’s in the expression, even 0 (if input symbol is null then also it is valid).
Step 3 − Now construct a*+b* using first and second steps.
The given language is divided into two parts like a* and b* and add two steps by using ‘+’ sign to get the result. | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ"
},
{
"code": null,
"e": 1255,
"s": 1209,
"text": "ε-NFA is defined in five-tuple representation"
},
{
"code": null,
"e": 1272,
"s": 1255,
"text": "{Q, q0, Σ, δ, F}"
},
{
"code": null,
"e": 1279,
"s": 1272,
"text": "Where,"
},
{
"code": null,
"e": 1296,
"s": 1279,
"text": "δ − Q × (Σ∪ε)→2Q"
},
{
"code": null,
"e": 1313,
"s": 1296,
"text": "δ − Q × (Σ∪ε)→2Q"
},
{
"code": null,
"e": 1338,
"s": 1313,
"text": "Q − Finite set of states"
},
{
"code": null,
"e": 1363,
"s": 1338,
"text": "Q − Finite set of states"
},
{
"code": null,
"e": 1398,
"s": 1363,
"text": "Σ − Finite set of the input symbol"
},
{
"code": null,
"e": 1433,
"s": 1398,
"text": "Σ − Finite set of the input symbol"
},
{
"code": null,
"e": 1452,
"s": 1433,
"text": "q0 − Initial state"
},
{
"code": null,
"e": 1471,
"s": 1452,
"text": "q0 − Initial state"
},
{
"code": null,
"e": 1487,
"s": 1471,
"text": "F − Final state"
},
{
"code": null,
"e": 1503,
"s": 1487,
"text": "F − Final state"
},
{
"code": null,
"e": 1527,
"s": 1503,
"text": "δ − Transition function"
},
{
"code": null,
"e": 1551,
"s": 1527,
"text": "δ − Transition function"
},
{
"code": null,
"e": 1595,
"s": 1551,
"text": "NFA is defined in five tuple representation"
},
{
"code": null,
"e": 1612,
"s": 1595,
"text": "{Q, q0, Σ, δ, F}"
},
{
"code": null,
"e": 1619,
"s": 1612,
"text": "Where,"
},
{
"code": null,
"e": 1633,
"s": 1619,
"text": "δ − Q X Σ→ 2Q"
},
{
"code": null,
"e": 1647,
"s": 1633,
"text": "δ − Q X Σ→ 2Q"
},
{
"code": null,
"e": 1672,
"s": 1647,
"text": "Q − Finite set of states"
},
{
"code": null,
"e": 1697,
"s": 1672,
"text": "Q − Finite set of states"
},
{
"code": null,
"e": 1732,
"s": 1697,
"text": "Σ − Finite set of the input symbol"
},
{
"code": null,
"e": 1767,
"s": 1732,
"text": "Σ − Finite set of the input symbol"
},
{
"code": null,
"e": 1786,
"s": 1767,
"text": "q0 − Initial state"
},
{
"code": null,
"e": 1805,
"s": 1786,
"text": "q0 − Initial state"
},
{
"code": null,
"e": 1821,
"s": 1805,
"text": "F − Final state"
},
{
"code": null,
"e": 1837,
"s": 1821,
"text": "F − Final state"
},
{
"code": null,
"e": 1861,
"s": 1837,
"text": "δ − Transition function"
},
{
"code": null,
"e": 1885,
"s": 1861,
"text": "δ − Transition function"
},
{
"code": null,
"e": 1986,
"s": 1885,
"text": "NFA and NFA with epsilon both are almost the same; the only difference is their transition function."
},
{
"code": null,
"e": 2032,
"s": 1986,
"text": "Let’s consider the given language L = (a*+b*)"
},
{
"code": null,
"e": 2081,
"s": 2032,
"text": "Step 1 − NFA with epsilon for a* is as follows −"
},
{
"code": null,
"e": 2201,
"s": 2081,
"text": "a* means there can be any number of ‘a’ in the expression, even 0 ( if the input symbol is null then also it is valid)."
},
{
"code": null,
"e": 2250,
"s": 2201,
"text": "Step 2 − NFA with epsilon for b* is as follows −"
},
{
"code": null,
"e": 2365,
"s": 2250,
"text": "b* means there can be any number of b’s in the expression, even 0 (if input symbol is null then also it is valid)."
},
{
"code": null,
"e": 2424,
"s": 2365,
"text": "Step 3 − Now construct a*+b* using first and second steps."
},
{
"code": null,
"e": 2539,
"s": 2424,
"text": "The given language is divided into two parts like a* and b* and add two steps by using ‘+’ sign to get the result."
}
] |
Convex Hull Graham Scan in C++ | In this tutorial, we will be discussing a program to find the convex hull of a given set of points.
Convex hull is the smallest polygon convex figure containing all the given points either on the boundary on inside the figure.
In Graham Scan, firstly the pointes are sorted to get to the bottommost point. Then the points are traversed in order and discarded or accepted to be on the boundary on the basis of their order.
#include <iostream>
#include <stack>
#include <stdlib.h>
using namespace std;
struct Point{
int x, y;
};
//point reference for sorting other points
Point p0;
//moving to the next top in stack
Point nextToTop(stack<Point> &S){
Point p = S.top();
S.pop();
Point res = S.top();
S.push(p);
return res;
}
//swapping two points
int swap(Point &p1, Point &p2){
Point temp = p1;
p1 = p2;
p2 = temp;
}
//calculating the square of difference
int distSq(Point p1, Point p2){
return (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y);
}
//checking the orientation of points
int orientation(Point p, Point q, Point r){
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0;
return (val > 0)? 1: 2;
}
//sorting and comparing the points
int compare(const void *vp1, const void *vp2){
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
}
//printing convex hull
void convexHull(Point points[], int n){
int ymin = points[0].y, min = 0;
for (int i = 1; i < n; i++){
int y = points[i].y;
if ((y < ymin) || (ymin == y &&
points[i].x < points[min].x))
ymin = points[i].y, min = i;
}
swap(points[0], points[min]);
p0 = points[0];
qsort(&points[1], n-1, sizeof(Point), compare);
for (int i=1; i<n; i++){
while (i < n-1 && orientation(p0, points[i],
points[i+1]) == 0)
i++;
points[m] = points[i];
m++; //updating size of modified array
}
if (m < 3) return;
stack<Point> S;
S.push(points[0]);
S.push(points[1]);
S.push(points[2]);
for (int i = 3; i < m; i++){
while (orientation(nextToTop(S), S.top(), points[i]) != 2)
S.pop();
S.push(points[i]);
}
while (!S.empty()){
Point p = S.top();
cout << "(" << p.x << ", " << p.y <<")" << endl;
S.pop();
}
}
int main(){
Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
{0, 0}, {1, 2}, {3, 1}, {3, 3}};
int n = sizeof(points)/sizeof(points[0]);
convexHull(points, n);
return 0;
}
(0, 3)
(4, 4)
(3, 1)
(0, 0) | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to find the convex hull of a given set of points."
},
{
"code": null,
"e": 1289,
"s": 1162,
"text": "Convex hull is the smallest polygon convex figure containing all the given points either on the boundary on inside the figure."
},
{
"code": null,
"e": 1484,
"s": 1289,
"text": "In Graham Scan, firstly the pointes are sorted to get to the bottommost point. Then the points are traversed in order and discarded or accepted to be on the boundary on the basis of their order."
},
{
"code": null,
"e": 3668,
"s": 1484,
"text": "#include <iostream>\n#include <stack>\n#include <stdlib.h>\nusing namespace std;\nstruct Point{\n int x, y;\n};\n//point reference for sorting other points\nPoint p0;\n//moving to the next top in stack\nPoint nextToTop(stack<Point> &S){\n Point p = S.top();\n S.pop();\n Point res = S.top();\n S.push(p);\n return res;\n}\n//swapping two points\nint swap(Point &p1, Point &p2){\n Point temp = p1;\n p1 = p2;\n p2 = temp;\n}\n//calculating the square of difference\nint distSq(Point p1, Point p2){\n return (p1.x - p2.x)*(p1.x - p2.x) +\n (p1.y - p2.y)*(p1.y - p2.y);\n}\n//checking the orientation of points\nint orientation(Point p, Point q, Point r){\n int val = (q.y - p.y) * (r.x - q.x) -\n (q.x - p.x) * (r.y - q.y);\n if (val == 0) return 0;\n return (val > 0)? 1: 2;\n}\n//sorting and comparing the points\nint compare(const void *vp1, const void *vp2){\n Point *p1 = (Point *)vp1;\n Point *p2 = (Point *)vp2;\n int o = orientation(p0, *p1, *p2);\n if (o == 0)\n return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;\n return (o == 2)? -1: 1;\n}\n//printing convex hull\nvoid convexHull(Point points[], int n){\n int ymin = points[0].y, min = 0;\n for (int i = 1; i < n; i++){\n int y = points[i].y;\n if ((y < ymin) || (ymin == y &&\n points[i].x < points[min].x))\n ymin = points[i].y, min = i;\n }\n swap(points[0], points[min]);\n p0 = points[0];\n qsort(&points[1], n-1, sizeof(Point), compare);\n for (int i=1; i<n; i++){\n while (i < n-1 && orientation(p0, points[i],\n points[i+1]) == 0)\n i++;\n points[m] = points[i];\n m++; //updating size of modified array\n }\n if (m < 3) return;\n stack<Point> S;\n S.push(points[0]);\n S.push(points[1]);\n S.push(points[2]);\n for (int i = 3; i < m; i++){\n while (orientation(nextToTop(S), S.top(), points[i]) != 2)\n S.pop();\n S.push(points[i]);\n }\n while (!S.empty()){\n Point p = S.top();\n cout << \"(\" << p.x << \", \" << p.y <<\")\" << endl;\n S.pop();\n }\n}\nint main(){\n Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},\n {0, 0}, {1, 2}, {3, 1}, {3, 3}};\n int n = sizeof(points)/sizeof(points[0]);\n convexHull(points, n);\n return 0;\n}"
},
{
"code": null,
"e": 3696,
"s": 3668,
"text": "(0, 3)\n(4, 4)\n(3, 1)\n(0, 0)"
}
] |
Check if two arrays are equal or not | Practice | GeeksforGeeks | Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.
Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal.
Example 1:
Input:
N = 5
A[] = {1,2,5,4,0}
B[] = {2,4,5,0,1}
Output: 1
Explanation: Both the array can be
rearranged to {0,1,2,4,5}
Example 2:
Input:
N = 3
A[] = {1,2,5}
B[] = {2,4,15}
Output: 0
Explanation: A[] and B[] have only
one common value.
Your Task:
Complete check() function which takes both the given array and their size as function arguments and returns true if the arrays are equal else returns false.The 0 and 1 printing is done by the driver code.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(N)
Constraints:
1<=N<=107
1<=A[],B[]<=1018
0
adamyasharma4933 days ago
bool check(vector<ll> A, vector<ll> B, int N) { //code here unordered_map<ll,int> m ; for(int i=0 ; i< N ; i++) { m[A[i]]++ ; } for(int i=0 ; i< N ;i++) { if(m.find(B[i]) != m.end()) { m[B[i]]-- ; } else {return false ; } } for(auto x : m) { if(x.second != 0)return false ; } return true ; }
0
samuelgroth4 days ago
Java (1.8)
Arrays.sort(A); Arrays.sort(B); for (int i = 0; i < N; i++) if ( A[i] != B[i] ) return false; return true;
+1
nikhilnaroliya69534 days ago
bool check(vector<ll> A, vector<ll> B, int N) { //code here int count=0; int result=0; sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++) { if(A[i]==B[i]) count++; } if(count==N) result=1; return result; }
0
ahmadaeccse
This comment was deleted.
0
faycalsawadogo4 days ago
#User function Template for python3
from collections import Counter
class Solution:
#Function to check if two arrays are equal or not.
def check(self,A,B,N):
return Counter(A) == Counter(B)
0
amitrrrvaa00035 days ago
Python:
A.sort()
B.sort()
if A==B:
return True
else:
return False
+1
priyansh708905 days ago
bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); return A==B; }
+2
harshscode6 days ago
unordered_map<long long,long long> m; for(auto i:a) m[i]++; for(auto i:b) m[i]--; for(auto i:a) { if(m[i]!=0) return 0; } return 1;
0
shubham211019976 days ago
simplest solution
public static boolean check(long A[],long B[],int N)
{
HashMap<Long,Integer>m=new HashMap<>();
for(long i:A){
m.put(i,m.getOrDefault(i,0)+1);
}
for(long i:B){
if(m.containsKey(i)==false) return false;
else{
m.put(i,m.get(i)-1);
}
}
for(long i:A){
if(m.get(i)!=0)return false;
}
return true;
}
0
subhaduleygba6 days ago
//c++ code
bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++){ if(A[i]!=B[i]){ return false; } } return true; }
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": 590,
"s": 238,
"text": "Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though.\nNote : If there are repetitions, then counts of repeated elements must also be same for two array to be equal."
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Example 1:"
},
{
"code": null,
"e": 723,
"s": 601,
"text": "Input:\nN = 5\nA[] = {1,2,5,4,0}\nB[] = {2,4,5,0,1}\nOutput: 1\nExplanation: Both the array can be \nrearranged to {0,1,2,4,5}\n"
},
{
"code": null,
"e": 734,
"s": 723,
"text": "Example 2:"
},
{
"code": null,
"e": 840,
"s": 734,
"text": "Input:\nN = 3\nA[] = {1,2,5}\nB[] = {2,4,15}\nOutput: 0\nExplanation: A[] and B[] have only \none common value."
},
{
"code": null,
"e": 1056,
"s": 840,
"text": "Your Task:\nComplete check() function which takes both the given array and their size as function arguments and returns true if the arrays are equal else returns false.The 0 and 1 printing is done by the driver code."
},
{
"code": null,
"e": 1121,
"s": 1056,
"text": "Expected Time Complexity : O(N)\nExpected Auxilliary Space : O(N)"
},
{
"code": null,
"e": 1161,
"s": 1121,
"text": "Constraints:\n1<=N<=107\n1<=A[],B[]<=1018"
},
{
"code": null,
"e": 1165,
"s": 1163,
"text": "0"
},
{
"code": null,
"e": 1191,
"s": 1165,
"text": "adamyasharma4933 days ago"
},
{
"code": null,
"e": 1644,
"s": 1191,
"text": "bool check(vector<ll> A, vector<ll> B, int N) { //code here unordered_map<ll,int> m ; for(int i=0 ; i< N ; i++) { m[A[i]]++ ; } for(int i=0 ; i< N ;i++) { if(m.find(B[i]) != m.end()) { m[B[i]]-- ; } else {return false ; } } for(auto x : m) { if(x.second != 0)return false ; } return true ; }"
},
{
"code": null,
"e": 1646,
"s": 1644,
"text": "0"
},
{
"code": null,
"e": 1668,
"s": 1646,
"text": "samuelgroth4 days ago"
},
{
"code": null,
"e": 1679,
"s": 1668,
"text": "Java (1.8)"
},
{
"code": null,
"e": 1838,
"s": 1681,
"text": "Arrays.sort(A); Arrays.sort(B); for (int i = 0; i < N; i++) if ( A[i] != B[i] ) return false; return true;"
},
{
"code": null,
"e": 1841,
"s": 1838,
"text": "+1"
},
{
"code": null,
"e": 1870,
"s": 1841,
"text": "nikhilnaroliya69534 days ago"
},
{
"code": null,
"e": 2208,
"s": 1870,
"text": " bool check(vector<ll> A, vector<ll> B, int N) { //code here int count=0; int result=0; sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++) { if(A[i]==B[i]) count++; } if(count==N) result=1; return result; }"
},
{
"code": null,
"e": 2210,
"s": 2208,
"text": "0"
},
{
"code": null,
"e": 2222,
"s": 2210,
"text": "ahmadaeccse"
},
{
"code": null,
"e": 2248,
"s": 2222,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2250,
"s": 2248,
"text": "0"
},
{
"code": null,
"e": 2275,
"s": 2250,
"text": "faycalsawadogo4 days ago"
},
{
"code": null,
"e": 2482,
"s": 2275,
"text": "#User function Template for python3\nfrom collections import Counter\n\nclass Solution:\n #Function to check if two arrays are equal or not.\n def check(self,A,B,N):\n return Counter(A) == Counter(B)"
},
{
"code": null,
"e": 2484,
"s": 2482,
"text": "0"
},
{
"code": null,
"e": 2509,
"s": 2484,
"text": "amitrrrvaa00035 days ago"
},
{
"code": null,
"e": 2517,
"s": 2509,
"text": "Python:"
},
{
"code": null,
"e": 2541,
"s": 2517,
"text": " A.sort()"
},
{
"code": null,
"e": 2565,
"s": 2541,
"text": " B.sort()"
},
{
"code": null,
"e": 2589,
"s": 2565,
"text": " if A==B:"
},
{
"code": null,
"e": 2622,
"s": 2589,
"text": " return True"
},
{
"code": null,
"e": 2643,
"s": 2622,
"text": " else:"
},
{
"code": null,
"e": 2677,
"s": 2643,
"text": " return False"
},
{
"code": null,
"e": 2680,
"s": 2677,
"text": "+1"
},
{
"code": null,
"e": 2704,
"s": 2680,
"text": "priyansh708905 days ago"
},
{
"code": null,
"e": 2866,
"s": 2704,
"text": " bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); return A==B; }"
},
{
"code": null,
"e": 2869,
"s": 2866,
"text": "+2"
},
{
"code": null,
"e": 2890,
"s": 2869,
"text": "harshscode6 days ago"
},
{
"code": null,
"e": 3091,
"s": 2890,
"text": " unordered_map<long long,long long> m; for(auto i:a) m[i]++; for(auto i:b) m[i]--; for(auto i:a) { if(m[i]!=0) return 0; } return 1;"
},
{
"code": null,
"e": 3093,
"s": 3091,
"text": "0"
},
{
"code": null,
"e": 3119,
"s": 3093,
"text": "shubham211019976 days ago"
},
{
"code": null,
"e": 3137,
"s": 3119,
"text": "simplest solution"
},
{
"code": null,
"e": 3588,
"s": 3137,
"text": " public static boolean check(long A[],long B[],int N)\n {\n HashMap<Long,Integer>m=new HashMap<>();\n for(long i:A){\n m.put(i,m.getOrDefault(i,0)+1);\n }\n \n for(long i:B){\n if(m.containsKey(i)==false) return false;\n else{\n m.put(i,m.get(i)-1);\n }\n }\n \n for(long i:A){\n if(m.get(i)!=0)return false;\n }\n \n return true;\n \n }"
},
{
"code": null,
"e": 3590,
"s": 3588,
"text": "0"
},
{
"code": null,
"e": 3614,
"s": 3590,
"text": "subhaduleygba6 days ago"
},
{
"code": null,
"e": 3626,
"s": 3614,
"text": "//c++ code "
},
{
"code": null,
"e": 3863,
"s": 3626,
"text": "bool check(vector<ll> A, vector<ll> B, int N) { //code here sort(A.begin(),A.end()); sort(B.begin(),B.end()); for(int i=0;i<N;i++){ if(A[i]!=B[i]){ return false; } } return true; }"
},
{
"code": null,
"e": 4009,
"s": 3863,
"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": 4045,
"s": 4009,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4055,
"s": 4045,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4065,
"s": 4055,
"text": "\nContest\n"
},
{
"code": null,
"e": 4128,
"s": 4065,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4276,
"s": 4128,
"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": 4484,
"s": 4276,
"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": 4590,
"s": 4484,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
SQL Tryit Editor v1.6 | SELECT * FROM Customers
WHERE CustomerID=1;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 24,
"s": 0,
"text": "SELECT * FROM Customers"
},
{
"code": null,
"e": 44,
"s": 24,
"text": "WHERE CustomerID=1;"
},
{
"code": null,
"e": 46,
"s": 44,
"text": ""
},
{
"code": null,
"e": 109,
"s": 46,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 169,
"s": 109,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 237,
"s": 169,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 275,
"s": 237,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 360,
"s": 275,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 534,
"s": 360,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 585,
"s": 534,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 653,
"s": 585,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 824,
"s": 653,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 924,
"s": 824,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 984,
"s": 924,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Why variable name does not start with numbers in C ? - GeeksforGeeks | 06 Jul, 2020
In C, apart from keywords, everything in the C program is treated as Identifier. Identifiers can be the names given to variables, constants, functions, and user-defined data. A variable name can consist of alphabets (upper case, lower case), numbers (0-9), and _ (underscore) character. But the name of any variable must not start with a number. Now we must have the answer that why can’t we name a variable starting with number. The following might be the reason for it. The compiler has 7 phase as follows:
Lexical Analysis
Syntax Analysis
Semantic Analysis
Intermediate Code Generation
Code Optimization
Code Generation
Symbol Table
Backtracking is avoided in the lexical analysis phase while compiling the piece of code. The variable like Apple;, the compiler will know it an identifier right away when it meets the letter ‘A’ character in the lexical analysis phase. However, a variable like 123apple; , compiler won’t be able to decide if its a number or identifier until it hits ‘a’ and it needs backtracking to go in the lexical analysis phase to identify that it is a variable. But it is not supported in the compiler.When you’re parsing the token you only have to look at the first character to determine if it’s an identifier or literal and then send it to the correct function for processing. So that’s a performance optimization.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
om_mishra
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C | [
{
"code": null,
"e": 24103,
"s": 24075,
"text": "\n06 Jul, 2020"
},
{
"code": null,
"e": 24612,
"s": 24103,
"text": "In C, apart from keywords, everything in the C program is treated as Identifier. Identifiers can be the names given to variables, constants, functions, and user-defined data. A variable name can consist of alphabets (upper case, lower case), numbers (0-9), and _ (underscore) character. But the name of any variable must not start with a number. Now we must have the answer that why can’t we name a variable starting with number. The following might be the reason for it. The compiler has 7 phase as follows:"
},
{
"code": null,
"e": 24768,
"s": 24612,
"text": " Lexical Analysis\n Syntax Analysis\n Semantic Analysis\n Intermediate Code Generation\n Code Optimization\n Code Generation\n Symbol Table\n"
},
{
"code": null,
"e": 25475,
"s": 24768,
"text": "Backtracking is avoided in the lexical analysis phase while compiling the piece of code. The variable like Apple;, the compiler will know it an identifier right away when it meets the letter ‘A’ character in the lexical analysis phase. However, a variable like 123apple; , compiler won’t be able to decide if its a number or identifier until it hits ‘a’ and it needs backtracking to go in the lexical analysis phase to identify that it is a variable. But it is not supported in the compiler.When you’re parsing the token you only have to look at the first character to determine if it’s an identifier or literal and then send it to the correct function for processing. So that’s a performance optimization."
},
{
"code": null,
"e": 25781,
"s": 25475,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 25906,
"s": 25781,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25916,
"s": 25906,
"text": "om_mishra"
},
{
"code": null,
"e": 25927,
"s": 25916,
"text": "C Language"
},
{
"code": null,
"e": 26025,
"s": 25927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26034,
"s": 26025,
"text": "Comments"
},
{
"code": null,
"e": 26047,
"s": 26034,
"text": "Old Comments"
},
{
"code": null,
"e": 26082,
"s": 26047,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26110,
"s": 26082,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26156,
"s": 26110,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26168,
"s": 26156,
"text": "fork() in C"
},
{
"code": null,
"e": 26208,
"s": 26168,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26240,
"s": 26208,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26257,
"s": 26240,
"text": "Substring in C++"
},
{
"code": null,
"e": 26279,
"s": 26257,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26326,
"s": 26279,
"text": "Different methods to reverse a string in C/C++"
}
] |
Java 8 Stream Filter Example | Filter Streams in Java | online TutorialsPoint Streams | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to show you how to filter a stream of objects in Java 8. We can filter the string values and as well as objects using the Java 8 Stream filter.
The filter() in Java 8 is a method which is coming from the Stream interface, which returns the Stream object consisting of the elements of this stream that matches the given Predicate(action).
Legacy way of filtering the list in Java :
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("Spring");
list.add("Hibernate");
list.add("Java8 Filter");
list.add("JQuery");
list.add("Hibernate 4");
list.add("AngularJs");
list.add("Java8 Streams");
for (String sub : list) {
if (sub.contains("Java8")) {
System.out.println(sub);
}
}
The similar way of filtering the list of strings using Java 8 Stream Filter.
List<String> subjects = list.stream()
.filter(sub -> sub.contains("Hibernate"))
.collect(Collectors.toList());
subjects.forEach(System.out::println);
package com.onlinetutorialspoint.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Java8_Streams_filter {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("Spring");
list.add("Hibernate");
list.add("Java8 Filter");
list.add("JQuery");
list.add("Hibernate 4");
list.add("AngularJs");
list.add("Java8 Streams");
java8_filter(list);
}
public static void normal_filter(List<String> list) {
for (String sub : list) {
if (sub.contains("Java8")) {
System.out.println(sub);
}
}
}
public static void java8_filter(List<String> list) {
List<String> subjects = list.stream().filter(sub -> sub.contains("Hibernate")).collect(Collectors.toList());
subjects.forEach(System.out::println);
}
}
Recommended: How to use Java8 foreach
Output:
Hibernate
Hibernate 4
We can filter the list of user-defined objects using the Stream filter in Java. Here I am going to create a Subject POJO class to filter the elements.
Student.java (POJO)
class Subject {
private int subId;
private String subName;
public Subject(int subId, String subName) {
super();
this.subId = subId;
this.subName = subName;
}
public int getSubId() {
return subId;
}
public String getSubName() {
return subName;
}
}
package com.onlinetutorialspoint.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Java8_Streams_filter {
public static void main(String[] args) {
List<Subject> subjects = Arrays.asList(new Subject(1, "Java"), new Subject(2, "Spring"),
new Subject(3, "Hiberate"));
java8_filterObjects(subjects);
}
public static void java8_filterObjects(List<Subject> subjects) {
Subject subject = subjects.stream().filter(name -> "Java".equals(name.getSubName())).findAny().orElse(null);
System.out.println(subject.getSubName());
}
}
Output:
Java
Happy Learning 🙂
Java 8 Read File Line By Line Example
Hibernate Filter Example Xml Configuration
How to convert List to Map in Java 8
How to Filter null values from Java8 Stream
Java 8 How to get common elements from two lists
How to Filter a Map in Java 8
How to Convert Java 8 Stream to Array
Java 8 How to convert Stream to List
How to get Stream count in Java 8
Java 8 Getting Min and Max values from a Stream
How to Convert Iterable to Stream Java 8
How Java 8 Stream generate random String and Numbers
Java8 Concatenate Arrays Example using Stream
Java 8 Stream API and Parallelism
Array of objects in AngularJs Example
Java 8 Read File Line By Line Example
Hibernate Filter Example Xml Configuration
How to convert List to Map in Java 8
How to Filter null values from Java8 Stream
Java 8 How to get common elements from two lists
How to Filter a Map in Java 8
How to Convert Java 8 Stream to Array
Java 8 How to convert Stream to List
How to get Stream count in Java 8
Java 8 Getting Min and Max values from a Stream
How to Convert Iterable to Stream Java 8
How Java 8 Stream generate random String and Numbers
Java8 Concatenate Arrays Example using Stream
Java 8 Stream API and Parallelism
Array of objects in AngularJs Example
Δ
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 573,
"s": 398,
"text": "In this tutorial, we are going to show you how to filter a stream of objects in Java 8. We can filter the string values and as well as objects using the Java 8 Stream filter."
},
{
"code": null,
"e": 767,
"s": 573,
"text": "The filter() in Java 8 is a method which is coming from the Stream interface, which returns the Stream object consisting of the elements of this stream that matches the given Predicate(action)."
},
{
"code": null,
"e": 810,
"s": 767,
"text": "Legacy way of filtering the list in Java :"
},
{
"code": null,
"e": 1206,
"s": 810,
"text": "List<String> list = new ArrayList<String>();\n list.add(\"Java\");\n list.add(\"Spring\");\n list.add(\"Hibernate\");\n list.add(\"Java8 Filter\");\n list.add(\"JQuery\");\n list.add(\"Hibernate 4\");\n list.add(\"AngularJs\");\n list.add(\"Java8 Streams\");\nfor (String sub : list) {\n if (sub.contains(\"Java8\")) {\n System.out.println(sub);\n }\n}"
},
{
"code": null,
"e": 1283,
"s": 1206,
"text": "The similar way of filtering the list of strings using Java 8 Stream Filter."
},
{
"code": null,
"e": 1474,
"s": 1283,
"text": "List<String> subjects = list.stream()\n .filter(sub -> sub.contains(\"Hibernate\"))\n .collect(Collectors.toList());\n\n subjects.forEach(System.out::println);"
},
{
"code": null,
"e": 2389,
"s": 1474,
"text": "package com.onlinetutorialspoint.java8;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class Java8_Streams_filter {\n public static void main(String[] args) {\n List<String> list = new ArrayList<String>();\n list.add(\"Java\");\n list.add(\"Spring\");\n list.add(\"Hibernate\");\n list.add(\"Java8 Filter\");\n list.add(\"JQuery\");\n list.add(\"Hibernate 4\");\n list.add(\"AngularJs\");\n list.add(\"Java8 Streams\");\n java8_filter(list);\n }\n\n public static void normal_filter(List<String> list) {\n for (String sub : list) {\n if (sub.contains(\"Java8\")) {\n System.out.println(sub);\n }\n }\n }\n\n public static void java8_filter(List<String> list) {\n List<String> subjects = list.stream().filter(sub -> sub.contains(\"Hibernate\")).collect(Collectors.toList());\n subjects.forEach(System.out::println);\n }\n}"
},
{
"code": null,
"e": 2435,
"s": 2389,
"text": "Recommended: How to use Java8 foreach\nOutput:"
},
{
"code": null,
"e": 2457,
"s": 2435,
"text": "Hibernate\nHibernate 4"
},
{
"code": null,
"e": 2608,
"s": 2457,
"text": "We can filter the list of user-defined objects using the Stream filter in Java. Here I am going to create a Subject POJO class to filter the elements."
},
{
"code": null,
"e": 2628,
"s": 2608,
"text": "Student.java (POJO)"
},
{
"code": null,
"e": 2914,
"s": 2628,
"text": "class Subject {\n private int subId;\n private String subName;\n\n public Subject(int subId, String subName) {\n super();\n this.subId = subId;\n this.subName = subName;\n }\n\n public int getSubId() {\n return subId;\n }\n\n public String getSubName() {\n return subName;\n }\n}"
},
{
"code": null,
"e": 3549,
"s": 2914,
"text": "package com.onlinetutorialspoint.java8;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class Java8_Streams_filter {\n public static void main(String[] args) {\n List<Subject> subjects = Arrays.asList(new Subject(1, \"Java\"), new Subject(2, \"Spring\"),\n new Subject(3, \"Hiberate\"));\n java8_filterObjects(subjects);\n }\n\n public static void java8_filterObjects(List<Subject> subjects) {\n Subject subject = subjects.stream().filter(name -> \"Java\".equals(name.getSubName())).findAny().orElse(null);\n System.out.println(subject.getSubName());\n }\n}"
},
{
"code": null,
"e": 3557,
"s": 3549,
"text": "Output:"
},
{
"code": null,
"e": 3562,
"s": 3557,
"text": "Java"
},
{
"code": null,
"e": 3579,
"s": 3562,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4192,
"s": 3579,
"text": "\nJava 8 Read File Line By Line Example\nHibernate Filter Example Xml Configuration\nHow to convert List to Map in Java 8\nHow to Filter null values from Java8 Stream\nJava 8 How to get common elements from two lists\nHow to Filter a Map in Java 8\nHow to Convert Java 8 Stream to Array\nJava 8 How to convert Stream to List\nHow to get Stream count in Java 8\nJava 8 Getting Min and Max values from a Stream\nHow to Convert Iterable to Stream Java 8\nHow Java 8 Stream generate random String and Numbers\nJava8 Concatenate Arrays Example using Stream\nJava 8 Stream API and Parallelism\nArray of objects in AngularJs Example\n"
},
{
"code": null,
"e": 4230,
"s": 4192,
"text": "Java 8 Read File Line By Line Example"
},
{
"code": null,
"e": 4273,
"s": 4230,
"text": "Hibernate Filter Example Xml Configuration"
},
{
"code": null,
"e": 4310,
"s": 4273,
"text": "How to convert List to Map in Java 8"
},
{
"code": null,
"e": 4354,
"s": 4310,
"text": "How to Filter null values from Java8 Stream"
},
{
"code": null,
"e": 4403,
"s": 4354,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 4433,
"s": 4403,
"text": "How to Filter a Map in Java 8"
},
{
"code": null,
"e": 4471,
"s": 4433,
"text": "How to Convert Java 8 Stream to Array"
},
{
"code": null,
"e": 4508,
"s": 4471,
"text": "Java 8 How to convert Stream to List"
},
{
"code": null,
"e": 4542,
"s": 4508,
"text": "How to get Stream count in Java 8"
},
{
"code": null,
"e": 4590,
"s": 4542,
"text": "Java 8 Getting Min and Max values from a Stream"
},
{
"code": null,
"e": 4631,
"s": 4590,
"text": "How to Convert Iterable to Stream Java 8"
},
{
"code": null,
"e": 4684,
"s": 4631,
"text": "How Java 8 Stream generate random String and Numbers"
},
{
"code": null,
"e": 4730,
"s": 4684,
"text": "Java8 Concatenate Arrays Example using Stream"
},
{
"code": null,
"e": 4764,
"s": 4730,
"text": "Java 8 Stream API and Parallelism"
},
{
"code": null,
"e": 4803,
"s": 4764,
"text": "Array of objects in AngularJs Example"
},
{
"code": null,
"e": 4809,
"s": 4807,
"text": "Δ"
},
{
"code": null,
"e": 4834,
"s": 4809,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4851,
"s": 4834,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4879,
"s": 4851,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4910,
"s": 4879,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4942,
"s": 4910,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 4962,
"s": 4942,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 4982,
"s": 4962,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 5006,
"s": 4982,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 5036,
"s": 5006,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 5068,
"s": 5036,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 5104,
"s": 5068,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 5148,
"s": 5104,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 5180,
"s": 5148,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 5221,
"s": 5180,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 5258,
"s": 5221,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 5298,
"s": 5258,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 5327,
"s": 5298,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 5359,
"s": 5327,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 5379,
"s": 5359,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 5401,
"s": 5379,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 5431,
"s": 5401,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 5482,
"s": 5431,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 5518,
"s": 5482,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 5550,
"s": 5518,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 5585,
"s": 5550,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 5608,
"s": 5585,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 5655,
"s": 5608,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 5680,
"s": 5655,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5724,
"s": 5680,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Typing Enter/Return key in Selenium. | We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys.ENTER as an argument to the method. Also, we can use pass Keys.RETURN as an argument to the sendKeys method for the same purpose.
To use the Keys class, we have to incorporate import org.openqa.selenium.Keys to the code. Let us type Enter/Return after inputting text within the below edit box.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class TypeEnter{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element
WebElement m=driver.findElement(By.id("gsc−i−id1"));
m.sendKeys("Java");
// type enter with sendKeys method and pass Keys.ENTER
m.sendKeys(Keys.ENTER);
driver.quit();
}
}
Code Implementation with Keys.RETURN.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class TypeReturn{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element
WebElement m=driver.findElement(By.id("gsc−i−id1"));
m.sendKeys("Java");
// type enter with sendKeys method and pass Keys.RETURN
m.sendKeys(Keys.RETURN);
driver.quit();
}
} | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys.ENTER as an argument to the method. Also, we can use pass Keys.RETURN as an argument to the sendKeys method for the same purpose."
},
{
"code": null,
"e": 1445,
"s": 1281,
"text": "To use the Keys class, we have to incorporate import org.openqa.selenium.Keys to the code. Let us type Enter/Return after inputting text within the below edit box."
},
{
"code": null,
"e": 2153,
"s": 1445,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\npublic class TypeEnter{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element\n WebElement m=driver.findElement(By.id(\"gsc−i−id1\"));\n m.sendKeys(\"Java\");\n // type enter with sendKeys method and pass Keys.ENTER\n m.sendKeys(Keys.ENTER);\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 2191,
"s": 2153,
"text": "Code Implementation with Keys.RETURN."
},
{
"code": null,
"e": 2902,
"s": 2191,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\npublic class TypeReturn{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element\n WebElement m=driver.findElement(By.id(\"gsc−i−id1\"));\n m.sendKeys(\"Java\");\n // type enter with sendKeys method and pass Keys.RETURN\n m.sendKeys(Keys.RETURN);\n driver.quit();\n }\n}"
}
] |
How to Change Root Password in Kali Linux? - GeeksforGeeks | 28 Jul, 2020
After completing the installation of the Kali Linux machine the most highly performed task and asked question is to change the root password of your Kali Linux machine.
Note: This is not exclusive only just with Kali Linux machine, you can perform the steps in any Linux machine with grub, we are using Kali as an example.
The default credentials of logging into the new kali machine are username: “kali” and password: “kali”. Which opens a session as user “kali” and to access root you need to use this user password following “sudo”.
Changing the root password is easy, but you need to ensure these few things:
You are using an active grub boot loaderYour boot loader is not locked
You are using an active grub boot loader
Your boot loader is not locked
If everything is okay then just follow the steps:
Step 1: Boot into your machine to grub menu, do not choose anything or boot into Kali.
Step 2: Now you need to edit the grub entries, so you can spawn a root session. Press “e” key to enter edit mode.
Now you need to find the keyword “linux”, in our case you can see that the last line starts with “linux”, which is kernel selection. In our case “/boot/v,linuz-5.5.0.0-kali2-amd64” represents our active kernel.
Navigate in the line to “ro” (read only) and replace it with “rw” (read and write).
In the same line navigate to “quite splash” and replace it with
init=/bin/bash
These changes are not saved permanently and grub uses default configurations, once you have made these changes press key “f10” to boot. This will create a terminal session with root privileges
Step 3: Once you are in the terminal session you just need to enter the command:
passwd root
After applying your new password reboot your system.
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Named Pipe or FIFO with example C program
Mutex lock for Linux Thread Synchronization
'crontab' in Linux with Examples
Cat command in Linux with examples
echo command in Linux with Examples
Thread functions in C/C++
touch command in Linux with Examples
Conditional Statements | Shell Script | [
{
"code": null,
"e": 24164,
"s": 24136,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 24333,
"s": 24164,
"text": "After completing the installation of the Kali Linux machine the most highly performed task and asked question is to change the root password of your Kali Linux machine."
},
{
"code": null,
"e": 24487,
"s": 24333,
"text": "Note: This is not exclusive only just with Kali Linux machine, you can perform the steps in any Linux machine with grub, we are using Kali as an example."
},
{
"code": null,
"e": 24701,
"s": 24487,
"text": "The default credentials of logging into the new kali machine are username: “kali” and password: “kali”. Which opens a session as user “kali” and to access root you need to use this user password following “sudo”."
},
{
"code": null,
"e": 24778,
"s": 24701,
"text": "Changing the root password is easy, but you need to ensure these few things:"
},
{
"code": null,
"e": 24849,
"s": 24778,
"text": "You are using an active grub boot loaderYour boot loader is not locked"
},
{
"code": null,
"e": 24890,
"s": 24849,
"text": "You are using an active grub boot loader"
},
{
"code": null,
"e": 24921,
"s": 24890,
"text": "Your boot loader is not locked"
},
{
"code": null,
"e": 24972,
"s": 24921,
"text": "If everything is okay then just follow the steps:"
},
{
"code": null,
"e": 25059,
"s": 24972,
"text": "Step 1: Boot into your machine to grub menu, do not choose anything or boot into Kali."
},
{
"code": null,
"e": 25173,
"s": 25059,
"text": "Step 2: Now you need to edit the grub entries, so you can spawn a root session. Press “e” key to enter edit mode."
},
{
"code": null,
"e": 25384,
"s": 25173,
"text": "Now you need to find the keyword “linux”, in our case you can see that the last line starts with “linux”, which is kernel selection. In our case “/boot/v,linuz-5.5.0.0-kali2-amd64” represents our active kernel."
},
{
"code": null,
"e": 25468,
"s": 25384,
"text": "Navigate in the line to “ro” (read only) and replace it with “rw” (read and write)."
},
{
"code": null,
"e": 25533,
"s": 25468,
"text": "In the same line navigate to “quite splash” and replace it with "
},
{
"code": null,
"e": 25549,
"s": 25533,
"text": "init=/bin/bash\n"
},
{
"code": null,
"e": 25742,
"s": 25549,
"text": "These changes are not saved permanently and grub uses default configurations, once you have made these changes press key “f10” to boot. This will create a terminal session with root privileges"
},
{
"code": null,
"e": 25823,
"s": 25742,
"text": "Step 3: Once you are in the terminal session you just need to enter the command:"
},
{
"code": null,
"e": 25836,
"s": 25823,
"text": "passwd root\n"
},
{
"code": null,
"e": 25889,
"s": 25836,
"text": "After applying your new password reboot your system."
},
{
"code": null,
"e": 25900,
"s": 25889,
"text": "Kali-Linux"
},
{
"code": null,
"e": 25911,
"s": 25900,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26009,
"s": 25911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26018,
"s": 26009,
"text": "Comments"
},
{
"code": null,
"e": 26031,
"s": 26018,
"text": "Old Comments"
},
{
"code": null,
"e": 26066,
"s": 26031,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26104,
"s": 26066,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26146,
"s": 26104,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26190,
"s": 26146,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 26223,
"s": 26190,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 26258,
"s": 26223,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 26294,
"s": 26258,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 26320,
"s": 26294,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26357,
"s": 26320,
"text": "touch command in Linux with Examples"
}
] |
PHP Syntax | A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with
?>:
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text
"Hello World!" on a web page:
Note: PHP statements end with a semicolon (;).
In PHP, keywords (e.g. if,
else, while,
echo, etc.), classes, functions,
and user-defined functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Note: However; all variable names are case-sensitive!
Look at the example below; only the first statement will display the value of the
$color variable! This is because
$color, $COLOR, and
$coLOR are treated as three
different variables:
Insert the missing part of the code below to output "Hello World".
"Hello World";
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 95,
"s": 0,
"text": "A PHP script is executed on the server, and the plain HTML result is sent back to the browser."
},
{
"code": null,
"e": 148,
"s": 95,
"text": "A PHP script can be placed anywhere in the document."
},
{
"code": null,
"e": 198,
"s": 148,
"text": "A PHP script starts with <?php and ends with \n?>:"
},
{
"code": null,
"e": 250,
"s": 198,
"text": "The default file extension for PHP files is \".php\"."
},
{
"code": null,
"e": 319,
"s": 250,
"text": "A PHP file normally contains HTML tags, and some PHP scripting code."
},
{
"code": null,
"e": 476,
"s": 319,
"text": "Below, we have an example of a simple PHP file, with a PHP script that uses a \nbuilt-in PHP function \"echo\" to output the text\n\"Hello World!\" on a web page:"
},
{
"code": null,
"e": 523,
"s": 476,
"text": "Note: PHP statements end with a semicolon (;)."
},
{
"code": null,
"e": 650,
"s": 523,
"text": "In PHP, keywords (e.g. if, \nelse, while, \necho, etc.), classes, functions, \nand user-defined functions are not case-sensitive."
},
{
"code": null,
"e": 725,
"s": 650,
"text": "In the example below, all three echo statements below are equal and legal:"
},
{
"code": null,
"e": 779,
"s": 725,
"text": "Note: However; all variable names are case-sensitive!"
},
{
"code": null,
"e": 967,
"s": 779,
"text": "Look at the example below; only the first statement will display the value of the \n$color variable! This is because \n$color, $COLOR, and \n$coLOR are treated as three \ndifferent variables:"
},
{
"code": null,
"e": 1034,
"s": 967,
"text": "Insert the missing part of the code below to output \"Hello World\"."
},
{
"code": null,
"e": 1051,
"s": 1034,
"text": " \"Hello World\";\n"
},
{
"code": null,
"e": 1084,
"s": 1051,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1126,
"s": 1084,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1233,
"s": 1126,
"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": 1252,
"s": 1233,
"text": "[email protected]"
}
] |
Remove Leading Zeros from an Array using C++ | We are provided an array, and we are tasked to remove the leading zeros from the given array and then print the array.
Input : arr[] = {0, 0, 0, 1, 2, 3}
Output : 1 2 3
Input : arr[] = {0, 0, 0, 1, 0, 2, 3}
Output : 1 0 2 3
We can make a new array that doesn’t contain the leading zeroes of the previous array in the given problem.
In this approach, we will go through the array and insert all the numbers but no leading zeros.
#include <iostream>
using namespace std;
int main() {
int arr[] = {0, 0, 0, 1, 2, 0, 4};
int n = sizeof(arr) / sizeof(int); // size of given array.
int last = -1;
for(int i = 0; i < n; i++) { // finding the first non zero element
if(arr[i] != 0) {
last = i;
break;
}
}
if(last == -1)
cout << "Empty\n";
else {
int b[n - last]; // the new array.
for(int i = last; i < n; i++) // inserting the elements in the new array
b[i-last] = arr[i];
for(int i = 0; i < n-last; i++) // printing the array
cout << b[i] << " ";
}
}
1 2 0 4
In the given program, we are firstly traversing through the array arr and finding the first non-zero element's index, which we store in variable called last now if last is -1 after the traversal, so that means our whole array is made up of zeroes, so we print our "Empty."
Now, as we got the index of the first non-zero elements, we can determine our new array's size, i.e. (n - last), and now we run a for loop from last till less than n. We insert these elements in the new array and print the new array.
In this article, we solve a problem to Remove leading zeros from an array. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "We are provided an array, and we are tasked to remove the leading zeros from the given array and then print the array."
},
{
"code": null,
"e": 1287,
"s": 1181,
"text": "Input : arr[] = {0, 0, 0, 1, 2, 3}\nOutput : 1 2 3\n\nInput : arr[] = {0, 0, 0, 1, 0, 2, 3}\nOutput : 1 0 2 3"
},
{
"code": null,
"e": 1395,
"s": 1287,
"text": "We can make a new array that doesn’t contain the leading zeroes of the previous array in the given problem."
},
{
"code": null,
"e": 1491,
"s": 1395,
"text": "In this approach, we will go through the array and insert all the numbers but no leading zeros."
},
{
"code": null,
"e": 2095,
"s": 1491,
"text": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n int arr[] = {0, 0, 0, 1, 2, 0, 4};\n int n = sizeof(arr) / sizeof(int); // size of given array.\n int last = -1;\n for(int i = 0; i < n; i++) { // finding the first non zero element\n if(arr[i] != 0) {\n last = i;\n break;\n }\n }\n if(last == -1)\n cout << \"Empty\\n\";\n else {\n int b[n - last]; // the new array.\n for(int i = last; i < n; i++) // inserting the elements in the new array\n b[i-last] = arr[i];\n\n for(int i = 0; i < n-last; i++) // printing the array\n cout << b[i] << \" \";\n }\n}"
},
{
"code": null,
"e": 2103,
"s": 2095,
"text": "1 2 0 4"
},
{
"code": null,
"e": 2376,
"s": 2103,
"text": "In the given program, we are firstly traversing through the array arr and finding the first non-zero element's index, which we store in variable called last now if last is -1 after the traversal, so that means our whole array is made up of zeroes, so we print our \"Empty.\""
},
{
"code": null,
"e": 2610,
"s": 2376,
"text": "Now, as we got the index of the first non-zero elements, we can determine our new array's size, i.e. (n - last), and now we run a for loop from last till less than n. We insert these elements in the new array and print the new array."
},
{
"code": null,
"e": 2905,
"s": 2610,
"text": "In this article, we solve a problem to Remove leading zeros from an array. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful."
}
] |
SQL Tryit Editor v1.6 | DROP TABLE Shippers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 21,
"s": 0,
"text": "DROP TABLE Shippers;"
},
{
"code": null,
"e": 23,
"s": 21,
"text": ""
},
{
"code": null,
"e": 86,
"s": 23,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 146,
"s": 86,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 214,
"s": 146,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 252,
"s": 214,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 337,
"s": 252,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 511,
"s": 337,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 562,
"s": 511,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 630,
"s": 562,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 801,
"s": 630,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 901,
"s": 801,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 961,
"s": 901,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Program to find number of arithmetic sequences from a list of numbers in Python? | Suppose we have a list of numbers called nums, we have to find the number of contiguous arithmetic sequences of length ≥ 3. As we know an arithmetic sequence is a list of numbers where the difference between one number and the next number is the same.
So, if the input is like nums = [6, 8, 10, 12, 13, 14], then the output will be 4, as we have the arithmetic sequences like: [6, 8, 10] [8, 10, 12] [6, 8, 10, 12] [12, 13, 14]
To solve this, we will follow these steps −
count := 0, ans := 0
count := 0, ans := 0
for i in range 2 to size of nums, doif nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], thencount := count + 1otherwise,ans := ans + quotient of (count * (count + 1)) / 2count := 0
for i in range 2 to size of nums, do
if nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], thencount := count + 1
if nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], then
count := count + 1
count := count + 1
otherwise,ans := ans + quotient of (count * (count + 1)) / 2count := 0
otherwise,
ans := ans + quotient of (count * (count + 1)) / 2
ans := ans + quotient of (count * (count + 1)) / 2
count := 0
count := 0
if count is non-zero, thenans := ans + quotient of (count *(count + 1)) / 2
if count is non-zero, then
ans := ans + quotient of (count *(count + 1)) / 2
ans := ans + quotient of (count *(count + 1)) / 2
return ans
return ans
Let us see the following implementation to get better understanding:
Live Demo
class Solution:
def solve(self, nums):
count = 0
ans = 0
for i in range(2, len(nums)):
if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:
count += 1
else:
ans += (count * (count + 1)) // 2
count = 0
if count:
ans += (count * (count + 1)) // 2
return ans
ob = Solution()
nums = [6, 8, 10, 12, 13, 14]
print(ob.solve(nums))
[6, 8, 10, 12, 13, 14]
4 | [
{
"code": null,
"e": 1314,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find the number of contiguous arithmetic sequences of length ≥ 3. As we know an arithmetic sequence is a list of numbers where the difference between one number and the next number is the same."
},
{
"code": null,
"e": 1490,
"s": 1314,
"text": "So, if the input is like nums = [6, 8, 10, 12, 13, 14], then the output will be 4, as we have the arithmetic sequences like: [6, 8, 10] [8, 10, 12] [6, 8, 10, 12] [12, 13, 14]"
},
{
"code": null,
"e": 1534,
"s": 1490,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1555,
"s": 1534,
"text": "count := 0, ans := 0"
},
{
"code": null,
"e": 1576,
"s": 1555,
"text": "count := 0, ans := 0"
},
{
"code": null,
"e": 1768,
"s": 1576,
"text": "for i in range 2 to size of nums, doif nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], thencount := count + 1otherwise,ans := ans + quotient of (count * (count + 1)) / 2count := 0"
},
{
"code": null,
"e": 1805,
"s": 1768,
"text": "for i in range 2 to size of nums, do"
},
{
"code": null,
"e": 1891,
"s": 1805,
"text": "if nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], thencount := count + 1"
},
{
"code": null,
"e": 1959,
"s": 1891,
"text": "if nums[i] - nums[i - 1] is same as nums[i - 1] - nums[i - 2], then"
},
{
"code": null,
"e": 1978,
"s": 1959,
"text": "count := count + 1"
},
{
"code": null,
"e": 1997,
"s": 1978,
"text": "count := count + 1"
},
{
"code": null,
"e": 2068,
"s": 1997,
"text": "otherwise,ans := ans + quotient of (count * (count + 1)) / 2count := 0"
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "otherwise,"
},
{
"code": null,
"e": 2130,
"s": 2079,
"text": "ans := ans + quotient of (count * (count + 1)) / 2"
},
{
"code": null,
"e": 2181,
"s": 2130,
"text": "ans := ans + quotient of (count * (count + 1)) / 2"
},
{
"code": null,
"e": 2192,
"s": 2181,
"text": "count := 0"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": "count := 0"
},
{
"code": null,
"e": 2279,
"s": 2203,
"text": "if count is non-zero, thenans := ans + quotient of (count *(count + 1)) / 2"
},
{
"code": null,
"e": 2306,
"s": 2279,
"text": "if count is non-zero, then"
},
{
"code": null,
"e": 2356,
"s": 2306,
"text": "ans := ans + quotient of (count *(count + 1)) / 2"
},
{
"code": null,
"e": 2406,
"s": 2356,
"text": "ans := ans + quotient of (count *(count + 1)) / 2"
},
{
"code": null,
"e": 2417,
"s": 2406,
"text": "return ans"
},
{
"code": null,
"e": 2428,
"s": 2417,
"text": "return ans"
},
{
"code": null,
"e": 2497,
"s": 2428,
"text": "Let us see the following implementation to get better understanding:"
},
{
"code": null,
"e": 2508,
"s": 2497,
"text": " Live Demo"
},
{
"code": null,
"e": 2931,
"s": 2508,
"text": "class Solution:\n def solve(self, nums):\n count = 0\n ans = 0\n for i in range(2, len(nums)):\n if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]:\n count += 1\n else:\n ans += (count * (count + 1)) // 2\n count = 0\n if count:\n ans += (count * (count + 1)) // 2\n return ans\n\nob = Solution()\nnums = [6, 8, 10, 12, 13, 14]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 2954,
"s": 2931,
"text": "[6, 8, 10, 12, 13, 14]"
},
{
"code": null,
"e": 2956,
"s": 2954,
"text": "4"
}
] |
Maximum XOR using K numbers from 1 to n - GeeksforGeeks | 15 Feb, 2022
Given an positive integer n and k. Find maximum xor of 1 to n using at most k numbers. Xor sum of 1 to n is defined as 1 ^ 2 ^ 3 ^ ... ^ n.Examples :
Input : n = 4, k = 3
Output : 7
Explanation
Maximum possible xor sum is 1 ^ 2 ^ 4 = 7.
Input : n = 11, k = 1
Output : 11
Explanation
Maximum Possible xor sum is 11.
If we have k = 1 then the maximum possible xor sum is ‘n’ itself. Now for k > 1 we can always have an number with its all bits set till the most significant set bit in ‘n’.
C++
Java
Python
C#
PHP
Javascript
// CPP program to find max xor sum// of 1 to n using atmost k numbers#include <bits/stdc++.h>using namespace std;typedef long long int ll; // To return max xor sum of 1 to n// using at most k numbersll maxXorSum(ll n, ll k){ // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 ll res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1;} // Driver programint main(){ ll n = 4, k = 3; cout << maxXorSum(n, k); return 0;}
// Java program to find max xor sum// of 1 to n using atmost k numberspublic class Main { // To return max xor sum of 1 to n // using at most k numbers static int maxXorSum(int n, int k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 int res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver program to test maxXorSum() public static void main(String[] args) { int n = 4, k = 3; System.out.print(maxXorSum(n, k)); }}
# Python3 code to find max xor sum# of 1 to n using atmost k numbers # To return max xor sum of 1 to n# using at most k numbersdef maxXorSum( n , k ): # If k is 1 then maximum # possible sum is n if k == 1: return n # Finding number greater than # or equal to n with most significant # bit same as n. For example, if n is # 4, result is 7. If n is 5 or 6, result # is 7 res = 1 while res <= n: res <<= 1 # Return res - 1 which denotes # a number with all bits set to 1 return res - 1 # Driver coden = 4k = 3print( maxXorSum(n, k) ) # This code is contributed by Abhishek Sharma44.
// C# program to find max xor sum// of 1 to n using atmost k numbersusing System; public class main { // To return max xor sum of 1 to n // using at most k numbers static int maxXorSum(int n, int k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 int res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver program public static void Main() { int n = 4, k = 3; Console.WriteLine(maxXorSum(n, k)); }} // This code is contributed by vt_m.
<?php// PHP program to find max xor sum// of 1 to n using atmost k numbers // To return max xor sum of 1 to n// using at most k numbersfunction maxXorSum($n, $k){ // If k is 1 then maximum // possible sum is n if ($k == 1) return $n; // Finding number greater than // or equal to n with most // significant bit same as n. // For example, if n is 4, result // is 7. If n is 5 or 6, result is 7 $res = 1; while ($res <= $n) $res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return $res - 1;} // Driver code$n = 4;$k = 3;echo maxXorSum($n, $k); // This code is contributed by Mithun Kumar?>
<script> // JavaScript program to find max xor sum// of 1 to n using atmost k numbers // To return max xor sum of 1 to n // using at most k numbers function maxXorSum(n, k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 let res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver code let n = 4, k = 3; document.write(maxXorSum(n, k)); </script>
Output :
7
YouTubeGeeksforGeeks500K subscribersMaximum XOR using K numbers from 1 to n | 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 / 3:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Jjlk_BqLK7Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Mithun Kumar
vikashkumar317
splevel62
shivamaggarwal5570
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Hamming code Implementation in C/C++
Implementation of Bit Stuffing and Bit Destuffing
Write an Efficient Method to Check if a Number is Multiple of 3
Check whether K-th bit is set or not
Builtin functions of GCC compiler
Count total bits in a number
Check for Integer Overflow
Swap all odd and even bits | [
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 25166,
"s": 25014,
"text": "Given an positive integer n and k. Find maximum xor of 1 to n using at most k numbers. Xor sum of 1 to n is defined as 1 ^ 2 ^ 3 ^ ... ^ n.Examples : "
},
{
"code": null,
"e": 25333,
"s": 25166,
"text": "Input : n = 4, k = 3\nOutput : 7\nExplanation\nMaximum possible xor sum is 1 ^ 2 ^ 4 = 7.\n\nInput : n = 11, k = 1\nOutput : 11\nExplanation\nMaximum Possible xor sum is 11."
},
{
"code": null,
"e": 25508,
"s": 25335,
"text": "If we have k = 1 then the maximum possible xor sum is ‘n’ itself. Now for k > 1 we can always have an number with its all bits set till the most significant set bit in ‘n’."
},
{
"code": null,
"e": 25512,
"s": 25508,
"text": "C++"
},
{
"code": null,
"e": 25517,
"s": 25512,
"text": "Java"
},
{
"code": null,
"e": 25524,
"s": 25517,
"text": "Python"
},
{
"code": null,
"e": 25527,
"s": 25524,
"text": "C#"
},
{
"code": null,
"e": 25531,
"s": 25527,
"text": "PHP"
},
{
"code": null,
"e": 25542,
"s": 25531,
"text": "Javascript"
},
{
"code": "// CPP program to find max xor sum// of 1 to n using atmost k numbers#include <bits/stdc++.h>using namespace std;typedef long long int ll; // To return max xor sum of 1 to n// using at most k numbersll maxXorSum(ll n, ll k){ // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 ll res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1;} // Driver programint main(){ ll n = 4, k = 3; cout << maxXorSum(n, k); return 0;}",
"e": 26265,
"s": 25542,
"text": null
},
{
"code": "// Java program to find max xor sum// of 1 to n using atmost k numberspublic class Main { // To return max xor sum of 1 to n // using at most k numbers static int maxXorSum(int n, int k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 int res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver program to test maxXorSum() public static void main(String[] args) { int n = 4, k = 3; System.out.print(maxXorSum(n, k)); }}",
"e": 27101,
"s": 26265,
"text": null
},
{
"code": "# Python3 code to find max xor sum# of 1 to n using atmost k numbers # To return max xor sum of 1 to n# using at most k numbersdef maxXorSum( n , k ): # If k is 1 then maximum # possible sum is n if k == 1: return n # Finding number greater than # or equal to n with most significant # bit same as n. For example, if n is # 4, result is 7. If n is 5 or 6, result # is 7 res = 1 while res <= n: res <<= 1 # Return res - 1 which denotes # a number with all bits set to 1 return res - 1 # Driver coden = 4k = 3print( maxXorSum(n, k) ) # This code is contributed by Abhishek Sharma44.",
"e": 27745,
"s": 27101,
"text": null
},
{
"code": "// C# program to find max xor sum// of 1 to n using atmost k numbersusing System; public class main { // To return max xor sum of 1 to n // using at most k numbers static int maxXorSum(int n, int k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 int res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver program public static void Main() { int n = 4, k = 3; Console.WriteLine(maxXorSum(n, k)); }} // This code is contributed by vt_m.",
"e": 28598,
"s": 27745,
"text": null
},
{
"code": "<?php// PHP program to find max xor sum// of 1 to n using atmost k numbers // To return max xor sum of 1 to n// using at most k numbersfunction maxXorSum($n, $k){ // If k is 1 then maximum // possible sum is n if ($k == 1) return $n; // Finding number greater than // or equal to n with most // significant bit same as n. // For example, if n is 4, result // is 7. If n is 5 or 6, result is 7 $res = 1; while ($res <= $n) $res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return $res - 1;} // Driver code$n = 4;$k = 3;echo maxXorSum($n, $k); // This code is contributed by Mithun Kumar?>",
"e": 29270,
"s": 28598,
"text": null
},
{
"code": "<script> // JavaScript program to find max xor sum// of 1 to n using atmost k numbers // To return max xor sum of 1 to n // using at most k numbers function maxXorSum(n, k) { // If k is 1 then maximum // possible sum is n if (k == 1) return n; // Finding number greater than // or equal to n with most significant // bit same as n. For example, if n is // 4, result is 7. If n is 5 or 6, result // is 7 let res = 1; while (res <= n) res <<= 1; // Return res - 1 which denotes // a number with all bits set to 1 return res - 1; } // Driver code let n = 4, k = 3; document.write(maxXorSum(n, k)); </script>",
"e": 30040,
"s": 29270,
"text": null
},
{
"code": null,
"e": 30050,
"s": 30040,
"text": "Output : "
},
{
"code": null,
"e": 30052,
"s": 30050,
"text": "7"
},
{
"code": null,
"e": 30892,
"s": 30054,
"text": "YouTubeGeeksforGeeks500K subscribersMaximum XOR using K numbers from 1 to n | 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 / 3:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Jjlk_BqLK7Q\" 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": 30907,
"s": 30894,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30922,
"s": 30907,
"text": "vikashkumar317"
},
{
"code": null,
"e": 30932,
"s": 30922,
"text": "splevel62"
},
{
"code": null,
"e": 30951,
"s": 30932,
"text": "shivamaggarwal5570"
},
{
"code": null,
"e": 30963,
"s": 30951,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 30973,
"s": 30963,
"text": "Bit Magic"
},
{
"code": null,
"e": 30983,
"s": 30973,
"text": "Bit Magic"
},
{
"code": null,
"e": 31081,
"s": 30983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31090,
"s": 31081,
"text": "Comments"
},
{
"code": null,
"e": 31103,
"s": 31090,
"text": "Old Comments"
},
{
"code": null,
"e": 31154,
"s": 31103,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 31177,
"s": 31154,
"text": "Program to find parity"
},
{
"code": null,
"e": 31214,
"s": 31177,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 31264,
"s": 31214,
"text": "Implementation of Bit Stuffing and Bit Destuffing"
},
{
"code": null,
"e": 31328,
"s": 31264,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 31365,
"s": 31328,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 31399,
"s": 31365,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 31428,
"s": 31399,
"text": "Count total bits in a number"
},
{
"code": null,
"e": 31455,
"s": 31428,
"text": "Check for Integer Overflow"
}
] |
How to set the decoration of a text with JavaScript? | Use the textDecoration property in JavaScript to decorate the text. You can underline a text using this property.
You can try to run the following code to set the decoration of a text with JavaScript −
<!DOCTYPE html>
<html>
<body>
<div id = "myText">This is demo text.</div><br>
<button onclick = "display()">Set Text Decoration</button>
<script>
function display() {
document.getElementById("myText").style.textDecoration = "underline";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "Use the textDecoration property in JavaScript to decorate the text. You can underline a text using this property."
},
{
"code": null,
"e": 1264,
"s": 1176,
"text": "You can try to run the following code to set the decoration of a text with JavaScript −"
},
{
"code": null,
"e": 1590,
"s": 1264,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <div id = \"myText\">This is demo text.</div><br>\n\n <button onclick = \"display()\">Set Text Decoration</button>\n <script>\n function display() {\n document.getElementById(\"myText\").style.textDecoration = \"underline\";\n }\n </script>\n </body>\n</html>"
}
] |
Program to print a pattern of numbers in C++ | In this tutorial, we will be discussing a program to print a given pattern of numbers.
Our task is to make use of looping structure in the code and print the given pattern −
1
232
34543
4567654
567898765
Live Demo
#include<bits/stdc++.h>
using namespace std;
int main(){
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for ( j = 1 ; j <= n ; j++ ){
num = j;
for ( i = 1 ; i <= gap ; i++ )
cout << " ";
gap --;
for ( i = 1 ; i <= j ; i++ ){
cout << num;
num++;
}
num--;
num--;
for ( i = 1 ; i < j ; i++){
cout << num;
num--;
}
cout << "\n";
}
return 0;
}
1
232
34543
4567654
567898765 | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to print a given pattern of numbers."
},
{
"code": null,
"e": 1236,
"s": 1149,
"text": "Our task is to make use of looping structure in the code and print the given pattern −"
},
{
"code": null,
"e": 1279,
"s": 1236,
"text": " 1\n 232\n 34543\n 4567654\n567898765"
},
{
"code": null,
"e": 1290,
"s": 1279,
"text": " Live Demo"
},
{
"code": null,
"e": 1743,
"s": 1290,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n int n = 5, i, j, num = 1, gap;\n gap = n - 1;\n for ( j = 1 ; j <= n ; j++ ){\n num = j;\n for ( i = 1 ; i <= gap ; i++ )\n cout << \" \";\n gap --;\n for ( i = 1 ; i <= j ; i++ ){\n cout << num;\n num++;\n }\n num--;\n num--;\n for ( i = 1 ; i < j ; i++){\n cout << num;\n num--;\n }\n cout << \"\\n\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 1783,
"s": 1743,
"text": " 1\n 232\n 34543\n 4567654\n567898765"
}
] |
ISRO | ISRO CS 2016 | Question 35 - GeeksforGeeks | 10 May, 2020
What is the highest type number that can be assigned to the following grammar?
S → Aa
A → Ba
B → abc
(A) Type 0(B) Type 1(C) Type 2(D) Type 3Answer: (D)Explanation: According to Chomsky Hierarchy, option (D) is correct.Quiz of this Question
ApurvaRaj
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2015 | Question 51
ISRO | ISRO CS 2013 | Question 8
ISRO | ISRO CS 2013 | Question 7
ISRO | ISRO CS 2013 | Question 22
ISRO | ISRO CS 2014 | Question 31
ISRO | ISRO CS 2013 | Question 31
ISRO | ISRO CS 2017 - May | Question 21
ISRO | ISRO CS 2017 | Question 42
ISRO | ISRO CS 2017 | Question 57 | [
{
"code": null,
"e": 24035,
"s": 24007,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24114,
"s": 24035,
"text": "What is the highest type number that can be assigned to the following grammar?"
},
{
"code": null,
"e": 24136,
"s": 24114,
"text": "S → Aa\nA → Ba\nB → abc"
},
{
"code": null,
"e": 24276,
"s": 24136,
"text": "(A) Type 0(B) Type 1(C) Type 2(D) Type 3Answer: (D)Explanation: According to Chomsky Hierarchy, option (D) is correct.Quiz of this Question"
},
{
"code": null,
"e": 24286,
"s": 24276,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 24291,
"s": 24286,
"text": "ISRO"
},
{
"code": null,
"e": 24389,
"s": 24291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24398,
"s": 24389,
"text": "Comments"
},
{
"code": null,
"e": 24411,
"s": 24398,
"text": "Old Comments"
},
{
"code": null,
"e": 24445,
"s": 24411,
"text": "ISRO | ISRO CS 2009 | Question 30"
},
{
"code": null,
"e": 24479,
"s": 24445,
"text": "ISRO | ISRO CS 2015 | Question 51"
},
{
"code": null,
"e": 24512,
"s": 24479,
"text": "ISRO | ISRO CS 2013 | Question 8"
},
{
"code": null,
"e": 24545,
"s": 24512,
"text": "ISRO | ISRO CS 2013 | Question 7"
},
{
"code": null,
"e": 24579,
"s": 24545,
"text": "ISRO | ISRO CS 2013 | Question 22"
},
{
"code": null,
"e": 24613,
"s": 24579,
"text": "ISRO | ISRO CS 2014 | Question 31"
},
{
"code": null,
"e": 24647,
"s": 24613,
"text": "ISRO | ISRO CS 2013 | Question 31"
},
{
"code": null,
"e": 24687,
"s": 24647,
"text": "ISRO | ISRO CS 2017 - May | Question 21"
},
{
"code": null,
"e": 24721,
"s": 24687,
"text": "ISRO | ISRO CS 2017 | Question 42"
}
] |
Count number of elements between two given elements in array in C++ | We are given an array containing integer elements and two numbers start and end and the task is to calculate the count of elements present between start and end in an array.
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. If the start element is occurring multiple times then we will consider the first occurrence of the start element and if the end element is occurring multiple times then we will consider the end occurrence of the end element.
Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
Start = 1 and End = 7
Output − count is 5
Explanation − In the given array, there are 7 elements and the range is 1-7. So, in between this range there are a total of 5 elements.
Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
Start = 7 and End = 9
Output − count is 0
Explanation − In the given array, there are 7 elements and the range is 7-9. So, in between this range there is no element so the count is 0.
Input an array let’s say, int arr[]
Input an array let’s say, int arr[]
Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array.
Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array.
Start the loop from i to 0 till i less than size of an array
Start the loop from i to 0 till i less than size of an array
Inside the loop, check if arr[i] = start then break
Inside the loop, check if arr[i] = start then break
Check if i>size-1 then return
Check if i>size-1 then return
Start another loop with j to size-1 and j>=i+1 and j--
Start another loop with j to size-1 and j>=i+1 and j--
Check if arr[j]=end then break
Check if arr[j]=end then break
Check if j=1 then return 0
Check if j=1 then return 0
Return j-i-1
Return j-i-1
Print the result.
Print the result.
Live Demo
#include <iostream>
using namespace std;
// For counting the numbers between the two elements
int countelements(int ar[], int n, int start, int end){
// Find start
int i = 0;
for (i = 0; i < n; i++){
if (ar[i] == start){
break;
}
}
// If start is not present or present at the last
if (i >= n-1){
return 0;
}
// Find end
int j;
for (j = n-1; j >= i+1; j--){
if (ar[j] == end){
break;
}
}
// If end is not present
if (j == i){
return 0;
}
// number of elements between the two elements
return (j - i - 1);
}
// Main Function
int main(){
int ar[] = { 1, 6, 2, 5, 9, 8, 3, 7, 4 };
int n = sizeof(ar) / sizeof(ar[0]);
int start = 5, end = 4;
cout <<"count is " <<countelements(ar, n, start, end);
return 0;
}
If we run the above code we will get the following output −
count is 4 | [
{
"code": null,
"e": 1236,
"s": 1062,
"text": "We are given an array containing integer elements and two numbers start and end and the task is to calculate the count of elements present between start and end in an array."
},
{
"code": null,
"e": 1717,
"s": 1236,
"text": "Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. If the start element is occurring multiple times then we will consider the first occurrence of the start element and if the end element is occurring multiple times then we will consider the end occurrence of the end element."
},
{
"code": null,
"e": 1807,
"s": 1717,
"text": "Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}\n Start = 1 and End = 7\nOutput − count is 5"
},
{
"code": null,
"e": 1943,
"s": 1807,
"text": "Explanation − In the given array, there are 7 elements and the range is 1-7. So, in between this range there are a total of 5 elements."
},
{
"code": null,
"e": 2033,
"s": 1943,
"text": "Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}\n Start = 7 and End = 9\nOutput − count is 0"
},
{
"code": null,
"e": 2175,
"s": 2033,
"text": "Explanation − In the given array, there are 7 elements and the range is 7-9. So, in between this range there is no element so the count is 0."
},
{
"code": null,
"e": 2211,
"s": 2175,
"text": "Input an array let’s say, int arr[]"
},
{
"code": null,
"e": 2247,
"s": 2211,
"text": "Input an array let’s say, int arr[]"
},
{
"code": null,
"e": 2382,
"s": 2247,
"text": "Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array."
},
{
"code": null,
"e": 2517,
"s": 2382,
"text": "Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array."
},
{
"code": null,
"e": 2578,
"s": 2517,
"text": "Start the loop from i to 0 till i less than size of an array"
},
{
"code": null,
"e": 2639,
"s": 2578,
"text": "Start the loop from i to 0 till i less than size of an array"
},
{
"code": null,
"e": 2691,
"s": 2639,
"text": "Inside the loop, check if arr[i] = start then break"
},
{
"code": null,
"e": 2743,
"s": 2691,
"text": "Inside the loop, check if arr[i] = start then break"
},
{
"code": null,
"e": 2773,
"s": 2743,
"text": "Check if i>size-1 then return"
},
{
"code": null,
"e": 2803,
"s": 2773,
"text": "Check if i>size-1 then return"
},
{
"code": null,
"e": 2858,
"s": 2803,
"text": "Start another loop with j to size-1 and j>=i+1 and j--"
},
{
"code": null,
"e": 2913,
"s": 2858,
"text": "Start another loop with j to size-1 and j>=i+1 and j--"
},
{
"code": null,
"e": 2944,
"s": 2913,
"text": "Check if arr[j]=end then break"
},
{
"code": null,
"e": 2975,
"s": 2944,
"text": "Check if arr[j]=end then break"
},
{
"code": null,
"e": 3002,
"s": 2975,
"text": "Check if j=1 then return 0"
},
{
"code": null,
"e": 3029,
"s": 3002,
"text": "Check if j=1 then return 0"
},
{
"code": null,
"e": 3042,
"s": 3029,
"text": "Return j-i-1"
},
{
"code": null,
"e": 3055,
"s": 3042,
"text": "Return j-i-1"
},
{
"code": null,
"e": 3073,
"s": 3055,
"text": "Print the result."
},
{
"code": null,
"e": 3091,
"s": 3073,
"text": "Print the result."
},
{
"code": null,
"e": 3102,
"s": 3091,
"text": " Live Demo"
},
{
"code": null,
"e": 3924,
"s": 3102,
"text": "#include <iostream>\nusing namespace std;\n// For counting the numbers between the two elements\nint countelements(int ar[], int n, int start, int end){\n // Find start\n int i = 0;\n for (i = 0; i < n; i++){\n if (ar[i] == start){\n break;\n }\n }\n // If start is not present or present at the last\n if (i >= n-1){\n return 0;\n }\n // Find end\n int j;\n for (j = n-1; j >= i+1; j--){\n if (ar[j] == end){\n break;\n }\n }\n // If end is not present\n if (j == i){\n return 0;\n }\n // number of elements between the two elements\n return (j - i - 1);\n}\n// Main Function\nint main(){\n int ar[] = { 1, 6, 2, 5, 9, 8, 3, 7, 4 };\n int n = sizeof(ar) / sizeof(ar[0]);\n int start = 5, end = 4;\n cout <<\"count is \" <<countelements(ar, n, start, end);\n return 0;\n}"
},
{
"code": null,
"e": 3984,
"s": 3924,
"text": "If we run the above code we will get the following output −"
},
{
"code": null,
"e": 3995,
"s": 3984,
"text": "count is 4"
}
] |
LocalDate atStartOfDay() method in Java with Examples - GeeksforGeeks | 28 Nov, 2018
The atStartOfDay() method of LocalDate class in Java is combines this date with the time of midnight to create a LocalDateTime at the start of this date.
Syntax:
public ZonedDateTime atStartOfDay(ZoneId zone)
Parameter: This method accepts a parameter zone which is the zone ID to be used and not necessary null. The parameter is not mandatory.
Return Value: It returns the the local date-time of midnight at the start of this date, not null.
Below programs illustrate the atStartOfDay() method of LocalDate in Java:
Program 1:
// Program to illustrate the atStartOfDay() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // parses the local date LocalDate dt = LocalDate.parse("2019-11-01"); System.out.println(dt); // Function call LocalDateTime dt1 = dt.atStartOfDay(); System.out.println(dt1); }}
2019-11-01
2019-11-01T00:00
Program 2: Program with parameters.
// Program to illustrate the atStartOfDay() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // parses the local date LocalDate dt = LocalDate.parse("2018-01-20"); System.out.println(dt); // Function call ZonedDateTime dt1 = dt.atStartOfDay(ZoneId.systemDefault()); System.out.println(dt1); }}
2018-01-20
2018-01-20T00:00Z[Etc/UTC]
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#atStartOfDay()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
HashMap containsKey() Method in Java
Difference between Abstract Class and Interface in Java
final Keyword in Java
How to Create Array of Objects in Java?
Java Math random() method with Examples
Java | Implementing Iterator and Iterable Interface | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 23711,
"s": 23557,
"text": "The atStartOfDay() method of LocalDate class in Java is combines this date with the time of midnight to create a LocalDateTime at the start of this date."
},
{
"code": null,
"e": 23719,
"s": 23711,
"text": "Syntax:"
},
{
"code": null,
"e": 23767,
"s": 23719,
"text": "public ZonedDateTime atStartOfDay(ZoneId zone)\n"
},
{
"code": null,
"e": 23903,
"s": 23767,
"text": "Parameter: This method accepts a parameter zone which is the zone ID to be used and not necessary null. The parameter is not mandatory."
},
{
"code": null,
"e": 24001,
"s": 23903,
"text": "Return Value: It returns the the local date-time of midnight at the start of this date, not null."
},
{
"code": null,
"e": 24075,
"s": 24001,
"text": "Below programs illustrate the atStartOfDay() method of LocalDate in Java:"
},
{
"code": null,
"e": 24086,
"s": 24075,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the atStartOfDay() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // parses the local date LocalDate dt = LocalDate.parse(\"2019-11-01\"); System.out.println(dt); // Function call LocalDateTime dt1 = dt.atStartOfDay(); System.out.println(dt1); }}",
"e": 24470,
"s": 24086,
"text": null
},
{
"code": null,
"e": 24499,
"s": 24470,
"text": "2019-11-01\n2019-11-01T00:00\n"
},
{
"code": null,
"e": 24535,
"s": 24499,
"text": "Program 2: Program with parameters."
},
{
"code": "// Program to illustrate the atStartOfDay() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // parses the local date LocalDate dt = LocalDate.parse(\"2018-01-20\"); System.out.println(dt); // Function call ZonedDateTime dt1 = dt.atStartOfDay(ZoneId.systemDefault()); System.out.println(dt1); }}",
"e": 24943,
"s": 24535,
"text": null
},
{
"code": null,
"e": 24982,
"s": 24943,
"text": "2018-01-20\n2018-01-20T00:00Z[Etc/UTC]\n"
},
{
"code": null,
"e": 25076,
"s": 24982,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#atStartOfDay()"
},
{
"code": null,
"e": 25091,
"s": 25076,
"text": "Java-Functions"
},
{
"code": null,
"e": 25106,
"s": 25091,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 25124,
"s": 25106,
"text": "Java-time package"
},
{
"code": null,
"e": 25129,
"s": 25124,
"text": "Java"
},
{
"code": null,
"e": 25134,
"s": 25129,
"text": "Java"
},
{
"code": null,
"e": 25232,
"s": 25134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25241,
"s": 25232,
"text": "Comments"
},
{
"code": null,
"e": 25254,
"s": 25241,
"text": "Old Comments"
},
{
"code": null,
"e": 25272,
"s": 25254,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 25293,
"s": 25272,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25339,
"s": 25293,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25382,
"s": 25339,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25419,
"s": 25382,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 25475,
"s": 25419,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 25497,
"s": 25475,
"text": "final Keyword in Java"
},
{
"code": null,
"e": 25537,
"s": 25497,
"text": "How to Create Array of Objects in Java?"
},
{
"code": null,
"e": 25577,
"s": 25537,
"text": "Java Math random() method with Examples"
}
] |
Using CX_Freeze in Python | Sometimes we feel to create something different which is very exciting, and according to human nature, we always love to share it.
Python also fulfills those wishes. Using Python, if we want to share our Python program with our friends we can do that, only need to have the same version of Python installed with all the modules those are used in program of their machine.
First we need to install CX_Freeze module using pip install CX_Frezze command in command prompt.
First step is to solve this assignment, a python program conversion. We need standard library modules, here we use urllib and re module where we parsed python.com.
import urllib.request
import urllib.parse
import re
import time
my_url = 'https://www.python.com/'
my_values = {'s' : 'basics',
'submit' : 'search'}
my_data = urllib.parse.urlencode(my_values)
my_data = data.encode('utf-8')
my_req = urllib.request.Request(my_url, my_data)
my_resp = urllib.request.urlopen(my_req)
my_respData = my_resp.read()
my_paragraphs = re.findall(r'<p>(.*?)</p>',str(my_respData))
for p in my_paragraphs:
print(p)
time.sleep(20)
Here we use 20 second sleep at the end, so we can see the output before it closes.
This program is saved as "pythonCX_Freeze.py" file name.
Now next step is to create setup file and this file is called "setup.py"
from cx_Freeze import setup, Executable
setup(name = "pythonCX_Freeze" ,
version = "0.1" ,
description = "" ,
executables = [Executable("pythonCX_Freeze.py")])
In this program we importing pythonCX_Freeze setup and executable. Next we call setup() function with 4 parameters. First parameter name, this is the name of the program that we want to execute, second is version, this is the version number to give it, description if we want then we write necessary line otherwise blank it and last one is executable function with one parameter.
Next we open cmd.exe then navigate the directory where has the setup.py and the script.
Then we run python setup.py build.
Now given a build directory and within this directory we find another directory and within that directory we find our executable. If every step is done correctly then it should parse the search result of basic form on python.com and display result for 20 seconds before closing. | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Sometimes we feel to create something different which is very exciting, and according to human nature, we always love to share it."
},
{
"code": null,
"e": 1434,
"s": 1193,
"text": "Python also fulfills those wishes. Using Python, if we want to share our Python program with our friends we can do that, only need to have the same version of Python installed with all the modules those are used in program of their machine."
},
{
"code": null,
"e": 1531,
"s": 1434,
"text": "First we need to install CX_Freeze module using pip install CX_Frezze command in command prompt."
},
{
"code": null,
"e": 1695,
"s": 1531,
"text": "First step is to solve this assignment, a python program conversion. We need standard library modules, here we use urllib and re module where we parsed python.com."
},
{
"code": null,
"e": 2160,
"s": 1695,
"text": "import urllib.request\nimport urllib.parse\nimport re\nimport time\nmy_url = 'https://www.python.com/'\nmy_values = {'s' : 'basics',\n 'submit' : 'search'}\nmy_data = urllib.parse.urlencode(my_values)\nmy_data = data.encode('utf-8')\nmy_req = urllib.request.Request(my_url, my_data)\nmy_resp = urllib.request.urlopen(my_req)\nmy_respData = my_resp.read()\nmy_paragraphs = re.findall(r'<p>(.*?)</p>',str(my_respData))\nfor p in my_paragraphs:\n print(p)\ntime.sleep(20)"
},
{
"code": null,
"e": 2243,
"s": 2160,
"text": "Here we use 20 second sleep at the end, so we can see the output before it closes."
},
{
"code": null,
"e": 2300,
"s": 2243,
"text": "This program is saved as \"pythonCX_Freeze.py\" file name."
},
{
"code": null,
"e": 2373,
"s": 2300,
"text": "Now next step is to create setup file and this file is called \"setup.py\""
},
{
"code": null,
"e": 2542,
"s": 2373,
"text": "from cx_Freeze import setup, Executable\nsetup(name = \"pythonCX_Freeze\" ,\n version = \"0.1\" ,\n description = \"\" ,\n executables = [Executable(\"pythonCX_Freeze.py\")])"
},
{
"code": null,
"e": 2922,
"s": 2542,
"text": "In this program we importing pythonCX_Freeze setup and executable. Next we call setup() function with 4 parameters. First parameter name, this is the name of the program that we want to execute, second is version, this is the version number to give it, description if we want then we write necessary line otherwise blank it and last one is executable function with one parameter."
},
{
"code": null,
"e": 3010,
"s": 2922,
"text": "Next we open cmd.exe then navigate the directory where has the setup.py and the script."
},
{
"code": null,
"e": 3045,
"s": 3010,
"text": "Then we run python setup.py build."
},
{
"code": null,
"e": 3324,
"s": 3045,
"text": "Now given a build directory and within this directory we find another directory and within that directory we find our executable. If every step is done correctly then it should parse the search result of basic form on python.com and display result for 20 seconds before closing."
}
] |
How to create an array of linked lists in java? | A linked list is a sequence of data structures, which are connected together via links.
To create an array of linked lists, create required linked lists and, create an array of objects with them.
Live Demo
import java.util.LinkedList;
public class ArrayOfLinkedList {
public static void main(String args[]) {
LinkedList list1 = new LinkedList();
list1.add("JavaFX");
list1.add("Hbase");
LinkedList list2 = new LinkedList();
list2.add("OpenCV");
list2.add("Mahout");
LinkedList list3 = new LinkedList();
list3.add("WebGL");
list3.add("CoffeeScript");
Object[] obj = {list1, list2, list3};
for (int i=0; i<obj.length; i++) {
System.out.println(obj[i].toString());
}
}
}
[JavaFX, Hbase]
[OpenCV, Mahout]
[WebGL, CoffeeScript]
You can also create Array list of linked lists as –
Live Demo
import java.util.ArrayList;
import java.util.LinkedList;
public class ArrayOfLinkedList {
public static void main(String args[]) {
LinkedList list1 = new LinkedList();
list1.add("JavaFX");
list1.add("Hbase");
LinkedList list2 = new LinkedList();
list2.add("OpenCV");
list2.add("Mahout");
LinkedList list3 = new LinkedList();
list3.add("WebGL");
list3.add("CoffeeScript");
ArrayList <LinkedList> aList = new ArrayList<LinkedList>();
aList.add(list1);
aList.add(list2);
aList.add(list1);
System.out.println(aList);
}
}
[[JavaFX, Hbase], [OpenCV, Mahout], [JavaFX, Hbase]] | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "A linked list is a sequence of data structures, which are connected together via links."
},
{
"code": null,
"e": 1258,
"s": 1150,
"text": "To create an array of linked lists, create required linked lists and, create an array of objects with them."
},
{
"code": null,
"e": 1268,
"s": 1258,
"text": "Live Demo"
},
{
"code": null,
"e": 1836,
"s": 1268,
"text": "import java.util.LinkedList;\n\npublic class ArrayOfLinkedList {\n public static void main(String args[]) {\n LinkedList list1 = new LinkedList();\n list1.add(\"JavaFX\");\n list1.add(\"Hbase\");\n \n LinkedList list2 = new LinkedList();\n list2.add(\"OpenCV\");\n list2.add(\"Mahout\");\n \n LinkedList list3 = new LinkedList();\n list3.add(\"WebGL\");\n list3.add(\"CoffeeScript\");\n Object[] obj = {list1, list2, list3};\n \n for (int i=0; i<obj.length; i++) {\n System.out.println(obj[i].toString());\n }\n }\n}"
},
{
"code": null,
"e": 1891,
"s": 1836,
"text": "[JavaFX, Hbase]\n[OpenCV, Mahout]\n[WebGL, CoffeeScript]"
},
{
"code": null,
"e": 1943,
"s": 1891,
"text": "You can also create Array list of linked lists as –"
},
{
"code": null,
"e": 1953,
"s": 1943,
"text": "Live Demo"
},
{
"code": null,
"e": 2579,
"s": 1953,
"text": "import java.util.ArrayList;\nimport java.util.LinkedList;\n\npublic class ArrayOfLinkedList {\n public static void main(String args[]) {\n LinkedList list1 = new LinkedList();\n list1.add(\"JavaFX\");\n list1.add(\"Hbase\");\n \n LinkedList list2 = new LinkedList();\n list2.add(\"OpenCV\");\n list2.add(\"Mahout\");\n \n LinkedList list3 = new LinkedList();\n list3.add(\"WebGL\");\n list3.add(\"CoffeeScript\");\n \n ArrayList <LinkedList> aList = new ArrayList<LinkedList>();\n aList.add(list1);\n aList.add(list2);\n aList.add(list1);\n System.out.println(aList);\n }\n}"
},
{
"code": null,
"e": 2632,
"s": 2579,
"text": "[[JavaFX, Hbase], [OpenCV, Mahout], [JavaFX, Hbase]]"
}
] |
What is One-Hot Encoding and how to use Pandas get_dummies function | by B. Chen | Towards Data Science | I get questions all the time about some concepts in machine learning and what they really mean, for example, in one of my previous articles Google’s 7 steps of Machine Learning in practice, I get asked what is one-hot encoding, and when should we use it? That’s is a great question and every machine learning practitioner needs to know the answer, so let’s talk about it and dive into some code with Pandas get_dummies().
In the step of data processing in machine learning, we often need to prepare our data in specific ways before feeding into a machine learning model. One of the examples is to perform a One-Hot encoding on categorical data.
One Hot Encoding is a process in the data processing that is applied to categorical data, to convert it into a binary vector representation for use in machine learning algorithms
One of the major problems with machine learning is that a lot of algorithms cannot work directly with categorical data. Categorical data [1] are variables that can take on one of a limited number of possible values. Some examples are:
The sex of a person: female or male.
The airline travel class: First Class, Business Class, and Economy Class.
The computer vendor: Lenovo, HP, Dell, Apple, Acer, Asus, and Others.
Therefore, we need a way to convert categorical data into a numerical form and our machine learning algorithm can take in that as input. The most widely used encoding techniques are:
Integer Encoding: encodes the values as integer.One-Hot Encoding: encodes the values as a binary vector array.Dummy Variable Encoding: same as One-Hot Encoding, but one less column.
Integer Encoding: encodes the values as integer.
One-Hot Encoding: encodes the values as a binary vector array.
Dummy Variable Encoding: same as One-Hot Encoding, but one less column.
In the above examples, each value in a categorical variable represents a different category. Some categories may have a natural relationship (known as a natural ordering) to each other. The airline travel class variable does have a natural ordering of values. This type of categorical variable is known as an ordinal variable. Ordinal variables should be treated differently in machine learning because the ordinality generally comes with some significance. In the case of airline travel class, the passengers in the higher classes tend to be wealthier and older. Integer Encoding is used to convert ordinal variable to numerical data, for example
First Class is 1, Business Class is 2, and Economy Class is 3
The integer values have a natural ordered relationship between each other and machine learning algorithms may be able to learn this relationship [2].
For categories variables where no such ordinal relationship exists, Integer Encoding could result in poor performance or unexpected results [2]. Fortunately, One-Hot Encoding is a way to combat this. One-Hot Encoding simply creates one column for every possible value and put a 1 in the appropriate column. Below is the equivalent One-Hot Encoding representation.
With One-Hot Encoding, the binary vector arrays representation allows a machine learning algorithm to leverage the information contained in a category value without the confusion caused by ordinality.
However, there is some redundancy in One-Hot encoding. For instance, in the above example, if we know that a passenger’s flight ticket is not First Class and not Economy Class, then it must be Business Class. So we only need to use two of these three dummy-coded variables as a predictor. More generally, the number of dummy-coded variables needed is one less than the number of possible values, which is K-1. In statistics, this is called a dummy encoding variable, or dummy variable. Below is the equivalent dummy encoding variable representation:
Dummy encoding variable is a standard advice in statistics to avoid the dummy variable trap, However, in the world of machine learning, One-Hot encoding is more recommended because dummy variable trap is not really a problem when applying regularization [3].
Before we diving into tutorial, let’s first pull up an example dataset we can work with. For this tutorial, we will be working on the Titanic Dataset from Kaggle. This is a very famous dataset and very often is a student’s first step in machine learning. Let’s import pandas and load data to get started.
import pandas as pddef load_data(): return pd.read_csv('data/train.csv')df = load_data()df.head()
We created a function load_data() to load train.csv file into pandas DataFrame.
Let’s pretend we want to create a One-Hot encoding variable for the Sex column. Here is how we create it.
pd.get_dummies(df.Sex)
What it does is create one column for every possible value and they are two possible values for Sex. It tells you whether it is female or male by putting a 1 in the appropriate column.
Generally speaking, if we have K possible values for a categorical variable, we will get K columns to represent it.
There is some redundancy in One-Hot encoding. For instance, in the above Sex One-Hot encoding, a person is either male or female. So we only need to use one of these two dummy-coded variables as a predictor. More generally, the number of dummy-coded variables needed is one less than the number of possible values, which is K-1. In statistics, this is called a dummy encoding variable, or dummy variable.
By default, the get_dummies() does not do dummy encoding, but One-Hot encoding. To produce an actual dummy encoding from a DataFrame, we need to pass drop_first=True
pd.get_dummies(df.Sex, drop_first=True)
By default, get_dummies() use variable values as column names. For instance, male and female in the above Sex column example. To identify where the dummy variables came from, we can use the prefix argument. For example:
pd.get_dummies(df.Sex, prefix='Sex')
Now, let’s try to get One-Hot encoding for a variable that has more than two possible values. For instance, there is an Embarked column and we can do value_counts() to check its different values.
df.Embarked.value_counts()S 644C 168Q 77Name: Embarked, dtype: int64
Let’s use get_dummies() for that
pd.get_dummies(df.Embarked, prefix='Embarked')
You might be thinking we have still got to attach the One-Hot encoding variables to the DataFrame. To do that, we first assign the output to a variable called embarked_dummies
embarked_dummies = pd.get_dummies(df.Embarked, prefix='Embarked')
Then, we use pd.concat() to attach embarked_dummies to the DataFrame df.
df = pd.concat([df, embarked_dummies], axis=1)
The way pd.concat() works is we can concatenate columns side by side or rows on top of one another. So in this case, we concatenate df and embarked_dummies along columns (axis =1). In the end, we overwrite the original df.
By running df.head(), we can see that we’ve now got the Embarked_C, Embarked_Q, and Embarked_S.
We have been passing a Series to get_dummies(), but we’re gonna pass a DataFrame.
df = load_data() # reset dataframedf = pd.get_dummies(df, columns=['Sex', 'Embarked'])
df is a DataFrame. We pass columns a list and we tell it Sex and Embarked are the columns we want to dummy.
By running df.head(), we can see that the original Sex column and Embarked column are gone, they have been replaced with the dummy columns.
Thanks for reading.
Please checkout the notebook on my Github for the source code.
Stay tuned if you are interested in the practical aspect of machine learning.
[1] Categorical variable in Wikipedia
[2] Why one-hot encoding in machine learning
[3] Are you getting burned by one-hot encoding | [
{
"code": null,
"e": 469,
"s": 47,
"text": "I get questions all the time about some concepts in machine learning and what they really mean, for example, in one of my previous articles Google’s 7 steps of Machine Learning in practice, I get asked what is one-hot encoding, and when should we use it? That’s is a great question and every machine learning practitioner needs to know the answer, so let’s talk about it and dive into some code with Pandas get_dummies()."
},
{
"code": null,
"e": 692,
"s": 469,
"text": "In the step of data processing in machine learning, we often need to prepare our data in specific ways before feeding into a machine learning model. One of the examples is to perform a One-Hot encoding on categorical data."
},
{
"code": null,
"e": 871,
"s": 692,
"text": "One Hot Encoding is a process in the data processing that is applied to categorical data, to convert it into a binary vector representation for use in machine learning algorithms"
},
{
"code": null,
"e": 1106,
"s": 871,
"text": "One of the major problems with machine learning is that a lot of algorithms cannot work directly with categorical data. Categorical data [1] are variables that can take on one of a limited number of possible values. Some examples are:"
},
{
"code": null,
"e": 1143,
"s": 1106,
"text": "The sex of a person: female or male."
},
{
"code": null,
"e": 1217,
"s": 1143,
"text": "The airline travel class: First Class, Business Class, and Economy Class."
},
{
"code": null,
"e": 1287,
"s": 1217,
"text": "The computer vendor: Lenovo, HP, Dell, Apple, Acer, Asus, and Others."
},
{
"code": null,
"e": 1470,
"s": 1287,
"text": "Therefore, we need a way to convert categorical data into a numerical form and our machine learning algorithm can take in that as input. The most widely used encoding techniques are:"
},
{
"code": null,
"e": 1652,
"s": 1470,
"text": "Integer Encoding: encodes the values as integer.One-Hot Encoding: encodes the values as a binary vector array.Dummy Variable Encoding: same as One-Hot Encoding, but one less column."
},
{
"code": null,
"e": 1701,
"s": 1652,
"text": "Integer Encoding: encodes the values as integer."
},
{
"code": null,
"e": 1764,
"s": 1701,
"text": "One-Hot Encoding: encodes the values as a binary vector array."
},
{
"code": null,
"e": 1836,
"s": 1764,
"text": "Dummy Variable Encoding: same as One-Hot Encoding, but one less column."
},
{
"code": null,
"e": 2484,
"s": 1836,
"text": "In the above examples, each value in a categorical variable represents a different category. Some categories may have a natural relationship (known as a natural ordering) to each other. The airline travel class variable does have a natural ordering of values. This type of categorical variable is known as an ordinal variable. Ordinal variables should be treated differently in machine learning because the ordinality generally comes with some significance. In the case of airline travel class, the passengers in the higher classes tend to be wealthier and older. Integer Encoding is used to convert ordinal variable to numerical data, for example"
},
{
"code": null,
"e": 2546,
"s": 2484,
"text": "First Class is 1, Business Class is 2, and Economy Class is 3"
},
{
"code": null,
"e": 2696,
"s": 2546,
"text": "The integer values have a natural ordered relationship between each other and machine learning algorithms may be able to learn this relationship [2]."
},
{
"code": null,
"e": 3060,
"s": 2696,
"text": "For categories variables where no such ordinal relationship exists, Integer Encoding could result in poor performance or unexpected results [2]. Fortunately, One-Hot Encoding is a way to combat this. One-Hot Encoding simply creates one column for every possible value and put a 1 in the appropriate column. Below is the equivalent One-Hot Encoding representation."
},
{
"code": null,
"e": 3261,
"s": 3060,
"text": "With One-Hot Encoding, the binary vector arrays representation allows a machine learning algorithm to leverage the information contained in a category value without the confusion caused by ordinality."
},
{
"code": null,
"e": 3811,
"s": 3261,
"text": "However, there is some redundancy in One-Hot encoding. For instance, in the above example, if we know that a passenger’s flight ticket is not First Class and not Economy Class, then it must be Business Class. So we only need to use two of these three dummy-coded variables as a predictor. More generally, the number of dummy-coded variables needed is one less than the number of possible values, which is K-1. In statistics, this is called a dummy encoding variable, or dummy variable. Below is the equivalent dummy encoding variable representation:"
},
{
"code": null,
"e": 4070,
"s": 3811,
"text": "Dummy encoding variable is a standard advice in statistics to avoid the dummy variable trap, However, in the world of machine learning, One-Hot encoding is more recommended because dummy variable trap is not really a problem when applying regularization [3]."
},
{
"code": null,
"e": 4375,
"s": 4070,
"text": "Before we diving into tutorial, let’s first pull up an example dataset we can work with. For this tutorial, we will be working on the Titanic Dataset from Kaggle. This is a very famous dataset and very often is a student’s first step in machine learning. Let’s import pandas and load data to get started."
},
{
"code": null,
"e": 4476,
"s": 4375,
"text": "import pandas as pddef load_data(): return pd.read_csv('data/train.csv')df = load_data()df.head()"
},
{
"code": null,
"e": 4556,
"s": 4476,
"text": "We created a function load_data() to load train.csv file into pandas DataFrame."
},
{
"code": null,
"e": 4662,
"s": 4556,
"text": "Let’s pretend we want to create a One-Hot encoding variable for the Sex column. Here is how we create it."
},
{
"code": null,
"e": 4685,
"s": 4662,
"text": "pd.get_dummies(df.Sex)"
},
{
"code": null,
"e": 4870,
"s": 4685,
"text": "What it does is create one column for every possible value and they are two possible values for Sex. It tells you whether it is female or male by putting a 1 in the appropriate column."
},
{
"code": null,
"e": 4986,
"s": 4870,
"text": "Generally speaking, if we have K possible values for a categorical variable, we will get K columns to represent it."
},
{
"code": null,
"e": 5391,
"s": 4986,
"text": "There is some redundancy in One-Hot encoding. For instance, in the above Sex One-Hot encoding, a person is either male or female. So we only need to use one of these two dummy-coded variables as a predictor. More generally, the number of dummy-coded variables needed is one less than the number of possible values, which is K-1. In statistics, this is called a dummy encoding variable, or dummy variable."
},
{
"code": null,
"e": 5557,
"s": 5391,
"text": "By default, the get_dummies() does not do dummy encoding, but One-Hot encoding. To produce an actual dummy encoding from a DataFrame, we need to pass drop_first=True"
},
{
"code": null,
"e": 5597,
"s": 5557,
"text": "pd.get_dummies(df.Sex, drop_first=True)"
},
{
"code": null,
"e": 5817,
"s": 5597,
"text": "By default, get_dummies() use variable values as column names. For instance, male and female in the above Sex column example. To identify where the dummy variables came from, we can use the prefix argument. For example:"
},
{
"code": null,
"e": 5854,
"s": 5817,
"text": "pd.get_dummies(df.Sex, prefix='Sex')"
},
{
"code": null,
"e": 6050,
"s": 5854,
"text": "Now, let’s try to get One-Hot encoding for a variable that has more than two possible values. For instance, there is an Embarked column and we can do value_counts() to check its different values."
},
{
"code": null,
"e": 6129,
"s": 6050,
"text": "df.Embarked.value_counts()S 644C 168Q 77Name: Embarked, dtype: int64"
},
{
"code": null,
"e": 6162,
"s": 6129,
"text": "Let’s use get_dummies() for that"
},
{
"code": null,
"e": 6209,
"s": 6162,
"text": "pd.get_dummies(df.Embarked, prefix='Embarked')"
},
{
"code": null,
"e": 6385,
"s": 6209,
"text": "You might be thinking we have still got to attach the One-Hot encoding variables to the DataFrame. To do that, we first assign the output to a variable called embarked_dummies"
},
{
"code": null,
"e": 6451,
"s": 6385,
"text": "embarked_dummies = pd.get_dummies(df.Embarked, prefix='Embarked')"
},
{
"code": null,
"e": 6524,
"s": 6451,
"text": "Then, we use pd.concat() to attach embarked_dummies to the DataFrame df."
},
{
"code": null,
"e": 6571,
"s": 6524,
"text": "df = pd.concat([df, embarked_dummies], axis=1)"
},
{
"code": null,
"e": 6794,
"s": 6571,
"text": "The way pd.concat() works is we can concatenate columns side by side or rows on top of one another. So in this case, we concatenate df and embarked_dummies along columns (axis =1). In the end, we overwrite the original df."
},
{
"code": null,
"e": 6890,
"s": 6794,
"text": "By running df.head(), we can see that we’ve now got the Embarked_C, Embarked_Q, and Embarked_S."
},
{
"code": null,
"e": 6972,
"s": 6890,
"text": "We have been passing a Series to get_dummies(), but we’re gonna pass a DataFrame."
},
{
"code": null,
"e": 7059,
"s": 6972,
"text": "df = load_data() # reset dataframedf = pd.get_dummies(df, columns=['Sex', 'Embarked'])"
},
{
"code": null,
"e": 7167,
"s": 7059,
"text": "df is a DataFrame. We pass columns a list and we tell it Sex and Embarked are the columns we want to dummy."
},
{
"code": null,
"e": 7307,
"s": 7167,
"text": "By running df.head(), we can see that the original Sex column and Embarked column are gone, they have been replaced with the dummy columns."
},
{
"code": null,
"e": 7327,
"s": 7307,
"text": "Thanks for reading."
},
{
"code": null,
"e": 7390,
"s": 7327,
"text": "Please checkout the notebook on my Github for the source code."
},
{
"code": null,
"e": 7468,
"s": 7390,
"text": "Stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 7506,
"s": 7468,
"text": "[1] Categorical variable in Wikipedia"
},
{
"code": null,
"e": 7551,
"s": 7506,
"text": "[2] Why one-hot encoding in machine learning"
}
] |
HTML course | Building Main Content - Section 3 - GeeksforGeeks | 10 Aug, 2021
Course Navigation
In the previous article we have seen the 3-Column layout and completed the Section 2 of the main content. The main content of the website is now almost complete. We just need to build the Section 3 of the main content. The Section 3 is shown in the below image:
If you look at the above image carefully then it can be seen that the Section 3 is almost the same as that of the Section 2 of the Website. The only difference is that it has 4 columns instead of 3 and every column has an image at the top before the title.Let’s start writing HTML for Section 3 of our Website, follow the below steps:
Declare a parent div with a class named row.Declare four div’s inside the parent row div to contain four columns and assign them id’s as column21, column22, column23 and column24 respectively.Download the images from given links and save them to your images folder. Column 1 Image.Column 2 Image.Column 3 Image.Column 4 Image.For Each Column: Use <img> tag to insert image for the respective column.Declare a div with class = “img-title”. For the title of the column.Declare a paragraph p element for the description of the content.Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag.
Declare a parent div with a class named row.
Declare four div’s inside the parent row div to contain four columns and assign them id’s as column21, column22, column23 and column24 respectively.
Download the images from given links and save them to your images folder. Column 1 Image.Column 2 Image.Column 3 Image.Column 4 Image.
Column 1 Image.
Column 2 Image.
Column 3 Image.
Column 4 Image.
For Each Column: Use <img> tag to insert image for the respective column.Declare a div with class = “img-title”. For the title of the column.Declare a paragraph p element for the description of the content.Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag.
Use <img> tag to insert image for the respective column.
Declare a div with class = “img-title”. For the title of the column.
Declare a paragraph p element for the description of the content.
Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag.
Below is the complete HTML code for the Section 3 of the Main Content:
HTML
<!-- Section 3 of Main content --><section class="container" id="section-3"> <div id="row"> <!-- Column 1 --> <div id="column21"> <img src="images/writer.jpg" class="image image-full"> <div class="img-title"> <h3>Technical Content Writer</h3> </div> <p> The work requires understanding of Computer Science concepts. Candidates who are active on Practice Portal will be preferred. </p> <a href="https://www.geeksforgeeks.org/careers/" target="_blank" class="button"> Apply Here </a> </div> <!-- Column 2 --> <div id="column22"> <img src="images/developer.jpg" class="image image-full"> <div class="img-title"> <h3>Software Developer</h3> </div> <p> Good knowledge of PHP, JavaScript, Amazon AWS and Web Development in general. Candidates who are active on Practice Portal will be preferred. </p> <a href="https://www.geeksforgeeks.org/careers/" target="_blank" class="button"> Apply Here </a> </div> <!-- Column 3 --> <div id="column23"> <img src="images/support.jpg" class="image image-full"> <div class="img-title"> <h3>Teaching Assistant</h3> </div> <p> It involves taking the doubt sessions, coordinating with mentors and requires in-depth knowledge of Data Structures and Algorithms. </p> <a href="https://www.geeksforgeeks.org/careers/" target="_blank" class="button"> Apply Here </a> </div> <!-- Column 4 --> <div id="column24"> <img src="images/teacher.jpg" class="image image-full"> <div class="img-title"> <h3>Mentor / Tutor</h3> </div> <p> Job involves teaching, problem solving in classes as well as doubt sessions and thus requires in-depth knowledge of Data Structures and Algorithms. </p> <a href="https://www.geeksforgeeks.org/careers/" target="_blank" class="button"> Apply Here </a> </div> </div></section>
On running the index.html file in the browser now, you will be able to see the content of Section 3 in a distorted order as that of Section 2 before adding CSS.Therefore, let’s start adding styles to the classes and complete Section 3 of Main Content:
Adding basic styles for layout: Firstly, set the overflow to hidden and add all the required margins and paddings. Next is to give the thin 1px border at the top of the section to separate it from the previous section and align all the text inside it to the center.Add below CSS code to your style.css file:
CSS
#section-3{ overflow: hidden; padding-top: 5em; border-top: 1px solid rgba(0, 0, 0, 0.2); text-align: center;}
Aligning Columns In-line: The next step is to align all the columns in a single line one after the other. To do this, add the below CSS code to your style.css file:
CSS
/* Add fixed width for each column and align text to center */#column21,#column22,#column23,#column24{ width: 282px; text-align: center;} /* Float first 3 columns to left */ #column21,#column22,#column23,#column24 { width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { float: left; margin: auto 25px;}
Styling the Title of columns: The next good thing to do is to style the title of the columns present just below the images. To give them appropriate font-sizes, padding color etc. apart from the default values. Add the below CSS code to your style.css file:
CSS
.img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);}
Styling the images: We have added two classes for our images in the column, namely image and image-full.
CSS
.image{ display: inline-block; border: 1px solid rgba(0, 0, 0, .5); border-radius: 5px;} .image img{ display: block; width: 100%;} .image-full{ display: block; width: 100%; margin: 0 0 3em 0;} .img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);}
The Complete CSS code for Section 3 of the Main Content of the website is given below:
CSS
/*****************************************//* Styling Main Content Section 3 *//*****************************************/ #section-3{ overflow: hidden; padding-top: 5em; border-top: 1px solid rgba(0, 0, 0, 0.2); text-align: center;} .image{ display: inline-block; border: 1px solid rgba(0, 0, 0, .5); border-radius: 5px;} .image img{ display: block; width: 100%;} .image-full{ display: block; width: 100%; margin: 0 0 3em 0;} .img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);} /* Add fixed width for each column and align text to center */#column21,#column22,#column23,#column24{ width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { float: left; margin: auto 25px;}
With this the Section 3 of the main content is successfully completed and will now look something as shown in the below image:
Supported Browser:
Google Chrome
Microsoft Edge
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.
ghoshsuman0129
ysachin2314
HTML-course-basic
HTML5
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 29988,
"s": 29960,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 30008,
"s": 29988,
"text": "Course Navigation "
},
{
"code": null,
"e": 30272,
"s": 30008,
"text": "In the previous article we have seen the 3-Column layout and completed the Section 2 of the main content. The main content of the website is now almost complete. We just need to build the Section 3 of the main content. The Section 3 is shown in the below image: "
},
{
"code": null,
"e": 30608,
"s": 30272,
"text": "If you look at the above image carefully then it can be seen that the Section 3 is almost the same as that of the Section 2 of the Website. The only difference is that it has 4 columns instead of 3 and every column has an image at the top before the title.Let’s start writing HTML for Section 3 of our Website, follow the below steps: "
},
{
"code": null,
"e": 31333,
"s": 30608,
"text": "Declare a parent div with a class named row.Declare four div’s inside the parent row div to contain four columns and assign them id’s as column21, column22, column23 and column24 respectively.Download the images from given links and save them to your images folder. Column 1 Image.Column 2 Image.Column 3 Image.Column 4 Image.For Each Column: Use <img> tag to insert image for the respective column.Declare a div with class = “img-title”. For the title of the column.Declare a paragraph p element for the description of the content.Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag."
},
{
"code": null,
"e": 31378,
"s": 31333,
"text": "Declare a parent div with a class named row."
},
{
"code": null,
"e": 31527,
"s": 31378,
"text": "Declare four div’s inside the parent row div to contain four columns and assign them id’s as column21, column22, column23 and column24 respectively."
},
{
"code": null,
"e": 31662,
"s": 31527,
"text": "Download the images from given links and save them to your images folder. Column 1 Image.Column 2 Image.Column 3 Image.Column 4 Image."
},
{
"code": null,
"e": 31678,
"s": 31662,
"text": "Column 1 Image."
},
{
"code": null,
"e": 31694,
"s": 31678,
"text": "Column 2 Image."
},
{
"code": null,
"e": 31710,
"s": 31694,
"text": "Column 3 Image."
},
{
"code": null,
"e": 31726,
"s": 31710,
"text": "Column 4 Image."
},
{
"code": null,
"e": 32125,
"s": 31726,
"text": "For Each Column: Use <img> tag to insert image for the respective column.Declare a div with class = “img-title”. For the title of the column.Declare a paragraph p element for the description of the content.Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag."
},
{
"code": null,
"e": 32182,
"s": 32125,
"text": "Use <img> tag to insert image for the respective column."
},
{
"code": null,
"e": 32251,
"s": 32182,
"text": "Declare a div with class = “img-title”. For the title of the column."
},
{
"code": null,
"e": 32317,
"s": 32251,
"text": "Declare a paragraph p element for the description of the content."
},
{
"code": null,
"e": 32510,
"s": 32317,
"text": "Declare an anchor tag <a> to add an external link which will be styled as a button. We will use the same button we created in the last article. So, assign the class “button” to the anchor tag."
},
{
"code": null,
"e": 32583,
"s": 32510,
"text": "Below is the complete HTML code for the Section 3 of the Main Content: "
},
{
"code": null,
"e": 32588,
"s": 32583,
"text": "HTML"
},
{
"code": "<!-- Section 3 of Main content --><section class=\"container\" id=\"section-3\"> <div id=\"row\"> <!-- Column 1 --> <div id=\"column21\"> <img src=\"images/writer.jpg\" class=\"image image-full\"> <div class=\"img-title\"> <h3>Technical Content Writer</h3> </div> <p> The work requires understanding of Computer Science concepts. Candidates who are active on Practice Portal will be preferred. </p> <a href=\"https://www.geeksforgeeks.org/careers/\" target=\"_blank\" class=\"button\"> Apply Here </a> </div> <!-- Column 2 --> <div id=\"column22\"> <img src=\"images/developer.jpg\" class=\"image image-full\"> <div class=\"img-title\"> <h3>Software Developer</h3> </div> <p> Good knowledge of PHP, JavaScript, Amazon AWS and Web Development in general. Candidates who are active on Practice Portal will be preferred. </p> <a href=\"https://www.geeksforgeeks.org/careers/\" target=\"_blank\" class=\"button\"> Apply Here </a> </div> <!-- Column 3 --> <div id=\"column23\"> <img src=\"images/support.jpg\" class=\"image image-full\"> <div class=\"img-title\"> <h3>Teaching Assistant</h3> </div> <p> It involves taking the doubt sessions, coordinating with mentors and requires in-depth knowledge of Data Structures and Algorithms. </p> <a href=\"https://www.geeksforgeeks.org/careers/\" target=\"_blank\" class=\"button\"> Apply Here </a> </div> <!-- Column 4 --> <div id=\"column24\"> <img src=\"images/teacher.jpg\" class=\"image image-full\"> <div class=\"img-title\"> <h3>Mentor / Tutor</h3> </div> <p> Job involves teaching, problem solving in classes as well as doubt sessions and thus requires in-depth knowledge of Data Structures and Algorithms. </p> <a href=\"https://www.geeksforgeeks.org/careers/\" target=\"_blank\" class=\"button\"> Apply Here </a> </div> </div></section>",
"e": 35537,
"s": 32588,
"text": null
},
{
"code": null,
"e": 35791,
"s": 35537,
"text": "On running the index.html file in the browser now, you will be able to see the content of Section 3 in a distorted order as that of Section 2 before adding CSS.Therefore, let’s start adding styles to the classes and complete Section 3 of Main Content: "
},
{
"code": null,
"e": 36101,
"s": 35791,
"text": "Adding basic styles for layout: Firstly, set the overflow to hidden and add all the required margins and paddings. Next is to give the thin 1px border at the top of the section to separate it from the previous section and align all the text inside it to the center.Add below CSS code to your style.css file: "
},
{
"code": null,
"e": 36105,
"s": 36101,
"text": "CSS"
},
{
"code": "#section-3{ overflow: hidden; padding-top: 5em; border-top: 1px solid rgba(0, 0, 0, 0.2); text-align: center;}",
"e": 36228,
"s": 36105,
"text": null
},
{
"code": null,
"e": 36394,
"s": 36228,
"text": "Aligning Columns In-line: The next step is to align all the columns in a single line one after the other. To do this, add the below CSS code to your style.css file: "
},
{
"code": null,
"e": 36398,
"s": 36394,
"text": "CSS"
},
{
"code": "/* Add fixed width for each column and align text to center */#column21,#column22,#column23,#column24{ width: 282px; text-align: center;} /* Float first 3 columns to left */ #column21,#column22,#column23,#column24 { width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { float: left; margin: auto 25px;}",
"e": 36746,
"s": 36398,
"text": null
},
{
"code": null,
"e": 37006,
"s": 36746,
"text": "Styling the Title of columns: The next good thing to do is to style the title of the columns present just below the images. To give them appropriate font-sizes, padding color etc. apart from the default values. Add the below CSS code to your style.css file: "
},
{
"code": null,
"e": 37010,
"s": 37006,
"text": "CSS"
},
{
"code": ".img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);}",
"e": 37115,
"s": 37010,
"text": null
},
{
"code": null,
"e": 37221,
"s": 37115,
"text": "Styling the images: We have added two classes for our images in the column, namely image and image-full. "
},
{
"code": null,
"e": 37225,
"s": 37221,
"text": "CSS"
},
{
"code": ".image{ display: inline-block; border: 1px solid rgba(0, 0, 0, .5); border-radius: 5px;} .image img{ display: block; width: 100%;} .image-full{ display: block; width: 100%; margin: 0 0 3em 0;} .img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);}",
"e": 37559,
"s": 37225,
"text": null
},
{
"code": null,
"e": 37648,
"s": 37559,
"text": "The Complete CSS code for Section 3 of the Main Content of the website is given below: "
},
{
"code": null,
"e": 37652,
"s": 37648,
"text": "CSS"
},
{
"code": "/*****************************************//* Styling Main Content Section 3 *//*****************************************/ #section-3{ overflow: hidden; padding-top: 5em; border-top: 1px solid rgba(0, 0, 0, 0.2); text-align: center;} .image{ display: inline-block; border: 1px solid rgba(0, 0, 0, .5); border-radius: 5px;} .image img{ display: block; width: 100%;} .image-full{ display: block; width: 100%; margin: 0 0 3em 0;} .img-title{ display: block; padding-bottom: 1em; font-size: 1em; color: rgba(0, 0, 0, 0.6);} /* Add fixed width for each column and align text to center */#column21,#column22,#column23,#column24{ width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { width: 282px; text-align: center;} #column21,#column22,#column23,#column24 { float: left; margin: auto 25px;}",
"e": 38553,
"s": 37652,
"text": null
},
{
"code": null,
"e": 38685,
"s": 38556,
"text": "With this the Section 3 of the main content is successfully completed and will now look something as shown in the below image: "
},
{
"code": null,
"e": 38709,
"s": 38689,
"text": " Supported Browser:"
},
{
"code": null,
"e": 38723,
"s": 38709,
"text": "Google Chrome"
},
{
"code": null,
"e": 38738,
"s": 38723,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 38746,
"s": 38738,
"text": "Firefox"
},
{
"code": null,
"e": 38752,
"s": 38746,
"text": "Opera"
},
{
"code": null,
"e": 38759,
"s": 38752,
"text": "Safari"
},
{
"code": null,
"e": 38904,
"s": 38767,
"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": 38919,
"s": 38904,
"text": "ghoshsuman0129"
},
{
"code": null,
"e": 38931,
"s": 38919,
"text": "ysachin2314"
},
{
"code": null,
"e": 38949,
"s": 38931,
"text": "HTML-course-basic"
},
{
"code": null,
"e": 38955,
"s": 38949,
"text": "HTML5"
},
{
"code": null,
"e": 38959,
"s": 38955,
"text": "CSS"
},
{
"code": null,
"e": 38964,
"s": 38959,
"text": "HTML"
},
{
"code": null,
"e": 38981,
"s": 38964,
"text": "Web Technologies"
},
{
"code": null,
"e": 38986,
"s": 38981,
"text": "HTML"
},
{
"code": null,
"e": 39084,
"s": 38986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39093,
"s": 39084,
"text": "Comments"
},
{
"code": null,
"e": 39106,
"s": 39093,
"text": "Old Comments"
},
{
"code": null,
"e": 39168,
"s": 39106,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39218,
"s": 39168,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 39276,
"s": 39218,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 39324,
"s": 39276,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39361,
"s": 39324,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 39423,
"s": 39361,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39473,
"s": 39423,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 39533,
"s": 39473,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 39581,
"s": 39533,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Java Program to check the end of a string | To check the end of a string, use the endsWith() method.
Let’s say the following is our string.
String str = "demo";
Now, check for the substring “mo” using the endsWith() method in an if-else condition.
if(str.endsWith("mo")) {
System.out.println("The string ends with the word mo");
} else {
System.out.println("The string does not end with the word mo");
}
The following is the complete example with output.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "demo";
if(str.endsWith("mo")) {
System.out.println("The string ends with the word mo");
} else {
System.out.println("The string does not end with the word mo");
}
}
}
The string ends with the word mo | [
{
"code": null,
"e": 1119,
"s": 1062,
"text": "To check the end of a string, use the endsWith() method."
},
{
"code": null,
"e": 1158,
"s": 1119,
"text": "Let’s say the following is our string."
},
{
"code": null,
"e": 1179,
"s": 1158,
"text": "String str = \"demo\";"
},
{
"code": null,
"e": 1266,
"s": 1179,
"text": "Now, check for the substring “mo” using the endsWith() method in an if-else condition."
},
{
"code": null,
"e": 1428,
"s": 1266,
"text": "if(str.endsWith(\"mo\")) {\n System.out.println(\"The string ends with the word mo\");\n} else {\n System.out.println(\"The string does not end with the word mo\");\n}"
},
{
"code": null,
"e": 1479,
"s": 1428,
"text": "The following is the complete example with output."
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": " Live Demo"
},
{
"code": null,
"e": 1788,
"s": 1490,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"demo\";\n if(str.endsWith(\"mo\")) {\n System.out.println(\"The string ends with the word mo\");\n } else {\n System.out.println(\"The string does not end with the word mo\");\n }\n }\n}"
},
{
"code": null,
"e": 1821,
"s": 1788,
"text": "The string ends with the word mo"
}
] |
Python Program to find whether a no is power of two | In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a number, we need to check that the number is a power of two or not.
We can solve this using two approaches as discussed below.
Live Demo
# power of 2
def find(n):
if (n == 0):
return False
while (n != 1):
if (n % 2 != 0):
return False
n = n // 2
return True
# Driver code
if(find(98)):
print('Yes')
else:
print('No')
No
Live Demo
# power of 2
def find(x):
# if x is 0 or not
return (x and (not(x & (x - 1))) )
# Driver code
if(find(98)):
print('Yes')
else:
print('No')
No
In this article, we have learned how we can check that the given number is a power of two. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1252,
"s": 1150,
"text": "Problem statement − We are given a number, we need to check that the number is a power of two or not."
},
{
"code": null,
"e": 1311,
"s": 1252,
"text": "We can solve this using two approaches as discussed below."
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": " Live Demo"
},
{
"code": null,
"e": 1544,
"s": 1322,
"text": "# power of 2\ndef find(n):\n if (n == 0):\n return False\n while (n != 1):\n if (n % 2 != 0):\n return False\n n = n // 2\n return True\n# Driver code\nif(find(98)):\n print('Yes')\nelse:\n print('No')"
},
{
"code": null,
"e": 1547,
"s": 1544,
"text": "No"
},
{
"code": null,
"e": 1558,
"s": 1547,
"text": " Live Demo"
},
{
"code": null,
"e": 1709,
"s": 1558,
"text": "# power of 2\ndef find(x):\n # if x is 0 or not\n return (x and (not(x & (x - 1))) )\n# Driver code\nif(find(98)):\n print('Yes')\nelse:\n print('No')"
},
{
"code": null,
"e": 1712,
"s": 1709,
"text": "No"
},
{
"code": null,
"e": 1803,
"s": 1712,
"text": "In this article, we have learned how we can check that the given number is a power of two."
}
] |
Get the position of the maximum element in each Row of a Matrix in R Programming - max.col() Function - GeeksforGeeks | 16 Jun, 2020
max.col() function in R Language check for maximum value in each row and returns the column no. for it.
Syntax: max.col(x, ties.method)
Parameters:x: Numeric matrixties.method: It takes random, first, and last as value and returns the position accordingly in case of a tie.
Example 1:
# R program to find positions # of maximum elements of a matrix # Creating matricesm1 <- matrix(c(1:4), 2)m2 <- matrix(c(4, 1, 2, 3), 2)m3 <- matrix(c(1:9), 3, 3) # Calling max.col() functionmax.col(m1)max.col(m2)max.col(m3)
Output:
[1] 2 2
[1] 1 2
[1] 3 3 3
Example 2:
# R program to find positions # of maximum elements of a matrix # Creating matricesm1 <- matrix(c(2, 3, 2, 4), 2)m2 <- matrix(c(2, 3, 2, 4), 2)m3 <- matrix(c(2, 3, 2, 4), 2)m1 # Calling max.col() functionmax.col(m1, ties.method = "random")max.col(m2, ties.method = "first")max.col(m3, ties.method = "last")
Output:
[, 1] [, 2]
[1, ] 2 2
[2, ] 3 4
[1] 2 2
[1] 1 2
[1] 2 2
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Remove rows with NA in one column of R DataFrame
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24794,
"s": 24766,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 24898,
"s": 24794,
"text": "max.col() function in R Language check for maximum value in each row and returns the column no. for it."
},
{
"code": null,
"e": 24930,
"s": 24898,
"text": "Syntax: max.col(x, ties.method)"
},
{
"code": null,
"e": 25068,
"s": 24930,
"text": "Parameters:x: Numeric matrixties.method: It takes random, first, and last as value and returns the position accordingly in case of a tie."
},
{
"code": null,
"e": 25079,
"s": 25068,
"text": "Example 1:"
},
{
"code": "# R program to find positions # of maximum elements of a matrix # Creating matricesm1 <- matrix(c(1:4), 2)m2 <- matrix(c(4, 1, 2, 3), 2)m3 <- matrix(c(1:9), 3, 3) # Calling max.col() functionmax.col(m1)max.col(m2)max.col(m3)",
"e": 25306,
"s": 25079,
"text": null
},
{
"code": null,
"e": 25314,
"s": 25306,
"text": "Output:"
},
{
"code": null,
"e": 25341,
"s": 25314,
"text": "[1] 2 2\n[1] 1 2\n[1] 3 3 3\n"
},
{
"code": null,
"e": 25352,
"s": 25341,
"text": "Example 2:"
},
{
"code": "# R program to find positions # of maximum elements of a matrix # Creating matricesm1 <- matrix(c(2, 3, 2, 4), 2)m2 <- matrix(c(2, 3, 2, 4), 2)m3 <- matrix(c(2, 3, 2, 4), 2)m1 # Calling max.col() functionmax.col(m1, ties.method = \"random\")max.col(m2, ties.method = \"first\")max.col(m3, ties.method = \"last\")",
"e": 25661,
"s": 25352,
"text": null
},
{
"code": null,
"e": 25669,
"s": 25661,
"text": "Output:"
},
{
"code": null,
"e": 25743,
"s": 25669,
"text": " [, 1] [, 2]\n[1, ] 2 2\n[2, ] 3 4\n[1] 2 2\n[1] 1 2\n[1] 2 2\n"
},
{
"code": null,
"e": 25761,
"s": 25743,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 25772,
"s": 25761,
"text": "R Language"
},
{
"code": null,
"e": 25870,
"s": 25772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25928,
"s": 25870,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 25980,
"s": 25928,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26012,
"s": 25980,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26064,
"s": 26012,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26108,
"s": 26064,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26140,
"s": 26108,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26178,
"s": 26140,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26213,
"s": 26178,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26262,
"s": 26213,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
Git: A Complete Guide. Covering the essential commands for a... | by Rahul Pathak | Towards Data Science | In a project where there are multiple collaborators, there can be conflict while building a project. Git & GitHub have provided us with the ultimate solution to such problems. Git simplifies the process of working with other people and makes it easy to collaborate on projects. In this post, we will be covering all the major commands needed to cover the workflow environment.
Here, we will be covering all the basic commands used in a workflow
Creating Repositories
Syncing Repositories
Making Changes
Parallel Development
Initially, we start by creating a repository
git init
The next step is to pull the files form the central or remote repository to your local machine.
git add origin master "link from your github account"git pull origin master
The next step is to add the files created or code developed to the index. This is known as Staging. The files are added to the index.
The index is a staging area where the new commit is prepared.
Also we can check the status. The git status command displays the state of the working directory and the staging area.
git add "file name"git add -A // to add all files in the foldergit status
As the files are added to the index the heart of Git (Commit) comes in to place.
The “commit” command is used to save your changes to the local repository. We need to call it explicitly to see the changes.
git commit -m "your message"git commit -a -m "your message" // to commit all the files
As of now we have created a repository, synced repositories & made changes in the local repository.Now the next step is to perform parallel development.
To check the log of all commits use the command git log
git log
The parallel development consists of: -
Branching
Merging
Rebasing
Let us move ahead and perform Branching
In Git, branches are a part of your everyday development process. Git branches are effectively a pointer to a snapshot of your changes.
git branch branchname
Here it creates a branch called “firstbranch”. In this branch all the files from master branch get copied and the changes can be made available in the created branch without affecting the master branch.
To access the branch we use the command
git checkout branchname ls // lists the file in the branchcat filename //view the contents of file
Once the new branch is made it is important to merge the branch with the master branch for generating production quality code.
The git merge command lets you take the independent lines of development created by git branch and integrate them into a single branch.
git merge firstbranch
There is another way to merge the branches to the master branch. It’s called Rebase. This is more efficient as it’s used to make a linear sequence of commits. It is used for cleaner project history & reduce the number of branches.
git rebase branchname
Please make sure to create files add them & commit them in order for the change to take place and keep your code error free & running.
To Push the code from local repository to remote repository we need to authenticate first. To do that we need SSH key . GitHub uses SHA-1 Algorithm for secure hash which generate a 40 digit hexadecimal code.
ssh-keygen
To generate the ssh key type in the command
cat 'path' // usually id_rsa.pub where the public key is saved
To check whether you have successfully authenticated type in the command
ssh -T [email protected]
A message pops up saying you have successfully authenticated yourself. Once ssh key generated your good to go to push the code from local repository to remote repository. To push the files from local to remote type in the command
git push origin branchname // to push any respective branchgit push origin master // to push master branch
Check your GitHub repositories to see the changes made from your Git
This covers the basic commands of Git.
I hope you all like this post and have understood the basic commands of Git and the workflow environment of Git. Thank you very much :) | [
{
"code": null,
"e": 548,
"s": 171,
"text": "In a project where there are multiple collaborators, there can be conflict while building a project. Git & GitHub have provided us with the ultimate solution to such problems. Git simplifies the process of working with other people and makes it easy to collaborate on projects. In this post, we will be covering all the major commands needed to cover the workflow environment."
},
{
"code": null,
"e": 616,
"s": 548,
"text": "Here, we will be covering all the basic commands used in a workflow"
},
{
"code": null,
"e": 638,
"s": 616,
"text": "Creating Repositories"
},
{
"code": null,
"e": 659,
"s": 638,
"text": "Syncing Repositories"
},
{
"code": null,
"e": 674,
"s": 659,
"text": "Making Changes"
},
{
"code": null,
"e": 695,
"s": 674,
"text": "Parallel Development"
},
{
"code": null,
"e": 740,
"s": 695,
"text": "Initially, we start by creating a repository"
},
{
"code": null,
"e": 749,
"s": 740,
"text": "git init"
},
{
"code": null,
"e": 845,
"s": 749,
"text": "The next step is to pull the files form the central or remote repository to your local machine."
},
{
"code": null,
"e": 921,
"s": 845,
"text": "git add origin master \"link from your github account\"git pull origin master"
},
{
"code": null,
"e": 1055,
"s": 921,
"text": "The next step is to add the files created or code developed to the index. This is known as Staging. The files are added to the index."
},
{
"code": null,
"e": 1117,
"s": 1055,
"text": "The index is a staging area where the new commit is prepared."
},
{
"code": null,
"e": 1236,
"s": 1117,
"text": "Also we can check the status. The git status command displays the state of the working directory and the staging area."
},
{
"code": null,
"e": 1311,
"s": 1236,
"text": "git add \"file name\"git add -A // to add all files in the foldergit status "
},
{
"code": null,
"e": 1392,
"s": 1311,
"text": "As the files are added to the index the heart of Git (Commit) comes in to place."
},
{
"code": null,
"e": 1517,
"s": 1392,
"text": "The “commit” command is used to save your changes to the local repository. We need to call it explicitly to see the changes."
},
{
"code": null,
"e": 1604,
"s": 1517,
"text": "git commit -m \"your message\"git commit -a -m \"your message\" // to commit all the files"
},
{
"code": null,
"e": 1757,
"s": 1604,
"text": "As of now we have created a repository, synced repositories & made changes in the local repository.Now the next step is to perform parallel development."
},
{
"code": null,
"e": 1813,
"s": 1757,
"text": "To check the log of all commits use the command git log"
},
{
"code": null,
"e": 1821,
"s": 1813,
"text": "git log"
},
{
"code": null,
"e": 1861,
"s": 1821,
"text": "The parallel development consists of: -"
},
{
"code": null,
"e": 1871,
"s": 1861,
"text": "Branching"
},
{
"code": null,
"e": 1879,
"s": 1871,
"text": "Merging"
},
{
"code": null,
"e": 1888,
"s": 1879,
"text": "Rebasing"
},
{
"code": null,
"e": 1928,
"s": 1888,
"text": "Let us move ahead and perform Branching"
},
{
"code": null,
"e": 2064,
"s": 1928,
"text": "In Git, branches are a part of your everyday development process. Git branches are effectively a pointer to a snapshot of your changes."
},
{
"code": null,
"e": 2086,
"s": 2064,
"text": "git branch branchname"
},
{
"code": null,
"e": 2289,
"s": 2086,
"text": "Here it creates a branch called “firstbranch”. In this branch all the files from master branch get copied and the changes can be made available in the created branch without affecting the master branch."
},
{
"code": null,
"e": 2329,
"s": 2289,
"text": "To access the branch we use the command"
},
{
"code": null,
"e": 2428,
"s": 2329,
"text": "git checkout branchname ls // lists the file in the branchcat filename //view the contents of file"
},
{
"code": null,
"e": 2555,
"s": 2428,
"text": "Once the new branch is made it is important to merge the branch with the master branch for generating production quality code."
},
{
"code": null,
"e": 2691,
"s": 2555,
"text": "The git merge command lets you take the independent lines of development created by git branch and integrate them into a single branch."
},
{
"code": null,
"e": 2713,
"s": 2691,
"text": "git merge firstbranch"
},
{
"code": null,
"e": 2944,
"s": 2713,
"text": "There is another way to merge the branches to the master branch. It’s called Rebase. This is more efficient as it’s used to make a linear sequence of commits. It is used for cleaner project history & reduce the number of branches."
},
{
"code": null,
"e": 2966,
"s": 2944,
"text": "git rebase branchname"
},
{
"code": null,
"e": 3101,
"s": 2966,
"text": "Please make sure to create files add them & commit them in order for the change to take place and keep your code error free & running."
},
{
"code": null,
"e": 3309,
"s": 3101,
"text": "To Push the code from local repository to remote repository we need to authenticate first. To do that we need SSH key . GitHub uses SHA-1 Algorithm for secure hash which generate a 40 digit hexadecimal code."
},
{
"code": null,
"e": 3320,
"s": 3309,
"text": "ssh-keygen"
},
{
"code": null,
"e": 3364,
"s": 3320,
"text": "To generate the ssh key type in the command"
},
{
"code": null,
"e": 3427,
"s": 3364,
"text": "cat 'path' // usually id_rsa.pub where the public key is saved"
},
{
"code": null,
"e": 3500,
"s": 3427,
"text": "To check whether you have successfully authenticated type in the command"
},
{
"code": null,
"e": 3522,
"s": 3500,
"text": "ssh -T [email protected]"
},
{
"code": null,
"e": 3752,
"s": 3522,
"text": "A message pops up saying you have successfully authenticated yourself. Once ssh key generated your good to go to push the code from local repository to remote repository. To push the files from local to remote type in the command"
},
{
"code": null,
"e": 3860,
"s": 3752,
"text": "git push origin branchname // to push any respective branchgit push origin master // to push master branch "
},
{
"code": null,
"e": 3929,
"s": 3860,
"text": "Check your GitHub repositories to see the changes made from your Git"
},
{
"code": null,
"e": 3968,
"s": 3929,
"text": "This covers the basic commands of Git."
}
] |
Tryit Editor v3.7 | CSS Grid Intro
Tryit: Grid lines | [
{
"code": null,
"e": 24,
"s": 9,
"text": "CSS Grid Intro"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.