title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Distance between two parallel lines - GeeksforGeeks | 18 Mar, 2021
Given are two parallel straight lines with slope m, and different y-intercepts b1 & b2.The task is to find the distance between these two parallel lines.Examples:
Input: m = 2, b1 = 4, b2 = 3
Output: 0.333333
Input: m = -4, b1 = 11, b2 = 23
Output: 0.8
Approach:
Let PQ and RS be the parallel lines, with equations y = mx + b1 y = mx + b2 The distance between these two lines is the distance between the two intersection points of these lines with the perpendicular line.Let that distance be d. So, equation of the line perpendicular to PQ and RS can be y = -x/m Now, solving the perpendicular line with PQ and RS separately to get the intersecting points (x1, y1) & (x2, y2), we get, From PQ, y = mx + b1 y = -x/m (x1, y1) = ( -b1*m/(m^2 + 1), b1/(m^2 + 1)) From RS, y = mx + b2 y = -x/m (x2, y2) = ( -b2*m/(m^2 + 1), b2/(m^2 + 1)) So, d = distance between (x1, y1) and (x2, y2)
Let PQ and RS be the parallel lines, with equations y = mx + b1 y = mx + b2
The distance between these two lines is the distance between the two intersection points of these lines with the perpendicular line.Let that distance be d.
So, equation of the line perpendicular to PQ and RS can be y = -x/m
Now, solving the perpendicular line with PQ and RS separately to get the intersecting points (x1, y1) & (x2, y2), we get,
From PQ, y = mx + b1 y = -x/m (x1, y1) = ( -b1*m/(m^2 + 1), b1/(m^2 + 1))
From RS, y = mx + b2 y = -x/m (x2, y2) = ( -b2*m/(m^2 + 1), b2/(m^2 + 1))
So, d = distance between (x1, y1) and (x2, y2)
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program find the distance// between two parallel lines #include <bits/stdc++.h>using namespace std; // Function to find the distance// between parallel linesdouble dist(double m, double b1, double b2){ double d = fabs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codeint main(){ double m = 2, b1 = 4, b2 = 3; cout << dist(m, b1, b2); return 0;}
// Java program find the distance// between two parallel linesclass GFG{ // Function to find the distance// between parallel linesstatic double dist(double m, double b1, double b2){ double d = Math.abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codepublic static void main(String[] args){ double m = 2, b1 = 4, b2 = 3; System.out.println(dist(m, b1, b2));}} // This code is contributed by Code_Mech.
# Python3 program find the distance# between two parallel lines # Function to find the distance# between parallel linesdef dist(m, b1, b2): d = abs(b2 - b1) / ((m * m) - 1); return d; # Driver Codedef main(): m, b1, b2 =2,4, 3; print(dist(m, b1, b2));if __name__ == '__main__': main() # This code contributed by PrinciRaj1992
// C# program find the distance// between two parallel linesusing System; class GFG{ // Function to find the distance// between parallel linesstatic double dist(double m, double b1, double b2){ double d = Math.Abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codepublic static void Main(){ double m = 2, b1 = 4, b2 = 3; Console.Write(dist(m, b1, b2));}} // This code is contributed by Akanksha Rai
<?php// PHP program find the distance// between two parallel lines // Function to find the distance// between parallel linesfunction dist($m, $b1, $b2){ $d = abs($b2 - $b1) / (($m * $m) - 1); return $d;} // Driver Code$m = 2;$b1 = 4;$b2 = 3; echo dist($m, $b1, $b2); // This code is contributed by Ryuga?>
<script> // javascript program find the distance// between two parallel lines // Function to find the distance// between parallel linesfunction dist(m, b1 , b2){ var d = Math.abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codevar m = 2, b1 = 4, b2 = 3;document.write(dist(m, b1, b2).toFixed(5)); // This code contributed by Princi Singh </script>
0.333333
ankthon
Akanksha_Rai
Code_Mech
princiraj1992
princi singh
school-programming
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull using Divide and Conquer Algorithm
Equation of circle when three points on the circle are given
Circle and Lattice Points
Orientation of 3 ordered points
Program to find slope of a line
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25354,
"s": 25326,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 25519,
"s": 25354,
"text": "Given are two parallel straight lines with slope m, and different y-intercepts b1 & b2.The task is to find the distance between these two parallel lines.Examples: "
},
{
"code": null,
"e": 25610,
"s": 25519,
"text": "Input: m = 2, b1 = 4, b2 = 3\nOutput: 0.333333\n\nInput: m = -4, b1 = 11, b2 = 23\nOutput: 0.8"
},
{
"code": null,
"e": 25623,
"s": 25612,
"text": "Approach: "
},
{
"code": null,
"e": 26247,
"s": 25623,
"text": "Let PQ and RS be the parallel lines, with equations y = mx + b1 y = mx + b2 The distance between these two lines is the distance between the two intersection points of these lines with the perpendicular line.Let that distance be d. So, equation of the line perpendicular to PQ and RS can be y = -x/m Now, solving the perpendicular line with PQ and RS separately to get the intersecting points (x1, y1) & (x2, y2), we get, From PQ, y = mx + b1 y = -x/m (x1, y1) = ( -b1*m/(m^2 + 1), b1/(m^2 + 1)) From RS, y = mx + b2 y = -x/m (x2, y2) = ( -b2*m/(m^2 + 1), b2/(m^2 + 1)) So, d = distance between (x1, y1) and (x2, y2) "
},
{
"code": null,
"e": 26324,
"s": 26247,
"text": "Let PQ and RS be the parallel lines, with equations y = mx + b1 y = mx + b2 "
},
{
"code": null,
"e": 26482,
"s": 26324,
"text": "The distance between these two lines is the distance between the two intersection points of these lines with the perpendicular line.Let that distance be d. "
},
{
"code": null,
"e": 26552,
"s": 26482,
"text": "So, equation of the line perpendicular to PQ and RS can be y = -x/m "
},
{
"code": null,
"e": 26676,
"s": 26552,
"text": "Now, solving the perpendicular line with PQ and RS separately to get the intersecting points (x1, y1) & (x2, y2), we get, "
},
{
"code": null,
"e": 26752,
"s": 26676,
"text": "From PQ, y = mx + b1 y = -x/m (x1, y1) = ( -b1*m/(m^2 + 1), b1/(m^2 + 1)) "
},
{
"code": null,
"e": 26828,
"s": 26752,
"text": "From RS, y = mx + b2 y = -x/m (x2, y2) = ( -b2*m/(m^2 + 1), b2/(m^2 + 1)) "
},
{
"code": null,
"e": 26877,
"s": 26828,
"text": "So, d = distance between (x1, y1) and (x2, y2) "
},
{
"code": null,
"e": 26930,
"s": 26877,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26934,
"s": 26930,
"text": "C++"
},
{
"code": null,
"e": 26939,
"s": 26934,
"text": "Java"
},
{
"code": null,
"e": 26947,
"s": 26939,
"text": "Python3"
},
{
"code": null,
"e": 26950,
"s": 26947,
"text": "C#"
},
{
"code": null,
"e": 26954,
"s": 26950,
"text": "PHP"
},
{
"code": null,
"e": 26965,
"s": 26954,
"text": "Javascript"
},
{
"code": "// C++ program find the distance// between two parallel lines #include <bits/stdc++.h>using namespace std; // Function to find the distance// between parallel linesdouble dist(double m, double b1, double b2){ double d = fabs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codeint main(){ double m = 2, b1 = 4, b2 = 3; cout << dist(m, b1, b2); return 0;}",
"e": 27334,
"s": 26965,
"text": null
},
{
"code": "// Java program find the distance// between two parallel linesclass GFG{ // Function to find the distance// between parallel linesstatic double dist(double m, double b1, double b2){ double d = Math.abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codepublic static void main(String[] args){ double m = 2, b1 = 4, b2 = 3; System.out.println(dist(m, b1, b2));}} // This code is contributed by Code_Mech.",
"e": 27789,
"s": 27334,
"text": null
},
{
"code": "# Python3 program find the distance# between two parallel lines # Function to find the distance# between parallel linesdef dist(m, b1, b2): d = abs(b2 - b1) / ((m * m) - 1); return d; # Driver Codedef main(): m, b1, b2 =2,4, 3; print(dist(m, b1, b2));if __name__ == '__main__': main() # This code contributed by PrinciRaj1992",
"e": 28130,
"s": 27789,
"text": null
},
{
"code": "// C# program find the distance// between two parallel linesusing System; class GFG{ // Function to find the distance// between parallel linesstatic double dist(double m, double b1, double b2){ double d = Math.Abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codepublic static void Main(){ double m = 2, b1 = 4, b2 = 3; Console.Write(dist(m, b1, b2));}} // This code is contributed by Akanksha Rai",
"e": 28585,
"s": 28130,
"text": null
},
{
"code": "<?php// PHP program find the distance// between two parallel lines // Function to find the distance// between parallel linesfunction dist($m, $b1, $b2){ $d = abs($b2 - $b1) / (($m * $m) - 1); return $d;} // Driver Code$m = 2;$b1 = 4;$b2 = 3; echo dist($m, $b1, $b2); // This code is contributed by Ryuga?>",
"e": 28897,
"s": 28585,
"text": null
},
{
"code": "<script> // javascript program find the distance// between two parallel lines // Function to find the distance// between parallel linesfunction dist(m, b1 , b2){ var d = Math.abs(b2 - b1) / ((m * m) - 1); return d;} // Driver Codevar m = 2, b1 = 4, b2 = 3;document.write(dist(m, b1, b2).toFixed(5)); // This code contributed by Princi Singh </script>",
"e": 29279,
"s": 28897,
"text": null
},
{
"code": null,
"e": 29288,
"s": 29279,
"text": "0.333333"
},
{
"code": null,
"e": 29298,
"s": 29290,
"text": "ankthon"
},
{
"code": null,
"e": 29311,
"s": 29298,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29321,
"s": 29311,
"text": "Code_Mech"
},
{
"code": null,
"e": 29335,
"s": 29321,
"text": "princiraj1992"
},
{
"code": null,
"e": 29348,
"s": 29335,
"text": "princi singh"
},
{
"code": null,
"e": 29367,
"s": 29348,
"text": "school-programming"
},
{
"code": null,
"e": 29377,
"s": 29367,
"text": "Geometric"
},
{
"code": null,
"e": 29390,
"s": 29377,
"text": "Mathematical"
},
{
"code": null,
"e": 29403,
"s": 29390,
"text": "Mathematical"
},
{
"code": null,
"e": 29413,
"s": 29403,
"text": "Geometric"
},
{
"code": null,
"e": 29511,
"s": 29413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29558,
"s": 29511,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 29619,
"s": 29558,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 29645,
"s": 29619,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 29677,
"s": 29645,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 29709,
"s": 29677,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 29739,
"s": 29709,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29799,
"s": 29739,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29814,
"s": 29799,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29857,
"s": 29814,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Count number of Object using Python-OpenCV - GeeksforGeeks | 26 Oct, 2021
In this article, we will use image processing to count the number of Objects using OpenCV in Python.
OpenCv: OpenCv is an open-source library that is useful for computer vision applications such as image processing, video processing, facial recognition, and detection, etc.
Numpy: Numpy is a python package for scientific computing. It is a popular math library for Machine Learning. The main Object of Numpy is a multidimensional array.
Matplotlib: Matplotlib is a Python library used for data visualization and graphical plotting of the data.
Step 1: Import required libraries.
Python3
# Import librariesimport cv2import numpy as npimport matplotlib.pyplot as plt
Step 2: We will read the image by using “cv2.imread(image-name)” command & then convert this image into grayscale image using “cv2.cvtColor(image-name, cv2.COLOR_BGR2GRAY)” command.
Python3
image = cv2.imread('coins.jpg')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)plt.imshow(gray, cmap='gray')
Output:
Step 3: For counting, we have to detect the edges but before detecting the edges we have to make the image blur to avoid the noises. Use “cv2.GaussianBlur(image-name, Kernal size, std. deviation)”.
Python3
blur = cv2.GaussianBlur(gray, (11, 11), 0)plt.imshow(blur, cmap='gray')
Output:
Step 4: Now we will detect edges using a canny algorithm, 2nd & 3rd parameters in cv2.canny() function are threshold values. a value between 30 & 150 are consider as an edge for this image.
Python3
canny = cv2.Canny(blur, 30, 150, 3)plt.imshow(canny, cmap='gray')
Output:
Step 5: We can see that edges are not connected. We need to connect the edges, have to make more thiker & visible.
Python3
dilated = cv2.dilate(canny, (1, 1), iterations=0)plt.imshow(dilated, cmap='gray')
Output:
Step 6: Now we have to calculate the contour in the image & convert the image into RGB from BGR & then draw the contours.
Python3
(cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2) plt.imshow(rgb)
Output:
Step 7: Printing the result
Python3
print("coins in the image : ", len(cnt))
Output:
coins in the image: 5
Below is the complete implementation:
Python3
# Import librariesimport cv2import numpy as npimport matplotlib.pyplot as plt image = cv2.imread('coins.jpg')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (11, 11), 0)canny = cv2.Canny(blur, 30, 150, 3)dilated = cv2.dilate(canny, (1, 1), iterations=0) (cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2) print("coins in the image : ", len(cnt))
Output:
coins in the image : 5
sagartomar9927
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 24393,
"s": 24292,
"text": "In this article, we will use image processing to count the number of Objects using OpenCV in Python."
},
{
"code": null,
"e": 24566,
"s": 24393,
"text": "OpenCv: OpenCv is an open-source library that is useful for computer vision applications such as image processing, video processing, facial recognition, and detection, etc."
},
{
"code": null,
"e": 24730,
"s": 24566,
"text": "Numpy: Numpy is a python package for scientific computing. It is a popular math library for Machine Learning. The main Object of Numpy is a multidimensional array."
},
{
"code": null,
"e": 24837,
"s": 24730,
"text": "Matplotlib: Matplotlib is a Python library used for data visualization and graphical plotting of the data."
},
{
"code": null,
"e": 24873,
"s": 24837,
"text": "Step 1: Import required libraries. "
},
{
"code": null,
"e": 24881,
"s": 24873,
"text": "Python3"
},
{
"code": "# Import librariesimport cv2import numpy as npimport matplotlib.pyplot as plt",
"e": 24959,
"s": 24881,
"text": null
},
{
"code": null,
"e": 25141,
"s": 24959,
"text": "Step 2: We will read the image by using “cv2.imread(image-name)” command & then convert this image into grayscale image using “cv2.cvtColor(image-name, cv2.COLOR_BGR2GRAY)” command."
},
{
"code": null,
"e": 25149,
"s": 25141,
"text": "Python3"
},
{
"code": "image = cv2.imread('coins.jpg')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)plt.imshow(gray, cmap='gray')",
"e": 25256,
"s": 25149,
"text": null
},
{
"code": null,
"e": 25264,
"s": 25256,
"text": "Output:"
},
{
"code": null,
"e": 25463,
"s": 25264,
"text": "Step 3: For counting, we have to detect the edges but before detecting the edges we have to make the image blur to avoid the noises. Use “cv2.GaussianBlur(image-name, Kernal size, std. deviation)”. "
},
{
"code": null,
"e": 25471,
"s": 25463,
"text": "Python3"
},
{
"code": "blur = cv2.GaussianBlur(gray, (11, 11), 0)plt.imshow(blur, cmap='gray')",
"e": 25543,
"s": 25471,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25543,
"text": "Output:"
},
{
"code": null,
"e": 25747,
"s": 25556,
"text": "Step 4: Now we will detect edges using a canny algorithm, 2nd & 3rd parameters in cv2.canny() function are threshold values. a value between 30 & 150 are consider as an edge for this image."
},
{
"code": null,
"e": 25755,
"s": 25747,
"text": "Python3"
},
{
"code": "canny = cv2.Canny(blur, 30, 150, 3)plt.imshow(canny, cmap='gray')",
"e": 25821,
"s": 25755,
"text": null
},
{
"code": null,
"e": 25829,
"s": 25821,
"text": "Output:"
},
{
"code": null,
"e": 25945,
"s": 25829,
"text": "Step 5: We can see that edges are not connected. We need to connect the edges, have to make more thiker & visible. "
},
{
"code": null,
"e": 25953,
"s": 25945,
"text": "Python3"
},
{
"code": "dilated = cv2.dilate(canny, (1, 1), iterations=0)plt.imshow(dilated, cmap='gray')",
"e": 26035,
"s": 25953,
"text": null
},
{
"code": null,
"e": 26043,
"s": 26035,
"text": "Output:"
},
{
"code": null,
"e": 26165,
"s": 26043,
"text": "Step 6: Now we have to calculate the contour in the image & convert the image into RGB from BGR & then draw the contours."
},
{
"code": null,
"e": 26173,
"s": 26165,
"text": "Python3"
},
{
"code": "(cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2) plt.imshow(rgb)",
"e": 26377,
"s": 26173,
"text": null
},
{
"code": null,
"e": 26385,
"s": 26377,
"text": "Output:"
},
{
"code": null,
"e": 26413,
"s": 26385,
"text": "Step 7: Printing the result"
},
{
"code": null,
"e": 26421,
"s": 26413,
"text": "Python3"
},
{
"code": "print(\"coins in the image : \", len(cnt))",
"e": 26462,
"s": 26421,
"text": null
},
{
"code": null,
"e": 26470,
"s": 26462,
"text": "Output:"
},
{
"code": null,
"e": 26493,
"s": 26470,
"text": "coins in the image: 5"
},
{
"code": null,
"e": 26531,
"s": 26493,
"text": "Below is the complete implementation:"
},
{
"code": null,
"e": 26539,
"s": 26531,
"text": "Python3"
},
{
"code": "# Import librariesimport cv2import numpy as npimport matplotlib.pyplot as plt image = cv2.imread('coins.jpg')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (11, 11), 0)canny = cv2.Canny(blur, 30, 150, 3)dilated = cv2.dilate(canny, (1, 1), iterations=0) (cnt, hierarchy) = cv2.findContours( dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)cv2.drawContours(rgb, cnt, -1, (0, 255, 0), 2) print(\"coins in the image : \", len(cnt))",
"e": 27052,
"s": 26539,
"text": null
},
{
"code": null,
"e": 27061,
"s": 27052,
"text": "Output: "
},
{
"code": null,
"e": 27085,
"s": 27061,
"text": "coins in the image : 5"
},
{
"code": null,
"e": 27100,
"s": 27085,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27114,
"s": 27100,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 27121,
"s": 27114,
"text": "Python"
},
{
"code": null,
"e": 27219,
"s": 27121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27251,
"s": 27219,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27307,
"s": 27251,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27349,
"s": 27307,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27391,
"s": 27349,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27413,
"s": 27391,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27452,
"s": 27413,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27483,
"s": 27452,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27538,
"s": 27483,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27567,
"s": 27538,
"text": "Create a directory in Python"
}
] |
How to locate the median in a (Seaborn) KDE plot? | To locate the median in a seaborn KDE plot, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Create random data using numpy.
Find the median of data (Step 2).
Use kdeplot() to plot the shaded region.
Use axvline() method to plot the vertical line.
To display the figure, use show() method.
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.randn(30)
xmedian = np.median(data)
k = sns.kdeplot(x=data, shade=True)
plt.axvline(xmedian, c='red')
plt.show() | [
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To locate the median in a seaborn KDE plot, we can take the following steps"
},
{
"code": null,
"e": 1214,
"s": 1138,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1246,
"s": 1214,
"text": "Create random data using numpy."
},
{
"code": null,
"e": 1280,
"s": 1246,
"text": "Find the median of data (Step 2)."
},
{
"code": null,
"e": 1321,
"s": 1280,
"text": "Use kdeplot() to plot the shaded region."
},
{
"code": null,
"e": 1369,
"s": 1321,
"text": "Use axvline() method to plot the vertical line."
},
{
"code": null,
"e": 1411,
"s": 1369,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1708,
"s": 1411,
"text": "import numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.randn(30)\nxmedian = np.median(data)\nk = sns.kdeplot(x=data, shade=True)\nplt.axvline(xmedian, c='red')\n\nplt.show()"
}
] |
PHP if else elseif | Conditional execution of one or more statements is a most important feature of any programming language. PHP provides this ability with its if, else and elseif statements. Primary usage of if statement is as follows −
if (expression)
statement;
The expression in front of if keyword is a logical expression, evaluated either to TRUE or FALSE. If its value is TRUE, statement in next line is executed, otherwise it is ignored. If there are more than one statements to be executed when the expression is TRUE, statements are grouped by using additional pair of curly brackets,
if (expression){
statement1;
statement2;
..
}
If another staement or a group of statements are required to be executed when expression is FALSE, else keyword is used and one or more statements (inside another pair of curly brackets) are written below it
if (expression){
statement1;
statement2;
..
} else {
statement3;
statement4;
..
}
Following example shows typical use of if and else keywords. It also uses readline() function to read keyboard input in command line execution of following code. It receive marks as input and displays result as pass or fail depending on marks>=50 or not.
Live Demo
<?php
$marks=(int)readline("enter marks: ");
if ($marks>=50){
echo "The result is pass" . "\n";
echo "congratulations" . "\n";
}
else{
echo "The result is Fail". "\n";
echo "Better luck next time" . "\n";
}
?>
This will produce following result −
The result is Fail
Better luck next time
Many a times, if a condition is false, you may require to check if another condition is fulfilled. In this case, another if statement has to be used in else clause of first if statement. There may be a series of cascaded if - else blocks which makes the program tedious. PHP provides elseif statement to address this problem.
As the keyword indicates, elseif is combination of if and else keywords. It works similar to else keyword, with a little difference. Conditional logic of the code has multiple if conditions. The program flow falls through cascade of elseif conditionals and first instance of elseif expression being true, its block is executed and the execution comes out. Last conditional block is a part of else clause, which will be executed only if all preceding if and elseif expressions are false
if (expression){
statement;
}
elseif (expression){
statement;
}
elseif (expression){
statement;
}
.
.
else{
statement;
}
}
In following example, elseif statement is used to calculate grade of student based on marks
Live Demo
<?php
$marks=(int)readline("enter marks: ");
if ($marks<35)
echo "fail";
elseif ($marks<50)
echo "pass class";
elseif ($marks<60)
echo "second class";
elseif ($marks<75)
echo "first class";
else
echo "distinction";
?>
This will produce following result −
fail | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "Conditional execution of one or more statements is a most important feature of any programming language. PHP provides this ability with its if, else and elseif statements. Primary usage of if statement is as follows −"
},
{
"code": null,
"e": 1310,
"s": 1280,
"text": "if (expression)\n statement;"
},
{
"code": null,
"e": 1640,
"s": 1310,
"text": "The expression in front of if keyword is a logical expression, evaluated either to TRUE or FALSE. If its value is TRUE, statement in next line is executed, otherwise it is ignored. If there are more than one statements to be executed when the expression is TRUE, statements are grouped by using additional pair of curly brackets,"
},
{
"code": null,
"e": 1695,
"s": 1640,
"text": "if (expression){\n statement1;\n statement2;\n ..\n}"
},
{
"code": null,
"e": 1903,
"s": 1695,
"text": "If another staement or a group of statements are required to be executed when expression is FALSE, else keyword is used and one or more statements (inside another pair of curly brackets) are written below it"
},
{
"code": null,
"e": 2003,
"s": 1903,
"text": "if (expression){\n statement1;\n statement2;\n ..\n} else {\n statement3;\n statement4;\n ..\n}"
},
{
"code": null,
"e": 2258,
"s": 2003,
"text": "Following example shows typical use of if and else keywords. It also uses readline() function to read keyboard input in command line execution of following code. It receive marks as input and displays result as pass or fail depending on marks>=50 or not."
},
{
"code": null,
"e": 2269,
"s": 2258,
"text": " Live Demo"
},
{
"code": null,
"e": 2491,
"s": 2269,
"text": "<?php\n$marks=(int)readline(\"enter marks: \");\nif ($marks>=50){\n echo \"The result is pass\" . \"\\n\";\n echo \"congratulations\" . \"\\n\";\n}\nelse{\n echo \"The result is Fail\". \"\\n\";\n echo \"Better luck next time\" . \"\\n\";\n}\n?>"
},
{
"code": null,
"e": 2528,
"s": 2491,
"text": "This will produce following result −"
},
{
"code": null,
"e": 2569,
"s": 2528,
"text": "The result is Fail\nBetter luck next time"
},
{
"code": null,
"e": 2895,
"s": 2569,
"text": "Many a times, if a condition is false, you may require to check if another condition is fulfilled. In this case, another if statement has to be used in else clause of first if statement. There may be a series of cascaded if - else blocks which makes the program tedious. PHP provides elseif statement to address this problem."
},
{
"code": null,
"e": 3381,
"s": 2895,
"text": "As the keyword indicates, elseif is combination of if and else keywords. It works similar to else keyword, with a little difference. Conditional logic of the code has multiple if conditions. The program flow falls through cascade of elseif conditionals and first instance of elseif expression being true, its block is executed and the execution comes out. Last conditional block is a part of else clause, which will be executed only if all preceding if and elseif expressions are false"
},
{
"code": null,
"e": 3516,
"s": 3381,
"text": "if (expression){\n statement;\n}\nelseif (expression){\n statement;\n}\nelseif (expression){\n statement;\n}\n.\n.\nelse{\n statement;\n}\n}"
},
{
"code": null,
"e": 3608,
"s": 3516,
"text": "In following example, elseif statement is used to calculate grade of student based on marks"
},
{
"code": null,
"e": 3619,
"s": 3608,
"text": " Live Demo"
},
{
"code": null,
"e": 3852,
"s": 3619,
"text": "<?php\n$marks=(int)readline(\"enter marks: \");\nif ($marks<35)\n echo \"fail\";\nelseif ($marks<50)\n echo \"pass class\";\nelseif ($marks<60)\n echo \"second class\";\nelseif ($marks<75)\n echo \"first class\";\nelse\n echo \"distinction\";\n?>"
},
{
"code": null,
"e": 3889,
"s": 3852,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3894,
"s": 3889,
"text": "fail"
}
] |
How to change the orientation of a slider in JavaFX? | JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider.
In JavaFx you can create a slider by instantiating the javafx.scene.control.Slider class.
The JavaFX slider can be either vertical or horizontal by default on instantiating the Slider class a horizontal slider is created. The orientation property specifies the orientation of the current slider i.e. horizontal or vertical. You can set the value to this property using the setOrientation() method.
To this method you can pass one of the following two constants as a parameter −
Orientation.VERTICAL
Orientation.VERTICAL
Orientation.HORIZONTAL
Orientation.HORIZONTAL
Therefore, to change the orientation of the slider you need to invoke the setOrientation method bypassing one of above two values as a parameter.
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
public class SliderOrientation extends Application {
public void start(Stage stage) {
//Drawing a Sphere
Sphere sphere = new Sphere();
sphere.setRadius(75.0);
sphere.setDrawMode(DrawMode.LINE);
//Creating a slider for rotation
Slider slider1 = new Slider(0, 360, 0);
//Setting its orientation to vertical
slider1.setOrientation(Orientation.VERTICAL);
slider1.setShowTickLabels(true);
slider1.setShowTickMarks(true);
slider1.setMajorTickUnit(90);
slider1.setBlockIncrement(10);
Rotate rotate = new Rotate();
slider1.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){
//Setting the angle for the rotation
rotate.setAngle((double) newValue);
}
});
//Creating a slider for scaling
Slider slider2 = new Slider(0.3, 2.1, 0.6);
//Setting its orientation to Horizontal
slider2.setOrientation(Orientation.HORIZONTAL);
slider2.setShowTickLabels(true);
slider2.setShowTickMarks(true);
slider2.setMajorTickUnit(0.5);
slider2.setBlockIncrement(0.1);
Scale scale = new Scale();
slider2.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){
scale.setX((double) newValue);
scale.setY((double) newValue);
}
});
//Adding all the transformations to the node
sphere.getTransforms().addAll(rotate, scale);
//Creating the pane
BorderPane pane = new BorderPane();
pane.setRight(new VBox(new Label("Rotate"), slider1));
pane.setCenter(sphere);
pane.setLeft(new VBox(new Label("Scale"), slider2));
pane.setPadding(new Insets(10, 10, 10, 10));
//Preparing the scene
Scene scene = new Scene(pane, 595, 330);
stage.setTitle("Slider Orientation");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1377,
"s": 1062,
"text": "JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider."
},
{
"code": null,
"e": 1467,
"s": 1377,
"text": "In JavaFx you can create a slider by instantiating the javafx.scene.control.Slider class."
},
{
"code": null,
"e": 1775,
"s": 1467,
"text": "The JavaFX slider can be either vertical or horizontal by default on instantiating the Slider class a horizontal slider is created. The orientation property specifies the orientation of the current slider i.e. horizontal or vertical. You can set the value to this property using the setOrientation() method."
},
{
"code": null,
"e": 1855,
"s": 1775,
"text": "To this method you can pass one of the following two constants as a parameter −"
},
{
"code": null,
"e": 1876,
"s": 1855,
"text": "Orientation.VERTICAL"
},
{
"code": null,
"e": 1897,
"s": 1876,
"text": "Orientation.VERTICAL"
},
{
"code": null,
"e": 1920,
"s": 1897,
"text": "Orientation.HORIZONTAL"
},
{
"code": null,
"e": 1943,
"s": 1920,
"text": "Orientation.HORIZONTAL"
},
{
"code": null,
"e": 2089,
"s": 1943,
"text": "Therefore, to change the orientation of the slider you need to invoke the setOrientation method bypassing one of above two values as a parameter."
},
{
"code": null,
"e": 4787,
"s": 2089,
"text": "import javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Insets;\nimport javafx.geometry.Orientation;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.shape.DrawMode;\nimport javafx.scene.shape.Sphere;\nimport javafx.scene.transform.Rotate;\nimport javafx.scene.transform.Scale;\nimport javafx.stage.Stage;\npublic class SliderOrientation extends Application {\n public void start(Stage stage) {\n //Drawing a Sphere\n Sphere sphere = new Sphere();\n sphere.setRadius(75.0);\n sphere.setDrawMode(DrawMode.LINE);\n //Creating a slider for rotation\n Slider slider1 = new Slider(0, 360, 0);\n //Setting its orientation to vertical\n slider1.setOrientation(Orientation.VERTICAL);\n slider1.setShowTickLabels(true);\n slider1.setShowTickMarks(true);\n slider1.setMajorTickUnit(90);\n slider1.setBlockIncrement(10);\n Rotate rotate = new Rotate();\n slider1.valueProperty().addListener(new ChangeListener<Number>() {\n public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){\n //Setting the angle for the rotation\n rotate.setAngle((double) newValue);\n }\n });\n //Creating a slider for scaling\n Slider slider2 = new Slider(0.3, 2.1, 0.6);\n //Setting its orientation to Horizontal\n slider2.setOrientation(Orientation.HORIZONTAL);\n slider2.setShowTickLabels(true);\n slider2.setShowTickMarks(true);\n slider2.setMajorTickUnit(0.5);\n slider2.setBlockIncrement(0.1);\n Scale scale = new Scale();\n slider2.valueProperty().addListener(new ChangeListener<Number>() {\n public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){\n scale.setX((double) newValue);\n scale.setY((double) newValue);\n }\n });\n //Adding all the transformations to the node\n sphere.getTransforms().addAll(rotate, scale);\n //Creating the pane\n BorderPane pane = new BorderPane();\n pane.setRight(new VBox(new Label(\"Rotate\"), slider1));\n pane.setCenter(sphere);\n pane.setLeft(new VBox(new Label(\"Scale\"), slider2));\n pane.setPadding(new Insets(10, 10, 10, 10));\n //Preparing the scene\n Scene scene = new Scene(pane, 595, 330);\n stage.setTitle(\"Slider Orientation\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Deep Learning for Detecting Pneumonia from X-ray Images | by Abhinav Sagar | Towards Data Science | Stuck behind the paywall? Click here to read the full story with my Friend Link!
The risk of pneumonia is immense for many, especially in developing nations where billions face energy poverty and rely on polluting forms of energy. The WHO estimates that over 4 million premature deaths occur annually from household air pollution-related diseases including pneumonia. Over 150 million people get infected with pneumonia on an annual basis especially children under 5 years old. In such regions, the problem can be further aggravated due to the dearth of medical resources and personnel. For example, in Africa’s 57 nations, a gap of 2.3 million doctors and nurses exists. For these populations, accurate and fast diagnosis means everything. It can guarantee timely access to treatment and save much needed time and money for those already experiencing poverty.
This project is a part of the Chest X-Ray Images (Pneumonia) held on Kaggle.
Build an algorithm to automatically identify whether a patient is suffering from pneumonia or not by looking at chest X-ray images. The algorithm had to be extremely accurate because lives of people is at stake.
scikit-learnkerasnumpypandasmatplotlib
scikit-learn
keras
numpy
pandas
matplotlib
The dataset can be downloaded from the kaggle website which can be found here.
Without much ado, let’s get started with the code. The complete project on github can be found here.
Let’s start with loading all the libraries and dependencies.
Next I displayed some normal and pneumonia images to just have a look at how much different they look from the naked eye. Well not much!
Then I split the data-set into three sets — train, validation and test sets.
Next I wrote a function in which I did some data augmentation, fed the training and test set images to the network. Also I created labels for the images.
The practice of data augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to “see” more diversified, but still representative, data points during training.
Then I defined a couple of data generators: one for training data, and the other for validation data. A data generator is capable of loading the required amount of data (a mini batch of images) directly from the source folder, convert them into training data (fed to the model) and training targets (a vector of attributes — the supervision signal).
For my experiments, I usually set the batch_size = 64. In general a value between 32 and 128 should work well. Usually you should increase/decrease the batch size according to computational resources and model’s performances.
After that I defined some constants for later usage.
The next step was to build the model. This can be described in the following 5 steps.
I used five convolutional blocks comprised of convolutional layer, max-pooling and batch-normalization.On top of it I used a flatten layer and followed it by four fully connected layers.Also in between I have used dropouts to reduce over-fitting.Activation function was Relu throughout except for the last layer where it was Sigmoid as this is a binary classification problem.I have used Adam as the optimizer and cross-entropy as the loss.
I used five convolutional blocks comprised of convolutional layer, max-pooling and batch-normalization.
On top of it I used a flatten layer and followed it by four fully connected layers.
Also in between I have used dropouts to reduce over-fitting.
Activation function was Relu throughout except for the last layer where it was Sigmoid as this is a binary classification problem.
I have used Adam as the optimizer and cross-entropy as the loss.
Before training the model is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and EarlyStopping.
ModelCheckpoint: when training requires a lot of time to achieve a good result, often many iterations are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends.
EarlyStopping: sometimes, during training we can notice that the generalization gap (i.e. the difference between training and validation error) starts to increase, instead of decreasing. This is a symptom of overfitting that can be solved in many ways (reducing model capacity, increasing training data, data augumentation, regularization, dropout, etc). Often a practical and efficient solution is to stop training when the generalization gap is getting worse.
Next I trained the model for 10 epochs with a batch size of 32. Please note that usually a higher batch size gives better results but at the expense of higher computational burden. Some research also claim that there is an optimal batch size for best results which could be found by investing some time on hyper-parameter tuning.
Let’s visualize the loss and accuracy plots.
So far so good. The model is converging which can be observed from the decrease in loss and validation loss with epochs. Also it is able to reach 90% validation accuracy in just 10 epochs.
Let’s plot the confusion matrix and get some of the other results also like precision, recall, F1 score and accuracy.
CONFUSION MATRIX ------------------[[191 43] [ 13 377]]TEST METRICS ----------------------Accuracy: 91.02564102564102%Precision: 89.76190476190476%Recall: 96.66666666666667%F1-score: 93.08641975308642TRAIN METRIC ----------------------Train acc: 94.23
The model is able to achieve an accuracy of 91.02% which is quite good considering the size of data that is used.
Although this project is far from complete but it is remarkable to see the success of deep learning in such varied real world problems. I have demonstrated how to classify positive and negative pneumonia data from a collection of X-ray images. The model was made from scratch, which separates it from other methods that rely heavily on transfer learning approach. In the future this work could be extended to detect and classify X-ray images consisting of lung cancer and pneumonia. Distinguishing X-ray images that contain lung cancer and pneumonia has been a big issue in recent times, and our next approach should be to tackle this problem.
medium.com
becominghuman.ai
stanfordmlgroup.github.io
The corresponding source code can be found here.
github.com
Happy reading, happy learning and happy coding!
If you want to keep updated with my latest articles and projects follow me on Medium. These are some of my contacts details: | [
{
"code": null,
"e": 253,
"s": 172,
"text": "Stuck behind the paywall? Click here to read the full story with my Friend Link!"
},
{
"code": null,
"e": 1033,
"s": 253,
"text": "The risk of pneumonia is immense for many, especially in developing nations where billions face energy poverty and rely on polluting forms of energy. The WHO estimates that over 4 million premature deaths occur annually from household air pollution-related diseases including pneumonia. Over 150 million people get infected with pneumonia on an annual basis especially children under 5 years old. In such regions, the problem can be further aggravated due to the dearth of medical resources and personnel. For example, in Africa’s 57 nations, a gap of 2.3 million doctors and nurses exists. For these populations, accurate and fast diagnosis means everything. It can guarantee timely access to treatment and save much needed time and money for those already experiencing poverty."
},
{
"code": null,
"e": 1110,
"s": 1033,
"text": "This project is a part of the Chest X-Ray Images (Pneumonia) held on Kaggle."
},
{
"code": null,
"e": 1322,
"s": 1110,
"text": "Build an algorithm to automatically identify whether a patient is suffering from pneumonia or not by looking at chest X-ray images. The algorithm had to be extremely accurate because lives of people is at stake."
},
{
"code": null,
"e": 1361,
"s": 1322,
"text": "scikit-learnkerasnumpypandasmatplotlib"
},
{
"code": null,
"e": 1374,
"s": 1361,
"text": "scikit-learn"
},
{
"code": null,
"e": 1380,
"s": 1374,
"text": "keras"
},
{
"code": null,
"e": 1386,
"s": 1380,
"text": "numpy"
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": "pandas"
},
{
"code": null,
"e": 1404,
"s": 1393,
"text": "matplotlib"
},
{
"code": null,
"e": 1483,
"s": 1404,
"text": "The dataset can be downloaded from the kaggle website which can be found here."
},
{
"code": null,
"e": 1584,
"s": 1483,
"text": "Without much ado, let’s get started with the code. The complete project on github can be found here."
},
{
"code": null,
"e": 1645,
"s": 1584,
"text": "Let’s start with loading all the libraries and dependencies."
},
{
"code": null,
"e": 1782,
"s": 1645,
"text": "Next I displayed some normal and pneumonia images to just have a look at how much different they look from the naked eye. Well not much!"
},
{
"code": null,
"e": 1859,
"s": 1782,
"text": "Then I split the data-set into three sets — train, validation and test sets."
},
{
"code": null,
"e": 2013,
"s": 1859,
"text": "Next I wrote a function in which I did some data augmentation, fed the training and test set images to the network. Also I created labels for the images."
},
{
"code": null,
"e": 2242,
"s": 2013,
"text": "The practice of data augmentation is an effective way to increase the size of the training set. Augmenting the training examples allow the network to “see” more diversified, but still representative, data points during training."
},
{
"code": null,
"e": 2592,
"s": 2242,
"text": "Then I defined a couple of data generators: one for training data, and the other for validation data. A data generator is capable of loading the required amount of data (a mini batch of images) directly from the source folder, convert them into training data (fed to the model) and training targets (a vector of attributes — the supervision signal)."
},
{
"code": null,
"e": 2818,
"s": 2592,
"text": "For my experiments, I usually set the batch_size = 64. In general a value between 32 and 128 should work well. Usually you should increase/decrease the batch size according to computational resources and model’s performances."
},
{
"code": null,
"e": 2871,
"s": 2818,
"text": "After that I defined some constants for later usage."
},
{
"code": null,
"e": 2957,
"s": 2871,
"text": "The next step was to build the model. This can be described in the following 5 steps."
},
{
"code": null,
"e": 3398,
"s": 2957,
"text": "I used five convolutional blocks comprised of convolutional layer, max-pooling and batch-normalization.On top of it I used a flatten layer and followed it by four fully connected layers.Also in between I have used dropouts to reduce over-fitting.Activation function was Relu throughout except for the last layer where it was Sigmoid as this is a binary classification problem.I have used Adam as the optimizer and cross-entropy as the loss."
},
{
"code": null,
"e": 3502,
"s": 3398,
"text": "I used five convolutional blocks comprised of convolutional layer, max-pooling and batch-normalization."
},
{
"code": null,
"e": 3586,
"s": 3502,
"text": "On top of it I used a flatten layer and followed it by four fully connected layers."
},
{
"code": null,
"e": 3647,
"s": 3586,
"text": "Also in between I have used dropouts to reduce over-fitting."
},
{
"code": null,
"e": 3778,
"s": 3647,
"text": "Activation function was Relu throughout except for the last layer where it was Sigmoid as this is a binary classification problem."
},
{
"code": null,
"e": 3843,
"s": 3778,
"text": "I have used Adam as the optimizer and cross-entropy as the loss."
},
{
"code": null,
"e": 3970,
"s": 3843,
"text": "Before training the model is useful to define one or more callbacks. Pretty handy one, are: ModelCheckpoint and EarlyStopping."
},
{
"code": null,
"e": 4208,
"s": 3970,
"text": "ModelCheckpoint: when training requires a lot of time to achieve a good result, often many iterations are required. In this case, it is better to save a copy of the best performing model only when an epoch that improves the metrics ends."
},
{
"code": null,
"e": 4670,
"s": 4208,
"text": "EarlyStopping: sometimes, during training we can notice that the generalization gap (i.e. the difference between training and validation error) starts to increase, instead of decreasing. This is a symptom of overfitting that can be solved in many ways (reducing model capacity, increasing training data, data augumentation, regularization, dropout, etc). Often a practical and efficient solution is to stop training when the generalization gap is getting worse."
},
{
"code": null,
"e": 5000,
"s": 4670,
"text": "Next I trained the model for 10 epochs with a batch size of 32. Please note that usually a higher batch size gives better results but at the expense of higher computational burden. Some research also claim that there is an optimal batch size for best results which could be found by investing some time on hyper-parameter tuning."
},
{
"code": null,
"e": 5045,
"s": 5000,
"text": "Let’s visualize the loss and accuracy plots."
},
{
"code": null,
"e": 5234,
"s": 5045,
"text": "So far so good. The model is converging which can be observed from the decrease in loss and validation loss with epochs. Also it is able to reach 90% validation accuracy in just 10 epochs."
},
{
"code": null,
"e": 5352,
"s": 5234,
"text": "Let’s plot the confusion matrix and get some of the other results also like precision, recall, F1 score and accuracy."
},
{
"code": null,
"e": 5605,
"s": 5352,
"text": "CONFUSION MATRIX ------------------[[191 43] [ 13 377]]TEST METRICS ----------------------Accuracy: 91.02564102564102%Precision: 89.76190476190476%Recall: 96.66666666666667%F1-score: 93.08641975308642TRAIN METRIC ----------------------Train acc: 94.23"
},
{
"code": null,
"e": 5719,
"s": 5605,
"text": "The model is able to achieve an accuracy of 91.02% which is quite good considering the size of data that is used."
},
{
"code": null,
"e": 6363,
"s": 5719,
"text": "Although this project is far from complete but it is remarkable to see the success of deep learning in such varied real world problems. I have demonstrated how to classify positive and negative pneumonia data from a collection of X-ray images. The model was made from scratch, which separates it from other methods that rely heavily on transfer learning approach. In the future this work could be extended to detect and classify X-ray images consisting of lung cancer and pneumonia. Distinguishing X-ray images that contain lung cancer and pneumonia has been a big issue in recent times, and our next approach should be to tackle this problem."
},
{
"code": null,
"e": 6374,
"s": 6363,
"text": "medium.com"
},
{
"code": null,
"e": 6391,
"s": 6374,
"text": "becominghuman.ai"
},
{
"code": null,
"e": 6417,
"s": 6391,
"text": "stanfordmlgroup.github.io"
},
{
"code": null,
"e": 6466,
"s": 6417,
"text": "The corresponding source code can be found here."
},
{
"code": null,
"e": 6477,
"s": 6466,
"text": "github.com"
},
{
"code": null,
"e": 6525,
"s": 6477,
"text": "Happy reading, happy learning and happy coding!"
}
] |
Find minimum and maximum element in an array | Practice | GeeksforGeeks | Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array.
Example 1:
Input:
N = 6
A[] = {3, 2, 1, 56, 10000, 167}
Output:
min = 1, max = 10000
Example 2:
Input:
N = 5
A[] = {1, 345, 234, 21, 56789}
Output:
min = 1, max = 56789
Your Task:
You don't need to read input or print anything. Your task is to complete the function getMinMax() which takes the array A[] and its size N as inputs and returns the minimum and maximum element of the array.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
1 <= Ai <=1012
0
shreyshah17120028 hours ago
def getMinMax( a, n): temp=0 for x in a: if x<temp: temp=x min=temp max=0 for x in a: if x <min: min=x elif x>max: max=x else: pass return min,max
0
piyush4for11 hours ago
pair<int,int> ans; priority_queue<int> getMaximum; priority_queue <int, vector<int>, greater<int>> getMinimum; for(int i=0;i<n;i++){ getMaximum.push(a[i]); getMinimum.push(a[i]); } ans.first = getMinimum.top(); ans.second = getMaximum.top(); return ans;
0
devanshdas14
This comment was deleted.
0
ifeelrook1 day ago
pair<long long, long long> getMinMax(long long a[], int n) {
//Your code here
long long max=a[0];
long long min=a[0];
pair<long long,long long> p;
for(int i=1;i<n;i++){
if(a[i]<min) min=a[i];
if(a[i]>max) max=a[i];
}
p=make_pair(min,max);
return p;
}
0
mukundrssharma2 days ago
class Compute { static pair getMinMax(long a[], long n) { //Write your code here long maxm=-2147483648; long minm=2147483647; for(int i=0;i<n;i++){ if(a[i]>maxm){ maxm=a[i]; } } for(int i=0;i<n;i++){ if(minm>a[i]){ minm=a[i]; } } pair p= new pair(minm,maxm); return p; } }
0
harshscode3 days ago
long long int ma=INT_MIN,mi=INT_MAX;
for(int i=0;i<n;i++)
{
if(a[i]>ma)
ma=a[i];
if(a[i]<mi)
mi=a[i];
}
return {mi,ma};
0
rahilarahman4 days ago
python two liner code:def getMinMax( a, n): a.sort() return a[0], a[n-1]
0
chhetriarjun555554 days ago
struct pair minmax;
minmax.min=arr[0];
minmax.max= arr[0];
for(int i=1;i<n;i++){if (arr[i] > minmax.max) minmax.max = arr[i]; if (arr[i] < minmax.min) minmax.min = arr[i];
}
return minmax;
+1
harshscode4 days ago
long long mi=a[0],ma=a[0]; for(int i=0;i<n;i++) { if(a[i]>ma) ma=a[i]; if(a[i]<mi) mi=a[i]; } return {mi,ma};
+1
hk63017359394 days ago
JAVA SOLUTION.............
class Compute { static pair getMinMax(long a[], long n) { Arrays.sort(a); pair o1 = new pair(a[0],a[a.length-1]); return o1; }}
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": 346,
"s": 238,
"text": "Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array."
},
{
"code": null,
"e": 359,
"s": 348,
"text": "Example 1:"
},
{
"code": null,
"e": 434,
"s": 359,
"text": "Input:\nN = 6\nA[] = {3, 2, 1, 56, 10000, 167}\nOutput:\nmin = 1, max = 10000"
},
{
"code": null,
"e": 447,
"s": 436,
"text": "Example 2:"
},
{
"code": null,
"e": 521,
"s": 447,
"text": "Input:\nN = 5\nA[] = {1, 345, 234, 21, 56789}\nOutput:\nmin = 1, max = 56789"
},
{
"code": null,
"e": 743,
"s": 523,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function getMinMax() which takes the array A[] and its size N as inputs and returns the minimum and maximum element of the array."
},
{
"code": null,
"e": 807,
"s": 745,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 851,
"s": 809,
"text": "Constraints:\n1 <= N <= 105\n1 <= Ai <=1012"
},
{
"code": null,
"e": 853,
"s": 851,
"text": "0"
},
{
"code": null,
"e": 881,
"s": 853,
"text": "shreyshah17120028 hours ago"
},
{
"code": null,
"e": 1107,
"s": 881,
"text": "def getMinMax( a, n): temp=0 for x in a: if x<temp: temp=x min=temp max=0 for x in a: if x <min: min=x elif x>max: max=x else: pass return min,max "
},
{
"code": null,
"e": 1109,
"s": 1107,
"text": "0"
},
{
"code": null,
"e": 1132,
"s": 1109,
"text": "piyush4for11 hours ago"
},
{
"code": null,
"e": 1416,
"s": 1132,
"text": " pair<int,int> ans; priority_queue<int> getMaximum; priority_queue <int, vector<int>, greater<int>> getMinimum; for(int i=0;i<n;i++){ getMaximum.push(a[i]); getMinimum.push(a[i]); } ans.first = getMinimum.top(); ans.second = getMaximum.top(); return ans;"
},
{
"code": null,
"e": 1418,
"s": 1416,
"text": "0"
},
{
"code": null,
"e": 1431,
"s": 1418,
"text": "devanshdas14"
},
{
"code": null,
"e": 1457,
"s": 1431,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1459,
"s": 1457,
"text": "0"
},
{
"code": null,
"e": 1478,
"s": 1459,
"text": "ifeelrook1 day ago"
},
{
"code": null,
"e": 1778,
"s": 1478,
"text": "pair<long long, long long> getMinMax(long long a[], int n) {\n\n //Your code here\n long long max=a[0];\n long long min=a[0];\n pair<long long,long long> p;\n for(int i=1;i<n;i++){\n if(a[i]<min) min=a[i];\n if(a[i]>max) max=a[i];\n }\n p=make_pair(min,max);\n return p;\n}"
},
{
"code": null,
"e": 1782,
"s": 1780,
"text": "0"
},
{
"code": null,
"e": 1807,
"s": 1782,
"text": "mukundrssharma2 days ago"
},
{
"code": null,
"e": 2173,
"s": 1807,
"text": "class Compute { static pair getMinMax(long a[], long n) { //Write your code here long maxm=-2147483648; long minm=2147483647; for(int i=0;i<n;i++){ if(a[i]>maxm){ maxm=a[i]; } } for(int i=0;i<n;i++){ if(minm>a[i]){ minm=a[i]; } } pair p= new pair(minm,maxm); return p; } } "
},
{
"code": null,
"e": 2175,
"s": 2173,
"text": "0"
},
{
"code": null,
"e": 2196,
"s": 2175,
"text": "harshscode3 days ago"
},
{
"code": null,
"e": 2373,
"s": 2196,
"text": " long long int ma=INT_MIN,mi=INT_MAX;\n \n for(int i=0;i<n;i++)\n {\n if(a[i]>ma)\n ma=a[i];\n \n if(a[i]<mi)\n mi=a[i];\n }\n \n return {mi,ma};"
},
{
"code": null,
"e": 2375,
"s": 2373,
"text": "0"
},
{
"code": null,
"e": 2398,
"s": 2375,
"text": "rahilarahman4 days ago"
},
{
"code": null,
"e": 2479,
"s": 2398,
"text": "python two liner code:def getMinMax( a, n): a.sort() return a[0], a[n-1] "
},
{
"code": null,
"e": 2481,
"s": 2479,
"text": "0"
},
{
"code": null,
"e": 2509,
"s": 2481,
"text": "chhetriarjun555554 days ago"
},
{
"code": null,
"e": 2529,
"s": 2509,
"text": "struct pair minmax;"
},
{
"code": null,
"e": 2548,
"s": 2529,
"text": "minmax.min=arr[0];"
},
{
"code": null,
"e": 2568,
"s": 2548,
"text": "minmax.max= arr[0];"
},
{
"code": null,
"e": 2729,
"s": 2570,
"text": "for(int i=1;i<n;i++){if (arr[i] > minmax.max) minmax.max = arr[i]; if (arr[i] < minmax.min) minmax.min = arr[i];"
},
{
"code": null,
"e": 2731,
"s": 2729,
"text": "}"
},
{
"code": null,
"e": 2746,
"s": 2731,
"text": "return minmax;"
},
{
"code": null,
"e": 2751,
"s": 2748,
"text": "+1"
},
{
"code": null,
"e": 2772,
"s": 2751,
"text": "harshscode4 days ago"
},
{
"code": null,
"e": 2925,
"s": 2772,
"text": " long long mi=a[0],ma=a[0]; for(int i=0;i<n;i++) { if(a[i]>ma) ma=a[i]; if(a[i]<mi) mi=a[i]; } return {mi,ma};"
},
{
"code": null,
"e": 2928,
"s": 2925,
"text": "+1"
},
{
"code": null,
"e": 2951,
"s": 2928,
"text": "hk63017359394 days ago"
},
{
"code": null,
"e": 2978,
"s": 2951,
"text": "JAVA SOLUTION............."
},
{
"code": null,
"e": 3132,
"s": 2978,
"text": "class Compute { static pair getMinMax(long a[], long n) { Arrays.sort(a); pair o1 = new pair(a[0],a[a.length-1]); return o1; }}"
},
{
"code": null,
"e": 3278,
"s": 3132,
"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": 3314,
"s": 3278,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3324,
"s": 3314,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3334,
"s": 3324,
"text": "\nContest\n"
},
{
"code": null,
"e": 3397,
"s": 3334,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3545,
"s": 3397,
"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": 3753,
"s": 3545,
"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": 3859,
"s": 3753,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Pseudo-Labeling to deal with small datasets — What, Why & How? | by Anirudh Shenoy | Towards Data Science | A few days ago I came across Yoshua Bengio’s reply to a Quora question — “Why is Unsupervised Learning important?”. Here’s an excerpt of his reply:
To climb the AI ladder with supervised learning may require “teaching” the computer all the concepts that matter to us by showing tons of examples where these concepts occur. This is not how humans learn: yes, thanks to language we get some examples illustrating new named concepts that are given to us, but the bulk of what we observe does not come labeled, at least initially.
His reply makes a lot of sense both from a neuroscientific perspective and a practical perspective. Labeling data is expensive in terms of time as well as money. The obvious solution to this problem is to figure out a way to either:
(a) Make ML algorithms work without labeled data (i.e. Unsupervised Learning)
(b) Automatically label data or use large amounts of unlabeled data along with small amounts of labeled data (i.e. Semi-Supervised Learning)
Unsupervised learning is quite a difficult problem to solve, as Yann LeCun mentions in this article:
“We know the ultimate answer is unsupervised learning, but we don’t have the answer yet.”
However, of late there has been renewed interest in Semi-Supervised Learning which is reflected in both academic and industrial research. Here’s a graph showing the number of research papers related to Semi-Supervised Learning on Google Scholar by year.
In this blog, we’ll take an in-depth look at Pseudo-Labeling — a simple Semi-Supervised Learning (SSL) algorithm. Although Pseudo-Labeling is a naive approach, it gives us an excellent opportunity to understand the challenges with SSL and provides a foundation to learn some of the modern improvements like MixMatch, Virtual Adversarial Training, etc.
What is Pseudo-Labeling?Understanding the Pseudo-Labeling methodImplementing Pseudo-LabelingWhy does Pseudo-Labeling work?When does Pseudo-Labeling not work well?Pseudo-Labeling with conventional ML algorithmsChallenges with Semi-Supervised Learning
What is Pseudo-Labeling?
Understanding the Pseudo-Labeling method
Implementing Pseudo-Labeling
Why does Pseudo-Labeling work?
When does Pseudo-Labeling not work well?
Pseudo-Labeling with conventional ML algorithms
Challenges with Semi-Supervised Learning
First proposed by Lee in 2013 [1], the pseudo-labeling method uses a small set of labeled data along with a large amount of unlabeled data to improve a model’s performance. The technique itself is incredibly simple and follows just 4 basic steps:
Train model on a batch of labeled dataUse the trained model to predict labels on a batch of unlabeled dataUse the predicted labels to calculate the loss on unlabeled dataCombine labeled loss with unlabeled loss and backpropagate
Train model on a batch of labeled data
Use the trained model to predict labels on a batch of unlabeled data
Use the predicted labels to calculate the loss on unlabeled data
Combine labeled loss with unlabeled loss and backpropagate
...and repeat.
This technique might seem quite strange — almost similar to the hundreds of “free energy device” videos on youtube. However, Pseudo-Labeling has been successfully used on several problems. In fact, in a Kaggle competition, a team used Pseudo-Labeling to improve their model’s performance just enough to secure the 1st place and win $25,000.
We’ll take a look at why this works in a bit, for now, let’s look at some details.
Pseudo-labeling trains the network with labeled and unlabeled data simultaneously in each batch. This means for each batch of labeled and unlabeled data, the training loop does:
One single forward pass on the labeled batch to calculate the loss → This is the labeled lossOne forward pass on the unlabeled batch to predict the “pseudo labels” for the unlabeled batchUse this “pseudo label” to calculate the unlabeled loss.
One single forward pass on the labeled batch to calculate the loss → This is the labeled loss
One forward pass on the unlabeled batch to predict the “pseudo labels” for the unlabeled batch
Use this “pseudo label” to calculate the unlabeled loss.
Now instead of simply adding the unlabeled loss with the labeled loss, Lee proposes using weights. The overall loss function looks like this:
Or in simpler words:
In the equation, the weight (alpha) is used to control the contribution of unlabeled data to the overall loss. In addition, the weight is a function of time (epochs) and is slowly increased during training. This allows the model to focus more on the labeled data initially when the performance of the classifier can be bad. As the model’s performance increases over time (epochs), the weight increases and the unlabeled loss has more emphasis on the overall loss.
Lee proposes using the following equation for alpha (t) :
where alpha_f = 3, T1 = 100 and T2 = 600. All of these are hyperparameters that change based on the model and the dataset.
Let’s check how Alpha changes with the epochs:
In the first T1 epochs (100 in this case) the weight is 0 — effectively forcing the model to train only on the labeled data. After T1 epochs, the weight linearly increases to alpha_f (3 in this case) until T2 epochs (600 in this case) — this allows the model to slowly incorporate the unlabeled data. T2 and alpha_f control the rate at which the weight increases and the value after saturation respectively.
If you’re familiar with optimization theory you might recognize this equation from Simulated Annealing.
And that’s all there is to understand Pseudo-Labeling from an implementation perspective. The paper uses MNIST to report performance so we’ll stick to the same dataset which will help us check if our implementation is working correctly.
We’ll use PyTorch 1.3 with CUDA for the implementation, although you should have no problems using Tensorflow/Keras as well.
While the paper uses a simple 3 fully-connected layer network, during testing I found that Conv Nets perform much better. We’ll use a simple 2 Conv Layer + 2 Fully Connected Layer network with dropout (as described in this repo)
We’ll use 1000 labeled images(class balanced) and 59,000 unlabeled images for the train set and 10,000 images for the test set.
First, let’s check the performance on the 1000 labeled images without using any of the unlabeled images (i.e. simple supervised training)
Epoch: 290 : Train Loss : 0.00004 | Test Acc : 95.57000 | Test Loss : 0.233
With 1000 labeled images the best test accuracy is 95.57%. Now that we have a baseline, let’s go ahead with the pseudo-labeling implementation.
For the implementation we’ll make 2 minor changes which make the code simpler and perform better:
In the first 100 epochs, we’ll train the model on the labeled data as usual (no unlabeled data). As we’ve seen earlier, this makes no difference to pseudo-labeling since alpha = 0 during this period anyway.In the next 100+ epochs, we will train on the unlabeled data (with alpha weights). Here for every 50 unlabeled batches, we will train one epoch on the labeled data — this acts as a correcting factor.
In the first 100 epochs, we’ll train the model on the labeled data as usual (no unlabeled data). As we’ve seen earlier, this makes no difference to pseudo-labeling since alpha = 0 during this period anyway.
In the next 100+ epochs, we will train on the unlabeled data (with alpha weights). Here for every 50 unlabeled batches, we will train one epoch on the labeled data — this acts as a correcting factor.
Don’t worry if this sounds confusing, it’s much easier in code. This modification is based on this Github repo and it helps in 2 ways:
It reduces overfitting on the labeled training dataImproves speed since we need to make only 1 forward pass per batch (on the unlabeled data) instead of 2 (unlabeled and labeled) as mentioned in the paper.
It reduces overfitting on the labeled training data
Improves speed since we need to make only 1 forward pass per batch (on the unlabeled data) instead of 2 (unlabeled and labeled) as mentioned in the paper.
Note: I’m not including the code for the supervised training (first 100 epochs) here as it’s very straightforward. You can find all the code in my repo here
Here’s the result after training 100 epochs on labeled data followed by 170 epochs of semi-supervised training:
# Best Accuracy is at 168 epochsEpoch: 168 : Alpha Weight : 3.00000 | Test Acc : 98.46000 | Test Loss : 0.075
After using the unlabelled data we reached an accuracy of 98.46% that’s ~ 3% more than with supervised training. In fact, our results are better than the results from the paper — 95.7% for 1000 labeled samples.
Let’s do some visualization to understand how pseudo-labeling is working under the hood.
Alpha Weight vs Accuracy
It’s clear that as alpha increases the test accuracy also slowly increases and later saturates.
TSNE Visualization
Now let’s have a look at how the pseudo labels are being assigned at every epoch. In the plot below, there are 3 things to note:
The faint color in the background of each cluster is the true label. This is created using TSNE of all 60k training images (labels used)The small circles inside each cluster are from the 1000 training images that were used in the supervised training phase.The small stars that keep moving are the pseudo labels that the model assigns for the unlabeled images for each epoch. (For each epoch I used ~750 randomly sampled unlabeled images to create the plot)
The faint color in the background of each cluster is the true label. This is created using TSNE of all 60k training images (labels used)
The small circles inside each cluster are from the 1000 training images that were used in the supervised training phase.
The small stars that keep moving are the pseudo labels that the model assigns for the unlabeled images for each epoch. (For each epoch I used ~750 randomly sampled unlabeled images to create the plot)
Here are some things to notice:
Most of the pseudo-labels are correct. (Stars are in clusters with the same color) This can be attributed to the high initial test accuracy.As training continues, the percentage of correct pseudo labels increases. This is reflected in the increased overall test accuracy of the model.
Most of the pseudo-labels are correct. (Stars are in clusters with the same color) This can be attributed to the high initial test accuracy.
As training continues, the percentage of correct pseudo labels increases. This is reflected in the increased overall test accuracy of the model.
Here’s a plot that shows the same 750 points at Epoch 0 (left) and Epoch 140 (right). I’ve marked the points that have improved in red circles.
Now let’s find out why pseudo labeling actually works.
The goal of any Semi-Supervised Learning algorithm is to use both the unlabeled and labeled samples to learn the underlying structure of the data. Pseudo-Labeling is able to do this by making two important assumptions:
Continuity Assumption (Smoothness): Points that are close to each other are more likely to share a label. (Wikipedia) In other words, small changes in input do not cause large changes in output. This assumption allows pseudo labeling to conclude that small changes in images like rotation, shearing, etc do not change the label.Cluster Assumption: The data tend to form discrete clusters, and points in the same cluster are more likely to share a label. This is a special case of the continuity assumption (Wikipedia) Another way to look at this is — the decision boundary between classes lies in the low-density region (doing so helps in generalization — similar to maximum margin classifiers like SVM).
Continuity Assumption (Smoothness): Points that are close to each other are more likely to share a label. (Wikipedia) In other words, small changes in input do not cause large changes in output. This assumption allows pseudo labeling to conclude that small changes in images like rotation, shearing, etc do not change the label.
Cluster Assumption: The data tend to form discrete clusters, and points in the same cluster are more likely to share a label. This is a special case of the continuity assumption (Wikipedia) Another way to look at this is — the decision boundary between classes lies in the low-density region (doing so helps in generalization — similar to maximum margin classifiers like SVM).
This is why the initial labeled data is important — it helps the model learn the underlying cluster structure. When we assign a pseudo label in the code, we are using the cluster structure that the model has learned to infer labels for the unlabeled data. As the training progresses, the learned cluster structure is improved using the unlabeled data.
If the initial labeled data is too small in size or contains outliers, pseudo labeling will likely assign incorrect labels to the unlabeled points. The opposite also holds, i.e. pseudo labeling can benefit from a classifier that is already performing well with just the labeled data.
This should make more sense in the next section when we look at scenarios where pseudo-labeling fails.
To understand this scenario better, let’s run a small experiment: Instead of using 1000 initial points let’s take the extreme case and use just 10 labeled points and see how pseudo-labeling performs:
As expected, pseudo-labeling has almost no difference. The model itself is as good as a random model with 10% accuracy. Since each class effectively has just 1 point, the model is incapable of learning the underlying structure for any class.
Let’s increase the number of labeled points to 20 (2 points per class) :
Now the model is performing slightly better as it learns the structure for some classes. Here’s something interesting — notice that pseudo-labeling assigns the correct labels for these points (marked in red in the image below) most likely because there are two labeled points closeby.
And finally, let’s try 50 points:
The performance is much better! And once again, notice the small group of brown labeled points right in the center of the images. The points in the same brown cluster but further away from the labeled points are always incorrectly predicted as Aqua green (‘4’) or Orange (‘7’).
A few things to note:
For all the above experiments (10,20 and 50 points) the way the labeled points were chosen made a huge difference. Any outliers completely changed the model’s performance and predictions for pseudo-labels. This is a common problem with small datasets. (You can read my previous blog where I’ve discussed this in detail)While TSNE is a great tool for visualization, we need to keep in mind that it is probabilistic and merely gives us an idea of how clusters might be distributed in higher-dimensional space.
For all the above experiments (10,20 and 50 points) the way the labeled points were chosen made a huge difference. Any outliers completely changed the model’s performance and predictions for pseudo-labels. This is a common problem with small datasets. (You can read my previous blog where I’ve discussed this in detail)
While TSNE is a great tool for visualization, we need to keep in mind that it is probabilistic and merely gives us an idea of how clusters might be distributed in higher-dimensional space.
To conclude, both the quantity and quality of initial labeled points make a difference when it comes to pseudo-labeling. Further, the model might require different amounts of data for different classes to understand that particular class’s structure.
Let’s see what happens if the labeled dataset does not contain one class (eg: ‘7’ not included in the labeled set, but the unlabeled data still retains all classes)
After training 100 epochs on the labeled data:
Test Acc : 85.63000 | Test Loss : 1.555
And after semi-supervised training :
Epoch: 99 : Alpha Weight : 2.50000 | Test Acc : 87.98000 | Test Loss : 2.987
The overall accuracy does increase from 85.6% to 87.98% but does not show any improvements after that. This is obviously because the model is unable to learn the cluster structure for the class label ‘7’.
The animations below should make these clear:
It’s no surprise that pseudo-labeling struggles here as our model does not have the capability to learn about classes that it has never seen before. However, over the past few years, a lot of interest has been shown in Zero-Shot Learning techniques which enable models to recognize labels even if they do not exist in the training data.
In some cases, the model might not have enough complexity to take advantage of the additional data. This usually happens when using pseudo-labeling with conventional ML algorithms like Logistic Regression or SVMs. When it comes to Deep Learning models, as Andrew Ng mentions in his Coursera course — Large DL models almost always benefit from having more data.
In this section, we’ll apply the pseudo-labeling concept to Logistic Regression. We’ll use the same MNIST dataset with 1000 labeled images, 59000 unlabeled images, and 10000 test images.
We’ll first normalize all the images, followed by PCA decomposition from 784 dimensions to 50 dimensions. Following this, we’ll use sklearn’s PolynomialFeatures() with degree = 2 to add interaction and quadratic features. This leaves us with 1326 features per data point.
Before we get started on pseudo-labeling let’s check how Logistic Regression performs when the training dataset size is slowly increased. This will help us understand if the model can benefit from pseudo-labeling.
As the number of samples in the training dataset increases from 100 to 1000 we see that the accuracy slowly increases. Further, it looks like the accuracy is not stagnating and is following an upward trend. From this, we can conclude that pseudo-labeling should give us a boost in performance here.
Let’s check the test accuracy when Logistic Regression uses only the 1000 labeled images. We’ll do 10 training runs to account for any variations in test scores.
from sklearn.linear_model import SGDClassifiertest_acc = []for _ in range(10): log_reg = SGDClassifier(loss = 'log', n_jobs = -1, alpha = 1e-5) log_reg.fit(x_train_poly, y_train) y_test_pred = log_reg.predict(x_test_poly) test_acc.append(accuracy_score(y_test_pred, y_test)) print('Test Accuracy: {:.2f}%'.format(np.array(test_acc).mean()*100))Output:Test Accuracy: 90.86%
Our baseline test accuracy using Logistic Regression is 90.86%
When working with Logistic Regression and other conventional ML algorithms we need to use pseudo-labeling in a slightly different way, although the concept remains the same.
Here are the steps:
We first train a classifier on our labeled train set.Next, we use this classifier to predict the labels on a randomly sampled set from the unlabeled dataset.We combine both the original train set and the predicted set and retrain the classifier on this new dataset.Repeat steps 2 and 3 until all of the unlabeled data has been used.
We first train a classifier on our labeled train set.
Next, we use this classifier to predict the labels on a randomly sampled set from the unlabeled dataset.
We combine both the original train set and the predicted set and retrain the classifier on this new dataset.
Repeat steps 2 and 3 until all of the unlabeled data has been used.
This technique is slightly similar to the one mentioned in this blog. However, here we recursively generate pseudo labels until all unlabeled data have been used. Thresholds can also be used to ensure that pseudo labels are generated only for points that the model is very confident about (though this is not necessary).
Here’s the implementation as a wrapper around a sklearn estimator:
(Complete code is available in the repo)
And now we can use it with Logistic Regression :
from sklearn.linear_model import SGDClassifierlog_reg = SGDClassifier(loss = 'log', n_jobs = -1, alpha = 1e-5)pseudo_labeller = pseudo_labeling( log_reg, x_unlabeled_poly, sample_rate = 0.04, verbose = True )pseudo_labeller.fit(x_train_poly, y_train)y_test_pred = pseudo_labeller.predict(x_test_poly)print('Test Accuracy: {:.2f}%'.format(accuracy_score(y_test_pred, y_test)*100))Output:Test Accuracy: 92.42%
Pseudo-Labeling increased the accuracy from 90.86% to 92.42%. (Non-linear models with higher complexity like XGBoost might perform better)
Here, sample_rate is similar to alpha(t) from the deep learning model example. Previously, alpha was used to control the amount of unlabeled loss that was used, while in this case sample_rate controls how many unlabeled points are used in each iteration.
The sample_rate value itself is a hyperparameter that needs to be tuned based on the dataset and model (similar to T1, T2, and alpha_f). A value of 0.04 worked best for the MNIST + Logistic Regression example.
An interesting modification would be to schedule sample_rate to ramp up as the training progresses exactly similar to alpha(t).
Before we conclude, let’s look at some of the challenges in Semi-Supervised Learning in general.
The primary objective of Semi-Supervised Learning is to use the unlabeled data along with the labeled data to understand the underlying structure of the dataset. The obvious question here is — How to utilize the unlabeled data to achieve this purpose?
In the Pseudo-Labeling technique, we saw that a scheduled weight function ( alpha) was used to slowly combine the unlabeled data with the labeled data. However, the alpha(t) function assumes that the model confidence increases over time and therefore increases the unlabeled loss linearly. This need not be the case as model predictions can sometimes be incorrect. In fact, if the model makes several wrong unlabeled predictions, pseudo-labeling can act like a bad feedback loop and deteriorate performance further. (Ref : Section 3.1 Arazo et al 2019 [2])
One solution for the problem above is to use probability thresholds — similar to what we did with Logistic Regression.
Other Semi-Supervised Learning algorithms use different ways to combine the data, for example, MixMatch uses a 2-step process for guessing the label (for the unlabeled data) followed by MixUp data augmentation to combine the unlabeled data with the labeled data. (Berthelot et al (2019)[3])
Another challenge with Semi-Supervised Learning is to design algorithms that can work with very small amounts of labeled data. As we’ve seen with pseudo labeling, the model works best with 1000 initial labeled samples. However, when the labeled dataset is reduced further (for eg: with 50 points), pseudo-labeling’s performance starts to drop.
Oliver et al. (2018) [4] did a comparison of several Semi-Supervised Learning algorithms and found that Pseudo-Labeling fails on the “two-moons” dataset while other models like VAT and pi-model worked much better.
As shown in the image, VAT and Pi-Model learn a decision boundary that is surprisingly good with just 6 labeled data points (shown in large white and black circles). Pseudo-Labeling on the other hand completely fails and learns a linear decision boundary instead.
I repeated the experiment using the same model that Oliver et al. used and found that pseudo-labeling required anywhere from 30–50 labeled points (depending on the position of the labeled points) to learn the underlying data structure.
To make Semi-Supervised Learning more practical we need algorithms that are highly data-efficient i.e. ones that can work on very small amounts of labeled data.
Oliver et al.[4] mention: “Pseudo-labeling is a simple heuristic which is widely used in practice, likely because of its simplicity and generality” and as we’ve seen it provides a nice way to learn about Semi-Supervised Learning.
Over the last 2–3 years, Semi-Supervised Learning for Image classification has seen some incredible improvements. Unsupervised Data Augmentation (Xie et al (2019) [5]) has achieved 97.3% on CIFAR- 10 with just 4000 Labels. To put that into perspective, DenseNet (Huang et al (2016)[6]) achieved 96.54% on the complete CIFAR-10 dataset in 2016.
It’s really interesting to see how the Machine Learning and Data Science community is moving towards algorithms that either uses less labeled data (like Semi-Supervised Learning, Zero/Few Shot Learning) or smaller datasets altogether (like Transfer Learning). Personally, I believe these developments are critical if we truly want to democratize Artificial Intelligence for all.
If you have any questions feel free to connect with me. I hope you enjoyed!
Github Repo: https://github.com/anirudhshenoy/pseudo_labeling_small_datasets
Dataset: https://www.kaggle.com/oddrationale/mnist-in-csv
Dong-Hyun Lee. “Pseudo-Label : The Simple and Efficient Semi-Supervised Learning Method for Deep Neural Networks” ICML 2013 Workshop : Challenges in Representation Learning (WREPL), Atlanta, Georgia, USA, 2013 (http://deeplearning.net/wp-content/uploads/2013/03/pseudo_label_final.pdf)Eric Arazo, Diego Ortego, Paul Albert, Noel E. O’Connor, Kevin McGuinness. “Pseudo-Labeling and Confirmation Bias in Deep Semi-Supervised Learning” (https://arxiv.org/abs/1908.02983)David Berthelot, Nicholas Carlini, Ian Goodfellow, Nicolas Papernot, Avital Oliver, Colin Raffel. “MixMatch: A Holistic Approach to Semi-Supervised Learning” (https://arxiv.org/abs/1905.02249)“Avital Oliver, Augustus Odena, Colin Raffel, Ekin D. Cubuk, Ian J. Goodfellow. “Realistic Evaluation of Deep Semi-Supervised Learning Algorithms” (https://arxiv.org/abs/1804.09170)Qizhe Xie, Zihang Dai, Eduard Hovy, Minh-Thang Luong, Quoc V. Le. ”Unsupervised Data Augmentation for Consistency Training” (https://arxiv.org/abs/1904.12848)Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger. “Densely Connected Convolutional Networks” (https://arxiv.org/abs/1608.06993)https://github.com/peimengsui/semi_supervised_mnisthttps://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/https://www.quora.com/Why-is-unsupervised-learning-importanthttps://www.wired.com/2014/08/deep-learning-yann-lecun/
Dong-Hyun Lee. “Pseudo-Label : The Simple and Efficient Semi-Supervised Learning Method for Deep Neural Networks” ICML 2013 Workshop : Challenges in Representation Learning (WREPL), Atlanta, Georgia, USA, 2013 (http://deeplearning.net/wp-content/uploads/2013/03/pseudo_label_final.pdf)
Eric Arazo, Diego Ortego, Paul Albert, Noel E. O’Connor, Kevin McGuinness. “Pseudo-Labeling and Confirmation Bias in Deep Semi-Supervised Learning” (https://arxiv.org/abs/1908.02983)
David Berthelot, Nicholas Carlini, Ian Goodfellow, Nicolas Papernot, Avital Oliver, Colin Raffel. “MixMatch: A Holistic Approach to Semi-Supervised Learning” (https://arxiv.org/abs/1905.02249)
“Avital Oliver, Augustus Odena, Colin Raffel, Ekin D. Cubuk, Ian J. Goodfellow. “Realistic Evaluation of Deep Semi-Supervised Learning Algorithms” (https://arxiv.org/abs/1804.09170)
Qizhe Xie, Zihang Dai, Eduard Hovy, Minh-Thang Luong, Quoc V. Le. ”Unsupervised Data Augmentation for Consistency Training” (https://arxiv.org/abs/1904.12848)
Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger. “Densely Connected Convolutional Networks” (https://arxiv.org/abs/1608.06993) | [
{
"code": null,
"e": 319,
"s": 171,
"text": "A few days ago I came across Yoshua Bengio’s reply to a Quora question — “Why is Unsupervised Learning important?”. Here’s an excerpt of his reply:"
},
{
"code": null,
"e": 698,
"s": 319,
"text": "To climb the AI ladder with supervised learning may require “teaching” the computer all the concepts that matter to us by showing tons of examples where these concepts occur. This is not how humans learn: yes, thanks to language we get some examples illustrating new named concepts that are given to us, but the bulk of what we observe does not come labeled, at least initially."
},
{
"code": null,
"e": 931,
"s": 698,
"text": "His reply makes a lot of sense both from a neuroscientific perspective and a practical perspective. Labeling data is expensive in terms of time as well as money. The obvious solution to this problem is to figure out a way to either:"
},
{
"code": null,
"e": 1009,
"s": 931,
"text": "(a) Make ML algorithms work without labeled data (i.e. Unsupervised Learning)"
},
{
"code": null,
"e": 1150,
"s": 1009,
"text": "(b) Automatically label data or use large amounts of unlabeled data along with small amounts of labeled data (i.e. Semi-Supervised Learning)"
},
{
"code": null,
"e": 1251,
"s": 1150,
"text": "Unsupervised learning is quite a difficult problem to solve, as Yann LeCun mentions in this article:"
},
{
"code": null,
"e": 1341,
"s": 1251,
"text": "“We know the ultimate answer is unsupervised learning, but we don’t have the answer yet.”"
},
{
"code": null,
"e": 1595,
"s": 1341,
"text": "However, of late there has been renewed interest in Semi-Supervised Learning which is reflected in both academic and industrial research. Here’s a graph showing the number of research papers related to Semi-Supervised Learning on Google Scholar by year."
},
{
"code": null,
"e": 1947,
"s": 1595,
"text": "In this blog, we’ll take an in-depth look at Pseudo-Labeling — a simple Semi-Supervised Learning (SSL) algorithm. Although Pseudo-Labeling is a naive approach, it gives us an excellent opportunity to understand the challenges with SSL and provides a foundation to learn some of the modern improvements like MixMatch, Virtual Adversarial Training, etc."
},
{
"code": null,
"e": 2197,
"s": 1947,
"text": "What is Pseudo-Labeling?Understanding the Pseudo-Labeling methodImplementing Pseudo-LabelingWhy does Pseudo-Labeling work?When does Pseudo-Labeling not work well?Pseudo-Labeling with conventional ML algorithmsChallenges with Semi-Supervised Learning"
},
{
"code": null,
"e": 2222,
"s": 2197,
"text": "What is Pseudo-Labeling?"
},
{
"code": null,
"e": 2263,
"s": 2222,
"text": "Understanding the Pseudo-Labeling method"
},
{
"code": null,
"e": 2292,
"s": 2263,
"text": "Implementing Pseudo-Labeling"
},
{
"code": null,
"e": 2323,
"s": 2292,
"text": "Why does Pseudo-Labeling work?"
},
{
"code": null,
"e": 2364,
"s": 2323,
"text": "When does Pseudo-Labeling not work well?"
},
{
"code": null,
"e": 2412,
"s": 2364,
"text": "Pseudo-Labeling with conventional ML algorithms"
},
{
"code": null,
"e": 2453,
"s": 2412,
"text": "Challenges with Semi-Supervised Learning"
},
{
"code": null,
"e": 2700,
"s": 2453,
"text": "First proposed by Lee in 2013 [1], the pseudo-labeling method uses a small set of labeled data along with a large amount of unlabeled data to improve a model’s performance. The technique itself is incredibly simple and follows just 4 basic steps:"
},
{
"code": null,
"e": 2929,
"s": 2700,
"text": "Train model on a batch of labeled dataUse the trained model to predict labels on a batch of unlabeled dataUse the predicted labels to calculate the loss on unlabeled dataCombine labeled loss with unlabeled loss and backpropagate"
},
{
"code": null,
"e": 2968,
"s": 2929,
"text": "Train model on a batch of labeled data"
},
{
"code": null,
"e": 3037,
"s": 2968,
"text": "Use the trained model to predict labels on a batch of unlabeled data"
},
{
"code": null,
"e": 3102,
"s": 3037,
"text": "Use the predicted labels to calculate the loss on unlabeled data"
},
{
"code": null,
"e": 3161,
"s": 3102,
"text": "Combine labeled loss with unlabeled loss and backpropagate"
},
{
"code": null,
"e": 3176,
"s": 3161,
"text": "...and repeat."
},
{
"code": null,
"e": 3517,
"s": 3176,
"text": "This technique might seem quite strange — almost similar to the hundreds of “free energy device” videos on youtube. However, Pseudo-Labeling has been successfully used on several problems. In fact, in a Kaggle competition, a team used Pseudo-Labeling to improve their model’s performance just enough to secure the 1st place and win $25,000."
},
{
"code": null,
"e": 3600,
"s": 3517,
"text": "We’ll take a look at why this works in a bit, for now, let’s look at some details."
},
{
"code": null,
"e": 3778,
"s": 3600,
"text": "Pseudo-labeling trains the network with labeled and unlabeled data simultaneously in each batch. This means for each batch of labeled and unlabeled data, the training loop does:"
},
{
"code": null,
"e": 4022,
"s": 3778,
"text": "One single forward pass on the labeled batch to calculate the loss → This is the labeled lossOne forward pass on the unlabeled batch to predict the “pseudo labels” for the unlabeled batchUse this “pseudo label” to calculate the unlabeled loss."
},
{
"code": null,
"e": 4116,
"s": 4022,
"text": "One single forward pass on the labeled batch to calculate the loss → This is the labeled loss"
},
{
"code": null,
"e": 4211,
"s": 4116,
"text": "One forward pass on the unlabeled batch to predict the “pseudo labels” for the unlabeled batch"
},
{
"code": null,
"e": 4268,
"s": 4211,
"text": "Use this “pseudo label” to calculate the unlabeled loss."
},
{
"code": null,
"e": 4410,
"s": 4268,
"text": "Now instead of simply adding the unlabeled loss with the labeled loss, Lee proposes using weights. The overall loss function looks like this:"
},
{
"code": null,
"e": 4431,
"s": 4410,
"text": "Or in simpler words:"
},
{
"code": null,
"e": 4895,
"s": 4431,
"text": "In the equation, the weight (alpha) is used to control the contribution of unlabeled data to the overall loss. In addition, the weight is a function of time (epochs) and is slowly increased during training. This allows the model to focus more on the labeled data initially when the performance of the classifier can be bad. As the model’s performance increases over time (epochs), the weight increases and the unlabeled loss has more emphasis on the overall loss."
},
{
"code": null,
"e": 4953,
"s": 4895,
"text": "Lee proposes using the following equation for alpha (t) :"
},
{
"code": null,
"e": 5076,
"s": 4953,
"text": "where alpha_f = 3, T1 = 100 and T2 = 600. All of these are hyperparameters that change based on the model and the dataset."
},
{
"code": null,
"e": 5123,
"s": 5076,
"text": "Let’s check how Alpha changes with the epochs:"
},
{
"code": null,
"e": 5531,
"s": 5123,
"text": "In the first T1 epochs (100 in this case) the weight is 0 — effectively forcing the model to train only on the labeled data. After T1 epochs, the weight linearly increases to alpha_f (3 in this case) until T2 epochs (600 in this case) — this allows the model to slowly incorporate the unlabeled data. T2 and alpha_f control the rate at which the weight increases and the value after saturation respectively."
},
{
"code": null,
"e": 5635,
"s": 5531,
"text": "If you’re familiar with optimization theory you might recognize this equation from Simulated Annealing."
},
{
"code": null,
"e": 5872,
"s": 5635,
"text": "And that’s all there is to understand Pseudo-Labeling from an implementation perspective. The paper uses MNIST to report performance so we’ll stick to the same dataset which will help us check if our implementation is working correctly."
},
{
"code": null,
"e": 5997,
"s": 5872,
"text": "We’ll use PyTorch 1.3 with CUDA for the implementation, although you should have no problems using Tensorflow/Keras as well."
},
{
"code": null,
"e": 6226,
"s": 5997,
"text": "While the paper uses a simple 3 fully-connected layer network, during testing I found that Conv Nets perform much better. We’ll use a simple 2 Conv Layer + 2 Fully Connected Layer network with dropout (as described in this repo)"
},
{
"code": null,
"e": 6354,
"s": 6226,
"text": "We’ll use 1000 labeled images(class balanced) and 59,000 unlabeled images for the train set and 10,000 images for the test set."
},
{
"code": null,
"e": 6492,
"s": 6354,
"text": "First, let’s check the performance on the 1000 labeled images without using any of the unlabeled images (i.e. simple supervised training)"
},
{
"code": null,
"e": 6568,
"s": 6492,
"text": "Epoch: 290 : Train Loss : 0.00004 | Test Acc : 95.57000 | Test Loss : 0.233"
},
{
"code": null,
"e": 6712,
"s": 6568,
"text": "With 1000 labeled images the best test accuracy is 95.57%. Now that we have a baseline, let’s go ahead with the pseudo-labeling implementation."
},
{
"code": null,
"e": 6810,
"s": 6712,
"text": "For the implementation we’ll make 2 minor changes which make the code simpler and perform better:"
},
{
"code": null,
"e": 7216,
"s": 6810,
"text": "In the first 100 epochs, we’ll train the model on the labeled data as usual (no unlabeled data). As we’ve seen earlier, this makes no difference to pseudo-labeling since alpha = 0 during this period anyway.In the next 100+ epochs, we will train on the unlabeled data (with alpha weights). Here for every 50 unlabeled batches, we will train one epoch on the labeled data — this acts as a correcting factor."
},
{
"code": null,
"e": 7423,
"s": 7216,
"text": "In the first 100 epochs, we’ll train the model on the labeled data as usual (no unlabeled data). As we’ve seen earlier, this makes no difference to pseudo-labeling since alpha = 0 during this period anyway."
},
{
"code": null,
"e": 7623,
"s": 7423,
"text": "In the next 100+ epochs, we will train on the unlabeled data (with alpha weights). Here for every 50 unlabeled batches, we will train one epoch on the labeled data — this acts as a correcting factor."
},
{
"code": null,
"e": 7758,
"s": 7623,
"text": "Don’t worry if this sounds confusing, it’s much easier in code. This modification is based on this Github repo and it helps in 2 ways:"
},
{
"code": null,
"e": 7964,
"s": 7758,
"text": "It reduces overfitting on the labeled training dataImproves speed since we need to make only 1 forward pass per batch (on the unlabeled data) instead of 2 (unlabeled and labeled) as mentioned in the paper."
},
{
"code": null,
"e": 8016,
"s": 7964,
"text": "It reduces overfitting on the labeled training data"
},
{
"code": null,
"e": 8171,
"s": 8016,
"text": "Improves speed since we need to make only 1 forward pass per batch (on the unlabeled data) instead of 2 (unlabeled and labeled) as mentioned in the paper."
},
{
"code": null,
"e": 8328,
"s": 8171,
"text": "Note: I’m not including the code for the supervised training (first 100 epochs) here as it’s very straightforward. You can find all the code in my repo here"
},
{
"code": null,
"e": 8440,
"s": 8328,
"text": "Here’s the result after training 100 epochs on labeled data followed by 170 epochs of semi-supervised training:"
},
{
"code": null,
"e": 8550,
"s": 8440,
"text": "# Best Accuracy is at 168 epochsEpoch: 168 : Alpha Weight : 3.00000 | Test Acc : 98.46000 | Test Loss : 0.075"
},
{
"code": null,
"e": 8761,
"s": 8550,
"text": "After using the unlabelled data we reached an accuracy of 98.46% that’s ~ 3% more than with supervised training. In fact, our results are better than the results from the paper — 95.7% for 1000 labeled samples."
},
{
"code": null,
"e": 8850,
"s": 8761,
"text": "Let’s do some visualization to understand how pseudo-labeling is working under the hood."
},
{
"code": null,
"e": 8875,
"s": 8850,
"text": "Alpha Weight vs Accuracy"
},
{
"code": null,
"e": 8971,
"s": 8875,
"text": "It’s clear that as alpha increases the test accuracy also slowly increases and later saturates."
},
{
"code": null,
"e": 8990,
"s": 8971,
"text": "TSNE Visualization"
},
{
"code": null,
"e": 9119,
"s": 8990,
"text": "Now let’s have a look at how the pseudo labels are being assigned at every epoch. In the plot below, there are 3 things to note:"
},
{
"code": null,
"e": 9576,
"s": 9119,
"text": "The faint color in the background of each cluster is the true label. This is created using TSNE of all 60k training images (labels used)The small circles inside each cluster are from the 1000 training images that were used in the supervised training phase.The small stars that keep moving are the pseudo labels that the model assigns for the unlabeled images for each epoch. (For each epoch I used ~750 randomly sampled unlabeled images to create the plot)"
},
{
"code": null,
"e": 9713,
"s": 9576,
"text": "The faint color in the background of each cluster is the true label. This is created using TSNE of all 60k training images (labels used)"
},
{
"code": null,
"e": 9834,
"s": 9713,
"text": "The small circles inside each cluster are from the 1000 training images that were used in the supervised training phase."
},
{
"code": null,
"e": 10035,
"s": 9834,
"text": "The small stars that keep moving are the pseudo labels that the model assigns for the unlabeled images for each epoch. (For each epoch I used ~750 randomly sampled unlabeled images to create the plot)"
},
{
"code": null,
"e": 10067,
"s": 10035,
"text": "Here are some things to notice:"
},
{
"code": null,
"e": 10352,
"s": 10067,
"text": "Most of the pseudo-labels are correct. (Stars are in clusters with the same color) This can be attributed to the high initial test accuracy.As training continues, the percentage of correct pseudo labels increases. This is reflected in the increased overall test accuracy of the model."
},
{
"code": null,
"e": 10493,
"s": 10352,
"text": "Most of the pseudo-labels are correct. (Stars are in clusters with the same color) This can be attributed to the high initial test accuracy."
},
{
"code": null,
"e": 10638,
"s": 10493,
"text": "As training continues, the percentage of correct pseudo labels increases. This is reflected in the increased overall test accuracy of the model."
},
{
"code": null,
"e": 10782,
"s": 10638,
"text": "Here’s a plot that shows the same 750 points at Epoch 0 (left) and Epoch 140 (right). I’ve marked the points that have improved in red circles."
},
{
"code": null,
"e": 10837,
"s": 10782,
"text": "Now let’s find out why pseudo labeling actually works."
},
{
"code": null,
"e": 11056,
"s": 10837,
"text": "The goal of any Semi-Supervised Learning algorithm is to use both the unlabeled and labeled samples to learn the underlying structure of the data. Pseudo-Labeling is able to do this by making two important assumptions:"
},
{
"code": null,
"e": 11761,
"s": 11056,
"text": "Continuity Assumption (Smoothness): Points that are close to each other are more likely to share a label. (Wikipedia) In other words, small changes in input do not cause large changes in output. This assumption allows pseudo labeling to conclude that small changes in images like rotation, shearing, etc do not change the label.Cluster Assumption: The data tend to form discrete clusters, and points in the same cluster are more likely to share a label. This is a special case of the continuity assumption (Wikipedia) Another way to look at this is — the decision boundary between classes lies in the low-density region (doing so helps in generalization — similar to maximum margin classifiers like SVM)."
},
{
"code": null,
"e": 12090,
"s": 11761,
"text": "Continuity Assumption (Smoothness): Points that are close to each other are more likely to share a label. (Wikipedia) In other words, small changes in input do not cause large changes in output. This assumption allows pseudo labeling to conclude that small changes in images like rotation, shearing, etc do not change the label."
},
{
"code": null,
"e": 12467,
"s": 12090,
"text": "Cluster Assumption: The data tend to form discrete clusters, and points in the same cluster are more likely to share a label. This is a special case of the continuity assumption (Wikipedia) Another way to look at this is — the decision boundary between classes lies in the low-density region (doing so helps in generalization — similar to maximum margin classifiers like SVM)."
},
{
"code": null,
"e": 12819,
"s": 12467,
"text": "This is why the initial labeled data is important — it helps the model learn the underlying cluster structure. When we assign a pseudo label in the code, we are using the cluster structure that the model has learned to infer labels for the unlabeled data. As the training progresses, the learned cluster structure is improved using the unlabeled data."
},
{
"code": null,
"e": 13103,
"s": 12819,
"text": "If the initial labeled data is too small in size or contains outliers, pseudo labeling will likely assign incorrect labels to the unlabeled points. The opposite also holds, i.e. pseudo labeling can benefit from a classifier that is already performing well with just the labeled data."
},
{
"code": null,
"e": 13206,
"s": 13103,
"text": "This should make more sense in the next section when we look at scenarios where pseudo-labeling fails."
},
{
"code": null,
"e": 13406,
"s": 13206,
"text": "To understand this scenario better, let’s run a small experiment: Instead of using 1000 initial points let’s take the extreme case and use just 10 labeled points and see how pseudo-labeling performs:"
},
{
"code": null,
"e": 13648,
"s": 13406,
"text": "As expected, pseudo-labeling has almost no difference. The model itself is as good as a random model with 10% accuracy. Since each class effectively has just 1 point, the model is incapable of learning the underlying structure for any class."
},
{
"code": null,
"e": 13721,
"s": 13648,
"text": "Let’s increase the number of labeled points to 20 (2 points per class) :"
},
{
"code": null,
"e": 14006,
"s": 13721,
"text": "Now the model is performing slightly better as it learns the structure for some classes. Here’s something interesting — notice that pseudo-labeling assigns the correct labels for these points (marked in red in the image below) most likely because there are two labeled points closeby."
},
{
"code": null,
"e": 14040,
"s": 14006,
"text": "And finally, let’s try 50 points:"
},
{
"code": null,
"e": 14318,
"s": 14040,
"text": "The performance is much better! And once again, notice the small group of brown labeled points right in the center of the images. The points in the same brown cluster but further away from the labeled points are always incorrectly predicted as Aqua green (‘4’) or Orange (‘7’)."
},
{
"code": null,
"e": 14340,
"s": 14318,
"text": "A few things to note:"
},
{
"code": null,
"e": 14848,
"s": 14340,
"text": "For all the above experiments (10,20 and 50 points) the way the labeled points were chosen made a huge difference. Any outliers completely changed the model’s performance and predictions for pseudo-labels. This is a common problem with small datasets. (You can read my previous blog where I’ve discussed this in detail)While TSNE is a great tool for visualization, we need to keep in mind that it is probabilistic and merely gives us an idea of how clusters might be distributed in higher-dimensional space."
},
{
"code": null,
"e": 15168,
"s": 14848,
"text": "For all the above experiments (10,20 and 50 points) the way the labeled points were chosen made a huge difference. Any outliers completely changed the model’s performance and predictions for pseudo-labels. This is a common problem with small datasets. (You can read my previous blog where I’ve discussed this in detail)"
},
{
"code": null,
"e": 15357,
"s": 15168,
"text": "While TSNE is a great tool for visualization, we need to keep in mind that it is probabilistic and merely gives us an idea of how clusters might be distributed in higher-dimensional space."
},
{
"code": null,
"e": 15608,
"s": 15357,
"text": "To conclude, both the quantity and quality of initial labeled points make a difference when it comes to pseudo-labeling. Further, the model might require different amounts of data for different classes to understand that particular class’s structure."
},
{
"code": null,
"e": 15773,
"s": 15608,
"text": "Let’s see what happens if the labeled dataset does not contain one class (eg: ‘7’ not included in the labeled set, but the unlabeled data still retains all classes)"
},
{
"code": null,
"e": 15820,
"s": 15773,
"text": "After training 100 epochs on the labeled data:"
},
{
"code": null,
"e": 15860,
"s": 15820,
"text": "Test Acc : 85.63000 | Test Loss : 1.555"
},
{
"code": null,
"e": 15897,
"s": 15860,
"text": "And after semi-supervised training :"
},
{
"code": null,
"e": 15974,
"s": 15897,
"text": "Epoch: 99 : Alpha Weight : 2.50000 | Test Acc : 87.98000 | Test Loss : 2.987"
},
{
"code": null,
"e": 16179,
"s": 15974,
"text": "The overall accuracy does increase from 85.6% to 87.98% but does not show any improvements after that. This is obviously because the model is unable to learn the cluster structure for the class label ‘7’."
},
{
"code": null,
"e": 16225,
"s": 16179,
"text": "The animations below should make these clear:"
},
{
"code": null,
"e": 16562,
"s": 16225,
"text": "It’s no surprise that pseudo-labeling struggles here as our model does not have the capability to learn about classes that it has never seen before. However, over the past few years, a lot of interest has been shown in Zero-Shot Learning techniques which enable models to recognize labels even if they do not exist in the training data."
},
{
"code": null,
"e": 16923,
"s": 16562,
"text": "In some cases, the model might not have enough complexity to take advantage of the additional data. This usually happens when using pseudo-labeling with conventional ML algorithms like Logistic Regression or SVMs. When it comes to Deep Learning models, as Andrew Ng mentions in his Coursera course — Large DL models almost always benefit from having more data."
},
{
"code": null,
"e": 17110,
"s": 16923,
"text": "In this section, we’ll apply the pseudo-labeling concept to Logistic Regression. We’ll use the same MNIST dataset with 1000 labeled images, 59000 unlabeled images, and 10000 test images."
},
{
"code": null,
"e": 17382,
"s": 17110,
"text": "We’ll first normalize all the images, followed by PCA decomposition from 784 dimensions to 50 dimensions. Following this, we’ll use sklearn’s PolynomialFeatures() with degree = 2 to add interaction and quadratic features. This leaves us with 1326 features per data point."
},
{
"code": null,
"e": 17596,
"s": 17382,
"text": "Before we get started on pseudo-labeling let’s check how Logistic Regression performs when the training dataset size is slowly increased. This will help us understand if the model can benefit from pseudo-labeling."
},
{
"code": null,
"e": 17895,
"s": 17596,
"text": "As the number of samples in the training dataset increases from 100 to 1000 we see that the accuracy slowly increases. Further, it looks like the accuracy is not stagnating and is following an upward trend. From this, we can conclude that pseudo-labeling should give us a boost in performance here."
},
{
"code": null,
"e": 18057,
"s": 17895,
"text": "Let’s check the test accuracy when Logistic Regression uses only the 1000 labeled images. We’ll do 10 training runs to account for any variations in test scores."
},
{
"code": null,
"e": 18450,
"s": 18057,
"text": "from sklearn.linear_model import SGDClassifiertest_acc = []for _ in range(10): log_reg = SGDClassifier(loss = 'log', n_jobs = -1, alpha = 1e-5) log_reg.fit(x_train_poly, y_train) y_test_pred = log_reg.predict(x_test_poly) test_acc.append(accuracy_score(y_test_pred, y_test)) print('Test Accuracy: {:.2f}%'.format(np.array(test_acc).mean()*100))Output:Test Accuracy: 90.86%"
},
{
"code": null,
"e": 18513,
"s": 18450,
"text": "Our baseline test accuracy using Logistic Regression is 90.86%"
},
{
"code": null,
"e": 18687,
"s": 18513,
"text": "When working with Logistic Regression and other conventional ML algorithms we need to use pseudo-labeling in a slightly different way, although the concept remains the same."
},
{
"code": null,
"e": 18707,
"s": 18687,
"text": "Here are the steps:"
},
{
"code": null,
"e": 19040,
"s": 18707,
"text": "We first train a classifier on our labeled train set.Next, we use this classifier to predict the labels on a randomly sampled set from the unlabeled dataset.We combine both the original train set and the predicted set and retrain the classifier on this new dataset.Repeat steps 2 and 3 until all of the unlabeled data has been used."
},
{
"code": null,
"e": 19094,
"s": 19040,
"text": "We first train a classifier on our labeled train set."
},
{
"code": null,
"e": 19199,
"s": 19094,
"text": "Next, we use this classifier to predict the labels on a randomly sampled set from the unlabeled dataset."
},
{
"code": null,
"e": 19308,
"s": 19199,
"text": "We combine both the original train set and the predicted set and retrain the classifier on this new dataset."
},
{
"code": null,
"e": 19376,
"s": 19308,
"text": "Repeat steps 2 and 3 until all of the unlabeled data has been used."
},
{
"code": null,
"e": 19697,
"s": 19376,
"text": "This technique is slightly similar to the one mentioned in this blog. However, here we recursively generate pseudo labels until all unlabeled data have been used. Thresholds can also be used to ensure that pseudo labels are generated only for points that the model is very confident about (though this is not necessary)."
},
{
"code": null,
"e": 19764,
"s": 19697,
"text": "Here’s the implementation as a wrapper around a sklearn estimator:"
},
{
"code": null,
"e": 19805,
"s": 19764,
"text": "(Complete code is available in the repo)"
},
{
"code": null,
"e": 19854,
"s": 19805,
"text": "And now we can use it with Logistic Regression :"
},
{
"code": null,
"e": 20293,
"s": 19854,
"text": "from sklearn.linear_model import SGDClassifierlog_reg = SGDClassifier(loss = 'log', n_jobs = -1, alpha = 1e-5)pseudo_labeller = pseudo_labeling( log_reg, x_unlabeled_poly, sample_rate = 0.04, verbose = True )pseudo_labeller.fit(x_train_poly, y_train)y_test_pred = pseudo_labeller.predict(x_test_poly)print('Test Accuracy: {:.2f}%'.format(accuracy_score(y_test_pred, y_test)*100))Output:Test Accuracy: 92.42%"
},
{
"code": null,
"e": 20432,
"s": 20293,
"text": "Pseudo-Labeling increased the accuracy from 90.86% to 92.42%. (Non-linear models with higher complexity like XGBoost might perform better)"
},
{
"code": null,
"e": 20687,
"s": 20432,
"text": "Here, sample_rate is similar to alpha(t) from the deep learning model example. Previously, alpha was used to control the amount of unlabeled loss that was used, while in this case sample_rate controls how many unlabeled points are used in each iteration."
},
{
"code": null,
"e": 20897,
"s": 20687,
"text": "The sample_rate value itself is a hyperparameter that needs to be tuned based on the dataset and model (similar to T1, T2, and alpha_f). A value of 0.04 worked best for the MNIST + Logistic Regression example."
},
{
"code": null,
"e": 21025,
"s": 20897,
"text": "An interesting modification would be to schedule sample_rate to ramp up as the training progresses exactly similar to alpha(t)."
},
{
"code": null,
"e": 21122,
"s": 21025,
"text": "Before we conclude, let’s look at some of the challenges in Semi-Supervised Learning in general."
},
{
"code": null,
"e": 21374,
"s": 21122,
"text": "The primary objective of Semi-Supervised Learning is to use the unlabeled data along with the labeled data to understand the underlying structure of the dataset. The obvious question here is — How to utilize the unlabeled data to achieve this purpose?"
},
{
"code": null,
"e": 21931,
"s": 21374,
"text": "In the Pseudo-Labeling technique, we saw that a scheduled weight function ( alpha) was used to slowly combine the unlabeled data with the labeled data. However, the alpha(t) function assumes that the model confidence increases over time and therefore increases the unlabeled loss linearly. This need not be the case as model predictions can sometimes be incorrect. In fact, if the model makes several wrong unlabeled predictions, pseudo-labeling can act like a bad feedback loop and deteriorate performance further. (Ref : Section 3.1 Arazo et al 2019 [2])"
},
{
"code": null,
"e": 22050,
"s": 21931,
"text": "One solution for the problem above is to use probability thresholds — similar to what we did with Logistic Regression."
},
{
"code": null,
"e": 22341,
"s": 22050,
"text": "Other Semi-Supervised Learning algorithms use different ways to combine the data, for example, MixMatch uses a 2-step process for guessing the label (for the unlabeled data) followed by MixUp data augmentation to combine the unlabeled data with the labeled data. (Berthelot et al (2019)[3])"
},
{
"code": null,
"e": 22685,
"s": 22341,
"text": "Another challenge with Semi-Supervised Learning is to design algorithms that can work with very small amounts of labeled data. As we’ve seen with pseudo labeling, the model works best with 1000 initial labeled samples. However, when the labeled dataset is reduced further (for eg: with 50 points), pseudo-labeling’s performance starts to drop."
},
{
"code": null,
"e": 22899,
"s": 22685,
"text": "Oliver et al. (2018) [4] did a comparison of several Semi-Supervised Learning algorithms and found that Pseudo-Labeling fails on the “two-moons” dataset while other models like VAT and pi-model worked much better."
},
{
"code": null,
"e": 23163,
"s": 22899,
"text": "As shown in the image, VAT and Pi-Model learn a decision boundary that is surprisingly good with just 6 labeled data points (shown in large white and black circles). Pseudo-Labeling on the other hand completely fails and learns a linear decision boundary instead."
},
{
"code": null,
"e": 23399,
"s": 23163,
"text": "I repeated the experiment using the same model that Oliver et al. used and found that pseudo-labeling required anywhere from 30–50 labeled points (depending on the position of the labeled points) to learn the underlying data structure."
},
{
"code": null,
"e": 23560,
"s": 23399,
"text": "To make Semi-Supervised Learning more practical we need algorithms that are highly data-efficient i.e. ones that can work on very small amounts of labeled data."
},
{
"code": null,
"e": 23790,
"s": 23560,
"text": "Oliver et al.[4] mention: “Pseudo-labeling is a simple heuristic which is widely used in practice, likely because of its simplicity and generality” and as we’ve seen it provides a nice way to learn about Semi-Supervised Learning."
},
{
"code": null,
"e": 24134,
"s": 23790,
"text": "Over the last 2–3 years, Semi-Supervised Learning for Image classification has seen some incredible improvements. Unsupervised Data Augmentation (Xie et al (2019) [5]) has achieved 97.3% on CIFAR- 10 with just 4000 Labels. To put that into perspective, DenseNet (Huang et al (2016)[6]) achieved 96.54% on the complete CIFAR-10 dataset in 2016."
},
{
"code": null,
"e": 24513,
"s": 24134,
"text": "It’s really interesting to see how the Machine Learning and Data Science community is moving towards algorithms that either uses less labeled data (like Semi-Supervised Learning, Zero/Few Shot Learning) or smaller datasets altogether (like Transfer Learning). Personally, I believe these developments are critical if we truly want to democratize Artificial Intelligence for all."
},
{
"code": null,
"e": 24589,
"s": 24513,
"text": "If you have any questions feel free to connect with me. I hope you enjoyed!"
},
{
"code": null,
"e": 24666,
"s": 24589,
"text": "Github Repo: https://github.com/anirudhshenoy/pseudo_labeling_small_datasets"
},
{
"code": null,
"e": 24724,
"s": 24666,
"text": "Dataset: https://www.kaggle.com/oddrationale/mnist-in-csv"
},
{
"code": null,
"e": 26132,
"s": 24724,
"text": "Dong-Hyun Lee. “Pseudo-Label : The Simple and Efficient Semi-Supervised Learning Method for Deep Neural Networks” ICML 2013 Workshop : Challenges in Representation Learning (WREPL), Atlanta, Georgia, USA, 2013 (http://deeplearning.net/wp-content/uploads/2013/03/pseudo_label_final.pdf)Eric Arazo, Diego Ortego, Paul Albert, Noel E. O’Connor, Kevin McGuinness. “Pseudo-Labeling and Confirmation Bias in Deep Semi-Supervised Learning” (https://arxiv.org/abs/1908.02983)David Berthelot, Nicholas Carlini, Ian Goodfellow, Nicolas Papernot, Avital Oliver, Colin Raffel. “MixMatch: A Holistic Approach to Semi-Supervised Learning” (https://arxiv.org/abs/1905.02249)“Avital Oliver, Augustus Odena, Colin Raffel, Ekin D. Cubuk, Ian J. Goodfellow. “Realistic Evaluation of Deep Semi-Supervised Learning Algorithms” (https://arxiv.org/abs/1804.09170)Qizhe Xie, Zihang Dai, Eduard Hovy, Minh-Thang Luong, Quoc V. Le. ”Unsupervised Data Augmentation for Consistency Training” (https://arxiv.org/abs/1904.12848)Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger. “Densely Connected Convolutional Networks” (https://arxiv.org/abs/1608.06993)https://github.com/peimengsui/semi_supervised_mnisthttps://www.analyticsvidhya.com/blog/2017/09/pseudo-labelling-semi-supervised-learning-technique/https://www.quora.com/Why-is-unsupervised-learning-importanthttps://www.wired.com/2014/08/deep-learning-yann-lecun/"
},
{
"code": null,
"e": 26418,
"s": 26132,
"text": "Dong-Hyun Lee. “Pseudo-Label : The Simple and Efficient Semi-Supervised Learning Method for Deep Neural Networks” ICML 2013 Workshop : Challenges in Representation Learning (WREPL), Atlanta, Georgia, USA, 2013 (http://deeplearning.net/wp-content/uploads/2013/03/pseudo_label_final.pdf)"
},
{
"code": null,
"e": 26601,
"s": 26418,
"text": "Eric Arazo, Diego Ortego, Paul Albert, Noel E. O’Connor, Kevin McGuinness. “Pseudo-Labeling and Confirmation Bias in Deep Semi-Supervised Learning” (https://arxiv.org/abs/1908.02983)"
},
{
"code": null,
"e": 26794,
"s": 26601,
"text": "David Berthelot, Nicholas Carlini, Ian Goodfellow, Nicolas Papernot, Avital Oliver, Colin Raffel. “MixMatch: A Holistic Approach to Semi-Supervised Learning” (https://arxiv.org/abs/1905.02249)"
},
{
"code": null,
"e": 26976,
"s": 26794,
"text": "“Avital Oliver, Augustus Odena, Colin Raffel, Ekin D. Cubuk, Ian J. Goodfellow. “Realistic Evaluation of Deep Semi-Supervised Learning Algorithms” (https://arxiv.org/abs/1804.09170)"
},
{
"code": null,
"e": 27135,
"s": 26976,
"text": "Qizhe Xie, Zihang Dai, Eduard Hovy, Minh-Thang Luong, Quoc V. Le. ”Unsupervised Data Augmentation for Consistency Training” (https://arxiv.org/abs/1904.12848)"
}
] |
Python | sympy.Matrix().col_insert() - GeeksforGeeks | 25 Jun, 2019
With the help of Matrix().col_insert() method, we can insert a column in a matrix having dimension nxm, where dimension of inserted column is nx1.
Syntax : Matrix().col_insert()Return : Return a new matrix.
Example #1 :In this example, we are able to insert a column in a matrix by using Matrix().col_insert() method.
# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(1, Matrix([[3], [4]])) print(new_mat)
Output :
Matrix([[1, 3, 2], [2, 4, 1]])
Example #2 :
# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(2, Matrix([[13], [24]])) print(new_mat)
Output :
Matrix([[1, 2, 13], [2, 1, 24]])
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 24048,
"s": 23901,
"text": "With the help of Matrix().col_insert() method, we can insert a column in a matrix having dimension nxm, where dimension of inserted column is nx1."
},
{
"code": null,
"e": 24108,
"s": 24048,
"text": "Syntax : Matrix().col_insert()Return : Return a new matrix."
},
{
"code": null,
"e": 24219,
"s": 24108,
"text": "Example #1 :In this example, we are able to insert a column in a matrix by using Matrix().col_insert() method."
},
{
"code": "# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(1, Matrix([[3], [4]])) print(new_mat)",
"e": 24435,
"s": 24219,
"text": null
},
{
"code": null,
"e": 24444,
"s": 24435,
"text": "Output :"
},
{
"code": null,
"e": 24475,
"s": 24444,
"text": "Matrix([[1, 3, 2], [2, 4, 1]])"
},
{
"code": null,
"e": 24488,
"s": 24475,
"text": "Example #2 :"
},
{
"code": "# Import all the methods from sympyfrom sympy import * # Make a matrixgfg_mat = Matrix([[1, 2], [2, 1]]) # use the col_insert() method for matrixnew_mat = gfg_mat.col_insert(2, Matrix([[13], [24]])) print(new_mat)",
"e": 24706,
"s": 24488,
"text": null
},
{
"code": null,
"e": 24715,
"s": 24706,
"text": "Output :"
},
{
"code": null,
"e": 24748,
"s": 24715,
"text": "Matrix([[1, 2, 13], [2, 1, 24]])"
},
{
"code": null,
"e": 24754,
"s": 24748,
"text": "SymPy"
},
{
"code": null,
"e": 24761,
"s": 24754,
"text": "Python"
},
{
"code": null,
"e": 24859,
"s": 24761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24868,
"s": 24859,
"text": "Comments"
},
{
"code": null,
"e": 24881,
"s": 24868,
"text": "Old Comments"
},
{
"code": null,
"e": 24913,
"s": 24881,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 24969,
"s": 24913,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25011,
"s": 24969,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25053,
"s": 25011,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25089,
"s": 25053,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25128,
"s": 25089,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25150,
"s": 25128,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25181,
"s": 25150,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25208,
"s": 25181,
"text": "Python Classes and Objects"
}
] |
GCD and Fibonacci Numbers - GeeksforGeeks | 06 Apr, 2021
You are given two positive numbers M and N. The task is to print greatest common divisor of M’th and N’th Fibonacci Numbers.The first few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... Note that 0 is considered as 0’th Fibonacci Number.Examples:
Input : M = 3, N = 6
Output : 2
Fib(3) = 2, Fib(6) = 8
GCD of above two numbers is 2
Input : M = 8, N = 12
Output : 3
Fib(8) = 21, Fib(12) = 144
GCD of above two numbers is 3
A Simple Solution is to follow below steps. 1) Find M’th Fibonacci Number. 2) Find N’th Fibonacci Number. 3) Return GCD of two numbers.A Better Solution is based on below identity
GCD(Fib(M), Fib(N)) = Fib(GCD(M, N))
The above property holds because Fibonacci Numbers follow
Divisibility Sequence, i.e., if M divides N, then Fib(M)
also divides N. For example, Fib(3) = 2 and every third
third Fibonacci Number is even.
Source : Wiki
The steps are: 1) Find GCD of M and N. Let GCD be g. 2) Return Fib(g).Below are implementations of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find GCD of Fib(M) and Fib(N)#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = {0}; // Returns n'th Fibonacci number using table f[].// Refer method 6 of below post for details.// https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1)? (n+1)/2 : n/2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Function to return gcd of a and bint gcd(int M, int N){ if (M == 0) return N; return gcd(N%M, M);} // Returns GCD of Fib(M) and Fib(N)int findGCDofFibMFibN(int M, int N){ return fib(gcd(M, N));} // Driver codeint main(){ int M = 3, N = 12; cout << findGCDofFibMFibN(M, N); return 0;}
// Java Program to find GCD of Fib(M) and Fib(N)class gcdOfFibonacci{ static final int MAX = 1000; static int[] f; gcdOfFibonacci() // Constructor { // Create an array for memoization f = new int[MAX]; } // Returns n'th Fibonacci number using table f[]. // Refer method 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ private static int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]!=0) return f[n]; int k = ((n & 1)==1)? (n+1)/2 : n/2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = ((n & 1)==1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n]; } // Function to return gcd of a and b private static int gcd(int M, int N) { if (M == 0) return N; return gcd(N%M, M); } // This method returns GCD of Fib(M) and Fib(N) static int findGCDofFibMFibN(int M, int N) { return fib(gcd(M, N)); } // Driver method public static void main(String[] args) { // Returns GCD of Fib(M) and Fib(N) gcdOfFibonacci obj = new gcdOfFibonacci(); int M = 3, N = 12; System.out.println(findGCDofFibMFibN(M, N)); }}// This code is contributed by Pankaj Kumar
# Python Program to find# GCD of Fib(M) and Fib(N) MAX = 1000 # Create an array for memoizationf=[0 for i in range(MAX)] # Returns n'th Fibonacci# number using table f[].# Refer method 6 of below# post for details.# https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/def fib(n): # Base cases if (n == 0): return 0 if (n == 1 or n == 2): f[n] = 1 # If fib(n) is already computed if (f[n]): return f[n] k = (n+1)//2 if(n & 1) else n//2 # Applying recursive # formula [Note value n&1 is 1 # if n is odd, else 0. f[n] = (fib(k)*fib(k) + fib(k-1)*fib(k-1)) if(n & 1) else ((2* fib(k-1) + fib(k))*fib(k)) return f[n] # Function to return# gcd of a and bdef gcd(M, N): if (M == 0): return N return gcd(N % M, M) # Returns GCD of# Fib(M) and Fib(N)def findGCDofFibMFibN(M, N): return fib(gcd(M, N)) # Driver code M = 3N = 12 print(findGCDofFibMFibN(M, N)) # This code is contributed# by Anant Agarwal.
// C# Program to find GCD of// Fib(M) and Fib(N)using System; class gcdOfFibonacci { static int MAX = 1000; static int []f; // Constructor gcdOfFibonacci() { // Create an array // for memoization f = new int[MAX]; } // Returns n'th Fibonacci number // using table f[]. Refer method // 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ private static int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is // already computed if (f[n]!=0) return f[n]; int k = ((n & 1)==1)? (n+1)/2 : n/2; // Applying recursive formula // [Note value n&1 is 1 // if n is odd, else 0. f[n] = ((n & 1) == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to return gcd of a and b private static int gcd(int M, int N) { if (M == 0) return N; return gcd(N%M, M); } // This method returns GCD of // Fib(M) and Fib(N) static int findGCDofFibMFibN(int M, int N) { return fib(gcd(M, N)); } // Driver method public static void Main() { // Returns GCD of Fib(M) and Fib(N) new gcdOfFibonacci(); int M = 3, N = 12; Console.Write(findGCDofFibMFibN(M, N)); }} // This code is contributed by nitin mittal.
<?php// PHP Program to find// GCD of Fib(M) and Fib(N)$MAX = 1000; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]. Refer method// 6 of below post for details.function fib($n){ global $f; // Base cases if ($n == 0) return 0; if ($n == 1 or $n == 2) $f[$n] = 1; // If fib(n) is already computed if ($f[$n]) return $f[$n]; $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying recursive formula [Note // value n&1 is 1, if n is odd, else 0. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : ((2 * fib($k - 1) + fib($k)) * fib($k)); return $f[$n];} // Function to return gcd of a and bfunction gcd($M, $N){ if ($M == 0) return $N; return gcd($N % $M, $M);} // Returns GCD of Fib(M) and Fib(N)function findGCDofFibMFibN($M, $N){ return fib(gcd($M, $N));} // Driver code$M = 3;$N = 12; print(findGCDofFibMFibN($M, $N)) // This code is contributed// by mits?>
<script> // JavaScript Program to find GCD of Fib(M) and Fib(N) const MAX = 1000; // Create an array for memoization var f = [...Array(MAX)]; f.fill(0); // Returns n'th Fibonacci number using table f[]. // Refer method 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ function fib(n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; var k = n & 1 ? (n + 1) / 2 : n / 2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = n & 1 ? fib(k) * fib(k) + fib(k - 1) * fib(k - 1) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to return gcd of a and b function gcd(M, N) { if (M == 0) return N; return gcd(N % M, M); } // Returns GCD of Fib(M) and Fib(N) function findGCDofFibMFibN(M, N) { return fib(gcd(M, N)); } // Driver code var M = 3, N = 12; document.write(findGCDofFibMFibN(M, N)); // This code is contributed by rdtank. </script>
Output:
2
This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
rdtank
Fibonacci
GCD-LCM
Mathematical
Mathematical
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Find all factors of a natural number | Set 1
Modulo 10^9+7 (1000000007)
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Operators in C / C++
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number | [
{
"code": null,
"e": 24205,
"s": 24177,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 24479,
"s": 24205,
"text": "You are given two positive numbers M and N. The task is to print greatest common divisor of M’th and N’th Fibonacci Numbers.The first few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... Note that 0 is considered as 0’th Fibonacci Number.Examples: "
},
{
"code": null,
"e": 24659,
"s": 24479,
"text": "Input : M = 3, N = 6\nOutput : 2\nFib(3) = 2, Fib(6) = 8\nGCD of above two numbers is 2\n\nInput : M = 8, N = 12\nOutput : 3\nFib(8) = 21, Fib(12) = 144\nGCD of above two numbers is 3"
},
{
"code": null,
"e": 24842,
"s": 24661,
"text": "A Simple Solution is to follow below steps. 1) Find M’th Fibonacci Number. 2) Find N’th Fibonacci Number. 3) Return GCD of two numbers.A Better Solution is based on below identity "
},
{
"code": null,
"e": 25098,
"s": 24842,
"text": "GCD(Fib(M), Fib(N)) = Fib(GCD(M, N))\n\nThe above property holds because Fibonacci Numbers follow\nDivisibility Sequence, i.e., if M divides N, then Fib(M)\nalso divides N. For example, Fib(3) = 2 and every third\nthird Fibonacci Number is even.\n\nSource : Wiki"
},
{
"code": null,
"e": 25210,
"s": 25098,
"text": "The steps are: 1) Find GCD of M and N. Let GCD be g. 2) Return Fib(g).Below are implementations of above idea. "
},
{
"code": null,
"e": 25214,
"s": 25210,
"text": "C++"
},
{
"code": null,
"e": 25219,
"s": 25214,
"text": "Java"
},
{
"code": null,
"e": 25227,
"s": 25219,
"text": "Python3"
},
{
"code": null,
"e": 25230,
"s": 25227,
"text": "C#"
},
{
"code": null,
"e": 25234,
"s": 25230,
"text": "PHP"
},
{
"code": null,
"e": 25245,
"s": 25234,
"text": "Javascript"
},
{
"code": "// C++ Program to find GCD of Fib(M) and Fib(N)#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = {0}; // Returns n'th Fibonacci number using table f[].// Refer method 6 of below post for details.// https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1)? (n+1)/2 : n/2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n];} // Function to return gcd of a and bint gcd(int M, int N){ if (M == 0) return N; return gcd(N%M, M);} // Returns GCD of Fib(M) and Fib(N)int findGCDofFibMFibN(int M, int N){ return fib(gcd(M, N));} // Driver codeint main(){ int M = 3, N = 12; cout << findGCDofFibMFibN(M, N); return 0;}",
"e": 26298,
"s": 25245,
"text": null
},
{
"code": "// Java Program to find GCD of Fib(M) and Fib(N)class gcdOfFibonacci{ static final int MAX = 1000; static int[] f; gcdOfFibonacci() // Constructor { // Create an array for memoization f = new int[MAX]; } // Returns n'th Fibonacci number using table f[]. // Refer method 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ private static int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]!=0) return f[n]; int k = ((n & 1)==1)? (n+1)/2 : n/2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = ((n & 1)==1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1)) : (2*fib(k-1) + fib(k))*fib(k); return f[n]; } // Function to return gcd of a and b private static int gcd(int M, int N) { if (M == 0) return N; return gcd(N%M, M); } // This method returns GCD of Fib(M) and Fib(N) static int findGCDofFibMFibN(int M, int N) { return fib(gcd(M, N)); } // Driver method public static void main(String[] args) { // Returns GCD of Fib(M) and Fib(N) gcdOfFibonacci obj = new gcdOfFibonacci(); int M = 3, N = 12; System.out.println(findGCDofFibMFibN(M, N)); }}// This code is contributed by Pankaj Kumar",
"e": 27804,
"s": 26298,
"text": null
},
{
"code": "# Python Program to find# GCD of Fib(M) and Fib(N) MAX = 1000 # Create an array for memoizationf=[0 for i in range(MAX)] # Returns n'th Fibonacci# number using table f[].# Refer method 6 of below# post for details.# https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/def fib(n): # Base cases if (n == 0): return 0 if (n == 1 or n == 2): f[n] = 1 # If fib(n) is already computed if (f[n]): return f[n] k = (n+1)//2 if(n & 1) else n//2 # Applying recursive # formula [Note value n&1 is 1 # if n is odd, else 0. f[n] = (fib(k)*fib(k) + fib(k-1)*fib(k-1)) if(n & 1) else ((2* fib(k-1) + fib(k))*fib(k)) return f[n] # Function to return# gcd of a and bdef gcd(M, N): if (M == 0): return N return gcd(N % M, M) # Returns GCD of# Fib(M) and Fib(N)def findGCDofFibMFibN(M, N): return fib(gcd(M, N)) # Driver code M = 3N = 12 print(findGCDofFibMFibN(M, N)) # This code is contributed# by Anant Agarwal.",
"e": 28809,
"s": 27804,
"text": null
},
{
"code": "// C# Program to find GCD of// Fib(M) and Fib(N)using System; class gcdOfFibonacci { static int MAX = 1000; static int []f; // Constructor gcdOfFibonacci() { // Create an array // for memoization f = new int[MAX]; } // Returns n'th Fibonacci number // using table f[]. Refer method // 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ private static int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is // already computed if (f[n]!=0) return f[n]; int k = ((n & 1)==1)? (n+1)/2 : n/2; // Applying recursive formula // [Note value n&1 is 1 // if n is odd, else 0. f[n] = ((n & 1) == 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to return gcd of a and b private static int gcd(int M, int N) { if (M == 0) return N; return gcd(N%M, M); } // This method returns GCD of // Fib(M) and Fib(N) static int findGCDofFibMFibN(int M, int N) { return fib(gcd(M, N)); } // Driver method public static void Main() { // Returns GCD of Fib(M) and Fib(N) new gcdOfFibonacci(); int M = 3, N = 12; Console.Write(findGCDofFibMFibN(M, N)); }} // This code is contributed by nitin mittal.",
"e": 30366,
"s": 28809,
"text": null
},
{
"code": "<?php// PHP Program to find// GCD of Fib(M) and Fib(N)$MAX = 1000; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]. Refer method// 6 of below post for details.function fib($n){ global $f; // Base cases if ($n == 0) return 0; if ($n == 1 or $n == 2) $f[$n] = 1; // If fib(n) is already computed if ($f[$n]) return $f[$n]; $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying recursive formula [Note // value n&1 is 1, if n is odd, else 0. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : ((2 * fib($k - 1) + fib($k)) * fib($k)); return $f[$n];} // Function to return gcd of a and bfunction gcd($M, $N){ if ($M == 0) return $N; return gcd($N % $M, $M);} // Returns GCD of Fib(M) and Fib(N)function findGCDofFibMFibN($M, $N){ return fib(gcd($M, $N));} // Driver code$M = 3;$N = 12; print(findGCDofFibMFibN($M, $N)) // This code is contributed// by mits?>",
"e": 31407,
"s": 30366,
"text": null
},
{
"code": "<script> // JavaScript Program to find GCD of Fib(M) and Fib(N) const MAX = 1000; // Create an array for memoization var f = [...Array(MAX)]; f.fill(0); // Returns n'th Fibonacci number using table f[]. // Refer method 6 of below post for details. // https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/ function fib(n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; var k = n & 1 ? (n + 1) / 2 : n / 2; // Applying recursive formula [Note value n&1 is 1 // if n is odd, else 0. f[n] = n & 1 ? fib(k) * fib(k) + fib(k - 1) * fib(k - 1) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to return gcd of a and b function gcd(M, N) { if (M == 0) return N; return gcd(N % M, M); } // Returns GCD of Fib(M) and Fib(N) function findGCDofFibMFibN(M, N) { return fib(gcd(M, N)); } // Driver code var M = 3, N = 12; document.write(findGCDofFibMFibN(M, N)); // This code is contributed by rdtank. </script>",
"e": 32668,
"s": 31407,
"text": null
},
{
"code": null,
"e": 32678,
"s": 32668,
"text": "Output: "
},
{
"code": null,
"e": 32680,
"s": 32678,
"text": "2"
},
{
"code": null,
"e": 33104,
"s": 32680,
"text": "This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33117,
"s": 33104,
"text": "nitin mittal"
},
{
"code": null,
"e": 33130,
"s": 33117,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 33137,
"s": 33130,
"text": "rdtank"
},
{
"code": null,
"e": 33147,
"s": 33137,
"text": "Fibonacci"
},
{
"code": null,
"e": 33155,
"s": 33147,
"text": "GCD-LCM"
},
{
"code": null,
"e": 33168,
"s": 33155,
"text": "Mathematical"
},
{
"code": null,
"e": 33181,
"s": 33168,
"text": "Mathematical"
},
{
"code": null,
"e": 33191,
"s": 33181,
"text": "Fibonacci"
},
{
"code": null,
"e": 33289,
"s": 33191,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33298,
"s": 33289,
"text": "Comments"
},
{
"code": null,
"e": 33311,
"s": 33298,
"text": "Old Comments"
},
{
"code": null,
"e": 33335,
"s": 33311,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33378,
"s": 33335,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33423,
"s": 33378,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 33450,
"s": 33423,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 33499,
"s": 33450,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33542,
"s": 33499,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 33576,
"s": 33542,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33597,
"s": 33576,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33634,
"s": 33597,
"text": "Minimum number of jumps to reach end"
}
] |
How to start the Azure VM using Azure CLI in PowerShell? | To start the stopped Azure VM using Az CLI, we can use the az vm start command. Before starting the azure VM, make sure that you are connected to the desired subscription and the Azure cloud account.
To start the specific VM, we will use the command below.
PS C:\> az vm start -n vmname -g RGname --verbose
Or you can use,
PS C:\> az vm start --name vmname --resource-group RGName --verbose
When you start the multiple VMs, you can specify the “--no-wait” parameter.
PS C:\> az vm start -n vmname -g RGname –no-wait | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "To start the stopped Azure VM using Az CLI, we can use the az vm start command. Before starting the azure VM, make sure that you are connected to the desired subscription and the Azure cloud account."
},
{
"code": null,
"e": 1319,
"s": 1262,
"text": "To start the specific VM, we will use the command below."
},
{
"code": null,
"e": 1369,
"s": 1319,
"text": "PS C:\\> az vm start -n vmname -g RGname --verbose"
},
{
"code": null,
"e": 1385,
"s": 1369,
"text": "Or you can use,"
},
{
"code": null,
"e": 1453,
"s": 1385,
"text": "PS C:\\> az vm start --name vmname --resource-group RGName --verbose"
},
{
"code": null,
"e": 1529,
"s": 1453,
"text": "When you start the multiple VMs, you can specify the “--no-wait” parameter."
},
{
"code": null,
"e": 1578,
"s": 1529,
"text": "PS C:\\> az vm start -n vmname -g RGname –no-wait"
}
] |
How can we retrieve a blob datatype from a table using the getBinaryStream() method in JDBC? | The ResultSet interface provides the method named getBlob() to retrieve blob datatype from a table in the database. In addition to this, it also provides a method named getBinaryStream()
Like getBlob() this method also accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column. The difference is unlike the getBlob() method (which returns a Blob object) this method returns an InputStream object which holds the contents of the blob datatype in the form of un-interpreted bytes.
Assume we have created a table named MyTable in the database with the following description.
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| Name | varchar(255) | YES | | NULL | |
| image | blob | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
And, we have inserted an image in it with name sample_image. Following program retrieves the contents of the MyTable using the getString() and getBinaryStream() methods.
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingBlob_ByteStream {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//retrieving the data
ResultSet rs = stmt.executeQuery("select * from MyTable");
int i = 0;
System.out.println("Contents of the table");
while(rs.next()) {
System.out.println(rs.getString("Name"));
InputStream inputStream = rs.getBinaryStream("image");
byte byteArray[] = new byte[inputStream.available()];
inputStream.read(byteArray);
FileOutputStream outPutStream = new
FileOutputStream("E:\\images\\blob_output"+i+".jpg");
outPutStream.write(byteArray);
System.out.println("E:\\images\\blob_output"+i+".jpg");
}
}
}
Connection established......
Contents of the table
sample_image
E:\images\blob_output0.jpg | [
{
"code": null,
"e": 1249,
"s": 1062,
"text": "The ResultSet interface provides the method named getBlob() to retrieve blob datatype from a table in the database. In addition to this, it also provides a method named getBinaryStream()"
},
{
"code": null,
"e": 1644,
"s": 1249,
"text": "Like getBlob() this method also accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column. The difference is unlike the getBlob() method (which returns a Blob object) this method returns an InputStream object which holds the contents of the blob datatype in the form of un-interpreted bytes."
},
{
"code": null,
"e": 1737,
"s": 1644,
"text": "Assume we have created a table named MyTable in the database with the following description."
},
{
"code": null,
"e": 2073,
"s": 1737,
"text": "+-------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| image | blob | YES | | NULL | |\n+-------+--------------+------+-----+---------+-------+"
},
{
"code": null,
"e": 2243,
"s": 2073,
"text": "And, we have inserted an image in it with name sample_image. Following program retrieves the contents of the MyTable using the getString() and getBinaryStream() methods."
},
{
"code": null,
"e": 3559,
"s": 2243,
"text": "import java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class RetrievingBlob_ByteStream {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from MyTable\");\n\n int i = 0;\n System.out.println(\"Contents of the table\");\n while(rs.next()) {\n System.out.println(rs.getString(\"Name\"));\n InputStream inputStream = rs.getBinaryStream(\"image\");\n byte byteArray[] = new byte[inputStream.available()];\n inputStream.read(byteArray);\n FileOutputStream outPutStream = new\n FileOutputStream(\"E:\\\\images\\\\blob_output\"+i+\".jpg\");\n outPutStream.write(byteArray);\n System.out.println(\"E:\\\\images\\\\blob_output\"+i+\".jpg\");\n }\n }\n}"
},
{
"code": null,
"e": 3650,
"s": 3559,
"text": "Connection established......\nContents of the table\nsample_image\nE:\\images\\blob_output0.jpg"
}
] |
How to capture the text from Alert Message in Selenium Webdriver? | We can capture the text from the alert message in Selenium webdriverwith the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the webdriver focus from the main page to the alert.
This is done with the help of the switchTo().alert() method. Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the method switchTo().alert().getText(). Finally we shall use the accept method to accept the alert and dismiss method to dismiss it.
Let us take an example of the below alert and obtain its message −
Alert a = driver.switchTo().alert();
String s= driver.switchTo().alert().getText();
a.accept();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class JsEnterText{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
// identify element
WebElement l = driver.
findElement(By.xpath("//*[text()='Click for JS Alert']"));
l.click();
//switch focus to alert
Alert a = driver.switchTo().alert();
//get alert text
String s= driver.switchTo().alert().getText();
System.out.println("Alert text is: " + s);
//accepting alert
a.accept();
driver.quit();
}
} | [
{
"code": null,
"e": 1340,
"s": 1062,
"text": "We can capture the text from the alert message in Selenium webdriverwith the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the webdriver focus from the main page to the alert."
},
{
"code": null,
"e": 1623,
"s": 1340,
"text": "This is done with the help of the switchTo().alert() method. Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the method switchTo().alert().getText(). Finally we shall use the accept method to accept the alert and dismiss method to dismiss it."
},
{
"code": null,
"e": 1690,
"s": 1623,
"text": "Let us take an example of the below alert and obtain its message −"
},
{
"code": null,
"e": 1786,
"s": 1690,
"text": "Alert a = driver.switchTo().alert();\nString s= driver.switchTo().alert().getText();\na.accept();"
},
{
"code": null,
"e": 2794,
"s": 1786,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class JsEnterText{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://the-internet.herokuapp.com/javascript_alerts\");\n // identify element\n WebElement l = driver.\n findElement(By.xpath(\"//*[text()='Click for JS Alert']\"));\n l.click();\n //switch focus to alert\n Alert a = driver.switchTo().alert();\n //get alert text\n String s= driver.switchTo().alert().getText();\n System.out.println(\"Alert text is: \" + s);\n //accepting alert\n a.accept();\n driver.quit();\n }\n}"
}
] |
Difference between fork() and exec() - GeeksforGeeks | 26 Apr, 2022
Every application(program) comes into execution through means of process, process is a running instance of a program. Processes are created through different system calls, most popular are fork() and exec()
fork()
pid_t pid = fork();
fork() creates a new process by duplicating the calling process, The new process, referred to as child, is an exact duplicate of the calling process, referred to as parent, except for the following :
The child has its own unique process ID, and this PID does not match the ID of any existing process group.The child’s parent process ID is the same as the parent’s process ID.The child does not inherit its parent’s memory locks and semaphore adjustments.The child does not inherit outstanding asynchronous I/O operations from its parent nor does it inherit any asynchronous I/O contexts from its parent.
The child has its own unique process ID, and this PID does not match the ID of any existing process group.
The child’s parent process ID is the same as the parent’s process ID.
The child does not inherit its parent’s memory locks and semaphore adjustments.
The child does not inherit outstanding asynchronous I/O operations from its parent nor does it inherit any asynchronous I/O contexts from its parent.
Return value of fork() On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. Detailed article on fork system call
exec()
The exec() family of functions replaces the current process image with a new process image. It loads the program into the current process space and runs it from the entry point. The exec() family consists of following functions, I have implemented execv() in following C program, you can try rest as an exercise
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ...,
char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
fork vs exec
fork starts a new process which is a copy of the one that calls it, while exec replaces the current process image with another (different) one.
Both parent and child processes are executed simultaneously in case of fork() while Control never returns to the original program unless there is an exec() error.
C
// C program to illustrate use of fork() &// exec() system call for process creation #include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <errno.h> #include <sys/wait.h> int main(){ pid_t pid; int ret = 1; int status; pid = fork(); if (pid == -1){ // pid == -1 means error occurred printf("can't fork, error occured\n"); exit(EXIT_FAILURE); } else if (pid == 0){ // pid == 0 means child process created // getpid() returns process id of calling process // Here It will return process id of child process printf("child process, pid = %u\n",getpid()); // Here It will return Parent of child Process means Parent process it self printf("parent of child process, pid = %u\n",getppid()); // the argv list first argument should point to // filename associated with file being executed // the array pointer must be terminated by NULL // pointer char * argv_list[] = {"ls","-lart","/home",NULL}; // the execv() only return if error occurred. // The return value is -1 execv("ls",argv_list); exit(0); } else{ // a positive number is returned for the pid of // parent process // getppid() returns process id of parent of // calling process// Here It will return parent of parent process's ID printf("Parent Of parent process, pid = %u\n",getppid()); printf("parent process, pid = %u\n",getpid()); // the parent process calls waitpid() on the child // waitpid() system call suspends execution of // calling process until a child specified by pid // argument has changed state // see wait() man page for all the flags or options // used here if (waitpid(pid, &status, 0) > 0) { if (WIFEXITED(status) && !WEXITSTATUS(status)) printf("program execution successful\n"); else if (WIFEXITED(status) && WEXITSTATUS(status)) { if (WEXITSTATUS(status) == 127) { // execv failed printf("execv failed\n"); } else printf("program terminated normally," " but returned a non-zero status\n"); } else printf("program didn't terminate normally\n"); } else { // waitpid() failed printf("waitpid() failed\n"); } exit(0); } return 0;}
Output:
parent process, pid = 11523
child process, pid = 14188
Program execution successful
References : Linux man pages This article is contributed by Mandeep 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.
nidhi_biet
executionover
surinderdawra388
system-programming
C Language
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Structures in C
Different methods to reverse a string in C/C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java | [
{
"code": null,
"e": 24422,
"s": 24394,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 24629,
"s": 24422,
"text": "Every application(program) comes into execution through means of process, process is a running instance of a program. Processes are created through different system calls, most popular are fork() and exec()"
},
{
"code": null,
"e": 24636,
"s": 24629,
"text": "fork()"
},
{
"code": null,
"e": 24656,
"s": 24636,
"text": "pid_t pid = fork();"
},
{
"code": null,
"e": 24856,
"s": 24656,
"text": "fork() creates a new process by duplicating the calling process, The new process, referred to as child, is an exact duplicate of the calling process, referred to as parent, except for the following :"
},
{
"code": null,
"e": 25260,
"s": 24856,
"text": "The child has its own unique process ID, and this PID does not match the ID of any existing process group.The child’s parent process ID is the same as the parent’s process ID.The child does not inherit its parent’s memory locks and semaphore adjustments.The child does not inherit outstanding asynchronous I/O operations from its parent nor does it inherit any asynchronous I/O contexts from its parent."
},
{
"code": null,
"e": 25367,
"s": 25260,
"text": "The child has its own unique process ID, and this PID does not match the ID of any existing process group."
},
{
"code": null,
"e": 25437,
"s": 25367,
"text": "The child’s parent process ID is the same as the parent’s process ID."
},
{
"code": null,
"e": 25517,
"s": 25437,
"text": "The child does not inherit its parent’s memory locks and semaphore adjustments."
},
{
"code": null,
"e": 25667,
"s": 25517,
"text": "The child does not inherit outstanding asynchronous I/O operations from its parent nor does it inherit any asynchronous I/O contexts from its parent."
},
{
"code": null,
"e": 25930,
"s": 25667,
"text": "Return value of fork() On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. Detailed article on fork system call"
},
{
"code": null,
"e": 25937,
"s": 25930,
"text": "exec()"
},
{
"code": null,
"e": 26249,
"s": 25937,
"text": "The exec() family of functions replaces the current process image with a new process image. It loads the program into the current process space and runs it from the entry point. The exec() family consists of following functions, I have implemented execv() in following C program, you can try rest as an exercise"
},
{
"code": null,
"e": 26658,
"s": 26249,
"text": "int execl(const char *path, const char *arg, ...);\nint execlp(const char *file, const char *arg, ...);\nint execle(const char *path, const char *arg, ..., \n char * const envp[]);\nint execv(const char *path, char *const argv[]);\nint execvp(const char *file, char *const argv[]);\nint execvpe(const char *file, char *const argv[], \n char *const envp[]);"
},
{
"code": null,
"e": 26671,
"s": 26658,
"text": "fork vs exec"
},
{
"code": null,
"e": 26815,
"s": 26671,
"text": "fork starts a new process which is a copy of the one that calls it, while exec replaces the current process image with another (different) one."
},
{
"code": null,
"e": 26978,
"s": 26815,
"text": "Both parent and child processes are executed simultaneously in case of fork() while Control never returns to the original program unless there is an exec() error."
},
{
"code": null,
"e": 26980,
"s": 26978,
"text": "C"
},
{
"code": "// C program to illustrate use of fork() &// exec() system call for process creation #include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <errno.h> #include <sys/wait.h> int main(){ pid_t pid; int ret = 1; int status; pid = fork(); if (pid == -1){ // pid == -1 means error occurred printf(\"can't fork, error occured\\n\"); exit(EXIT_FAILURE); } else if (pid == 0){ // pid == 0 means child process created // getpid() returns process id of calling process // Here It will return process id of child process printf(\"child process, pid = %u\\n\",getpid()); // Here It will return Parent of child Process means Parent process it self printf(\"parent of child process, pid = %u\\n\",getppid()); // the argv list first argument should point to // filename associated with file being executed // the array pointer must be terminated by NULL // pointer char * argv_list[] = {\"ls\",\"-lart\",\"/home\",NULL}; // the execv() only return if error occurred. // The return value is -1 execv(\"ls\",argv_list); exit(0); } else{ // a positive number is returned for the pid of // parent process // getppid() returns process id of parent of // calling process// Here It will return parent of parent process's ID printf(\"Parent Of parent process, pid = %u\\n\",getppid()); printf(\"parent process, pid = %u\\n\",getpid()); // the parent process calls waitpid() on the child // waitpid() system call suspends execution of // calling process until a child specified by pid // argument has changed state // see wait() man page for all the flags or options // used here if (waitpid(pid, &status, 0) > 0) { if (WIFEXITED(status) && !WEXITSTATUS(status)) printf(\"program execution successful\\n\"); else if (WIFEXITED(status) && WEXITSTATUS(status)) { if (WEXITSTATUS(status) == 127) { // execv failed printf(\"execv failed\\n\"); } else printf(\"program terminated normally,\" \" but returned a non-zero status\\n\"); } else printf(\"program didn't terminate normally\\n\"); } else { // waitpid() failed printf(\"waitpid() failed\\n\"); } exit(0); } return 0;}",
"e": 29512,
"s": 26980,
"text": null
},
{
"code": null,
"e": 29520,
"s": 29512,
"text": "Output:"
},
{
"code": null,
"e": 29604,
"s": 29520,
"text": "parent process, pid = 11523\nchild process, pid = 14188\nProgram execution successful"
},
{
"code": null,
"e": 30055,
"s": 29604,
"text": "References : Linux man pages This article is contributed by Mandeep 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": 30066,
"s": 30055,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30080,
"s": 30066,
"text": "executionover"
},
{
"code": null,
"e": 30097,
"s": 30080,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30116,
"s": 30097,
"text": "system-programming"
},
{
"code": null,
"e": 30127,
"s": 30116,
"text": "C Language"
},
{
"code": null,
"e": 30146,
"s": 30127,
"text": "Difference Between"
},
{
"code": null,
"e": 30244,
"s": 30146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30276,
"s": 30244,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 30298,
"s": 30276,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 30315,
"s": 30298,
"text": "Substring in C++"
},
{
"code": null,
"e": 30331,
"s": 30315,
"text": "Structures in C"
},
{
"code": null,
"e": 30378,
"s": 30331,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 30409,
"s": 30378,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 30449,
"s": 30409,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 30481,
"s": 30449,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 30542,
"s": 30481,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
JavaScript - if...else Statement | While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement.
The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
if statement
if statement
if...else statement
if...else statement
if...else if... statement.
if...else if... statement.
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions.
Try the following example to understand how the if statement works.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Qualifies for driving
Set the variable to different value and then try...
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed.
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Does not qualify for driving
Set the variable to different value and then try...
The if...else if... statement is an advanced form of if...else that allows JavaScript to make a correct decision out of several conditions.
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Maths Book
Set the variable to different value and then try...
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2703,
"s": 2466,
"text": "While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions."
},
{
"code": null,
"e": 2866,
"s": 2703,
"text": "JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement."
},
{
"code": null,
"e": 2930,
"s": 2866,
"text": "The following flow chart shows how the if-else statement works."
},
{
"code": null,
"e": 2994,
"s": 2930,
"text": "JavaScript supports the following forms of if..else statement −"
},
{
"code": null,
"e": 3007,
"s": 2994,
"text": "if statement"
},
{
"code": null,
"e": 3020,
"s": 3007,
"text": "if statement"
},
{
"code": null,
"e": 3040,
"s": 3020,
"text": "if...else statement"
},
{
"code": null,
"e": 3060,
"s": 3040,
"text": "if...else statement"
},
{
"code": null,
"e": 3087,
"s": 3060,
"text": "if...else if... statement."
},
{
"code": null,
"e": 3114,
"s": 3087,
"text": "if...else if... statement."
},
{
"code": null,
"e": 3247,
"s": 3114,
"text": "The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally."
},
{
"code": null,
"e": 3299,
"s": 3247,
"text": "The syntax for a basic if statement is as follows −"
},
{
"code": null,
"e": 3373,
"s": 3299,
"text": "if (expression) {\n Statement(s) to be executed if expression is true\n}\n"
},
{
"code": null,
"e": 3631,
"s": 3373,
"text": "Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions."
},
{
"code": null,
"e": 3699,
"s": 3631,
"text": "Try the following example to understand how the if statement works."
},
{
"code": null,
"e": 4038,
"s": 3699,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var age = 20;\n \n if( age > 18 ) {\n document.write(\"<b>Qualifies for driving</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4113,
"s": 4038,
"text": "Qualifies for driving\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 4248,
"s": 4113,
"text": "The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way."
},
{
"code": null,
"e": 4385,
"s": 4248,
"text": "if (expression) {\n Statement(s) to be executed if expression is true\n} else {\n Statement(s) to be executed if expression is false\n}\n"
},
{
"code": null,
"e": 4602,
"s": 4385,
"text": "Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed."
},
{
"code": null,
"e": 4687,
"s": 4602,
"text": "Try the following code to learn how to implement an if-else statement in JavaScript."
},
{
"code": null,
"e": 5114,
"s": 4687,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var age = 15;\n \n if( age > 18 ) {\n document.write(\"<b>Qualifies for driving</b>\");\n } else {\n document.write(\"<b>Does not qualify for driving</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>"
},
{
"code": null,
"e": 5196,
"s": 5114,
"text": "Does not qualify for driving\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 5336,
"s": 5196,
"text": "The if...else if... statement is an advanced form of if...else that allows JavaScript to make a correct decision out of several conditions."
},
{
"code": null,
"e": 5390,
"s": 5336,
"text": "The syntax of an if-else-if statement is as follows −"
},
{
"code": null,
"e": 5697,
"s": 5390,
"text": "if (expression 1) {\n Statement(s) to be executed if expression 1 is true\n} else if (expression 2) {\n Statement(s) to be executed if expression 2 is true\n} else if (expression 3) {\n Statement(s) to be executed if expression 3 is true\n} else {\n Statement(s) to be executed if no expression is true\n}\n"
},
{
"code": null,
"e": 5970,
"s": 5697,
"text": "There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed."
},
{
"code": null,
"e": 6058,
"s": 5970,
"text": "Try the following code to learn how to implement an if-else-if statement in JavaScript."
},
{
"code": null,
"e": 6663,
"s": 6058,
"text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var book = \"maths\";\n if( book == \"history\" ) {\n document.write(\"<b>History Book</b>\");\n } else if( book == \"maths\" ) {\n document.write(\"<b>Maths Book</b>\");\n } else if( book == \"economics\" ) {\n document.write(\"<b>Economics Book</b>\");\n } else {\n document.write(\"<b>Unknown Book</b>\");\n }\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n<html>"
},
{
"code": null,
"e": 6727,
"s": 6663,
"text": "Maths Book\nSet the variable to different value and then try...\n"
},
{
"code": null,
"e": 6762,
"s": 6727,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6776,
"s": 6762,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6810,
"s": 6776,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6824,
"s": 6810,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6859,
"s": 6824,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6876,
"s": 6859,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6911,
"s": 6876,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6928,
"s": 6911,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6961,
"s": 6928,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6989,
"s": 6961,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7023,
"s": 6989,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 7051,
"s": 7023,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7058,
"s": 7051,
"text": " Print"
},
{
"code": null,
"e": 7069,
"s": 7058,
"text": " Add Notes"
}
] |
What are the rules for naming classes in C#? | A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces.
The following is the syntax −
<access specifier> class class_name {
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list) {
// method body
}
<access specifier> <return type> method2(parameter_list) {
// method body
}
...
<access specifier> <return type> methodN(parameter_list) {
// method body
}
}
The following are the conventions for class names −
The coding conventions for a class name is the name of the class name, for example, it should being PascalCasing −
public class CalculateCost {
}
Above, the class name CalculateCost is in PascalCasing.
Prefer adding class names as noun or noun phrases −
public class Department {
} | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces."
},
{
"code": null,
"e": 1224,
"s": 1194,
"text": "The following is the syntax −"
},
{
"code": null,
"e": 1720,
"s": 1224,
"text": "<access specifier> class class_name {\n // member variables\n <access specifier> <data type> variable1;\n <access specifier> <data type> variable2;\n ...\n <access specifier> <data type> variableN;\n // member methods\n <access specifier> <return type> method1(parameter_list) {\n // method body\n }\n\n <access specifier> <return type> method2(parameter_list) {\n // method body\n }\n\n ...\n <access specifier> <return type> methodN(parameter_list) {\n // method body\n }\n}"
},
{
"code": null,
"e": 1772,
"s": 1720,
"text": "The following are the conventions for class names −"
},
{
"code": null,
"e": 1887,
"s": 1772,
"text": "The coding conventions for a class name is the name of the class name, for example, it should being PascalCasing −"
},
{
"code": null,
"e": 1919,
"s": 1887,
"text": "public class CalculateCost {\n\n}"
},
{
"code": null,
"e": 1975,
"s": 1919,
"text": "Above, the class name CalculateCost is in PascalCasing."
},
{
"code": null,
"e": 2027,
"s": 1975,
"text": "Prefer adding class names as noun or noun phrases −"
},
{
"code": null,
"e": 2056,
"s": 2027,
"text": "public class Department {\n\n}"
}
] |
Advanced Time Series Analysis with ARMA and ARIMA | by Marco Peixeiro | Towards Data Science | In previous articles, we introduced moving average processes MA(q), and autoregressive processes AR(p) as two ways to model time series. Now, we will combine both methods and explore how ARMA(p,q) and ARIMA(p,d,q) models can help us to model and forecast more complex time series.
This article will cover the following topics:
ARMA models
ARIMA models
Ljung-Box test
Akaike information criterion (AIC)
By the end of this article, you should be comfortable with implementing ARMA and ARIMA models in Python and you will have a checklist of steps to take when modelling time series.
The notebook and dataset are here.
Let’s get started!
Learn the latest time series analysis techniques with Applied Time Series Analysis in Python. The course covers both statistical and deep learning models, and you will work with Python and TensorFlow!
Recall that an autoregressive process of order p is defined as:
Where:
p is the order
c is a constant
epsilon: noise
Recall also that a moving average process q is defined as:
Where:
q is the order
c is a constant
epsilon is noise
Then, an ARMA(p,q) is simply the combination of both models into a single equation:
Hence, this model can explain the relationship of a time series with both random noise (moving average part) and itself at a previous step (autoregressive part).
Let’s how an ARMA(p,q) process behaves with a few simulations.
Let’s start with a simple example of an ARMA process of order 1 in both its moving average and autoregressive part.
First, let’s import all libraries that will be required throughout this tutorial:
from statsmodels.graphics.tsaplots import plot_pacffrom statsmodels.graphics.tsaplots import plot_acffrom statsmodels.tsa.arima_process import ArmaProcessfrom statsmodels.stats.diagnostic import acorr_ljungboxfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import adfullerfrom statsmodels.tsa.stattools import pacffrom statsmodels.tsa.stattools import acffrom tqdm import tqdm_notebookimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport warningswarnings.filterwarnings('ignore')%matplotlib inline
Then, we will simulate the following ARMA process:
In code:
ar1 = np.array([1, 0.33])ma1 = np.array([1, 0.9])simulated_ARMA_data = ArmaProcess(ar1, ma1).generate_sample(nsample=10000)
We can now plot the first 200 points to visualize our generated time series:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(simulated_ARMA_data)plt.title("Simulated ARMA(1,1) Process")plt.xlim([0, 200])plt.show()
And you should get something similar to:
Then, we can take a look at the ACF and PACF plots:
plot_pacf(simulated_ARMA_data);plot_acf(simulated_ARMA_data);
As you can see, we cannot infer the order of the ARMA process by looking at these plots. In fact, looking closely, we can see some sinusoidal shape in both ACF and PACF functions. This suggests that both processes are in play.
Similarly, we can simulate an ARMA(2,2) process. In this example, we will simulate the following equation:
In code:
ar2 = np.array([1, 0.33, 0.5])ma2 = np.array([1, 0.9, 0.3])simulated_ARMA2_data = ArmaProcess(ar1, ma1).generate_sample(nsample=10000)
Then, we can visualize the simulated data:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(simulated_ARMA2_data)plt.title("Simulated ARMA(2,2) Process")plt.xlim([0, 200])plt.show()
Looking at the ACF and PACF plots:
plot_pacf(simulated_ARMA2_data);plot_acf(simulated_ARMA2_data);
As you can see, both plots exhibit the same sinusoidal trend, which further supports the fact that both an AR(p) process and a MA(q) process is in play.
ARIMA stands for AutoRegressive Integrated Moving Average.
This model is the combination of autoregression, a moving average model and differencing. In this context, integration is the opposite of differencing.
Differencing is useful to remove the trend in a time series and make it stationary.
It simply involves subtracting a point a t-1 from time t. Realize that you will, therefore, lose the first data point in a time series if you apply differencing once.
Mathematically, the ARIMA(p,d,q) now requires three parameters:
p: the order of the autoregressive process
d: the degree of differencing (number of times it was differenced)
q: the order of the moving average process
and the equations is expressed as:
Just like with ARMA models, the ACF and PACF cannot be used to identify reliable values for p and q.
However, in the presence of an ARIMA(p,d,0) process:
the ACF is exponentially decaying or sinusoidal
the PACF has a significant spike at lag p but none after
Similarly, in the presence of an ARIMA(0,d,q) process:
the PACF is exponentially decaying or sinusoidal
the ACF has a significant spike at lag q but none after
Let’s walk through an example of modelling with ARIMA to get some hands-on experience and better understand some modelling concepts.
Let’s revisit a dataset that we analyzed previously. This dataset was used to show the Yule-Walker equation can help us estimate the coefficients of an AR(p) process.
Now, we will use the same dataset, but model the time series with an ARIMA(p,d,q) model.
You can grab the notebook or download the dataset to follow along.
First, we import the dataset and display the first five rows:
data = pd.read_csv('jj.csv')data.head()
Then, let’s plot the entire dataset:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.scatter(data['date'], data['data'])plt.title('Quarterly EPS for Johnson & Johnson')plt.ylabel('EPS per share ($)')plt.xlabel('Date')plt.xticks(rotation=90)plt.grid(True)plt.show()
As you can see, there is both a trend and a change in variance in this time series.
Let’s plot the ACF and PACF functions:
plot_pacf(data['data']);plot_acf(data['data']);
As you can see, there is no way of determining the right order for the AR(p) process or MA(q) process.
The plots above are also a clear indication of non-stationarity. To further prove this point, let’s use the augmented Dicker-Fuller test:
# Augmented Dickey-Fuller testad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')
Here, the p-value is larger than 0.05, meaning the we cannot reject the null hypothesis stating that the time series is non-stationary.
Therefore, we must apply some transformation and some differencing to remove the trend and remove the change in variance.
We will hence take the log difference of the time series. This is equivalent to taking the logarithm of the EPS, and then apply differencing once. Note that because we are differencing once, we will get rid of the first data point.
# Take the log difference to make data stationarydata['data'] = np.log(data['data'])data['data'] = data['data'].diff()data = data.drop(data.index[0])data.head()
Now, let’s plot the new transformed data:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title("Log Difference of Quarterly EPS for Johnson & Johnson")plt.show()
It seems that trend and the change in variance were removed, but we want to make sure that it is the case. Therefore, we apply the augmented Dickey-Fuller test again to test for stationarity.
# Augmented Dickey-Fuller testad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')
This time, the p-value is less than 0.05, we reject the null hypothesis, and assume that the time series is stationary.
Now, let’s look at the PACF and ACF to see if we can estimate the order of one of the processes in play.
plot_pacf(data['data']);plot_acf(data['data']);
Examining the PACF above, it seems that there is an AR process of order 3 or 4 in play. However, the ACF is not informative and we see some sinusoidal shape.
Therefore, how can we make sure that we choose the right order for both the AR(p) and MA(q) processes?
We will need try different combinations of orders, fit an ARIMA model with those orders, and use a criterion for order selection.
This brings us to the topic of Akaike’s Information Criterion or AIC.
This criterion is useful for selecting the order (p,d,q) of an ARIMA model. The AIC is expressed as:
Where L is the likelihood of the data and k is the number of parameters.
In practice, we select the model with the lowest AIC compared to other models.
It is important to note that the AIC cannot be used to select the order of differencing (d). Differencing the data will the change the likelihood (L) of the data. The AIC of models with different orders of differencing are therefore not comparable.
Also, notice that since we select the model with the lowest AIC, more parameters will increase the AIC score and thus penalize the model. While a model with more parameters could perform better, the AIC is used to find the model with the least number of parameters that will still give good results.
A final note on AIC is that it can only be used relative to other models. A small AIC value is not a guarantee that the model will have a good performance on unsee data, or that its SSE will be small.
Now that we know how we will base our decision to select the best order for the ARIMA model, let’s write a function that will test all orders for us.
def optimize_ARIMA(order_list, exog): """ Return dataframe with parameters and corresponding AIC order_list - list with (p, d, q) tuples exog - the exogenous variable """ results = [] for order in tqdm_notebook(order_list): try: model = SARIMAX(exog, order=order).fit(disp=-1) except: continue aic = model.aic results.append([order, model.aic]) result_df = pd.DataFrame(results) result_df.columns = ['(p, d, q)', 'AIC'] #Sort in ascending order, lower AIC is better result_df = result_df.sort_values(by='AIC', ascending=True).reset_index(drop=True) return result_df
The function above will result in a dataframe that will list the orders and the corresponding AIC, starting with the best model on top.
We will try all combinations with orders (p,q) ranging from 0 to 8, but keeping the differencing order equal to 1.
ps = range(0, 8, 1)d = 1qs = range(0, 8, 1)# Create a list with all possible combination of parametersparameters = product(ps, qs)parameters_list = list(parameters)order_list = []for each in parameters_list: each = list(each) each.insert(1, 1) each = tuple(each) order_list.append(each) result_df = optimize_ARIMA(order_list, exog=data['data'])result_df
Once the function is done running, you should see that the order associated with the lowest AIC is (3,1,3). Therefore, this suggests are ARIMA model with an AR(3) process and a MA(3) process.
Now, we can print a summary of the best model, which an ARIMA (3,1,3).
best_model = SARIMAX(data['data'], order=(3,1,3)).fit()print(best_model.summary())
From the summary above, we can see the value for all coefficients and their associated p-values. Notice how the parameter for the MA process at lag 2 does not seem to be statistically significant according to the p-value. Still, let’s keep it in the model for now.
Hence, from the table above, the time series can be modeled as:
Where epsilon is noise with a variance of 0.0077.
The final part of modelling a time series is to study the residuals.
Ideally, the residuals will be white noise, with no autocorrelation.
A good way to test this is to use the Ljung-Box test. Note that this test can only be applied to the residuals.
# Ljung-Box testljung_box, p_value = acorr_ljungbox(best_model.resid)print(f'Ljung-Box test: {ljung_box[:10]}')print(f'p-value: {p_value[:10]}')
Here, the null hypothesis for the Ljung-Box test is that there is no autocorrelation. Looking at the p-values above, we can see that they are above 0.05. Therefore, we cannot reject the null hypothesis, and the residuals are indeed not correlated.
We can further support that by plotting the ACF and PACF of the residuals.
plot_pacf(best_model.resid);plot_acf(best_model.resid);
As you can see, the plots above resemble those of white noise.
Therefore, this model is ready to be used for forecasting.
Here is a general procedure that you can follow whenever you are faced with a time series:
Plot the data and identify unsual observations. Understand the pattern of the data.Apply a transormation or differencing to remove the trend and stabilize the varianceTest for stationarity. If the series is not stationary, apply another transformation or differencing.Plot the ACF and PACF to maybe estimate the order of the MA or AR process.Try different combinations of orders and select the model with the lowest AIC.Check the residuals and make sure that they look like white noise. Apply the Ljung-Box test to make sure.Calculate forecasts.
Plot the data and identify unsual observations. Understand the pattern of the data.
Apply a transormation or differencing to remove the trend and stabilize the variance
Test for stationarity. If the series is not stationary, apply another transformation or differencing.
Plot the ACF and PACF to maybe estimate the order of the MA or AR process.
Try different combinations of orders and select the model with the lowest AIC.
Check the residuals and make sure that they look like white noise. Apply the Ljung-Box test to make sure.
Calculate forecasts.
Congratulations! You now understand what an ARMA model is and you understand how to use non-seasonal ARIMA models for advanced time series analysis. You also have a road map for time series analysis that you can apply to make sure that you obtain the best model possible.
Learn more about time series analysis with the following course:
Applied Time Series Analysis in Python | [
{
"code": null,
"e": 453,
"s": 172,
"text": "In previous articles, we introduced moving average processes MA(q), and autoregressive processes AR(p) as two ways to model time series. Now, we will combine both methods and explore how ARMA(p,q) and ARIMA(p,d,q) models can help us to model and forecast more complex time series."
},
{
"code": null,
"e": 499,
"s": 453,
"text": "This article will cover the following topics:"
},
{
"code": null,
"e": 511,
"s": 499,
"text": "ARMA models"
},
{
"code": null,
"e": 524,
"s": 511,
"text": "ARIMA models"
},
{
"code": null,
"e": 539,
"s": 524,
"text": "Ljung-Box test"
},
{
"code": null,
"e": 574,
"s": 539,
"text": "Akaike information criterion (AIC)"
},
{
"code": null,
"e": 753,
"s": 574,
"text": "By the end of this article, you should be comfortable with implementing ARMA and ARIMA models in Python and you will have a checklist of steps to take when modelling time series."
},
{
"code": null,
"e": 788,
"s": 753,
"text": "The notebook and dataset are here."
},
{
"code": null,
"e": 807,
"s": 788,
"text": "Let’s get started!"
},
{
"code": null,
"e": 1008,
"s": 807,
"text": "Learn the latest time series analysis techniques with Applied Time Series Analysis in Python. The course covers both statistical and deep learning models, and you will work with Python and TensorFlow!"
},
{
"code": null,
"e": 1072,
"s": 1008,
"text": "Recall that an autoregressive process of order p is defined as:"
},
{
"code": null,
"e": 1079,
"s": 1072,
"text": "Where:"
},
{
"code": null,
"e": 1094,
"s": 1079,
"text": "p is the order"
},
{
"code": null,
"e": 1110,
"s": 1094,
"text": "c is a constant"
},
{
"code": null,
"e": 1125,
"s": 1110,
"text": "epsilon: noise"
},
{
"code": null,
"e": 1184,
"s": 1125,
"text": "Recall also that a moving average process q is defined as:"
},
{
"code": null,
"e": 1191,
"s": 1184,
"text": "Where:"
},
{
"code": null,
"e": 1206,
"s": 1191,
"text": "q is the order"
},
{
"code": null,
"e": 1222,
"s": 1206,
"text": "c is a constant"
},
{
"code": null,
"e": 1239,
"s": 1222,
"text": "epsilon is noise"
},
{
"code": null,
"e": 1323,
"s": 1239,
"text": "Then, an ARMA(p,q) is simply the combination of both models into a single equation:"
},
{
"code": null,
"e": 1485,
"s": 1323,
"text": "Hence, this model can explain the relationship of a time series with both random noise (moving average part) and itself at a previous step (autoregressive part)."
},
{
"code": null,
"e": 1548,
"s": 1485,
"text": "Let’s how an ARMA(p,q) process behaves with a few simulations."
},
{
"code": null,
"e": 1664,
"s": 1548,
"text": "Let’s start with a simple example of an ARMA process of order 1 in both its moving average and autoregressive part."
},
{
"code": null,
"e": 1746,
"s": 1664,
"text": "First, let’s import all libraries that will be required throughout this tutorial:"
},
{
"code": null,
"e": 2303,
"s": 1746,
"text": "from statsmodels.graphics.tsaplots import plot_pacffrom statsmodels.graphics.tsaplots import plot_acffrom statsmodels.tsa.arima_process import ArmaProcessfrom statsmodels.stats.diagnostic import acorr_ljungboxfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import adfullerfrom statsmodels.tsa.stattools import pacffrom statsmodels.tsa.stattools import acffrom tqdm import tqdm_notebookimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport warningswarnings.filterwarnings('ignore')%matplotlib inline"
},
{
"code": null,
"e": 2354,
"s": 2303,
"text": "Then, we will simulate the following ARMA process:"
},
{
"code": null,
"e": 2363,
"s": 2354,
"text": "In code:"
},
{
"code": null,
"e": 2487,
"s": 2363,
"text": "ar1 = np.array([1, 0.33])ma1 = np.array([1, 0.9])simulated_ARMA_data = ArmaProcess(ar1, ma1).generate_sample(nsample=10000)"
},
{
"code": null,
"e": 2564,
"s": 2487,
"text": "We can now plot the first 200 points to visualize our generated time series:"
},
{
"code": null,
"e": 2720,
"s": 2564,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(simulated_ARMA_data)plt.title(\"Simulated ARMA(1,1) Process\")plt.xlim([0, 200])plt.show()"
},
{
"code": null,
"e": 2761,
"s": 2720,
"text": "And you should get something similar to:"
},
{
"code": null,
"e": 2813,
"s": 2761,
"text": "Then, we can take a look at the ACF and PACF plots:"
},
{
"code": null,
"e": 2875,
"s": 2813,
"text": "plot_pacf(simulated_ARMA_data);plot_acf(simulated_ARMA_data);"
},
{
"code": null,
"e": 3102,
"s": 2875,
"text": "As you can see, we cannot infer the order of the ARMA process by looking at these plots. In fact, looking closely, we can see some sinusoidal shape in both ACF and PACF functions. This suggests that both processes are in play."
},
{
"code": null,
"e": 3209,
"s": 3102,
"text": "Similarly, we can simulate an ARMA(2,2) process. In this example, we will simulate the following equation:"
},
{
"code": null,
"e": 3218,
"s": 3209,
"text": "In code:"
},
{
"code": null,
"e": 3353,
"s": 3218,
"text": "ar2 = np.array([1, 0.33, 0.5])ma2 = np.array([1, 0.9, 0.3])simulated_ARMA2_data = ArmaProcess(ar1, ma1).generate_sample(nsample=10000)"
},
{
"code": null,
"e": 3396,
"s": 3353,
"text": "Then, we can visualize the simulated data:"
},
{
"code": null,
"e": 3553,
"s": 3396,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(simulated_ARMA2_data)plt.title(\"Simulated ARMA(2,2) Process\")plt.xlim([0, 200])plt.show()"
},
{
"code": null,
"e": 3588,
"s": 3553,
"text": "Looking at the ACF and PACF plots:"
},
{
"code": null,
"e": 3652,
"s": 3588,
"text": "plot_pacf(simulated_ARMA2_data);plot_acf(simulated_ARMA2_data);"
},
{
"code": null,
"e": 3805,
"s": 3652,
"text": "As you can see, both plots exhibit the same sinusoidal trend, which further supports the fact that both an AR(p) process and a MA(q) process is in play."
},
{
"code": null,
"e": 3864,
"s": 3805,
"text": "ARIMA stands for AutoRegressive Integrated Moving Average."
},
{
"code": null,
"e": 4016,
"s": 3864,
"text": "This model is the combination of autoregression, a moving average model and differencing. In this context, integration is the opposite of differencing."
},
{
"code": null,
"e": 4100,
"s": 4016,
"text": "Differencing is useful to remove the trend in a time series and make it stationary."
},
{
"code": null,
"e": 4267,
"s": 4100,
"text": "It simply involves subtracting a point a t-1 from time t. Realize that you will, therefore, lose the first data point in a time series if you apply differencing once."
},
{
"code": null,
"e": 4331,
"s": 4267,
"text": "Mathematically, the ARIMA(p,d,q) now requires three parameters:"
},
{
"code": null,
"e": 4374,
"s": 4331,
"text": "p: the order of the autoregressive process"
},
{
"code": null,
"e": 4441,
"s": 4374,
"text": "d: the degree of differencing (number of times it was differenced)"
},
{
"code": null,
"e": 4484,
"s": 4441,
"text": "q: the order of the moving average process"
},
{
"code": null,
"e": 4519,
"s": 4484,
"text": "and the equations is expressed as:"
},
{
"code": null,
"e": 4620,
"s": 4519,
"text": "Just like with ARMA models, the ACF and PACF cannot be used to identify reliable values for p and q."
},
{
"code": null,
"e": 4673,
"s": 4620,
"text": "However, in the presence of an ARIMA(p,d,0) process:"
},
{
"code": null,
"e": 4721,
"s": 4673,
"text": "the ACF is exponentially decaying or sinusoidal"
},
{
"code": null,
"e": 4778,
"s": 4721,
"text": "the PACF has a significant spike at lag p but none after"
},
{
"code": null,
"e": 4833,
"s": 4778,
"text": "Similarly, in the presence of an ARIMA(0,d,q) process:"
},
{
"code": null,
"e": 4882,
"s": 4833,
"text": "the PACF is exponentially decaying or sinusoidal"
},
{
"code": null,
"e": 4938,
"s": 4882,
"text": "the ACF has a significant spike at lag q but none after"
},
{
"code": null,
"e": 5071,
"s": 4938,
"text": "Let’s walk through an example of modelling with ARIMA to get some hands-on experience and better understand some modelling concepts."
},
{
"code": null,
"e": 5238,
"s": 5071,
"text": "Let’s revisit a dataset that we analyzed previously. This dataset was used to show the Yule-Walker equation can help us estimate the coefficients of an AR(p) process."
},
{
"code": null,
"e": 5327,
"s": 5238,
"text": "Now, we will use the same dataset, but model the time series with an ARIMA(p,d,q) model."
},
{
"code": null,
"e": 5394,
"s": 5327,
"text": "You can grab the notebook or download the dataset to follow along."
},
{
"code": null,
"e": 5456,
"s": 5394,
"text": "First, we import the dataset and display the first five rows:"
},
{
"code": null,
"e": 5496,
"s": 5456,
"text": "data = pd.read_csv('jj.csv')data.head()"
},
{
"code": null,
"e": 5533,
"s": 5496,
"text": "Then, let’s plot the entire dataset:"
},
{
"code": null,
"e": 5775,
"s": 5533,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.scatter(data['date'], data['data'])plt.title('Quarterly EPS for Johnson & Johnson')plt.ylabel('EPS per share ($)')plt.xlabel('Date')plt.xticks(rotation=90)plt.grid(True)plt.show()"
},
{
"code": null,
"e": 5859,
"s": 5775,
"text": "As you can see, there is both a trend and a change in variance in this time series."
},
{
"code": null,
"e": 5898,
"s": 5859,
"text": "Let’s plot the ACF and PACF functions:"
},
{
"code": null,
"e": 5946,
"s": 5898,
"text": "plot_pacf(data['data']);plot_acf(data['data']);"
},
{
"code": null,
"e": 6049,
"s": 5946,
"text": "As you can see, there is no way of determining the right order for the AR(p) process or MA(q) process."
},
{
"code": null,
"e": 6187,
"s": 6049,
"text": "The plots above are also a clear indication of non-stationarity. To further prove this point, let’s use the augmented Dicker-Fuller test:"
},
{
"code": null,
"e": 6345,
"s": 6187,
"text": "# Augmented Dickey-Fuller testad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')"
},
{
"code": null,
"e": 6481,
"s": 6345,
"text": "Here, the p-value is larger than 0.05, meaning the we cannot reject the null hypothesis stating that the time series is non-stationary."
},
{
"code": null,
"e": 6603,
"s": 6481,
"text": "Therefore, we must apply some transformation and some differencing to remove the trend and remove the change in variance."
},
{
"code": null,
"e": 6835,
"s": 6603,
"text": "We will hence take the log difference of the time series. This is equivalent to taking the logarithm of the EPS, and then apply differencing once. Note that because we are differencing once, we will get rid of the first data point."
},
{
"code": null,
"e": 6996,
"s": 6835,
"text": "# Take the log difference to make data stationarydata['data'] = np.log(data['data'])data['data'] = data['data'].diff()data = data.drop(data.index[0])data.head()"
},
{
"code": null,
"e": 7038,
"s": 6996,
"text": "Now, let’s plot the new transformed data:"
},
{
"code": null,
"e": 7195,
"s": 7038,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title(\"Log Difference of Quarterly EPS for Johnson & Johnson\")plt.show()"
},
{
"code": null,
"e": 7387,
"s": 7195,
"text": "It seems that trend and the change in variance were removed, but we want to make sure that it is the case. Therefore, we apply the augmented Dickey-Fuller test again to test for stationarity."
},
{
"code": null,
"e": 7545,
"s": 7387,
"text": "# Augmented Dickey-Fuller testad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')"
},
{
"code": null,
"e": 7665,
"s": 7545,
"text": "This time, the p-value is less than 0.05, we reject the null hypothesis, and assume that the time series is stationary."
},
{
"code": null,
"e": 7770,
"s": 7665,
"text": "Now, let’s look at the PACF and ACF to see if we can estimate the order of one of the processes in play."
},
{
"code": null,
"e": 7818,
"s": 7770,
"text": "plot_pacf(data['data']);plot_acf(data['data']);"
},
{
"code": null,
"e": 7976,
"s": 7818,
"text": "Examining the PACF above, it seems that there is an AR process of order 3 or 4 in play. However, the ACF is not informative and we see some sinusoidal shape."
},
{
"code": null,
"e": 8079,
"s": 7976,
"text": "Therefore, how can we make sure that we choose the right order for both the AR(p) and MA(q) processes?"
},
{
"code": null,
"e": 8209,
"s": 8079,
"text": "We will need try different combinations of orders, fit an ARIMA model with those orders, and use a criterion for order selection."
},
{
"code": null,
"e": 8279,
"s": 8209,
"text": "This brings us to the topic of Akaike’s Information Criterion or AIC."
},
{
"code": null,
"e": 8380,
"s": 8279,
"text": "This criterion is useful for selecting the order (p,d,q) of an ARIMA model. The AIC is expressed as:"
},
{
"code": null,
"e": 8453,
"s": 8380,
"text": "Where L is the likelihood of the data and k is the number of parameters."
},
{
"code": null,
"e": 8532,
"s": 8453,
"text": "In practice, we select the model with the lowest AIC compared to other models."
},
{
"code": null,
"e": 8781,
"s": 8532,
"text": "It is important to note that the AIC cannot be used to select the order of differencing (d). Differencing the data will the change the likelihood (L) of the data. The AIC of models with different orders of differencing are therefore not comparable."
},
{
"code": null,
"e": 9081,
"s": 8781,
"text": "Also, notice that since we select the model with the lowest AIC, more parameters will increase the AIC score and thus penalize the model. While a model with more parameters could perform better, the AIC is used to find the model with the least number of parameters that will still give good results."
},
{
"code": null,
"e": 9282,
"s": 9081,
"text": "A final note on AIC is that it can only be used relative to other models. A small AIC value is not a guarantee that the model will have a good performance on unsee data, or that its SSE will be small."
},
{
"code": null,
"e": 9432,
"s": 9282,
"text": "Now that we know how we will base our decision to select the best order for the ARIMA model, let’s write a function that will test all orders for us."
},
{
"code": null,
"e": 10137,
"s": 9432,
"text": "def optimize_ARIMA(order_list, exog): \"\"\" Return dataframe with parameters and corresponding AIC order_list - list with (p, d, q) tuples exog - the exogenous variable \"\"\" results = [] for order in tqdm_notebook(order_list): try: model = SARIMAX(exog, order=order).fit(disp=-1) except: continue aic = model.aic results.append([order, model.aic]) result_df = pd.DataFrame(results) result_df.columns = ['(p, d, q)', 'AIC'] #Sort in ascending order, lower AIC is better result_df = result_df.sort_values(by='AIC', ascending=True).reset_index(drop=True) return result_df"
},
{
"code": null,
"e": 10273,
"s": 10137,
"text": "The function above will result in a dataframe that will list the orders and the corresponding AIC, starting with the best model on top."
},
{
"code": null,
"e": 10388,
"s": 10273,
"text": "We will try all combinations with orders (p,q) ranging from 0 to 8, but keeping the differencing order equal to 1."
},
{
"code": null,
"e": 10757,
"s": 10388,
"text": "ps = range(0, 8, 1)d = 1qs = range(0, 8, 1)# Create a list with all possible combination of parametersparameters = product(ps, qs)parameters_list = list(parameters)order_list = []for each in parameters_list: each = list(each) each.insert(1, 1) each = tuple(each) order_list.append(each) result_df = optimize_ARIMA(order_list, exog=data['data'])result_df"
},
{
"code": null,
"e": 10949,
"s": 10757,
"text": "Once the function is done running, you should see that the order associated with the lowest AIC is (3,1,3). Therefore, this suggests are ARIMA model with an AR(3) process and a MA(3) process."
},
{
"code": null,
"e": 11020,
"s": 10949,
"text": "Now, we can print a summary of the best model, which an ARIMA (3,1,3)."
},
{
"code": null,
"e": 11103,
"s": 11020,
"text": "best_model = SARIMAX(data['data'], order=(3,1,3)).fit()print(best_model.summary())"
},
{
"code": null,
"e": 11368,
"s": 11103,
"text": "From the summary above, we can see the value for all coefficients and their associated p-values. Notice how the parameter for the MA process at lag 2 does not seem to be statistically significant according to the p-value. Still, let’s keep it in the model for now."
},
{
"code": null,
"e": 11432,
"s": 11368,
"text": "Hence, from the table above, the time series can be modeled as:"
},
{
"code": null,
"e": 11482,
"s": 11432,
"text": "Where epsilon is noise with a variance of 0.0077."
},
{
"code": null,
"e": 11551,
"s": 11482,
"text": "The final part of modelling a time series is to study the residuals."
},
{
"code": null,
"e": 11620,
"s": 11551,
"text": "Ideally, the residuals will be white noise, with no autocorrelation."
},
{
"code": null,
"e": 11732,
"s": 11620,
"text": "A good way to test this is to use the Ljung-Box test. Note that this test can only be applied to the residuals."
},
{
"code": null,
"e": 11877,
"s": 11732,
"text": "# Ljung-Box testljung_box, p_value = acorr_ljungbox(best_model.resid)print(f'Ljung-Box test: {ljung_box[:10]}')print(f'p-value: {p_value[:10]}')"
},
{
"code": null,
"e": 12125,
"s": 11877,
"text": "Here, the null hypothesis for the Ljung-Box test is that there is no autocorrelation. Looking at the p-values above, we can see that they are above 0.05. Therefore, we cannot reject the null hypothesis, and the residuals are indeed not correlated."
},
{
"code": null,
"e": 12200,
"s": 12125,
"text": "We can further support that by plotting the ACF and PACF of the residuals."
},
{
"code": null,
"e": 12256,
"s": 12200,
"text": "plot_pacf(best_model.resid);plot_acf(best_model.resid);"
},
{
"code": null,
"e": 12319,
"s": 12256,
"text": "As you can see, the plots above resemble those of white noise."
},
{
"code": null,
"e": 12378,
"s": 12319,
"text": "Therefore, this model is ready to be used for forecasting."
},
{
"code": null,
"e": 12469,
"s": 12378,
"text": "Here is a general procedure that you can follow whenever you are faced with a time series:"
},
{
"code": null,
"e": 13015,
"s": 12469,
"text": "Plot the data and identify unsual observations. Understand the pattern of the data.Apply a transormation or differencing to remove the trend and stabilize the varianceTest for stationarity. If the series is not stationary, apply another transformation or differencing.Plot the ACF and PACF to maybe estimate the order of the MA or AR process.Try different combinations of orders and select the model with the lowest AIC.Check the residuals and make sure that they look like white noise. Apply the Ljung-Box test to make sure.Calculate forecasts."
},
{
"code": null,
"e": 13099,
"s": 13015,
"text": "Plot the data and identify unsual observations. Understand the pattern of the data."
},
{
"code": null,
"e": 13184,
"s": 13099,
"text": "Apply a transormation or differencing to remove the trend and stabilize the variance"
},
{
"code": null,
"e": 13286,
"s": 13184,
"text": "Test for stationarity. If the series is not stationary, apply another transformation or differencing."
},
{
"code": null,
"e": 13361,
"s": 13286,
"text": "Plot the ACF and PACF to maybe estimate the order of the MA or AR process."
},
{
"code": null,
"e": 13440,
"s": 13361,
"text": "Try different combinations of orders and select the model with the lowest AIC."
},
{
"code": null,
"e": 13546,
"s": 13440,
"text": "Check the residuals and make sure that they look like white noise. Apply the Ljung-Box test to make sure."
},
{
"code": null,
"e": 13567,
"s": 13546,
"text": "Calculate forecasts."
},
{
"code": null,
"e": 13839,
"s": 13567,
"text": "Congratulations! You now understand what an ARMA model is and you understand how to use non-seasonal ARIMA models for advanced time series analysis. You also have a road map for time series analysis that you can apply to make sure that you obtain the best model possible."
},
{
"code": null,
"e": 13904,
"s": 13839,
"text": "Learn more about time series analysis with the following course:"
}
] |
How do you improve Matplotlib image quality? | To improve matplotlib image quality we can use greater dot per inch i.e dpi value (greater than 600) and pdf or .eps format can be recommended.
Set the figure size and adjust the padding between and around the subplots.
Make a 2D data raster using a np.array.
Display data as an image, i.e., on a 2D regular raster.
Save the current image using savefig() with dpi=1200 and .eps format,
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.array(
[[0.1, 0.7, 0.6, 0.3],
[0.2, 0.6, 0.5, 0.2],
[0.8, 0.3, 0.80, 0.01],
[0.3, 0.4, 0.2, 0.1]]
)
plt.imshow(data, interpolation="nearest", cmap="RdYlGn_r")
plt.savefig("myimage.eps", dpi=1200)
plt.show() | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "To improve matplotlib image quality we can use greater dot per inch i.e dpi value (greater than 600) and pdf or .eps format can be recommended."
},
{
"code": null,
"e": 1282,
"s": 1206,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1322,
"s": 1282,
"text": "Make a 2D data raster using a np.array."
},
{
"code": null,
"e": 1378,
"s": 1322,
"text": "Display data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1448,
"s": 1378,
"text": "Save the current image using savefig() with dpi=1200 and .eps format,"
},
{
"code": null,
"e": 1490,
"s": 1448,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1862,
"s": 1490,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.array(\n [[0.1, 0.7, 0.6, 0.3],\n [0.2, 0.6, 0.5, 0.2],\n [0.8, 0.3, 0.80, 0.01],\n [0.3, 0.4, 0.2, 0.1]]\n)\nplt.imshow(data, interpolation=\"nearest\", cmap=\"RdYlGn_r\")\nplt.savefig(\"myimage.eps\", dpi=1200)\nplt.show()"
}
] |
Decision Tree In Python. An example of how to implement a... | by Cory Maklin | Towards Data Science | In my opinion, Decision Tree models help highlight how we can use machine learning to enhance our decision making abilities. We’ve all encountered Decision Trees at one point or another. However, where Decision Tree machine learning models differ is in the fact that they use logic and math to generate rules, rather than selecting them on the basis of intuition and subjectivity.
When attempting to build a decision tree, the question that should immediately come to mind is:
On what basis should we make decisions?
In other words, what should we select as the yes or no questions which are used to classify our data. We could take an educated guess (i.e. all mice with a weight over 5 pounds are obese). However, it isn’t necessarily the best way to categorize our samples. What if, we could use some kind of machine learning algorithm to learn what questions to ask in order to do the best job at classifying our data? That is the purpose behind decision tree models.
Suppose that we were trying to build a decision tree to predict whether a person is married. Therefore, we went around the neighborhood knocking on people’s doors and politely asked them to provide their age, sex and income for our little research project. Out of the couple thousand people we asked, 240 didn’t slam the door into our face.
Now, before we continue it’s important that we grasp the following terminology. The top of the tree (or bottom depending on how you look at it) is called the root node. Intermediate nodes have arrows pointing to and away from them. Finally, the nodes at the bottom of the tree without any edges pointing away from them are called leaves. Leaves tell you what class each sample belongs to.
Going back to our example, we need to figure out how to go from a table of data to a decision tree. Rather than selecting the branches ourselves, we decide to use a machine learning algorithm to construct the decision tree for us. The model looks at how well each feature separates people who are and aren’t married. Since income is a continuous variable, we set an arbitrary value.
In order to determine which of the three splits is better, we introduce a concept called impurity. Impurity refers to the fact that none of the leaves have a 100% “yes married”. There are several ways to measure impurity (quality of a split), however, the scikit-learn implementation of the DecisionTreeClassifer uses gini by default, therefore, that’s the one we’re going to cover in this article.
To calculate the Gini impurity of the left leaf, we subtract 1 by the fraction of people that are married squared and the fraction of people that aren’t married squared.
The equation is the exact same for the impurity of the right leaf.
The Gini impurity for the node itself is 1 minus the fraction of samples in the left child, minus the fraction of samples in the right child.
The information gain (with Gini Index) is written as follows.
The process is then repeated for income and sex. We ultimately decide on the split with the largest information gain. In this case, it’s income, which makes sense since there is a strong correlation between an income of greater than 50,000 and being married. If we ask that question right away, we make a substantial leap towards correctly classifying our data.
Once we’ve decided on the root, we repeat the process for the other nodes in the tree. It’s worth noting that:
a) We can split on income again
b) The number of samples in each branch can differ
We can’t go on splitting indefinitely. Therefore, we need a way of telling the tree when to stop. The scikit-learn implementation of the DecisionTreeClassifer uses the minimum impurity decrease to determine whether a node should be split.
Suppose that we after a few more iterations, we end up with the following node on the left hand side of the tree.
The result is greater than the default threshold of 0. Therefore, the node will be split. Had it been below 0, the node’s children would have been considered a leaves.
Let’s take a look at how we could go about implementing a decision tree classifier in Python. To begin, we import the following libraries.
from sklearn.datasets import load_irisfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image from pydot import graph_from_dot_dataimport pandas as pdimport numpy as np
For this tutorial, we’ll be working with what has to be the most popular dataset in the field of machine learning, the iris dataset from UC Irvine Machine Learning Repository.
iris = load_iris()X = pd.DataFrame(iris.data, columns=iris.feature_names)y = pd.Categorical.from_codes(iris.target, iris.target_names)
In the proceeding section, we’ll attempt to build a decision tree classifier to determine the kind of flower given its dimensions.
X.head()
Although, decision trees can handle categorical data, we still encode the targets in terms of digits (i.e. setosa=0, versicolor=1, virginica=2) in order to create a confusion matrix at a later point. Fortunately, the pandas library provides a method for this very purpose.
y = pd.get_dummies(y)
We’ll want to evaluate the performance of our model. Therefore, we set a quarter of the data aside for testing.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
Next, we create and train an instance of the DecisionTreeClassifer class. We provide the y values because our model uses a supervised machine learning algorithm.
dt = DecisionTreeClassifier()dt.fit(X_train, y_train)
We can view the actual decision tree produced by our model by running the following block of code.
dot_data = StringIO()export_graphviz(dt, out_file=dot_data, feature_names=iris.feature_names)(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png())
Notice how it provides the Gini impurity, the total number of samples, the classification criteria and the number of samples on the left/right sides.
Let’s see how our decision tree does when its presented with test data.
y_pred = dt.predict(X_test)
If this were a regression problem, we’d use some kind of loss function such as Mean Square Error (MSE). However, since this is a classification problem, we make use of a confusion matrix to gauge the accuracy of our model. The confusion matrix is best explained with the use of an example.
Suppose your friend just took a pregnancy test. The results could fall in one of the 4 following categories.
True Positive:
Interpretation: You predicted positive and it’s true.
You predicted that a woman is pregnant and she actually is.
True Negative:
Interpretation: You predicted negative and it’s true.
You predicted that a man is not pregnant and he actually is not.
False Positive: (Type 1 Error)
Interpretation: You predicted positive and it’s false.
You predicted that a man is pregnant but he actually is not.
False Negative: (Type 2 Error)
Interpretation: You predicted negative and it’s false.
You predicted that a woman is not pregnant but she actually is.
That being said, the numbers on the diagonal of the confusion matrix correspond to correct predictions. When there are more than two potential outcomes, we simply extend the number of columns and rows in the confusion matrix.
species = np.array(y_test).argmax(axis=1)predictions = np.array(y_pred).argmax(axis=1)confusion_matrix(species, predictions)
As we can see, our decision tree classifier correctly classified 37/38 plants.
Decision Trees are easy to interpret, don’t require any normalization, and can be applied to both regression and classification problems. Unfortunately, Decision Trees are seldom used in practice because they don’t generalize well. Stay tuned for the next article where we’ll cover Random Forest, a method of combining multiple Decision Trees to achieve better accuracy. | [
{
"code": null,
"e": 553,
"s": 172,
"text": "In my opinion, Decision Tree models help highlight how we can use machine learning to enhance our decision making abilities. We’ve all encountered Decision Trees at one point or another. However, where Decision Tree machine learning models differ is in the fact that they use logic and math to generate rules, rather than selecting them on the basis of intuition and subjectivity."
},
{
"code": null,
"e": 649,
"s": 553,
"text": "When attempting to build a decision tree, the question that should immediately come to mind is:"
},
{
"code": null,
"e": 689,
"s": 649,
"text": "On what basis should we make decisions?"
},
{
"code": null,
"e": 1143,
"s": 689,
"text": "In other words, what should we select as the yes or no questions which are used to classify our data. We could take an educated guess (i.e. all mice with a weight over 5 pounds are obese). However, it isn’t necessarily the best way to categorize our samples. What if, we could use some kind of machine learning algorithm to learn what questions to ask in order to do the best job at classifying our data? That is the purpose behind decision tree models."
},
{
"code": null,
"e": 1484,
"s": 1143,
"text": "Suppose that we were trying to build a decision tree to predict whether a person is married. Therefore, we went around the neighborhood knocking on people’s doors and politely asked them to provide their age, sex and income for our little research project. Out of the couple thousand people we asked, 240 didn’t slam the door into our face."
},
{
"code": null,
"e": 1873,
"s": 1484,
"text": "Now, before we continue it’s important that we grasp the following terminology. The top of the tree (or bottom depending on how you look at it) is called the root node. Intermediate nodes have arrows pointing to and away from them. Finally, the nodes at the bottom of the tree without any edges pointing away from them are called leaves. Leaves tell you what class each sample belongs to."
},
{
"code": null,
"e": 2256,
"s": 1873,
"text": "Going back to our example, we need to figure out how to go from a table of data to a decision tree. Rather than selecting the branches ourselves, we decide to use a machine learning algorithm to construct the decision tree for us. The model looks at how well each feature separates people who are and aren’t married. Since income is a continuous variable, we set an arbitrary value."
},
{
"code": null,
"e": 2655,
"s": 2256,
"text": "In order to determine which of the three splits is better, we introduce a concept called impurity. Impurity refers to the fact that none of the leaves have a 100% “yes married”. There are several ways to measure impurity (quality of a split), however, the scikit-learn implementation of the DecisionTreeClassifer uses gini by default, therefore, that’s the one we’re going to cover in this article."
},
{
"code": null,
"e": 2825,
"s": 2655,
"text": "To calculate the Gini impurity of the left leaf, we subtract 1 by the fraction of people that are married squared and the fraction of people that aren’t married squared."
},
{
"code": null,
"e": 2892,
"s": 2825,
"text": "The equation is the exact same for the impurity of the right leaf."
},
{
"code": null,
"e": 3034,
"s": 2892,
"text": "The Gini impurity for the node itself is 1 minus the fraction of samples in the left child, minus the fraction of samples in the right child."
},
{
"code": null,
"e": 3096,
"s": 3034,
"text": "The information gain (with Gini Index) is written as follows."
},
{
"code": null,
"e": 3458,
"s": 3096,
"text": "The process is then repeated for income and sex. We ultimately decide on the split with the largest information gain. In this case, it’s income, which makes sense since there is a strong correlation between an income of greater than 50,000 and being married. If we ask that question right away, we make a substantial leap towards correctly classifying our data."
},
{
"code": null,
"e": 3569,
"s": 3458,
"text": "Once we’ve decided on the root, we repeat the process for the other nodes in the tree. It’s worth noting that:"
},
{
"code": null,
"e": 3601,
"s": 3569,
"text": "a) We can split on income again"
},
{
"code": null,
"e": 3652,
"s": 3601,
"text": "b) The number of samples in each branch can differ"
},
{
"code": null,
"e": 3891,
"s": 3652,
"text": "We can’t go on splitting indefinitely. Therefore, we need a way of telling the tree when to stop. The scikit-learn implementation of the DecisionTreeClassifer uses the minimum impurity decrease to determine whether a node should be split."
},
{
"code": null,
"e": 4005,
"s": 3891,
"text": "Suppose that we after a few more iterations, we end up with the following node on the left hand side of the tree."
},
{
"code": null,
"e": 4173,
"s": 4005,
"text": "The result is greater than the default threshold of 0. Therefore, the node will be split. Had it been below 0, the node’s children would have been considered a leaves."
},
{
"code": null,
"e": 4312,
"s": 4173,
"text": "Let’s take a look at how we could go about implementing a decision tree classifier in Python. To begin, we import the following libraries."
},
{
"code": null,
"e": 4685,
"s": 4312,
"text": "from sklearn.datasets import load_irisfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import confusion_matrixfrom sklearn.tree import export_graphvizfrom sklearn.externals.six import StringIO from IPython.display import Image from pydot import graph_from_dot_dataimport pandas as pdimport numpy as np"
},
{
"code": null,
"e": 4861,
"s": 4685,
"text": "For this tutorial, we’ll be working with what has to be the most popular dataset in the field of machine learning, the iris dataset from UC Irvine Machine Learning Repository."
},
{
"code": null,
"e": 4996,
"s": 4861,
"text": "iris = load_iris()X = pd.DataFrame(iris.data, columns=iris.feature_names)y = pd.Categorical.from_codes(iris.target, iris.target_names)"
},
{
"code": null,
"e": 5127,
"s": 4996,
"text": "In the proceeding section, we’ll attempt to build a decision tree classifier to determine the kind of flower given its dimensions."
},
{
"code": null,
"e": 5136,
"s": 5127,
"text": "X.head()"
},
{
"code": null,
"e": 5409,
"s": 5136,
"text": "Although, decision trees can handle categorical data, we still encode the targets in terms of digits (i.e. setosa=0, versicolor=1, virginica=2) in order to create a confusion matrix at a later point. Fortunately, the pandas library provides a method for this very purpose."
},
{
"code": null,
"e": 5431,
"s": 5409,
"text": "y = pd.get_dummies(y)"
},
{
"code": null,
"e": 5543,
"s": 5431,
"text": "We’ll want to evaluate the performance of our model. Therefore, we set a quarter of the data aside for testing."
},
{
"code": null,
"e": 5617,
"s": 5543,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)"
},
{
"code": null,
"e": 5779,
"s": 5617,
"text": "Next, we create and train an instance of the DecisionTreeClassifer class. We provide the y values because our model uses a supervised machine learning algorithm."
},
{
"code": null,
"e": 5833,
"s": 5779,
"text": "dt = DecisionTreeClassifier()dt.fit(X_train, y_train)"
},
{
"code": null,
"e": 5932,
"s": 5833,
"text": "We can view the actual decision tree produced by our model by running the following block of code."
},
{
"code": null,
"e": 6103,
"s": 5932,
"text": "dot_data = StringIO()export_graphviz(dt, out_file=dot_data, feature_names=iris.feature_names)(graph, ) = graph_from_dot_data(dot_data.getvalue())Image(graph.create_png())"
},
{
"code": null,
"e": 6253,
"s": 6103,
"text": "Notice how it provides the Gini impurity, the total number of samples, the classification criteria and the number of samples on the left/right sides."
},
{
"code": null,
"e": 6325,
"s": 6253,
"text": "Let’s see how our decision tree does when its presented with test data."
},
{
"code": null,
"e": 6353,
"s": 6325,
"text": "y_pred = dt.predict(X_test)"
},
{
"code": null,
"e": 6643,
"s": 6353,
"text": "If this were a regression problem, we’d use some kind of loss function such as Mean Square Error (MSE). However, since this is a classification problem, we make use of a confusion matrix to gauge the accuracy of our model. The confusion matrix is best explained with the use of an example."
},
{
"code": null,
"e": 6752,
"s": 6643,
"text": "Suppose your friend just took a pregnancy test. The results could fall in one of the 4 following categories."
},
{
"code": null,
"e": 6767,
"s": 6752,
"text": "True Positive:"
},
{
"code": null,
"e": 6821,
"s": 6767,
"text": "Interpretation: You predicted positive and it’s true."
},
{
"code": null,
"e": 6881,
"s": 6821,
"text": "You predicted that a woman is pregnant and she actually is."
},
{
"code": null,
"e": 6896,
"s": 6881,
"text": "True Negative:"
},
{
"code": null,
"e": 6950,
"s": 6896,
"text": "Interpretation: You predicted negative and it’s true."
},
{
"code": null,
"e": 7015,
"s": 6950,
"text": "You predicted that a man is not pregnant and he actually is not."
},
{
"code": null,
"e": 7046,
"s": 7015,
"text": "False Positive: (Type 1 Error)"
},
{
"code": null,
"e": 7101,
"s": 7046,
"text": "Interpretation: You predicted positive and it’s false."
},
{
"code": null,
"e": 7162,
"s": 7101,
"text": "You predicted that a man is pregnant but he actually is not."
},
{
"code": null,
"e": 7193,
"s": 7162,
"text": "False Negative: (Type 2 Error)"
},
{
"code": null,
"e": 7248,
"s": 7193,
"text": "Interpretation: You predicted negative and it’s false."
},
{
"code": null,
"e": 7312,
"s": 7248,
"text": "You predicted that a woman is not pregnant but she actually is."
},
{
"code": null,
"e": 7538,
"s": 7312,
"text": "That being said, the numbers on the diagonal of the confusion matrix correspond to correct predictions. When there are more than two potential outcomes, we simply extend the number of columns and rows in the confusion matrix."
},
{
"code": null,
"e": 7663,
"s": 7538,
"text": "species = np.array(y_test).argmax(axis=1)predictions = np.array(y_pred).argmax(axis=1)confusion_matrix(species, predictions)"
},
{
"code": null,
"e": 7742,
"s": 7663,
"text": "As we can see, our decision tree classifier correctly classified 37/38 plants."
}
] |
Python | Extract substrings between brackets | 07 Feb, 2022
Sometimes, while working with Python strings, we can have a problem in which we need to extract the substrings between certain characters and can be brackets. This can have application in cases we have tuples embedded in string. Lets discuss certain ways in which this task can be performed.Method #1 : Using regex One way to solve this problem is by using regex. In this we employ suitable regex and perform the task of extraction of required elements.
Python3
# Python3 code to demonstrate working of# Extract substrings between brackets# Using regeximport re # initializing stringtest_str = "geeks(for)geeks is (best)" # printing original stringprint("The original string is : " + test_str) # Extract substrings between brackets# Using regexres = re.findall(r'\(.*?\)', test_str) # printing resultprint("The element between brackets : " + str(res))
The original string is : geeks(for)geeks is (best)
The element between brackets : ['(for)', '(best)']
Method #2 : Using list comprehension + isinstance() + eval() The combination of above methods can also be used to solve this problem. In this eval() assume the brackets to be tuples and helps the extraction of strings within them.
Python3
# Python3 code to demonstrate working of# Extract substrings between brackets# Using list comprehension + eval() + isinstance() # initializing stringtest_str = "[(234, ), 4, (432, )]" # printing original stringprint("The original string is : " + test_str) # Extract substrings between brackets# Using list comprehension + eval() + isinstance()res = [str(idx) for idx in eval(test_str) if isinstance(idx, tuple)] # printing resultprint("The element between brackets : " + str(res))
The original string is : [(234, ), 4, (432, )]
The element between brackets : ['(234, )', '(432, )']
saurabh1990aror
Python string-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": "\n07 Feb, 2022"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "Sometimes, while working with Python strings, we can have a problem in which we need to extract the substrings between certain characters and can be brackets. This can have application in cases we have tuples embedded in string. Lets discuss certain ways in which this task can be performed.Method #1 : Using regex One way to solve this problem is by using regex. In this we employ suitable regex and perform the task of extraction of required elements. "
},
{
"code": null,
"e": 492,
"s": 484,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Extract substrings between brackets# Using regeximport re # initializing stringtest_str = \"geeks(for)geeks is (best)\" # printing original stringprint(\"The original string is : \" + test_str) # Extract substrings between brackets# Using regexres = re.findall(r'\\(.*?\\)', test_str) # printing resultprint(\"The element between brackets : \" + str(res))",
"e": 882,
"s": 492,
"text": null
},
{
"code": null,
"e": 984,
"s": 882,
"text": "The original string is : geeks(for)geeks is (best)\nThe element between brackets : ['(for)', '(best)']"
},
{
"code": null,
"e": 1219,
"s": 986,
"text": " Method #2 : Using list comprehension + isinstance() + eval() The combination of above methods can also be used to solve this problem. In this eval() assume the brackets to be tuples and helps the extraction of strings within them. "
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Extract substrings between brackets# Using list comprehension + eval() + isinstance() # initializing stringtest_str = \"[(234, ), 4, (432, )]\" # printing original stringprint(\"The original string is : \" + test_str) # Extract substrings between brackets# Using list comprehension + eval() + isinstance()res = [str(idx) for idx in eval(test_str) if isinstance(idx, tuple)] # printing resultprint(\"The element between brackets : \" + str(res))",
"e": 1708,
"s": 1227,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1708,
"text": "The original string is : [(234, ), 4, (432, )]\nThe element between brackets : ['(234, )', '(432, )']"
},
{
"code": null,
"e": 1827,
"s": 1811,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1850,
"s": 1827,
"text": "Python string-programs"
},
{
"code": null,
"e": 1857,
"s": 1850,
"text": "Python"
},
{
"code": null,
"e": 1873,
"s": 1857,
"text": "Python Programs"
}
] |
Maryam – Perfect OSINT Framework | 15 Dec, 2021
OSINT techniques are used to collect the data from publicly possible sources like Social Media Platforms etc. There are various ways to collect information. There are some automated tools that make the task easier. Maryam tool is one of the best tools which is been designed by the OWASP team and has the potential to collect information from open sources. This tool is developed in the Python language and it also comes as the package in the Python Pip. We can collect lots of information from Twitter, LinkedIn, and also from Google. This tool is also available on the GitHub platform. It’s free and open-source to use.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/saeeddhqan/Maryam.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd Maryam
Step 3: You are in the directory of the Maryam. Now you have to install a dependency of the Maryam using the following command.
sudo pip install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system.
./maryam
Example 1: Modules
show modules
In this example, we have displayed the list of available modules which the tool offers.
Example 2: Anonymous Email Grabbing – OSINT
email_search
In this example, we are using the Email Grabbing module.
email_search -q gmail.com -e bing,google,yahoo –output
We have got the email address for public sources.
Example 3: Social Nets – OSINT
social_nets
In this example, we are using the Social Nets module.
social_nets -q geeksforgeeks.org -e google,yahoo,bing
We have got the information about the geeksforgeeks username for public sources.
Example 4: Crawl Pages – Footprinting
crawl_pages
In this example, we are using the Crawl Pages module.
crawl_pages -d geeksforgeeks.org -r “https?://[A-z0-9./]+” –output
We have got the URLs that match the regex which is been provided in the query
Example 5: Getting Profiles From LinkedIn – Search
linkedin
In this example, we are using the LinkedIn module.
linkedin -q geeksforgeeks -e google,bing,yahoo
We have got the link of profiles on LinkedIn which are been associated with the geeksforgeeks organization.
Example 6: Getting Profiles From Twitter – Search
twitter
In this example, we are using the Twitter module.
twitter -q geeksforgeeks -e bing,google
We have got the link of profiles on Twitter which are been associated with the geeksforgeeks organization.
adnanirshad158
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 650,
"s": 28,
"text": "OSINT techniques are used to collect the data from publicly possible sources like Social Media Platforms etc. There are various ways to collect information. There are some automated tools that make the task easier. Maryam tool is one of the best tools which is been designed by the OWASP team and has the potential to collect information from open sources. This tool is developed in the Python language and it also comes as the package in the Python Pip. We can collect lots of information from Twitter, LinkedIn, and also from Google. This tool is also available on the GitHub platform. It’s free and open-source to use."
},
{
"code": null,
"e": 816,
"s": 650,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 907,
"s": 816,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 958,
"s": 907,
"text": "git clone https://github.com/saeeddhqan/Maryam.git"
},
{
"code": null,
"e": 1096,
"s": 958,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 1106,
"s": 1096,
"text": "cd Maryam"
},
{
"code": null,
"e": 1234,
"s": 1106,
"text": "Step 3: You are in the directory of the Maryam. Now you have to install a dependency of the Maryam using the following command."
},
{
"code": null,
"e": 1271,
"s": 1234,
"text": "sudo pip install -r requirements.txt"
},
{
"code": null,
"e": 1357,
"s": 1271,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system."
},
{
"code": null,
"e": 1366,
"s": 1357,
"text": "./maryam"
},
{
"code": null,
"e": 1385,
"s": 1366,
"text": "Example 1: Modules"
},
{
"code": null,
"e": 1398,
"s": 1385,
"text": "show modules"
},
{
"code": null,
"e": 1486,
"s": 1398,
"text": "In this example, we have displayed the list of available modules which the tool offers."
},
{
"code": null,
"e": 1530,
"s": 1486,
"text": "Example 2: Anonymous Email Grabbing – OSINT"
},
{
"code": null,
"e": 1543,
"s": 1530,
"text": "email_search"
},
{
"code": null,
"e": 1600,
"s": 1543,
"text": "In this example, we are using the Email Grabbing module."
},
{
"code": null,
"e": 1655,
"s": 1600,
"text": "email_search -q gmail.com -e bing,google,yahoo –output"
},
{
"code": null,
"e": 1705,
"s": 1655,
"text": "We have got the email address for public sources."
},
{
"code": null,
"e": 1736,
"s": 1705,
"text": "Example 3: Social Nets – OSINT"
},
{
"code": null,
"e": 1748,
"s": 1736,
"text": "social_nets"
},
{
"code": null,
"e": 1802,
"s": 1748,
"text": "In this example, we are using the Social Nets module."
},
{
"code": null,
"e": 1856,
"s": 1802,
"text": "social_nets -q geeksforgeeks.org -e google,yahoo,bing"
},
{
"code": null,
"e": 1937,
"s": 1856,
"text": "We have got the information about the geeksforgeeks username for public sources."
},
{
"code": null,
"e": 1975,
"s": 1937,
"text": "Example 4: Crawl Pages – Footprinting"
},
{
"code": null,
"e": 1987,
"s": 1975,
"text": "crawl_pages"
},
{
"code": null,
"e": 2041,
"s": 1987,
"text": "In this example, we are using the Crawl Pages module."
},
{
"code": null,
"e": 2108,
"s": 2041,
"text": "crawl_pages -d geeksforgeeks.org -r “https?://[A-z0-9./]+” –output"
},
{
"code": null,
"e": 2186,
"s": 2108,
"text": "We have got the URLs that match the regex which is been provided in the query"
},
{
"code": null,
"e": 2237,
"s": 2186,
"text": "Example 5: Getting Profiles From LinkedIn – Search"
},
{
"code": null,
"e": 2246,
"s": 2237,
"text": "linkedin"
},
{
"code": null,
"e": 2297,
"s": 2246,
"text": "In this example, we are using the LinkedIn module."
},
{
"code": null,
"e": 2344,
"s": 2297,
"text": "linkedin -q geeksforgeeks -e google,bing,yahoo"
},
{
"code": null,
"e": 2452,
"s": 2344,
"text": "We have got the link of profiles on LinkedIn which are been associated with the geeksforgeeks organization."
},
{
"code": null,
"e": 2502,
"s": 2452,
"text": "Example 6: Getting Profiles From Twitter – Search"
},
{
"code": null,
"e": 2510,
"s": 2502,
"text": "twitter"
},
{
"code": null,
"e": 2560,
"s": 2510,
"text": "In this example, we are using the Twitter module."
},
{
"code": null,
"e": 2600,
"s": 2560,
"text": "twitter -q geeksforgeeks -e bing,google"
},
{
"code": null,
"e": 2707,
"s": 2600,
"text": "We have got the link of profiles on Twitter which are been associated with the geeksforgeeks organization."
},
{
"code": null,
"e": 2722,
"s": 2707,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2733,
"s": 2722,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2745,
"s": 2733,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2756,
"s": 2745,
"text": "Linux-Unix"
}
] |
Python | os.read() method | 18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.read() method in Python is used to read at most n bytes from the file associated with the given file descriptor.
If the end of the file has been reached while reading bytes from the given file descriptor, os.read() method will return an empty bytes object for all bytes left to be read.
A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc.
Note: os.read() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method.
Syntax: os.read(fd, n)
Parameter:fd: A file descriptor representing the file to be read.n: An integer value denoting the number of bytes to be read from the file associated with the given file descriptor fd.
Return Type: This method returns a bytestring which represents the bytes read from the file associated with the file descriptor fd.
Consider the below text as the content of the file named Python_intro.txt.
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
# Python program to explain os.read() method # importing os module import os # File path path = "/home / ihritik / Documents / Python_intro.txt" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDONLY) # Number of bytes to be readn = 50 # Read at most n bytes # from file descriptor fd# using os.read() methodreadBytes = os.read(fd, n) # Print the bytes readprint(readBytes) # close the file descriptoros.close(fd)
b'Python is a widely used general-purpose, high leve'
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 389,
"s": 273,
"text": "os.read() method in Python is used to read at most n bytes from the file associated with the given file descriptor."
},
{
"code": null,
"e": 563,
"s": 389,
"text": "If the end of the file has been reached while reading bytes from the given file descriptor, os.read() method will return an empty bytes object for all bytes left to be read."
},
{
"code": null,
"e": 761,
"s": 563,
"text": "A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc."
},
{
"code": null,
"e": 909,
"s": 761,
"text": "Note: os.read() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method."
},
{
"code": null,
"e": 932,
"s": 909,
"text": "Syntax: os.read(fd, n)"
},
{
"code": null,
"e": 1117,
"s": 932,
"text": "Parameter:fd: A file descriptor representing the file to be read.n: An integer value denoting the number of bytes to be read from the file associated with the given file descriptor fd."
},
{
"code": null,
"e": 1249,
"s": 1117,
"text": "Return Type: This method returns a bytestring which represents the bytes read from the file associated with the file descriptor fd."
},
{
"code": null,
"e": 1324,
"s": 1249,
"text": "Consider the below text as the content of the file named Python_intro.txt."
},
{
"code": null,
"e": 1733,
"s": 1324,
"text": "Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently."
},
{
"code": "# Python program to explain os.read() method # importing os module import os # File path path = \"/home / ihritik / Documents / Python_intro.txt\" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDONLY) # Number of bytes to be readn = 50 # Read at most n bytes # from file descriptor fd# using os.read() methodreadBytes = os.read(fd, n) # Print the bytes readprint(readBytes) # close the file descriptoros.close(fd)",
"e": 2224,
"s": 1733,
"text": null
},
{
"code": null,
"e": 2279,
"s": 2224,
"text": "b'Python is a widely used general-purpose, high leve'\n"
},
{
"code": null,
"e": 2296,
"s": 2279,
"text": "python-os-module"
},
{
"code": null,
"e": 2303,
"s": 2296,
"text": "Python"
}
] |
Modulo power for large numbers represented as strings | 03 May, 2021
Given two numbers sa and sb represented as strings, find ab % MOD where MOD is 1e9 + 7. The numbers a and b can contain upto 106 digits.Examples:
Input : sa = 2, sb = 3 Output : 8Input : sa = 10000000000000000000000000000000000000000000 sb = 10000000000000000000000000000000000000000000 Output : 494234546
As a and b very large (may contain upto 10^6 digits each). So what we can do, we apply Fermat’s little theorem and property of modulo to reduce a and b. Reduce a: As we know,
(ab) % MOD = ((a % MOD)b) % MOD
Reduce b: How to reduce b, We have already discuss in Find (a^b)%m where ‘b’ is very largeNow finally we have both a and b are in range of 1<=a, b<=10^9+7. Hence we can now use our modular exponentiation to calculate required answer.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find (a^b) % MOD where a and// b may be very large and represented as strings.#include <bits/stdc++.h>using namespace std; #define ll long long intconst ll MOD = 1e9 + 7; // Returns modulo exponentiation for two numbers// represented as long long int. It is used by// powerStrings(). Its complexity is log(n)ll powerLL(ll x, ll n){ ll result = 1; while (n) { if (n & 1) result = result * x % MOD; n = n / 2; x = x * x % MOD; } return result;} // Returns modulo exponentiation for two numbers// represented as strings. It is used by// powerStrings()ll powerStrings(string sa, string sb){ // We convert strings to number ll a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa[i] - '0')) % MOD; // calculating b % (MOD - 1) for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb[i] - '0')) % (MOD - 1); // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b);} int main(){ // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. string sa = "2", sb = "3"; cout << powerStrings(sa, sb) << endl; return 0;}
// Java program to find (a^b) % MOD// where a and b may be very large// and represented as strings.import java.util.*; class GFG{ static long MOD = (long) (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long int. It is used by // powerStrings(). Its complexity is log(n) static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = n / 2; x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() static long powerStrings(String sa, String sb) { // We convert strings to number long a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.length(); i++) { a = (a * 10 + (sa.charAt(i) - '0')) % MOD; } // calculating b % (MOD - 1) for (int i = 0; i < sb.length(); i++) { b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); } // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver code public static void main(String[] args) { // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. String sa = "2", sb = "3"; System.out.println(powerStrings(sa, sb)); }} // This code is contributed by Rajput-JI
# Python3 program to find (a^b) % MOD# where a and b may be very large# and represented as strings.MOD = 1000000007; # Returns modulo exponentiation# for two numbers represented as# long long int. It is used by# powerStrings(). Its complexity# is log(n)def powerLL(x, n): result = 1; while (n): if (n & 1): result = result * x % MOD; n = int(n / 2); x = x * x % MOD; return result; # Returns modulo exponentiation# for two numbers represented as# strings. It is used by powerStrings()def powerStrings(sa, sb): # We convert strings to number a = 0; b = 0; # calculating a % MOD for i in range(len(sa)): a = (a * 10 + (ord(sa[i]) - ord('0'))) % MOD; # calculating b % (MOD - 1) for i in range(len(sb)): b = (b * 10 + (ord(sb[i]) - ord('0'))) % (MOD - 1); # Now a and b are long long int. # We calculate a^b using modulo # exponentiation return powerLL(a, b); # Driver code # As numbers are very large# that is it may contains upto# 10^6 digits. So, we use string.sa = "2";sb = "3"; print(powerStrings(sa, sb)); # This code is contributed by mits
// C# program to find (a^b) % MOD where a and b // may be very large and represented as strings.using System; class GFG{ static long MOD = (long) (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long int. It is used by // powerStrings(). Its complexity is log(n) static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = n / 2; x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() static long powerStrings(String sa, String sb) { // We convert strings to number long a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.Length; i++) { a = (a * 10 + (sa[i] - '0')) % MOD; } // calculating b % (MOD - 1) for (int i = 0; i < sb.Length; i++) { b = (b * 10 + (sb[i] - '0')) % (MOD - 1); } // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver code public static void Main(String[] args) { // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. String sa = "2", sb = "3"; Console.WriteLine(powerStrings(sa, sb)); }} // This code is contributed by 29AjayKumar
<?php// PHP program to find (a^b) % MOD// where a and b may be very large// and represented as strings.$MOD = 1000000007; // Returns modulo exponentiation// for two numbers represented as// long long int. It is used by// powerStrings(). Its complexity// is log(n)function powerLL($x, $n){ global $MOD; $result = 1; while ($n) { if ($n & 1) $result = $result * $x % $MOD; $n = (int)$n / 2; $x = $x * $x % $MOD; } return $result;} // Returns modulo exponentiation// for two numbers represented as// strings. It is used by powerStrings()function powerStrings($sa, $sb){ global $MOD; // We convert strings to number $a = 0; $b = 0; // calculating a % MOD for ($i = 0; $i < strlen($sa); $i++) $a = ($a * 10 + ($sa[$i] - '0')) % $MOD; // calculating b % (MOD - 1) for ($i = 0; $i < strlen($sb); $i++) $b = ($b * 10 + ($sb[$i] - '0')) % ($MOD - 1); // Now a and b are long long int. // We calculate a^b using modulo // exponentiation return powerLL($a, $b);} // Driver code // As numbers are very large// that is it may contains upto// 10^6 digits. So, we use string.$sa = "2";$sb = "3"; echo powerStrings($sa, $sb); // This code is contributed by mits?>
<script> // Javascript program to find (a^b) % MOD where a and b // may be very large and represented as strings. let MOD = (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long let. It is used by // powerStrings(). Its complexity is log(n) function powerLL(x, n) { let result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = Math.floor(n / 2); x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() function powerStrings(sa, sb) { // We convert strings to number let a = 0, b = 0; // calculating a % MOD for (let i = 0; i < sa.length; i++) { a = (a * 10 + (sa[i] - '0')) % MOD; } // calculating b % (MOD - 1) for (let i = 0; i < sb.length; i++) { b = (b * 10 + (sb[i] - '0')) % (MOD - 1); } // Now a and b are long long let. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver Code // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. let sa = "2", sb = "3"; document.write(powerStrings(sa, sb)); </script>
8
Mithun Kumar
Rajput-Ji
29AjayKumar
sanjoy_62
large-numbers
math
Modular Arithmetic
number-digits
number-theory
Competitive Programming
Mathematical
number-theory
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 202,
"s": 54,
"text": "Given two numbers sa and sb represented as strings, find ab % MOD where MOD is 1e9 + 7. The numbers a and b can contain upto 106 digits.Examples: "
},
{
"code": null,
"e": 362,
"s": 202,
"text": "Input : sa = 2, sb = 3 Output : 8Input : sa = 10000000000000000000000000000000000000000000 sb = 10000000000000000000000000000000000000000000 Output : 494234546"
},
{
"code": null,
"e": 540,
"s": 364,
"text": "As a and b very large (may contain upto 10^6 digits each). So what we can do, we apply Fermat’s little theorem and property of modulo to reduce a and b. Reduce a: As we know, "
},
{
"code": null,
"e": 572,
"s": 540,
"text": "(ab) % MOD = ((a % MOD)b) % MOD"
},
{
"code": null,
"e": 808,
"s": 572,
"text": "Reduce b: How to reduce b, We have already discuss in Find (a^b)%m where ‘b’ is very largeNow finally we have both a and b are in range of 1<=a, b<=10^9+7. Hence we can now use our modular exponentiation to calculate required answer. "
},
{
"code": null,
"e": 812,
"s": 808,
"text": "C++"
},
{
"code": null,
"e": 817,
"s": 812,
"text": "Java"
},
{
"code": null,
"e": 825,
"s": 817,
"text": "Python3"
},
{
"code": null,
"e": 828,
"s": 825,
"text": "C#"
},
{
"code": null,
"e": 832,
"s": 828,
"text": "PHP"
},
{
"code": null,
"e": 843,
"s": 832,
"text": "Javascript"
},
{
"code": "// CPP program to find (a^b) % MOD where a and// b may be very large and represented as strings.#include <bits/stdc++.h>using namespace std; #define ll long long intconst ll MOD = 1e9 + 7; // Returns modulo exponentiation for two numbers// represented as long long int. It is used by// powerStrings(). Its complexity is log(n)ll powerLL(ll x, ll n){ ll result = 1; while (n) { if (n & 1) result = result * x % MOD; n = n / 2; x = x * x % MOD; } return result;} // Returns modulo exponentiation for two numbers// represented as strings. It is used by// powerStrings()ll powerStrings(string sa, string sb){ // We convert strings to number ll a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa[i] - '0')) % MOD; // calculating b % (MOD - 1) for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb[i] - '0')) % (MOD - 1); // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b);} int main(){ // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. string sa = \"2\", sb = \"3\"; cout << powerStrings(sa, sb) << endl; return 0;}",
"e": 2102,
"s": 843,
"text": null
},
{
"code": "// Java program to find (a^b) % MOD// where a and b may be very large// and represented as strings.import java.util.*; class GFG{ static long MOD = (long) (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long int. It is used by // powerStrings(). Its complexity is log(n) static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = n / 2; x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() static long powerStrings(String sa, String sb) { // We convert strings to number long a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.length(); i++) { a = (a * 10 + (sa.charAt(i) - '0')) % MOD; } // calculating b % (MOD - 1) for (int i = 0; i < sb.length(); i++) { b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); } // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver code public static void main(String[] args) { // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. String sa = \"2\", sb = \"3\"; System.out.println(powerStrings(sa, sb)); }} // This code is contributed by Rajput-JI",
"e": 3787,
"s": 2102,
"text": null
},
{
"code": "# Python3 program to find (a^b) % MOD# where a and b may be very large# and represented as strings.MOD = 1000000007; # Returns modulo exponentiation# for two numbers represented as# long long int. It is used by# powerStrings(). Its complexity# is log(n)def powerLL(x, n): result = 1; while (n): if (n & 1): result = result * x % MOD; n = int(n / 2); x = x * x % MOD; return result; # Returns modulo exponentiation# for two numbers represented as# strings. It is used by powerStrings()def powerStrings(sa, sb): # We convert strings to number a = 0; b = 0; # calculating a % MOD for i in range(len(sa)): a = (a * 10 + (ord(sa[i]) - ord('0'))) % MOD; # calculating b % (MOD - 1) for i in range(len(sb)): b = (b * 10 + (ord(sb[i]) - ord('0'))) % (MOD - 1); # Now a and b are long long int. # We calculate a^b using modulo # exponentiation return powerLL(a, b); # Driver code # As numbers are very large# that is it may contains upto# 10^6 digits. So, we use string.sa = \"2\";sb = \"3\"; print(powerStrings(sa, sb)); # This code is contributed by mits",
"e": 4976,
"s": 3787,
"text": null
},
{
"code": "// C# program to find (a^b) % MOD where a and b // may be very large and represented as strings.using System; class GFG{ static long MOD = (long) (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long int. It is used by // powerStrings(). Its complexity is log(n) static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = n / 2; x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() static long powerStrings(String sa, String sb) { // We convert strings to number long a = 0, b = 0; // calculating a % MOD for (int i = 0; i < sa.Length; i++) { a = (a * 10 + (sa[i] - '0')) % MOD; } // calculating b % (MOD - 1) for (int i = 0; i < sb.Length; i++) { b = (b * 10 + (sb[i] - '0')) % (MOD - 1); } // Now a and b are long long int. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver code public static void Main(String[] args) { // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. String sa = \"2\", sb = \"3\"; Console.WriteLine(powerStrings(sa, sb)); }} // This code is contributed by 29AjayKumar",
"e": 6575,
"s": 4976,
"text": null
},
{
"code": "<?php// PHP program to find (a^b) % MOD// where a and b may be very large// and represented as strings.$MOD = 1000000007; // Returns modulo exponentiation// for two numbers represented as// long long int. It is used by// powerStrings(). Its complexity// is log(n)function powerLL($x, $n){ global $MOD; $result = 1; while ($n) { if ($n & 1) $result = $result * $x % $MOD; $n = (int)$n / 2; $x = $x * $x % $MOD; } return $result;} // Returns modulo exponentiation// for two numbers represented as// strings. It is used by powerStrings()function powerStrings($sa, $sb){ global $MOD; // We convert strings to number $a = 0; $b = 0; // calculating a % MOD for ($i = 0; $i < strlen($sa); $i++) $a = ($a * 10 + ($sa[$i] - '0')) % $MOD; // calculating b % (MOD - 1) for ($i = 0; $i < strlen($sb); $i++) $b = ($b * 10 + ($sb[$i] - '0')) % ($MOD - 1); // Now a and b are long long int. // We calculate a^b using modulo // exponentiation return powerLL($a, $b);} // Driver code // As numbers are very large// that is it may contains upto// 10^6 digits. So, we use string.$sa = \"2\";$sb = \"3\"; echo powerStrings($sa, $sb); // This code is contributed by mits?>",
"e": 7878,
"s": 6575,
"text": null
},
{
"code": "<script> // Javascript program to find (a^b) % MOD where a and b // may be very large and represented as strings. let MOD = (1e9 + 7); // Returns modulo exponentiation for two numbers // represented as long long let. It is used by // powerStrings(). Its complexity is log(n) function powerLL(x, n) { let result = 1; while (n > 0) { if (n % 2 == 1) { result = result * x % MOD; } n = Math.floor(n / 2); x = x * x % MOD; } return result; } // Returns modulo exponentiation for // two numbers represented as strings. // It is used by powerStrings() function powerStrings(sa, sb) { // We convert strings to number let a = 0, b = 0; // calculating a % MOD for (let i = 0; i < sa.length; i++) { a = (a * 10 + (sa[i] - '0')) % MOD; } // calculating b % (MOD - 1) for (let i = 0; i < sb.length; i++) { b = (b * 10 + (sb[i] - '0')) % (MOD - 1); } // Now a and b are long long let. We // calculate a^b using modulo exponentiation return powerLL(a, b); } // Driver Code // As numbers are very large // that is it may contains upto // 10^6 digits. So, we use string. let sa = \"2\", sb = \"3\"; document.write(powerStrings(sa, sb)); </script>",
"e": 9333,
"s": 7878,
"text": null
},
{
"code": null,
"e": 9335,
"s": 9333,
"text": "8"
},
{
"code": null,
"e": 9350,
"s": 9337,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9360,
"s": 9350,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9372,
"s": 9360,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9382,
"s": 9372,
"text": "sanjoy_62"
},
{
"code": null,
"e": 9396,
"s": 9382,
"text": "large-numbers"
},
{
"code": null,
"e": 9401,
"s": 9396,
"text": "math"
},
{
"code": null,
"e": 9420,
"s": 9401,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 9434,
"s": 9420,
"text": "number-digits"
},
{
"code": null,
"e": 9448,
"s": 9434,
"text": "number-theory"
},
{
"code": null,
"e": 9472,
"s": 9448,
"text": "Competitive Programming"
},
{
"code": null,
"e": 9485,
"s": 9472,
"text": "Mathematical"
},
{
"code": null,
"e": 9499,
"s": 9485,
"text": "number-theory"
},
{
"code": null,
"e": 9512,
"s": 9499,
"text": "Mathematical"
},
{
"code": null,
"e": 9531,
"s": 9512,
"text": "Modular Arithmetic"
}
] |
PHP | Arrays | 05 Aug, 2021
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key. An array is created using an array() function in PHP.
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices.
Indexed or Numeric Arrays
These type of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways as shown in the following example:
PHP
<?php // One way to create an indexed array$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav"); // Accessing the elements directlyecho "Accessing the 1st array elements directly:\n";echo $name_one[2], "\n";echo $name_one[0], "\n";echo $name_one[4], "\n"; // Second way to create an indexed array$name_two[0] = "ZACK";$name_two[1] = "ANTHONY";$name_two[2] = "RAM";$name_two[3] = "SALIM";$name_two[4] = "RAGHAV"; // Accessing the elements directlyecho "Accessing the 2nd array elements directly:\n";echo $name_two[2], "\n";echo $name_two[0], "\n";echo $name_two[4], "\n"; ?>
Output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV
Traversing: We can traverse an indexed array using loops in PHP. We can loop through the indexed array in two ways. First by using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax and basic use.
Example:
PHP
<?php // Creating an indexed array$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav"); // One way of Looping through an array using foreachecho "Looping using foreach: \n";foreach ($name_one as $val){ echo $val. "\n";} // count() function is used to count// the number of elements in an array$round = count($name_one);echo "\nThe number of elements are $round \n"; // Another way to loop through the array using forecho "Looping using for: \n";for($n = 0; $n < $round; $n++){ echo $name_one[$n], "\n";} ?>
Output:
Looping using foreach:
Zack
Anthony
Ram
Salim
Raghav
The number of elements is 5
Looping using for:
ZACK
ANTHONY
RAM
SALIM
RAGHAV
Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.
Example:
PHP
<?php // One way to create an associative array$name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani", "Salim"=>"Sara", "Raghav"=>"Ravina"); // Second way to create an associative array$name_two["zack"] = "zara";$name_two["anthony"] = "any";$name_two["ram"] = "rani";$name_two["salim"] = "sara";$name_two["raghav"] = "ravina"; // Accessing the elements directlyecho "Accessing the elements directly:\n";echo $name_two["zack"], "\n";echo $name_two["salim"], "\n";echo $name_two["anthony"], "\n";echo $name_one["Ram"], "\n";echo $name_one["Raghav"], "\n"; ?>
Output:
Accessing the elements directly:
zara
sara
any
Rani
Ravina
Traversing Associative Arrays: We can traverse associative arrays in a similar way did in numeric arrays using loops. We can loop through the associative array in two ways. First by using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax and basic use.
Example:
PHP
<?php // Creating an associative array$name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani", "Salim"=>"Sara", "Raghav"=>"Ravina"); // Looping through an array using foreachecho "Looping using foreach: \n";foreach ($name_one as $val => $val_value){ echo "Husband is ".$val." and Wife is ".$val_value."\n";} // Looping through an array using forecho "\nLooping using for: \n";$keys = array_keys($name_two);$round = count($name_two); for($i=0; $i < $round; ++$i) { echo $keys[$i] . ' ' . $name_two[$keys[$i]] . "\n";} ?>
Output:
Looping using foreach:
Husband is Zack and Wife is Zara
Husband is Anthony and Wife is Any
Husband is Ram and Wife is Rani
Husband is Salim and Wife is Sara
Husband is Raghav and Wife is Ravina
Looping using for:
zack zara
anthony any
ram rani
salim sara
raghav ravina
Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
Example:
PHP
<?php // Defining a multidimensional array$favorites = array( array( "name" => "Dave Punk", "mob" => "5689741523", "email" => "[email protected]", ), array( "name" => "Monty Smith", "mob" => "2584369721", "email" => "[email protected]", ), array( "name" => "John Flinch", "mob" => "9875147536", "email" => "[email protected]", )); // Accessing elementsecho "Dave Punk email-id is: " . $favorites[0]["email"], "\n";echo "John Flinch mobile number is: " . $favorites[2]["mob"]; ?>
Output:
Dave Punk email-id is: [email protected]
John Flinch mobile number is: 9875147536
Traversing Multidimensional Arrays: We can traverse through the multidimensional array using for and foreach loop in a nested way. That is, one for loop for the outer array and one for loop for the inner array.
Example:
PHP
<?php// Defining a multidimensional array$favorites = array( "Dave Punk" => array( "mob" => "5689741523", "email" => "[email protected]", ), "Dave Punk" => array( "mob" => "2584369721", "email" => "[email protected]", ), "John Flinch" => array( "mob" => "9875147536", "email" => "[email protected]", )); // Using for and foreach in nested form$keys = array_keys($favorites);for($i = 0; $i < count($favorites); $i++) { echo $keys[$i] . "\n"; foreach($favorites[$keys[$i]] as $key => $value) { echo $key . " : " . $value . "\n"; } echo "\n";} ?>
Output:
Dave Punk
mob : 2584369721
email : [email protected]
John Flinch
mob : 9875147536
email : [email protected]
This article is contributed by Chinmoy Lenka. 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.
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.
sourabh1031
KunalKumarOfficial
aounbaloch
snehasajmec
anikakapoor
PHP-array
PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 861,
"s": 52,
"text": "Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key. An array is created using an array() function in PHP."
},
{
"code": null,
"e": 912,
"s": 861,
"text": "There are basically three types of arrays in PHP: "
},
{
"code": null,
"e": 1003,
"s": 912,
"text": "Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly."
},
{
"code": null,
"e": 1128,
"s": 1003,
"text": "Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key."
},
{
"code": null,
"e": 1254,
"s": 1128,
"text": "Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices."
},
{
"code": null,
"e": 1280,
"s": 1254,
"text": "Indexed or Numeric Arrays"
},
{
"code": null,
"e": 1501,
"s": 1280,
"text": "These type of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways as shown in the following example: "
},
{
"code": null,
"e": 1505,
"s": 1501,
"text": "PHP"
},
{
"code": "<?php // One way to create an indexed array$name_one = array(\"Zack\", \"Anthony\", \"Ram\", \"Salim\", \"Raghav\"); // Accessing the elements directlyecho \"Accessing the 1st array elements directly:\\n\";echo $name_one[2], \"\\n\";echo $name_one[0], \"\\n\";echo $name_one[4], \"\\n\"; // Second way to create an indexed array$name_two[0] = \"ZACK\";$name_two[1] = \"ANTHONY\";$name_two[2] = \"RAM\";$name_two[3] = \"SALIM\";$name_two[4] = \"RAGHAV\"; // Accessing the elements directlyecho \"Accessing the 2nd array elements directly:\\n\";echo $name_two[2], \"\\n\";echo $name_two[0], \"\\n\";echo $name_two[4], \"\\n\"; ?>",
"e": 2089,
"s": 1505,
"text": null
},
{
"code": null,
"e": 2098,
"s": 2089,
"text": "Output: "
},
{
"code": null,
"e": 2216,
"s": 2098,
"text": "Accessing the 1st array elements directly:\nRam\nZack\nRaghav\nAccessing the 2nd array elements directly:\nRAM\nZACK\nRAGHAV"
},
{
"code": null,
"e": 2447,
"s": 2216,
"text": "Traversing: We can traverse an indexed array using loops in PHP. We can loop through the indexed array in two ways. First by using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax and basic use. "
},
{
"code": null,
"e": 2458,
"s": 2447,
"text": "Example: "
},
{
"code": null,
"e": 2462,
"s": 2458,
"text": "PHP"
},
{
"code": "<?php // Creating an indexed array$name_one = array(\"Zack\", \"Anthony\", \"Ram\", \"Salim\", \"Raghav\"); // One way of Looping through an array using foreachecho \"Looping using foreach: \\n\";foreach ($name_one as $val){ echo $val. \"\\n\";} // count() function is used to count// the number of elements in an array$round = count($name_one);echo \"\\nThe number of elements are $round \\n\"; // Another way to loop through the array using forecho \"Looping using for: \\n\";for($n = 0; $n < $round; $n++){ echo $name_one[$n], \"\\n\";} ?>",
"e": 2985,
"s": 2462,
"text": null
},
{
"code": null,
"e": 2994,
"s": 2985,
"text": "Output: "
},
{
"code": null,
"e": 3128,
"s": 2994,
"text": "Looping using foreach: \nZack\nAnthony\nRam\nSalim\nRaghav\n\nThe number of elements is 5 \nLooping using for: \nZACK\nANTHONY\nRAM\nSALIM\nRAGHAV"
},
{
"code": null,
"e": 3147,
"s": 3128,
"text": "Associative Arrays"
},
{
"code": null,
"e": 3303,
"s": 3147,
"text": "These types of arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type. "
},
{
"code": null,
"e": 3314,
"s": 3303,
"text": "Example: "
},
{
"code": null,
"e": 3318,
"s": 3314,
"text": "PHP"
},
{
"code": "<?php // One way to create an associative array$name_one = array(\"Zack\"=>\"Zara\", \"Anthony\"=>\"Any\", \"Ram\"=>\"Rani\", \"Salim\"=>\"Sara\", \"Raghav\"=>\"Ravina\"); // Second way to create an associative array$name_two[\"zack\"] = \"zara\";$name_two[\"anthony\"] = \"any\";$name_two[\"ram\"] = \"rani\";$name_two[\"salim\"] = \"sara\";$name_two[\"raghav\"] = \"ravina\"; // Accessing the elements directlyecho \"Accessing the elements directly:\\n\";echo $name_two[\"zack\"], \"\\n\";echo $name_two[\"salim\"], \"\\n\";echo $name_two[\"anthony\"], \"\\n\";echo $name_one[\"Ram\"], \"\\n\";echo $name_one[\"Raghav\"], \"\\n\"; ?>",
"e": 3920,
"s": 3318,
"text": null
},
{
"code": null,
"e": 3929,
"s": 3920,
"text": "Output: "
},
{
"code": null,
"e": 3988,
"s": 3929,
"text": "Accessing the elements directly:\nzara\nsara\nany\nRani\nRavina"
},
{
"code": null,
"e": 4276,
"s": 3988,
"text": "Traversing Associative Arrays: We can traverse associative arrays in a similar way did in numeric arrays using loops. We can loop through the associative array in two ways. First by using for loop and secondly by using foreach. You can refer to PHP | Loops for the syntax and basic use. "
},
{
"code": null,
"e": 4287,
"s": 4276,
"text": "Example: "
},
{
"code": null,
"e": 4291,
"s": 4287,
"text": "PHP"
},
{
"code": "<?php // Creating an associative array$name_one = array(\"Zack\"=>\"Zara\", \"Anthony\"=>\"Any\", \"Ram\"=>\"Rani\", \"Salim\"=>\"Sara\", \"Raghav\"=>\"Ravina\"); // Looping through an array using foreachecho \"Looping using foreach: \\n\";foreach ($name_one as $val => $val_value){ echo \"Husband is \".$val.\" and Wife is \".$val_value.\"\\n\";} // Looping through an array using forecho \"\\nLooping using for: \\n\";$keys = array_keys($name_two);$round = count($name_two); for($i=0; $i < $round; ++$i) { echo $keys[$i] . ' ' . $name_two[$keys[$i]] . \"\\n\";} ?>",
"e": 4865,
"s": 4291,
"text": null
},
{
"code": null,
"e": 4874,
"s": 4865,
"text": "Output: "
},
{
"code": null,
"e": 5146,
"s": 4874,
"text": "Looping using foreach: \nHusband is Zack and Wife is Zara\nHusband is Anthony and Wife is Any\nHusband is Ram and Wife is Rani\nHusband is Salim and Wife is Sara\nHusband is Raghav and Wife is Ravina\n\nLooping using for: \nzack zara\nanthony any\nram rani\nsalim sara\nraghav ravina"
},
{
"code": null,
"e": 5170,
"s": 5146,
"text": "Multidimensional Arrays"
},
{
"code": null,
"e": 5563,
"s": 5170,
"text": "Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions. "
},
{
"code": null,
"e": 5574,
"s": 5563,
"text": "Example: "
},
{
"code": null,
"e": 5578,
"s": 5574,
"text": "PHP"
},
{
"code": "<?php // Defining a multidimensional array$favorites = array( array( \"name\" => \"Dave Punk\", \"mob\" => \"5689741523\", \"email\" => \"[email protected]\", ), array( \"name\" => \"Monty Smith\", \"mob\" => \"2584369721\", \"email\" => \"[email protected]\", ), array( \"name\" => \"John Flinch\", \"mob\" => \"9875147536\", \"email\" => \"[email protected]\", )); // Accessing elementsecho \"Dave Punk email-id is: \" . $favorites[0][\"email\"], \"\\n\";echo \"John Flinch mobile number is: \" . $favorites[2][\"mob\"]; ?>",
"e": 6145,
"s": 5578,
"text": null
},
{
"code": null,
"e": 6154,
"s": 6145,
"text": "Output: "
},
{
"code": null,
"e": 6237,
"s": 6154,
"text": "Dave Punk email-id is: [email protected]\nJohn Flinch mobile number is: 9875147536"
},
{
"code": null,
"e": 6448,
"s": 6237,
"text": "Traversing Multidimensional Arrays: We can traverse through the multidimensional array using for and foreach loop in a nested way. That is, one for loop for the outer array and one for loop for the inner array."
},
{
"code": null,
"e": 6459,
"s": 6448,
"text": "Example: "
},
{
"code": null,
"e": 6463,
"s": 6459,
"text": "PHP"
},
{
"code": "<?php// Defining a multidimensional array$favorites = array( \"Dave Punk\" => array( \"mob\" => \"5689741523\", \"email\" => \"[email protected]\", ), \"Dave Punk\" => array( \"mob\" => \"2584369721\", \"email\" => \"[email protected]\", ), \"John Flinch\" => array( \"mob\" => \"9875147536\", \"email\" => \"[email protected]\", )); // Using for and foreach in nested form$keys = array_keys($favorites);for($i = 0; $i < count($favorites); $i++) { echo $keys[$i] . \"\\n\"; foreach($favorites[$keys[$i]] as $key => $value) { echo $key . \" : \" . $value . \"\\n\"; } echo \"\\n\";} ?>",
"e": 7093,
"s": 6463,
"text": null
},
{
"code": null,
"e": 7102,
"s": 7093,
"text": "Output: "
},
{
"code": null,
"e": 7217,
"s": 7102,
"text": "Dave Punk\nmob : 2584369721\nemail : [email protected]\n\nJohn Flinch\nmob : 9875147536\nemail : [email protected]"
},
{
"code": null,
"e": 7639,
"s": 7217,
"text": "This article is contributed by Chinmoy Lenka. 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": 7808,
"s": 7639,
"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": 7822,
"s": 7810,
"text": "sourabh1031"
},
{
"code": null,
"e": 7841,
"s": 7822,
"text": "KunalKumarOfficial"
},
{
"code": null,
"e": 7852,
"s": 7841,
"text": "aounbaloch"
},
{
"code": null,
"e": 7864,
"s": 7852,
"text": "snehasajmec"
},
{
"code": null,
"e": 7876,
"s": 7864,
"text": "anikakapoor"
},
{
"code": null,
"e": 7886,
"s": 7876,
"text": "PHP-array"
},
{
"code": null,
"e": 7897,
"s": 7886,
"text": "PHP-basics"
},
{
"code": null,
"e": 7901,
"s": 7897,
"text": "PHP"
},
{
"code": null,
"e": 7918,
"s": 7901,
"text": "Web Technologies"
},
{
"code": null,
"e": 7922,
"s": 7918,
"text": "PHP"
}
] |
ML | Fuzzy Clustering | 17 Sep, 2019
Prerequisite: Clustering in Machine Learning
What is clustering?Clustering is an unsupervised machine learning technique which divides the given data into different clusters based on their distances (similarity) from each other.
The unsupervised k-means clustering algorithm gives the values of any point lying in some particular cluster to be either as 0 or 1 i.e., either true or false. But the fuzzy logic gives the fuzzy values of any particular data point to be lying in either of the clusters. Here, in fuzzy c-means clustering, we find out the centroid of the data points and then calculate the distance of each data point from the given centroids until the clusters formed becomes constant.
Suppose the given data points are {(1, 3), (2, 5), (6, 8), (7, 9)} The steps to perform algorithm are:
Step 1: Initialize the data points into desired number of clusters randomly.Let’s assume there are 2 clusters in which the data is to be divided, initializing the data point randomly. Each data point lies in both the clusters with some membership value which can be assumed anything in the initial state.
The table below represents the values of the data points along with their membership (gamma) in each of the cluster.
Cluster (1, 3) (2, 5) (4, 8) (7, 9)
1) 0.8 0.7 0.2 0.1
2) 0.2 0.3 0.8 0.9
Step 2: Find out the centroid.The formula for finding out the centroid (V) is:
Where, μ is fuzzy membership value of the data point, m is the fuzziness parameter (generally taken as 2), and xk is the data point.Here,
V11 = (0.82 *1 + 0.72 * 2 + 0.22 * 4 + 0.12 * 7) / ( (0.82 + 0.72 + 0.22 + 0.12 ) = 1.568
V12 = (0.82 *3 + 0.72 * 5 + 0.22 * 8 + 0.12 * 9) / ( (0.82 + 0.72 + 0.22 + 0.12 ) = 4.051
V11 = (0.22 *1 + 0.32 * 2 + 0.82 * 4 + 0.92 * 7) / ( (0.22 + 0.32 + 0.82 + 0.92 ) = 5.35
V11 = (0.22 *3 + 0.32 * 5 + 0.82 * 8 + 0.92 * 9) / ( (0.22 + 0.32 + 0.82 + 0.92 ) = 8.215
Centroids are: (1.568, 4.051) and (5.35, 8.215)
Step 3: Find out the distance of each point from centroid.
D11 = ((1 - 1.568)2 + (3 - 4.051)2)0.5 = 1.2
D12 = ((1 - 5.35)2 + (3 - 8.215)2)0.5 = 6.79
Similarly, the distance of all other points is computed from both the centroids.
Step 4: Updating membership values.
For point 1 new membership values are:
Similarly, compute all other membership values, and update the matrix.
Step 5: Repeat the steps(2-4) until the constant values are obtained for the membership values or the difference is less than the tolerance value (a small value up to which the difference in values of two consequent updations is accepted).
Step 6: Defuzzify the obtained membership values. Implementation: The fuzzy scikit learn library has a pre-defined function for fuzzy c-means which can be used in Python. For using fuzzy c-means you need to install the skfuzzy library.
pip install sklearn
pip install skfuzzy
fuzzy-logic
Articles
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 97,
"s": 52,
"text": "Prerequisite: Clustering in Machine Learning"
},
{
"code": null,
"e": 281,
"s": 97,
"text": "What is clustering?Clustering is an unsupervised machine learning technique which divides the given data into different clusters based on their distances (similarity) from each other."
},
{
"code": null,
"e": 751,
"s": 281,
"text": "The unsupervised k-means clustering algorithm gives the values of any point lying in some particular cluster to be either as 0 or 1 i.e., either true or false. But the fuzzy logic gives the fuzzy values of any particular data point to be lying in either of the clusters. Here, in fuzzy c-means clustering, we find out the centroid of the data points and then calculate the distance of each data point from the given centroids until the clusters formed becomes constant."
},
{
"code": null,
"e": 854,
"s": 751,
"text": "Suppose the given data points are {(1, 3), (2, 5), (6, 8), (7, 9)} The steps to perform algorithm are:"
},
{
"code": null,
"e": 1159,
"s": 854,
"text": "Step 1: Initialize the data points into desired number of clusters randomly.Let’s assume there are 2 clusters in which the data is to be divided, initializing the data point randomly. Each data point lies in both the clusters with some membership value which can be assumed anything in the initial state."
},
{
"code": null,
"e": 1276,
"s": 1159,
"text": "The table below represents the values of the data points along with their membership (gamma) in each of the cluster."
},
{
"code": null,
"e": 1419,
"s": 1276,
"text": "Cluster (1, 3) (2, 5) (4, 8) (7, 9)\n1) 0.8 0.7 0.2 0.1\n2) 0.2 0.3 0.8 0.9\n"
},
{
"code": null,
"e": 1498,
"s": 1419,
"text": "Step 2: Find out the centroid.The formula for finding out the centroid (V) is:"
},
{
"code": null,
"e": 1636,
"s": 1498,
"text": "Where, μ is fuzzy membership value of the data point, m is the fuzziness parameter (generally taken as 2), and xk is the data point.Here,"
},
{
"code": null,
"e": 2057,
"s": 1636,
"text": "V11 = (0.82 *1 + 0.72 * 2 + 0.22 * 4 + 0.12 * 7) / ( (0.82 + 0.72 + 0.22 + 0.12 ) = 1.568\nV12 = (0.82 *3 + 0.72 * 5 + 0.22 * 8 + 0.12 * 9) / ( (0.82 + 0.72 + 0.22 + 0.12 ) = 4.051\nV11 = (0.22 *1 + 0.32 * 2 + 0.82 * 4 + 0.92 * 7) / ( (0.22 + 0.32 + 0.82 + 0.92 ) = 5.35\nV11 = (0.22 *3 + 0.32 * 5 + 0.82 * 8 + 0.92 * 9) / ( (0.22 + 0.32 + 0.82 + 0.92 ) = 8.215\n\nCentroids are: (1.568, 4.051) and (5.35, 8.215)\n"
},
{
"code": null,
"e": 2116,
"s": 2057,
"text": "Step 3: Find out the distance of each point from centroid."
},
{
"code": null,
"e": 2207,
"s": 2116,
"text": "D11 = ((1 - 1.568)2 + (3 - 4.051)2)0.5 = 1.2\nD12 = ((1 - 5.35)2 + (3 - 8.215)2)0.5 = 6.79\n"
},
{
"code": null,
"e": 2288,
"s": 2207,
"text": "Similarly, the distance of all other points is computed from both the centroids."
},
{
"code": null,
"e": 2324,
"s": 2288,
"text": "Step 4: Updating membership values."
},
{
"code": null,
"e": 2363,
"s": 2324,
"text": "For point 1 new membership values are:"
},
{
"code": null,
"e": 2434,
"s": 2363,
"text": "Similarly, compute all other membership values, and update the matrix."
},
{
"code": null,
"e": 2674,
"s": 2434,
"text": "Step 5: Repeat the steps(2-4) until the constant values are obtained for the membership values or the difference is less than the tolerance value (a small value up to which the difference in values of two consequent updations is accepted)."
},
{
"code": null,
"e": 2910,
"s": 2674,
"text": "Step 6: Defuzzify the obtained membership values. Implementation: The fuzzy scikit learn library has a pre-defined function for fuzzy c-means which can be used in Python. For using fuzzy c-means you need to install the skfuzzy library."
},
{
"code": null,
"e": 2950,
"s": 2910,
"text": "pip install sklearn\npip install skfuzzy"
},
{
"code": null,
"e": 2962,
"s": 2950,
"text": "fuzzy-logic"
},
{
"code": null,
"e": 2971,
"s": 2962,
"text": "Articles"
},
{
"code": null,
"e": 2988,
"s": 2971,
"text": "Machine Learning"
},
{
"code": null,
"e": 3005,
"s": 2988,
"text": "Machine Learning"
}
] |
How to use react-dropzone module in ReactJS ? | 21 May, 2021
React-Dropzone module is a simple React hook that is used to create an HTML5-compliant drag-drop zone for n number of files. We can use this module to provide a way for users to drop and drop their multiple files, and then we can handle these files as per the business requirement. We can use the following approach in ReactJS to use the react-dropzone module.
Approach: In the following example, we have used the react-dropzone module to demonstrate how we can use it in our ReactJS application. We have imported the useDropzone which is a wrapper component from the module to get the dropzone property getters which we have used to create the drag ‘n’ drop zone on our Input element. Now whenever user clicks on our sample text: Click to select file or drag-and-drop the file here!! , it will allow the user to select the file, and then we can perform any operation on that file as per business requirement.
Dropzone Props Getters: It helps in creating a drag ‘n’ drop zone as these are the getter functions that return objects with properties that are used for creating drag ‘n’ drop zone. The input properties should be applied to an <input> element whereas the root properties can be applied to any element.
Refs: The getRootProps and getInputProps functions which we get from the Dropzone props accept a custom refKey as one of the parameter attributes. It is useful when the props from getRootProps and getInputPropse function which we try to apply to an element does not expose a reference to the element.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-dropzone
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-dropzone
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { useCallback } from 'react'import { useDropzone } from 'react-dropzone' export default function App() { const onDrop = useCallback(acceptedFiles => { alert(acceptedFiles[0].name) console.log("Now you can do anything with"+ " this file as per your requirement") }, []) const { getInputProps, getRootProps } = useDropzone({ onDrop }) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Dropzone Module Demo</h4> <div {...getRootProps()}> <input {...getInputProps()} /> <p>Click to select file or drag-and-drop the file here!!</p> </div> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://www.npmjs.com/package/react-dropzone
React-Modules
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "React-Dropzone module is a simple React hook that is used to create an HTML5-compliant drag-drop zone for n number of files. We can use this module to provide a way for users to drop and drop their multiple files, and then we can handle these files as per the business requirement. We can use the following approach in ReactJS to use the react-dropzone module."
},
{
"code": null,
"e": 938,
"s": 389,
"text": "Approach: In the following example, we have used the react-dropzone module to demonstrate how we can use it in our ReactJS application. We have imported the useDropzone which is a wrapper component from the module to get the dropzone property getters which we have used to create the drag ‘n’ drop zone on our Input element. Now whenever user clicks on our sample text: Click to select file or drag-and-drop the file here!! , it will allow the user to select the file, and then we can perform any operation on that file as per business requirement."
},
{
"code": null,
"e": 1241,
"s": 938,
"text": "Dropzone Props Getters: It helps in creating a drag ‘n’ drop zone as these are the getter functions that return objects with properties that are used for creating drag ‘n’ drop zone. The input properties should be applied to an <input> element whereas the root properties can be applied to any element."
},
{
"code": null,
"e": 1542,
"s": 1241,
"text": "Refs: The getRootProps and getInputProps functions which we get from the Dropzone props accept a custom refKey as one of the parameter attributes. It is useful when the props from getRootProps and getInputPropse function which we try to apply to an element does not expose a reference to the element."
},
{
"code": null,
"e": 1592,
"s": 1542,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1687,
"s": 1592,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1751,
"s": 1687,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1783,
"s": 1751,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1896,
"s": 1783,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1996,
"s": 1896,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2010,
"s": 1996,
"text": "cd foldername"
},
{
"code": null,
"e": 2142,
"s": 2010,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-dropzone "
},
{
"code": null,
"e": 2247,
"s": 2142,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2275,
"s": 2247,
"text": "npm install react-dropzone "
},
{
"code": null,
"e": 2327,
"s": 2275,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2345,
"s": 2327,
"text": "Project Structure"
},
{
"code": null,
"e": 2475,
"s": 2345,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2482,
"s": 2475,
"text": "App.js"
},
{
"code": "import React, { useCallback } from 'react'import { useDropzone } from 'react-dropzone' export default function App() { const onDrop = useCallback(acceptedFiles => { alert(acceptedFiles[0].name) console.log(\"Now you can do anything with\"+ \" this file as per your requirement\") }, []) const { getInputProps, getRootProps } = useDropzone({ onDrop }) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Dropzone Module Demo</h4> <div {...getRootProps()}> <input {...getInputProps()} /> <p>Click to select file or drag-and-drop the file here!!</p> </div> </div> );}",
"e": 3151,
"s": 2482,
"text": null
},
{
"code": null,
"e": 3264,
"s": 3151,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3274,
"s": 3264,
"text": "npm start"
},
{
"code": null,
"e": 3373,
"s": 3274,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3429,
"s": 3373,
"text": "Reference: https://www.npmjs.com/package/react-dropzone"
},
{
"code": null,
"e": 3443,
"s": 3429,
"text": "React-Modules"
},
{
"code": null,
"e": 3459,
"s": 3443,
"text": "React-Questions"
},
{
"code": null,
"e": 3467,
"s": 3459,
"text": "ReactJS"
},
{
"code": null,
"e": 3484,
"s": 3467,
"text": "Web Technologies"
}
] |
lseek() in C/C++ to read the alternate nth byte and write it in another file | 07 Feb, 2018
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”.lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.Function Definition
off_t lseek(int fildes, off_t offset, int whence);
Field Descriptionint fildes : The file descriptor of the pointer that is going to be movedoff_t offset : The offset of the pointer (measured in bytes).int whence : The method in which the offset is to be interpreted(rela, absolute, etc.). Legal value r this variable are provided at the end.return value : Returns the offset of the pointer (in bytes) from thebeginning of the file. If the return value is -1,then there was an error moving the pointer.
For example, say our Input file is as follows:
// C program to read nth byte of a file and// copy it to another file using lseek#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <fcntl.h> void func(char arr[], int n){ // Open the file for READ only. int f_write = open("start.txt", O_RDONLY); // Open the file for WRITE and READ only. int f_read = open("end.txt", O_WRONLY); int count = 0; while (read(f_write, arr, 1)) { // to write the 1st byte of the input file in // the output file if (count < n) { // SEEK_CUR specifies that // the offset provided is relative to the // current file position lseek (f_write, n, SEEK_CUR); write (f_read, arr, 1); count = n; } // After the nth byte (now taking the alternate // nth byte) else { count = (2*n); lseek(f_write, count, SEEK_CUR); write(f_read, arr, 1); } } close(f_write); close(f_read);} // Driver codeint main(){ char arr[100]; int n; n = 5; // Calling for the function func(arr, n); return 0;}
Output file (end.txt)
This article is contributed by Kishlay Verma. 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.
cpp-file-handling
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 382,
"s": 54,
"text": "From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”.lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.Function Definition"
},
{
"code": null,
"e": 433,
"s": 382,
"text": "off_t lseek(int fildes, off_t offset, int whence);"
},
{
"code": null,
"e": 885,
"s": 433,
"text": "Field Descriptionint fildes : The file descriptor of the pointer that is going to be movedoff_t offset : The offset of the pointer (measured in bytes).int whence : The method in which the offset is to be interpreted(rela, absolute, etc.). Legal value r this variable are provided at the end.return value : Returns the offset of the pointer (in bytes) from thebeginning of the file. If the return value is -1,then there was an error moving the pointer."
},
{
"code": null,
"e": 932,
"s": 885,
"text": "For example, say our Input file is as follows:"
},
{
"code": "// C program to read nth byte of a file and// copy it to another file using lseek#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <fcntl.h> void func(char arr[], int n){ // Open the file for READ only. int f_write = open(\"start.txt\", O_RDONLY); // Open the file for WRITE and READ only. int f_read = open(\"end.txt\", O_WRONLY); int count = 0; while (read(f_write, arr, 1)) { // to write the 1st byte of the input file in // the output file if (count < n) { // SEEK_CUR specifies that // the offset provided is relative to the // current file position lseek (f_write, n, SEEK_CUR); write (f_read, arr, 1); count = n; } // After the nth byte (now taking the alternate // nth byte) else { count = (2*n); lseek(f_write, count, SEEK_CUR); write(f_read, arr, 1); } } close(f_write); close(f_read);} // Driver codeint main(){ char arr[100]; int n; n = 5; // Calling for the function func(arr, n); return 0;}",
"e": 2078,
"s": 932,
"text": null
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Output file (end.txt)"
},
{
"code": null,
"e": 2401,
"s": 2100,
"text": "This article is contributed by Kishlay Verma. 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": 2526,
"s": 2401,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2544,
"s": 2526,
"text": "cpp-file-handling"
},
{
"code": null,
"e": 2555,
"s": 2544,
"text": "C Language"
},
{
"code": null,
"e": 2559,
"s": 2555,
"text": "C++"
},
{
"code": null,
"e": 2563,
"s": 2559,
"text": "CPP"
}
] |
Natural Cubic spline | 18 Jul, 2021
The cubic spline is a spline that uses the third-degree polynomial which satisfied the given m control points. To derive the solutions for the cubic spline, we assume the second derivation 0 at endpoints, which in turn provides a boundary condition that adds two equations to m-2 equations to make them solvable. The system of equations for the Cubic spline for 1-dimension can be given by:
We take a set of points [xi, yi] for i = 0, 1, ..., n for the function y = f(x). The cubic spline interpolation is a piecewise continuous curve, passing through each of the values in the table.
Following are the conditions for the spline of degree K=3:The domain of s is in intervals of [a, b].S, S’, S” are all continuous function on [a,b].
The domain of s is in intervals of [a, b].
S, S’, S” are all continuous function on [a,b].
Here Si(x) is the cubic polynomial that will be used on the subinterval [xi, xi+1].
Since, there are n intervals and 4 coefficients of each equation, for that we require a 4n parameters to solve the spline, we can get 2n equation from the fact that each of the cubic spline equation should satisfy the value at both ends:
The above cubic spline equations should not only continuous and differentiable but also have defined first and second derivatives that are also continuous on control points.
and
For 1, 2, 3...n-1 provides the 2n -2 equation constraints. So, we need 2 more equations to solve the above cubic spline. For that, we will use some natural boundary conditions.
In Natural cubic spline, we assume that the second derivative of the spline at boundary points is 0:
Now, since the S(x) is a third-order polynomial we know that S”(x) is a linear spline which interpolates. Hence, first, we construct S”(x) then integrate it twice to obtain S(x).
Now, let’s assume t_i = x_i for i= 0, 1,...n, and and from the natural boundary condition . Twice differentiating a cubic spline gives a linear spline which can be written as:
where,
Now, the equation becomes:
Integrating this equation two times to obtain the cubic spline:
where,
Now, to check for the continuity of derivative at t_i i.e S^{‘}_{i}(t_i) = S^{‘}_{i-1}(t_{i}). We first need to find derivatives and put that condition:
where,
Putting the above equation for the continuity and solving it gives the following equation:
Take, v_i = 6(b_i – b_{i-1}) and the above equation can be written as form of matrix:
In this implementation, we will be performing the spline interpolation for function f(x) = 1/x for points b/w 2-10 with cubic spline that satisfied natural boundary condition.
Python3
#importsimport matplotlib.pyplot as pltimport numpy as npfrom scipy.interpolate import CubicSpline, interp1dplt.rcParams['figure.figsize'] =(12,8) x = np.arange(2,10)y = 1/(x)# apply cubic spline interpolationcs = CubicSpline(x, y, extrapolate=True)# apply natural cubic spline interpolationns = CubicSpline(x, y,bc_type='natural', extrapolate=True) # Apply Linear interpolationlinear_int = interp1d(x,y) xs = np.arange(2, 9, 0.1)ys = linear_int(xs) # plot linear interpolationplt.plot(x, y,'o', label='data')plt.plot(xs,ys, label="interpolation", color='green')plt.legend(loc='upper right', ncol=2)plt.title('Linear Interpolation')plt.show() # define a new xsxs = np.arange(1,15)#plot cubic spline and natural cubic splineplt.plot(x, y, 'o', label='data')plt.plot(xs, 1/(xs), label='true')plt.plot(xs, cs(xs), label="S")plt.plot(xs, ns(xs), label="NS")plt.plot(xs, ns(xs,2), label="NS''")plt.plot(xs, ns(xs,1), label="NS'") plt.legend(loc='upper right', ncol=2)plt.title('Cubic/Natural Cubic Spline Interpolation')plt.show() # check for boundary conditionprint("Value of double differentiation at boundary conditions are %s and %s" %(ns(2,2),ns(10,2)))
Output:
Value of double differentiation at boundary conditions are -1.1102230246251565e-16 and -0.00450262550915248
Linear Interpolation
Cubic/Natural Spline Interpolation
Natural Cubic Spline NTNU university
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 419,
"s": 28,
"text": "The cubic spline is a spline that uses the third-degree polynomial which satisfied the given m control points. To derive the solutions for the cubic spline, we assume the second derivation 0 at endpoints, which in turn provides a boundary condition that adds two equations to m-2 equations to make them solvable. The system of equations for the Cubic spline for 1-dimension can be given by:"
},
{
"code": null,
"e": 614,
"s": 419,
"text": "We take a set of points [xi, yi] for i = 0, 1, ..., n for the function y = f(x). The cubic spline interpolation is a piecewise continuous curve, passing through each of the values in the table. "
},
{
"code": null,
"e": 762,
"s": 614,
"text": "Following are the conditions for the spline of degree K=3:The domain of s is in intervals of [a, b].S, S’, S” are all continuous function on [a,b]."
},
{
"code": null,
"e": 805,
"s": 762,
"text": "The domain of s is in intervals of [a, b]."
},
{
"code": null,
"e": 853,
"s": 805,
"text": "S, S’, S” are all continuous function on [a,b]."
},
{
"code": null,
"e": 938,
"s": 853,
"text": "Here Si(x) is the cubic polynomial that will be used on the subinterval [xi, xi+1]. "
},
{
"code": null,
"e": 1176,
"s": 938,
"text": "Since, there are n intervals and 4 coefficients of each equation, for that we require a 4n parameters to solve the spline, we can get 2n equation from the fact that each of the cubic spline equation should satisfy the value at both ends:"
},
{
"code": null,
"e": 1350,
"s": 1176,
"text": "The above cubic spline equations should not only continuous and differentiable but also have defined first and second derivatives that are also continuous on control points."
},
{
"code": null,
"e": 1354,
"s": 1350,
"text": "and"
},
{
"code": null,
"e": 1531,
"s": 1354,
"text": "For 1, 2, 3...n-1 provides the 2n -2 equation constraints. So, we need 2 more equations to solve the above cubic spline. For that, we will use some natural boundary conditions."
},
{
"code": null,
"e": 1632,
"s": 1531,
"text": "In Natural cubic spline, we assume that the second derivative of the spline at boundary points is 0:"
},
{
"code": null,
"e": 1814,
"s": 1634,
"text": "Now, since the S(x) is a third-order polynomial we know that S”(x) is a linear spline which interpolates. Hence, first, we construct S”(x) then integrate it twice to obtain S(x). "
},
{
"code": null,
"e": 1991,
"s": 1814,
"text": "Now, let’s assume t_i = x_i for i= 0, 1,...n, and and from the natural boundary condition . Twice differentiating a cubic spline gives a linear spline which can be written as:"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "where, "
},
{
"code": null,
"e": 2026,
"s": 1999,
"text": "Now, the equation becomes:"
},
{
"code": null,
"e": 2090,
"s": 2026,
"text": "Integrating this equation two times to obtain the cubic spline:"
},
{
"code": null,
"e": 2098,
"s": 2090,
"text": "where, "
},
{
"code": null,
"e": 2251,
"s": 2098,
"text": "Now, to check for the continuity of derivative at t_i i.e S^{‘}_{i}(t_i) = S^{‘}_{i-1}(t_{i}). We first need to find derivatives and put that condition:"
},
{
"code": null,
"e": 2258,
"s": 2251,
"text": "where,"
},
{
"code": null,
"e": 2349,
"s": 2258,
"text": "Putting the above equation for the continuity and solving it gives the following equation:"
},
{
"code": null,
"e": 2435,
"s": 2349,
"text": "Take, v_i = 6(b_i – b_{i-1}) and the above equation can be written as form of matrix:"
},
{
"code": null,
"e": 2611,
"s": 2435,
"text": "In this implementation, we will be performing the spline interpolation for function f(x) = 1/x for points b/w 2-10 with cubic spline that satisfied natural boundary condition."
},
{
"code": null,
"e": 2619,
"s": 2611,
"text": "Python3"
},
{
"code": "#importsimport matplotlib.pyplot as pltimport numpy as npfrom scipy.interpolate import CubicSpline, interp1dplt.rcParams['figure.figsize'] =(12,8) x = np.arange(2,10)y = 1/(x)# apply cubic spline interpolationcs = CubicSpline(x, y, extrapolate=True)# apply natural cubic spline interpolationns = CubicSpline(x, y,bc_type='natural', extrapolate=True) # Apply Linear interpolationlinear_int = interp1d(x,y) xs = np.arange(2, 9, 0.1)ys = linear_int(xs) # plot linear interpolationplt.plot(x, y,'o', label='data')plt.plot(xs,ys, label=\"interpolation\", color='green')plt.legend(loc='upper right', ncol=2)plt.title('Linear Interpolation')plt.show() # define a new xsxs = np.arange(1,15)#plot cubic spline and natural cubic splineplt.plot(x, y, 'o', label='data')plt.plot(xs, 1/(xs), label='true')plt.plot(xs, cs(xs), label=\"S\")plt.plot(xs, ns(xs), label=\"NS\")plt.plot(xs, ns(xs,2), label=\"NS''\")plt.plot(xs, ns(xs,1), label=\"NS'\") plt.legend(loc='upper right', ncol=2)plt.title('Cubic/Natural Cubic Spline Interpolation')plt.show() # check for boundary conditionprint(\"Value of double differentiation at boundary conditions are %s and %s\" %(ns(2,2),ns(10,2)))",
"e": 3786,
"s": 2619,
"text": null
},
{
"code": null,
"e": 3794,
"s": 3786,
"text": "Output:"
},
{
"code": null,
"e": 3902,
"s": 3794,
"text": "Value of double differentiation at boundary conditions are -1.1102230246251565e-16 and -0.00450262550915248"
},
{
"code": null,
"e": 3923,
"s": 3902,
"text": "Linear Interpolation"
},
{
"code": null,
"e": 3958,
"s": 3923,
"text": "Cubic/Natural Spline Interpolation"
},
{
"code": null,
"e": 3995,
"s": 3958,
"text": "Natural Cubic Spline NTNU university"
},
{
"code": null,
"e": 4012,
"s": 3995,
"text": "Machine Learning"
},
{
"code": null,
"e": 4029,
"s": 4012,
"text": "Machine Learning"
}
] |
StringBuffer setLength() in Java with Examples | 19 Aug, 2019
The setLength(int newLength) method of StringBuffer class is the inbuilt method used to set the length of the character sequence equal to newLength. If the newLength passed as argument is less than the old length, the old length is changed to the newLength. If the newLength passed as argument is greater than or equal to the old length, null characters (‘\u0000’) are appended at the end of old sequence so that length becomes the newLength argument.
Syntax:
public void setLength(int newLength)
Parameters:This method accepts one parameter newLength which is Integer type value refers to the new length of sequence you want to set.Returns:This method returns nothing.Exception:If the newLength is negative then IndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuffer.setLength() method:Example 1:
// Java program to demonstrate// the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("WelcomeGeeks"); // print string System.out.println("String length = " + str.length() + " and contains = " + str); // set length equal to 10 str.setLength(10); // print string System.out.println("After setLength() String = " + str.toString()); }}
Output:
String length = 12 and contains = WelcomeGeeks
After setLength() String = WelcomeGee
Example 2:
// Java program to demonstrate// the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Tony Stark will die"); // print string System.out.println("String length = " + str.length() + " and contains = \"" + str + "\""); // set length equal to 25 str.setLength(25); // print string System.out.println("After setLength() String = \"" + str.toString() + "\""); }}
Output:
String length = 19 and contains = "Tony Stark will die"
After setLength() String = "Tony Stark will die "
Example 3: When negative new length is passed:
// Java program to demonstrate// Exception thrown by the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer("Tony Stark"); try { // pass length -15 str.setLength(-15); } catch (Exception e) { e.printStackTrace(); } }}
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: -15
at java.lang.AbstractStringBuffer.setLength(AbstractStringBuffer.java:207)
at java.lang.StringBuffer.setLength(StringBuffer.java:76)
at GFG.main(File.java:15)
References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#setLength(int)
Akanksha_Rai
java-basics
Java-Functions
Java-lang package
java-StringBuffer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "The setLength(int newLength) method of StringBuffer class is the inbuilt method used to set the length of the character sequence equal to newLength. If the newLength passed as argument is less than the old length, the old length is changed to the newLength. If the newLength passed as argument is greater than or equal to the old length, null characters (‘\\u0000’) are appended at the end of old sequence so that length becomes the newLength argument."
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Syntax:"
},
{
"code": null,
"e": 525,
"s": 488,
"text": "public void setLength(int newLength)"
},
{
"code": null,
"e": 768,
"s": 525,
"text": "Parameters:This method accepts one parameter newLength which is Integer type value refers to the new length of sequence you want to set.Returns:This method returns nothing.Exception:If the newLength is negative then IndexOutOfBoundsException."
},
{
"code": null,
"e": 851,
"s": 768,
"text": "Below programs illustrate the java.lang.StringBuffer.setLength() method:Example 1:"
},
{
"code": "// Java program to demonstrate// the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"WelcomeGeeks\"); // print string System.out.println(\"String length = \" + str.length() + \" and contains = \" + str); // set length equal to 10 str.setLength(10); // print string System.out.println(\"After setLength() String = \" + str.toString()); }}",
"e": 1473,
"s": 851,
"text": null
},
{
"code": null,
"e": 1481,
"s": 1473,
"text": "Output:"
},
{
"code": null,
"e": 1567,
"s": 1481,
"text": "String length = 12 and contains = WelcomeGeeks\nAfter setLength() String = WelcomeGee\n"
},
{
"code": null,
"e": 1578,
"s": 1567,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"Tony Stark will die\"); // print string System.out.println(\"String length = \" + str.length() + \" and contains = \\\"\" + str + \"\\\"\"); // set length equal to 25 str.setLength(25); // print string System.out.println(\"After setLength() String = \\\"\" + str.toString() + \"\\\"\"); }}",
"e": 2215,
"s": 1578,
"text": null
},
{
"code": null,
"e": 2223,
"s": 2215,
"text": "Output:"
},
{
"code": null,
"e": 2335,
"s": 2223,
"text": "String length = 19 and contains = \"Tony Stark will die\"\nAfter setLength() String = \"Tony Stark will die \"\n"
},
{
"code": null,
"e": 2382,
"s": 2335,
"text": "Example 3: When negative new length is passed:"
},
{
"code": "// Java program to demonstrate// Exception thrown by the setLength() Method. class GFG { public static void main(String[] args) { // create a StringBuffer object // with a String pass as parameter StringBuffer str = new StringBuffer(\"Tony Stark\"); try { // pass length -15 str.setLength(-15); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 2834,
"s": 2382,
"text": null
},
{
"code": null,
"e": 2842,
"s": 2834,
"text": "Output:"
},
{
"code": null,
"e": 3088,
"s": 2842,
"text": "java.lang.StringIndexOutOfBoundsException: String index out of range: -15\n at java.lang.AbstractStringBuffer.setLength(AbstractStringBuffer.java:207)\n at java.lang.StringBuffer.setLength(StringBuffer.java:76)\n at GFG.main(File.java:15)\n"
},
{
"code": null,
"e": 3185,
"s": 3088,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#setLength(int)"
},
{
"code": null,
"e": 3198,
"s": 3185,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3210,
"s": 3198,
"text": "java-basics"
},
{
"code": null,
"e": 3225,
"s": 3210,
"text": "Java-Functions"
},
{
"code": null,
"e": 3243,
"s": 3225,
"text": "Java-lang package"
},
{
"code": null,
"e": 3261,
"s": 3243,
"text": "java-StringBuffer"
},
{
"code": null,
"e": 3266,
"s": 3261,
"text": "Java"
},
{
"code": null,
"e": 3271,
"s": 3266,
"text": "Java"
}
] |
Inbuilt function for calculating LCM in C++ | 24 Jul, 2017
Many times while we do programming, we need to calculate the Least Common Multiple (LCM) between two numbers. We have already discussed how to find LCM in this post.In place of defining and then using a function for calculating lcm , we can simply use an inbuilt function of boost library of C++ , boost::math::lcm ().
For using this function , we have to declare a header file <boost/math/common_factor.hpp>.
Syntax:
boost::math::lcm (m,n)
Parameters: m, n
Return Value: 0 if either m or n are zero,
else lcm of mod(m) and mod(n).
// CPP program to illustrate// boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << "LCM(10,20) = " << boost::math::lcm(10,20) << endl; return 0;}
Output:
LCM(10,20) = 20
Important points:
The function will calculate the lcm after taking the modulus of both the numbers, so in case if any of the number being negative, it will be converted to its modulus and then LCM is calculated.In case if any of the number being a non-integer data type , then this function will throw an error.// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << "LCM(1.0,20) = " << boost::math::lcm(1.0,20) << endl; return 0;}This code will throw an error, as one of the argument of the function is a double type, so this code will not work.In C++17, a new STL function for calculating LCM of two numbers, std::lcm(), has been introduced, which can be used on any compiler supporting C++17 features.This article is contributed by Mrigendra Singh. 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.My Personal Notes
arrow_drop_upSave
The function will calculate the lcm after taking the modulus of both the numbers, so in case if any of the number being negative, it will be converted to its modulus and then LCM is calculated.
In case if any of the number being a non-integer data type , then this function will throw an error.// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << "LCM(1.0,20) = " << boost::math::lcm(1.0,20) << endl; return 0;}This code will throw an error, as one of the argument of the function is a double type, so this code will not work.
// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << "LCM(1.0,20) = " << boost::math::lcm(1.0,20) << endl; return 0;}
This code will throw an error, as one of the argument of the function is a double type, so this code will not work.
In C++17, a new STL function for calculating LCM of two numbers, std::lcm(), has been introduced, which can be used on any compiler supporting C++17 features.
This article is contributed by Mrigendra Singh. 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.
LCM
C++
Mathematical
Mathematical
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jul, 2017"
},
{
"code": null,
"e": 373,
"s": 54,
"text": "Many times while we do programming, we need to calculate the Least Common Multiple (LCM) between two numbers. We have already discussed how to find LCM in this post.In place of defining and then using a function for calculating lcm , we can simply use an inbuilt function of boost library of C++ , boost::math::lcm ()."
},
{
"code": null,
"e": 464,
"s": 373,
"text": "For using this function , we have to declare a header file <boost/math/common_factor.hpp>."
},
{
"code": null,
"e": 472,
"s": 464,
"text": "Syntax:"
},
{
"code": null,
"e": 587,
"s": 472,
"text": "boost::math::lcm (m,n)\nParameters: m, n\nReturn Value: 0 if either m or n are zero,\nelse lcm of mod(m) and mod(n).\n"
},
{
"code": "// CPP program to illustrate// boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << \"LCM(10,20) = \" << boost::math::lcm(10,20) << endl; return 0;}",
"e": 831,
"s": 587,
"text": null
},
{
"code": null,
"e": 839,
"s": 831,
"text": "Output:"
},
{
"code": null,
"e": 856,
"s": 839,
"text": "LCM(10,20) = 20\n"
},
{
"code": null,
"e": 874,
"s": 856,
"text": "Important points:"
},
{
"code": null,
"e": 2168,
"s": 874,
"text": "The function will calculate the lcm after taking the modulus of both the numbers, so in case if any of the number being negative, it will be converted to its modulus and then LCM is calculated.In case if any of the number being a non-integer data type , then this function will throw an error.// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << \"LCM(1.0,20) = \" << boost::math::lcm(1.0,20) << endl; return 0;}This code will throw an error, as one of the argument of the function is a double type, so this code will not work.In C++17, a new STL function for calculating LCM of two numbers, std::lcm(), has been introduced, which can be used on any compiler supporting C++17 features.This article is contributed by Mrigendra Singh. 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.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2362,
"s": 2168,
"text": "The function will calculate the lcm after taking the modulus of both the numbers, so in case if any of the number being negative, it will be converted to its modulus and then LCM is calculated."
},
{
"code": null,
"e": 2844,
"s": 2362,
"text": "In case if any of the number being a non-integer data type , then this function will throw an error.// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << \"LCM(1.0,20) = \" << boost::math::lcm(1.0,20) << endl; return 0;}This code will throw an error, as one of the argument of the function is a double type, so this code will not work."
},
{
"code": "// CPP program to illustrate illegal// behaviour of boost::math::lcm function of C++ #include <iostream>#include <boost/math/common_factor.hpp> using namespace std; int main(){ cout << \"LCM(1.0,20) = \" << boost::math::lcm(1.0,20) << endl; return 0;}",
"e": 3111,
"s": 2844,
"text": null
},
{
"code": null,
"e": 3227,
"s": 3111,
"text": "This code will throw an error, as one of the argument of the function is a double type, so this code will not work."
},
{
"code": null,
"e": 3386,
"s": 3227,
"text": "In C++17, a new STL function for calculating LCM of two numbers, std::lcm(), has been introduced, which can be used on any compiler supporting C++17 features."
},
{
"code": null,
"e": 3689,
"s": 3386,
"text": "This article is contributed by Mrigendra Singh. 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": 3814,
"s": 3689,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3818,
"s": 3814,
"text": "LCM"
},
{
"code": null,
"e": 3822,
"s": 3818,
"text": "C++"
},
{
"code": null,
"e": 3835,
"s": 3822,
"text": "Mathematical"
},
{
"code": null,
"e": 3848,
"s": 3835,
"text": "Mathematical"
},
{
"code": null,
"e": 3852,
"s": 3848,
"text": "CPP"
},
{
"code": null,
"e": 3950,
"s": 3852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3993,
"s": 3950,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4047,
"s": 3993,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4081,
"s": 4047,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4098,
"s": 4081,
"text": "Substring in C++"
},
{
"code": null,
"e": 4123,
"s": 4098,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4153,
"s": 4123,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4196,
"s": 4153,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4256,
"s": 4196,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4271,
"s": 4256,
"text": "C++ Data Types"
}
] |
Two elements whose sum is closest to zero | 16 Jun, 2022
Question: An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero.For the below array, program should print -80 and 85.
METHOD 1 (Simple) For each element, find the sum of it with every other element in the array and compare sums. Finally, return the minimum sum.
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ code to find Two elements// whose sum is closest to zero# include <bits/stdc++.h># include <stdlib.h> /* for abs() */# include <math.h> using namespace std;void minAbsSumPair(int arr[], int arr_size){ int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { cout << "Invalid Input"; return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l + 1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(abs(min_sum) > abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } cout << "The two elements whose sum is minimum are " << arr[min_l] << " and " << arr[min_r];} // Driver Codeint main(){ int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// C code to find Two elements// whose sum is closest to zero# include <stdio.h># include <stdlib.h> /* for abs() */# include <math.h>void minAbsSumPair(int arr[], int arr_size){ int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { printf("Invalid Input"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(abs(min_sum) > abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } printf(" The two elements whose sum is minimum are %d and %d", arr[min_l], arr[min_r]);} /* Driver program to test above function */int main(){ int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); getchar(); return 0;}
// Java code to find Two elements// whose sum is closest to zeroimport java.util.*;import java.lang.*;class Main{ static void minAbsSumPair(int arr[], int arr_size) { int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { System.out.println("Invalid Input"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(Math.abs(min_sum) > Math.abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } System.out.println(" The two elements whose "+ "sum is minimum are "+ arr[min_l]+ " and "+arr[min_r]); } // main function public static void main (String[] args) { int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); } }
# Python3 code to find Two elements# whose sum is closest to zero def minAbsSumPair(arr,arr_size): inv_count = 0 # Array should have at least # two elements if arr_size < 2: print("Invalid Input") return # Initialization of values min_l = 0 min_r = 1 min_sum = arr[0] + arr[1] for l in range (0, arr_size - 1): for r in range (l + 1, arr_size): sum = arr[l] + arr[r] if abs(min_sum) > abs(sum): min_sum = sum min_l = l min_r = r print("The two elements whose sum is minimum are", arr[min_l], "and ", arr[min_r]) # Driver program to test above functionarr = [1, 60, -10, 70, -80, 85] minAbsSumPair(arr, 6); # This code is contributed by Smitha Dinesh Semwal
// C# code to find Two elements// whose sum is closest to zerousing System; class GFG{static void minAbsSumPair(int []arr, int arr_size) { int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if (arr_size < 2) { Console.Write("Invalid Input"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for (l = 0; l < arr_size - 1; l++) { for (r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if (Math.Abs(min_sum) > Math.Abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } Console.Write(" The two elements whose "+ "sum is minimum are "+ arr[min_l]+ " and "+arr[min_r]); } // main function public static void Main () { int []arr = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); } } // This code is contributed by Sam007
<?php// PHP program to find the Two elements// whose sum is closest to zero function minAbsSumPair($arr, $arr_size){ $inv_count = 0; /* Array should have at least two elements*/ if($arr_size < 2) { echo "Invalid Input"; return; } /* Initialization of values */ $min_l = 0; $min_r = 1; $min_sum = $arr[0] + $arr[1]; for($l = 0; $l < $arr_size - 1; $l++) { for($r = $l+1; $r < $arr_size; $r++) { $sum = $arr[$l] + $arr[$r]; if(abs($min_sum) > abs($sum)) { $min_sum = $sum; $min_l = $l; $min_r = $r; } } } echo "The two elements whose sum is minimum are " .$arr[$min_l]." and ". $arr[$min_r]; } // Driver Code$arr = array(1, 60, -10, 70, -80, 85);minAbsSumPair($arr, 6); // This code is contributed by Sam007?>
<script>// JavaScript code to find Two elements// whose sum is closest to zero function minAbsSumPair( arr, arr_size){ var inv_count = 0; var l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { document.write("Invalid Input"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l + 1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(Math.abs(min_sum) > Math.abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } document.write("The two elements whose sum is minimum are " + arr[min_l] + " and " + arr[min_r]);} // Driver Code arr = new Array(1, 60, -10, 70, -80, 85); minAbsSumPair(arr, 6); // This code is contributed by simranarora5sos</script>
Output:
The two elements whose sum is minimum are -80 and 85
Time complexity: O(n2)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space: O(1)
METHOD 2 (Use Sorting):
Algorithm :
Sort all the elements of the input array. Use two index variables l and r to traverse from left and right ends respectively. Initialize l as 0 and r as n-1. sum = a[l] + a[r] If sum is -ve, then l++ If sum is +ve, then r– Keep track of abs min sum. Repeat steps 3, 4, 5 and 6 while l < r
Sort all the elements of the input array.
Use two index variables l and r to traverse from left and right ends respectively. Initialize l as 0 and r as n-1.
sum = a[l] + a[r]
If sum is -ve, then l++
If sum is +ve, then r–
Keep track of abs min sum.
Repeat steps 3, 4, 5 and 6 while l < r
Implementation:
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void quickSort(int *, int, int); /* Function to print pair of elements having minimum sum */void minAbsSumPair(int arr[], int n){ // Variables to keep track // of current sum and minimum sum int sum, min_sum = INT_MAX; // left and right index variables int l = 0, r = n-1; // variable to keep track of // the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { cout << "Invalid Input"; return; } /* Sort the elements */ quickSort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(abs(sum) < abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } cout << "The two elements whose sum is minimum are " << arr[min_l] << " and " << arr[min_r];} // Driver Codeint main(){ int arr[] = {1, 60, -10, 70, -80, 85}; int n = sizeof(arr) / sizeof(arr[0]); minAbsSumPair(arr, n); return 0;}/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }} // This code is contributed by rathbhupendra
# include <stdio.h># include <math.h># include <limits.h> void quickSort(int *, int, int); /* Function to print pair of elements having minimum sum */void minAbsSumPair(int arr[], int n){ // Variables to keep track of current sum and minimum sum int sum, min_sum = INT_MAX; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { printf("Invalid Input"); return; } /* Sort the elements */ quickSort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(abs(sum) < abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } printf(" The two elements whose sum is minimum are %d and %d", arr[min_l], arr[min_r]);} /* Driver program to test above function */int main(){ int arr[] = {1, 60, -10, 70, -80, 85}; int n = sizeof(arr)/sizeof(arr[0]); minAbsSumPair(arr, n); getchar(); return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }}
import java.util.*;import java.lang.*;class Main{ static void minAbsSumPair(int arr[], int n) { // Variables to keep track of current sum and minimum sum int sum, min_sum = 999999; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { System.out.println("Invalid Input"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(Math.abs(sum) < Math.abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } System.out.println(" The two elements whose "+ "sum is minimum are "+ arr[min_l]+ " and "+arr[min_r]); } // main function public static void main (String[] args) { int arr[] = {1, 60, -10, 70, -80, 85}; int n = arr.length; minAbsSumPair(arr, n); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } }}
# Function to print pair of elements# having minimum sum */ # FOLLOWING FUNCTIONS ARE ONLY FOR# SORTING PURPOSE */def partition(arr, si, ei): x = arr[ei] i = (si - 1) for j in range(si,ei): if(arr[j] <= x): i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[ei] = arr[ei], arr[i + 1] return (i + 1) # Implementation of Quick Sort# arr[] --> Array to be sorted# si --> Starting index# ei --> Ending indexdef quickSort(arr, si, ei): pi = 0 # Partitioning index */ if(si < ei): pi = partition(arr, si, ei) quickSort(arr, si, pi - 1) quickSort(arr, pi + 1, ei) def minAbsSumPair(arr, n): # Variables to keep track # of current sum and minimum sum sum, min_sum = 0, 10**9 # left and right index variables l = 0 r = n - 1 # variable to keep track of # the left and right pair for min_sum min_l = l min_r = n - 1 # Array should have at least two elements*/ if(n < 2): print("Invalid Input", end = "") return # Sort the elements */ quickSort(arr, l, r) while(l < r): sum = arr[l] + arr[r] # If abs(sum) is less # then update the result items if(abs(sum) < abs(min_sum)): min_sum = sum min_l = l min_r = r if(sum < 0): l += 1 else: r -= 1 print("The two elements whose sum is minimum are", arr[min_l], "and", arr[min_r]) # Driver Codearr = [1, 60, -10, 70, -80, 85]n = len(arr)minAbsSumPair(arr, n) # This code is contributed by mohit kumar 29
using System; class GFG{ static void minAbsSumPair(int []arr ,int n) { // Variables to keep track // of current sum and minimum sum int sum, min_sum = 999999; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left // and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if (n < 2) { Console.Write("Invalid Input"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if (Math.Abs(sum) < Math.Abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if (sum < 0) l++; else r--; } Console.Write(" The two elements whose " + "sum is minimum are " + arr[min_l]+ " and " + arr[min_r]); } // driver code public static void Main () { int []arr = {1, 60, -10, 70, -80, 85}; int n = arr.Length; minAbsSumPair(arr, n); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int []arr, int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp1 = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp1; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int []arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } }} // This code is contributed by Sam007
<script> function minAbsSumPair(arr,n) { // Variables to keep track of current sum and minimum sum let sum, min_sum = 999999; // left and right index variables let l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum let min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { document.write("Invalid Input"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(Math.abs(sum) < Math.abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } document.write(" The two elements whose "+ "sum is minimum are "+ arr[min_l]+ " and "+arr[min_r]); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr,low,high) { let pivot = arr[high]; let i = (low-1); // index of smaller element for (let j=low; j<high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) let temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function sort(arr,low,high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ let pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } } // main function let arr=[1, 60, -10, 70, -80, 85]; let n = arr.length; minAbsSumPair(arr, n); // This code is contributed by unknown2108</script>
Output:
The two elements whose sum is minimum are -80 and 85
Time Complexity: complexity to sort + complexity of finding the optimum pair = O(nlogn) + O(n) = O(nlogn)
Auxiliary Space: O(1)
STL implementation of Method-2:
Algorithm 1) Sort all the elements of the input array using their absolute values. 2) Check absolute sum of arr[i-1] and arr[i] if their absolute sum is less than min update min with their absolute value. 3) Use two variables to store the index of the elements.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ implementation using STL#include <bits/stdc++.h>using namespace std; // Modified to sort by absolute valuesbool compare(int x, int y){ return abs(x) < abs(y);} void findMinSum(int arr[], int n){ sort(arr, arr + n, compare); int min = INT_MAX, x, y; for (int i = 1; i < n; i++) { // Absolute value shows how close it is to zero if (abs(arr[i - 1] + arr[i]) <= min) { // if found an even close value // update min and store the index min = abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } cout << "The two elements whose sum is minimum are " << arr[x] << " and " << arr[y];} // Driver codeint main(){ int arr[] = { 1, 60, -10, 70, -80, 85 }; int n = sizeof(arr) / sizeof(arr[0]); findMinSum(arr, n); return 0; // This code is contributed by ceeyesharish}
// Java implementation using STLimport java.io.*; class GFG{ static void findMinSum(int[] arr, int n){ for(int i = 1; i < n; i++) { if (!(Math.abs(arr[i - 1]) < Math.abs(arr[i]))) { int temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } int min = Integer.MAX_VALUE; int x = 0, y = 0; for(int i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } System.out.println("The two elements whose " + "sum is minimum are " + arr[x] + " and " + arr[y]);} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 60, -10, 70, -80, 85 }; int n = arr.length; findMinSum(arr, n);}} // This code is contributed by rag2127
# Python3 implementation using STLimport sys def findMinSum(arr, n): for i in range(1, n): # Modified to sort by absolute values if (not abs(arr[i - 1]) < abs(arr[i])): arr[i - 1], arr[i] = arr[i], arr[i - 1] Min = sys.maxsize x = 0 y = 0 for i in range(1, n): # Absolute value shows how # close it is to zero if (abs(arr[i - 1] + arr[i]) <= Min): # If found an even close value # update min and store the index Min = abs(arr[i - 1] + arr[i]) x = i - 1 y = i print("The two elements whose sum is minimum are", arr[x], "and", arr[y]) # Driver codearr = [ 1, 60, -10, 70, -80, 85 ]n = len(arr) findMinSum(arr, n) # This code is contributed by avanitrachhadiya2155
// C# implementation using STLusing System;class GFG{ static void findMinSum(int[] arr, int n){ for(int i = 1; i < n; i++) { if (!(Math.Abs(arr[i - 1]) < Math.Abs(arr[i]))) { int temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } int min = Int32.MaxValue; int x = 0, y = 0; for(int i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.Abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.Abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } Console.WriteLine("The two elements whose " + "sum is minimum are " + arr[x] + " and " + arr[y]);} // Driver Codestatic void Main(){ int[] arr = { 1, 60, -10, 70, -80, 85 }; int n = arr.Length; findMinSum(arr, n);}} // This code is contributed by divyesh072019
<script> // Javascript implementation using STLfunction findMinSum(arr, n){ for(let i = 1; i < n; i++) { if (!(Math.abs(arr[i - 1]) < Math.abs(arr[i]))) { let temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } let min = Number.MAX_VALUE; let x = 0, y = 0; for(let i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } document.write("The two elements whose " + "sum is minimum are " + arr[x] + " and " + arr[y]);} // Driver codelet arr = [ 1, 60, -10, 70, -80, 85 ];let n = arr.length; findMinSum(arr, n); // This code is contributed by suresh07 </script>
Output:
The two elements whose sum is minimum are -80 and 85
Time Complexity: O(nlogn) Auxiliary Space : O(1)
Sam007
Akanksha_Rai
ceeyesharish
rathbhupendra
mohit kumar 29
avanitrachhadiya2155
rag2127
divyesh072019
suresh07
simranarora5sos
unknown2108
simmytarika5
deamitnautiyal
codewithshinchan
hardikkoriintern
Accolite
Amazon
Fab.com
Microsoft
Snapdeal
Arrays
Searching
Accolite
Amazon
Microsoft
Snapdeal
Fab.com
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 238,
"s": 52,
"text": "Question: An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero.For the below array, program should print -80 and 85."
},
{
"code": null,
"e": 382,
"s": 238,
"text": "METHOD 1 (Simple) For each element, find the sum of it with every other element in the array and compare sums. Finally, return the minimum sum."
},
{
"code": null,
"e": 398,
"s": 382,
"text": "Implementation:"
},
{
"code": null,
"e": 402,
"s": 398,
"text": "C++"
},
{
"code": null,
"e": 404,
"s": 402,
"text": "C"
},
{
"code": null,
"e": 409,
"s": 404,
"text": "Java"
},
{
"code": null,
"e": 417,
"s": 409,
"text": "Python3"
},
{
"code": null,
"e": 420,
"s": 417,
"text": "C#"
},
{
"code": null,
"e": 424,
"s": 420,
"text": "PHP"
},
{
"code": null,
"e": 435,
"s": 424,
"text": "Javascript"
},
{
"code": "// C++ code to find Two elements// whose sum is closest to zero# include <bits/stdc++.h># include <stdlib.h> /* for abs() */# include <math.h> using namespace std;void minAbsSumPair(int arr[], int arr_size){ int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { cout << \"Invalid Input\"; return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l + 1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(abs(min_sum) > abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } cout << \"The two elements whose sum is minimum are \" << arr[min_l] << \" and \" << arr[min_r];} // Driver Codeint main(){ int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 1483,
"s": 435,
"text": null
},
{
"code": "// C code to find Two elements// whose sum is closest to zero# include <stdio.h># include <stdlib.h> /* for abs() */# include <math.h>void minAbsSumPair(int arr[], int arr_size){ int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { printf(\"Invalid Input\"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(abs(min_sum) > abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } printf(\" The two elements whose sum is minimum are %d and %d\", arr[min_l], arr[min_r]);} /* Driver program to test above function */int main(){ int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); getchar(); return 0;}",
"e": 2379,
"s": 1483,
"text": null
},
{
"code": "// Java code to find Two elements// whose sum is closest to zeroimport java.util.*;import java.lang.*;class Main{ static void minAbsSumPair(int arr[], int arr_size) { int inv_count = 0; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { System.out.println(\"Invalid Input\"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(Math.abs(min_sum) > Math.abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } System.out.println(\" The two elements whose \"+ \"sum is minimum are \"+ arr[min_l]+ \" and \"+arr[min_r]); } // main function public static void main (String[] args) { int arr[] = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); } }",
"e": 3494,
"s": 2379,
"text": null
},
{
"code": "# Python3 code to find Two elements# whose sum is closest to zero def minAbsSumPair(arr,arr_size): inv_count = 0 # Array should have at least # two elements if arr_size < 2: print(\"Invalid Input\") return # Initialization of values min_l = 0 min_r = 1 min_sum = arr[0] + arr[1] for l in range (0, arr_size - 1): for r in range (l + 1, arr_size): sum = arr[l] + arr[r] if abs(min_sum) > abs(sum): min_sum = sum min_l = l min_r = r print(\"The two elements whose sum is minimum are\", arr[min_l], \"and \", arr[min_r]) # Driver program to test above functionarr = [1, 60, -10, 70, -80, 85] minAbsSumPair(arr, 6); # This code is contributed by Smitha Dinesh Semwal",
"e": 4307,
"s": 3494,
"text": null
},
{
"code": "// C# code to find Two elements// whose sum is closest to zerousing System; class GFG{static void minAbsSumPair(int []arr, int arr_size) { int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if (arr_size < 2) { Console.Write(\"Invalid Input\"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for (l = 0; l < arr_size - 1; l++) { for (r = l+1; r < arr_size; r++) { sum = arr[l] + arr[r]; if (Math.Abs(min_sum) > Math.Abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } Console.Write(\" The two elements whose \"+ \"sum is minimum are \"+ arr[min_l]+ \" and \"+arr[min_r]); } // main function public static void Main () { int []arr = {1, 60, -10, 70, -80, 85}; minAbsSumPair(arr, 6); } } // This code is contributed by Sam007",
"e": 5399,
"s": 4307,
"text": null
},
{
"code": "<?php// PHP program to find the Two elements// whose sum is closest to zero function minAbsSumPair($arr, $arr_size){ $inv_count = 0; /* Array should have at least two elements*/ if($arr_size < 2) { echo \"Invalid Input\"; return; } /* Initialization of values */ $min_l = 0; $min_r = 1; $min_sum = $arr[0] + $arr[1]; for($l = 0; $l < $arr_size - 1; $l++) { for($r = $l+1; $r < $arr_size; $r++) { $sum = $arr[$l] + $arr[$r]; if(abs($min_sum) > abs($sum)) { $min_sum = $sum; $min_l = $l; $min_r = $r; } } } echo \"The two elements whose sum is minimum are \" .$arr[$min_l].\" and \". $arr[$min_r]; } // Driver Code$arr = array(1, 60, -10, 70, -80, 85);minAbsSumPair($arr, 6); // This code is contributed by Sam007?>",
"e": 6288,
"s": 5399,
"text": null
},
{
"code": "<script>// JavaScript code to find Two elements// whose sum is closest to zero function minAbsSumPair( arr, arr_size){ var inv_count = 0; var l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if(arr_size < 2) { document.write(\"Invalid Input\"); return; } /* Initialization of values */ min_l = 0; min_r = 1; min_sum = arr[0] + arr[1]; for(l = 0; l < arr_size - 1; l++) { for(r = l + 1; r < arr_size; r++) { sum = arr[l] + arr[r]; if(Math.abs(min_sum) > Math.abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } document.write(\"The two elements whose sum is minimum are \" + arr[min_l] + \" and \" + arr[min_r]);} // Driver Code arr = new Array(1, 60, -10, 70, -80, 85); minAbsSumPair(arr, 6); // This code is contributed by simranarora5sos</script>",
"e": 7266,
"s": 6288,
"text": null
},
{
"code": null,
"e": 7275,
"s": 7266,
"text": "Output: "
},
{
"code": null,
"e": 7328,
"s": 7275,
"text": "The two elements whose sum is minimum are -80 and 85"
},
{
"code": null,
"e": 7351,
"s": 7328,
"text": "Time complexity: O(n2)"
},
{
"code": null,
"e": 7360,
"s": 7351,
"text": "Chapters"
},
{
"code": null,
"e": 7387,
"s": 7360,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 7437,
"s": 7387,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 7460,
"s": 7437,
"text": "captions off, selected"
},
{
"code": null,
"e": 7468,
"s": 7460,
"text": "English"
},
{
"code": null,
"e": 7486,
"s": 7468,
"text": "default, selected"
},
{
"code": null,
"e": 7510,
"s": 7486,
"text": "This is a modal window."
},
{
"code": null,
"e": 7579,
"s": 7510,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 7601,
"s": 7579,
"text": "End of dialog window."
},
{
"code": null,
"e": 7623,
"s": 7601,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7647,
"s": 7623,
"text": "METHOD 2 (Use Sorting):"
},
{
"code": null,
"e": 7659,
"s": 7647,
"text": "Algorithm :"
},
{
"code": null,
"e": 7947,
"s": 7659,
"text": "Sort all the elements of the input array. Use two index variables l and r to traverse from left and right ends respectively. Initialize l as 0 and r as n-1. sum = a[l] + a[r] If sum is -ve, then l++ If sum is +ve, then r– Keep track of abs min sum. Repeat steps 3, 4, 5 and 6 while l < r"
},
{
"code": null,
"e": 7990,
"s": 7947,
"text": "Sort all the elements of the input array. "
},
{
"code": null,
"e": 8106,
"s": 7990,
"text": "Use two index variables l and r to traverse from left and right ends respectively. Initialize l as 0 and r as n-1. "
},
{
"code": null,
"e": 8125,
"s": 8106,
"text": "sum = a[l] + a[r] "
},
{
"code": null,
"e": 8150,
"s": 8125,
"text": "If sum is -ve, then l++ "
},
{
"code": null,
"e": 8174,
"s": 8150,
"text": "If sum is +ve, then r– "
},
{
"code": null,
"e": 8202,
"s": 8174,
"text": "Keep track of abs min sum. "
},
{
"code": null,
"e": 8241,
"s": 8202,
"text": "Repeat steps 3, 4, 5 and 6 while l < r"
},
{
"code": null,
"e": 8257,
"s": 8241,
"text": "Implementation:"
},
{
"code": null,
"e": 8261,
"s": 8257,
"text": "C++"
},
{
"code": null,
"e": 8263,
"s": 8261,
"text": "C"
},
{
"code": null,
"e": 8268,
"s": 8263,
"text": "Java"
},
{
"code": null,
"e": 8276,
"s": 8268,
"text": "Python3"
},
{
"code": null,
"e": 8279,
"s": 8276,
"text": "C#"
},
{
"code": null,
"e": 8290,
"s": 8279,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void quickSort(int *, int, int); /* Function to print pair of elements having minimum sum */void minAbsSumPair(int arr[], int n){ // Variables to keep track // of current sum and minimum sum int sum, min_sum = INT_MAX; // left and right index variables int l = 0, r = n-1; // variable to keep track of // the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { cout << \"Invalid Input\"; return; } /* Sort the elements */ quickSort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(abs(sum) < abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } cout << \"The two elements whose sum is minimum are \" << arr[min_l] << \" and \" << arr[min_r];} // Driver Codeint main(){ int arr[] = {1, 60, -10, 70, -80, 85}; int n = sizeof(arr) / sizeof(arr[0]); minAbsSumPair(arr, n); return 0;}/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }} // This code is contributed by rathbhupendra",
"e": 10300,
"s": 8290,
"text": null
},
{
"code": "# include <stdio.h># include <math.h># include <limits.h> void quickSort(int *, int, int); /* Function to print pair of elements having minimum sum */void minAbsSumPair(int arr[], int n){ // Variables to keep track of current sum and minimum sum int sum, min_sum = INT_MAX; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { printf(\"Invalid Input\"); return; } /* Sort the elements */ quickSort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(abs(sum) < abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } printf(\" The two elements whose sum is minimum are %d and %d\", arr[min_l], arr[min_r]);} /* Driver program to test above function */int main(){ int arr[] = {1, 60, -10, 70, -80, 85}; int n = sizeof(arr)/sizeof(arr[0]); minAbsSumPair(arr, n); getchar(); return 0;} /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING PURPOSE */void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }}",
"e": 12088,
"s": 10300,
"text": null
},
{
"code": "import java.util.*;import java.lang.*;class Main{ static void minAbsSumPair(int arr[], int n) { // Variables to keep track of current sum and minimum sum int sum, min_sum = 999999; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { System.out.println(\"Invalid Input\"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(Math.abs(sum) < Math.abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } System.out.println(\" The two elements whose \"+ \"sum is minimum are \"+ arr[min_l]+ \" and \"+arr[min_r]); } // main function public static void main (String[] args) { int arr[] = {1, 60, -10, 70, -80, 85}; int n = arr.length; minAbsSumPair(arr, n); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } }}",
"e": 14833,
"s": 12088,
"text": null
},
{
"code": "# Function to print pair of elements# having minimum sum */ # FOLLOWING FUNCTIONS ARE ONLY FOR# SORTING PURPOSE */def partition(arr, si, ei): x = arr[ei] i = (si - 1) for j in range(si,ei): if(arr[j] <= x): i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[ei] = arr[ei], arr[i + 1] return (i + 1) # Implementation of Quick Sort# arr[] --> Array to be sorted# si --> Starting index# ei --> Ending indexdef quickSort(arr, si, ei): pi = 0 # Partitioning index */ if(si < ei): pi = partition(arr, si, ei) quickSort(arr, si, pi - 1) quickSort(arr, pi + 1, ei) def minAbsSumPair(arr, n): # Variables to keep track # of current sum and minimum sum sum, min_sum = 0, 10**9 # left and right index variables l = 0 r = n - 1 # variable to keep track of # the left and right pair for min_sum min_l = l min_r = n - 1 # Array should have at least two elements*/ if(n < 2): print(\"Invalid Input\", end = \"\") return # Sort the elements */ quickSort(arr, l, r) while(l < r): sum = arr[l] + arr[r] # If abs(sum) is less # then update the result items if(abs(sum) < abs(min_sum)): min_sum = sum min_l = l min_r = r if(sum < 0): l += 1 else: r -= 1 print(\"The two elements whose sum is minimum are\", arr[min_l], \"and\", arr[min_r]) # Driver Codearr = [1, 60, -10, 70, -80, 85]n = len(arr)minAbsSumPair(arr, n) # This code is contributed by mohit kumar 29",
"e": 16434,
"s": 14833,
"text": null
},
{
"code": "using System; class GFG{ static void minAbsSumPair(int []arr ,int n) { // Variables to keep track // of current sum and minimum sum int sum, min_sum = 999999; // left and right index variables int l = 0, r = n-1; // variable to keep track of the left // and right pair for min_sum int min_l = l, min_r = n-1; /* Array should have at least two elements*/ if (n < 2) { Console.Write(\"Invalid Input\"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if (Math.Abs(sum) < Math.Abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if (sum < 0) l++; else r--; } Console.Write(\" The two elements whose \" + \"sum is minimum are \" + arr[min_l]+ \" and \" + arr[min_r]); } // driver code public static void Main () { int []arr = {1, 60, -10, 70, -80, 85}; int n = arr.Length; minAbsSumPair(arr, n); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int []arr, int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp1 = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp1; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int []arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } }} // This code is contributed by Sam007",
"e": 19310,
"s": 16434,
"text": null
},
{
"code": "<script> function minAbsSumPair(arr,n) { // Variables to keep track of current sum and minimum sum let sum, min_sum = 999999; // left and right index variables let l = 0, r = n-1; // variable to keep track of the left and right pair for min_sum let min_l = l, min_r = n-1; /* Array should have at least two elements*/ if(n < 2) { document.write(\"Invalid Input\"); return; } /* Sort the elements */ sort(arr, l, r); while(l < r) { sum = arr[l] + arr[r]; /*If abs(sum) is less then update the result items*/ if(Math.abs(sum) < Math.abs(min_sum)) { min_sum = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } document.write(\" The two elements whose \"+ \"sum is minimum are \"+ arr[min_l]+ \" and \"+arr[min_r]); } /* Functions for QuickSort */ /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ function partition(arr,low,high) { let pivot = arr[high]; let i = (low-1); // index of smaller element for (let j=low; j<high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // swap arr[i] and arr[j] let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) let temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ function sort(arr,low,high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ let pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } } // main function let arr=[1, 60, -10, 70, -80, 85]; let n = arr.length; minAbsSumPair(arr, n); // This code is contributed by unknown2108</script>",
"e": 21967,
"s": 19310,
"text": null
},
{
"code": null,
"e": 21976,
"s": 21967,
"text": "Output: "
},
{
"code": null,
"e": 22029,
"s": 21976,
"text": "The two elements whose sum is minimum are -80 and 85"
},
{
"code": null,
"e": 22135,
"s": 22029,
"text": "Time Complexity: complexity to sort + complexity of finding the optimum pair = O(nlogn) + O(n) = O(nlogn)"
},
{
"code": null,
"e": 22157,
"s": 22135,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 22189,
"s": 22157,
"text": "STL implementation of Method-2:"
},
{
"code": null,
"e": 22451,
"s": 22189,
"text": "Algorithm 1) Sort all the elements of the input array using their absolute values. 2) Check absolute sum of arr[i-1] and arr[i] if their absolute sum is less than min update min with their absolute value. 3) Use two variables to store the index of the elements."
},
{
"code": null,
"e": 22467,
"s": 22451,
"text": "Implementation:"
},
{
"code": null,
"e": 22471,
"s": 22467,
"text": "C++"
},
{
"code": null,
"e": 22476,
"s": 22471,
"text": "Java"
},
{
"code": null,
"e": 22484,
"s": 22476,
"text": "Python3"
},
{
"code": null,
"e": 22487,
"s": 22484,
"text": "C#"
},
{
"code": null,
"e": 22498,
"s": 22487,
"text": "Javascript"
},
{
"code": "// C++ implementation using STL#include <bits/stdc++.h>using namespace std; // Modified to sort by absolute valuesbool compare(int x, int y){ return abs(x) < abs(y);} void findMinSum(int arr[], int n){ sort(arr, arr + n, compare); int min = INT_MAX, x, y; for (int i = 1; i < n; i++) { // Absolute value shows how close it is to zero if (abs(arr[i - 1] + arr[i]) <= min) { // if found an even close value // update min and store the index min = abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } cout << \"The two elements whose sum is minimum are \" << arr[x] << \" and \" << arr[y];} // Driver codeint main(){ int arr[] = { 1, 60, -10, 70, -80, 85 }; int n = sizeof(arr) / sizeof(arr[0]); findMinSum(arr, n); return 0; // This code is contributed by ceeyesharish}",
"e": 23377,
"s": 22498,
"text": null
},
{
"code": "// Java implementation using STLimport java.io.*; class GFG{ static void findMinSum(int[] arr, int n){ for(int i = 1; i < n; i++) { if (!(Math.abs(arr[i - 1]) < Math.abs(arr[i]))) { int temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } int min = Integer.MAX_VALUE; int x = 0, y = 0; for(int i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } System.out.println(\"The two elements whose \" + \"sum is minimum are \" + arr[x] + \" and \" + arr[y]);} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 60, -10, 70, -80, 85 }; int n = arr.length; findMinSum(arr, n);}} // This code is contributed by rag2127",
"e": 24467,
"s": 23377,
"text": null
},
{
"code": "# Python3 implementation using STLimport sys def findMinSum(arr, n): for i in range(1, n): # Modified to sort by absolute values if (not abs(arr[i - 1]) < abs(arr[i])): arr[i - 1], arr[i] = arr[i], arr[i - 1] Min = sys.maxsize x = 0 y = 0 for i in range(1, n): # Absolute value shows how # close it is to zero if (abs(arr[i - 1] + arr[i]) <= Min): # If found an even close value # update min and store the index Min = abs(arr[i - 1] + arr[i]) x = i - 1 y = i print(\"The two elements whose sum is minimum are\", arr[x], \"and\", arr[y]) # Driver codearr = [ 1, 60, -10, 70, -80, 85 ]n = len(arr) findMinSum(arr, n) # This code is contributed by avanitrachhadiya2155",
"e": 25298,
"s": 24467,
"text": null
},
{
"code": "// C# implementation using STLusing System;class GFG{ static void findMinSum(int[] arr, int n){ for(int i = 1; i < n; i++) { if (!(Math.Abs(arr[i - 1]) < Math.Abs(arr[i]))) { int temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } int min = Int32.MaxValue; int x = 0, y = 0; for(int i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.Abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.Abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } Console.WriteLine(\"The two elements whose \" + \"sum is minimum are \" + arr[x] + \" and \" + arr[y]);} // Driver Codestatic void Main(){ int[] arr = { 1, 60, -10, 70, -80, 85 }; int n = arr.Length; findMinSum(arr, n);}} // This code is contributed by divyesh072019",
"e": 26363,
"s": 25298,
"text": null
},
{
"code": "<script> // Javascript implementation using STLfunction findMinSum(arr, n){ for(let i = 1; i < n; i++) { if (!(Math.abs(arr[i - 1]) < Math.abs(arr[i]))) { let temp = arr[i - 1]; arr[i - 1] = arr[i]; arr[i] = temp; } } let min = Number.MAX_VALUE; let x = 0, y = 0; for(let i = 1; i < n; i++) { // Absolute value shows how close // it is to zero if (Math.abs(arr[i - 1] + arr[i]) <= min) { // If found an even close value // update min and store the index min = Math.abs(arr[i - 1] + arr[i]); x = i - 1; y = i; } } document.write(\"The two elements whose \" + \"sum is minimum are \" + arr[x] + \" and \" + arr[y]);} // Driver codelet arr = [ 1, 60, -10, 70, -80, 85 ];let n = arr.length; findMinSum(arr, n); // This code is contributed by suresh07 </script>",
"e": 27371,
"s": 26363,
"text": null
},
{
"code": null,
"e": 27380,
"s": 27371,
"text": "Output: "
},
{
"code": null,
"e": 27433,
"s": 27380,
"text": "The two elements whose sum is minimum are -80 and 85"
},
{
"code": null,
"e": 27482,
"s": 27433,
"text": "Time Complexity: O(nlogn) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 27489,
"s": 27482,
"text": "Sam007"
},
{
"code": null,
"e": 27502,
"s": 27489,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27515,
"s": 27502,
"text": "ceeyesharish"
},
{
"code": null,
"e": 27529,
"s": 27515,
"text": "rathbhupendra"
},
{
"code": null,
"e": 27544,
"s": 27529,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 27565,
"s": 27544,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 27573,
"s": 27565,
"text": "rag2127"
},
{
"code": null,
"e": 27587,
"s": 27573,
"text": "divyesh072019"
},
{
"code": null,
"e": 27596,
"s": 27587,
"text": "suresh07"
},
{
"code": null,
"e": 27612,
"s": 27596,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27624,
"s": 27612,
"text": "unknown2108"
},
{
"code": null,
"e": 27637,
"s": 27624,
"text": "simmytarika5"
},
{
"code": null,
"e": 27652,
"s": 27637,
"text": "deamitnautiyal"
},
{
"code": null,
"e": 27669,
"s": 27652,
"text": "codewithshinchan"
},
{
"code": null,
"e": 27686,
"s": 27669,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 27695,
"s": 27686,
"text": "Accolite"
},
{
"code": null,
"e": 27702,
"s": 27695,
"text": "Amazon"
},
{
"code": null,
"e": 27710,
"s": 27702,
"text": "Fab.com"
},
{
"code": null,
"e": 27720,
"s": 27710,
"text": "Microsoft"
},
{
"code": null,
"e": 27729,
"s": 27720,
"text": "Snapdeal"
},
{
"code": null,
"e": 27736,
"s": 27729,
"text": "Arrays"
},
{
"code": null,
"e": 27746,
"s": 27736,
"text": "Searching"
},
{
"code": null,
"e": 27755,
"s": 27746,
"text": "Accolite"
},
{
"code": null,
"e": 27762,
"s": 27755,
"text": "Amazon"
},
{
"code": null,
"e": 27772,
"s": 27762,
"text": "Microsoft"
},
{
"code": null,
"e": 27781,
"s": 27772,
"text": "Snapdeal"
},
{
"code": null,
"e": 27789,
"s": 27781,
"text": "Fab.com"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Arrays"
},
{
"code": null,
"e": 27806,
"s": 27796,
"text": "Searching"
}
] |
Implementation of 0/1 Knapsack using Branch and Bound | 26 Nov, 2019
We strongly recommend to refer below post as a prerequisite for this.
Branch and Bound | Set 1 (Introduction with 0/1 Knapsack)
We discussed different approaches to solve above problem and saw that the Branch and Bound solution is the best suited method when item weights are not integers.
In this post implementation of Branch and Bound method for 0/1 knapsack problem is discussed.
How to find bound for every node for 0/1 Knapsack?The idea is to use the fact that the Greedy approach provides the best solution for Fractional Knapsack problem.To check if a particular node can give us a better solution or not, we compute the optimal solution (through the node) using Greedy approach. If the solution computed by Greedy approach itself is more than the best so far, then we can’t get a better solution through the node.
Complete Algorithm:
Sort all items in decreasing order of ratio of value per unit weight so that an upper bound can be computed using Greedy Approach.Initialize maximum profit, maxProfit = 0Create an empty queue, Q.Create a dummy node of decision tree and enqueue it to Q. Profit and weight of dummy node are 0.Do following while Q is not empty.Extract an item from Q. Let the extracted item be u.Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit.Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q.Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes.
Sort all items in decreasing order of ratio of value per unit weight so that an upper bound can be computed using Greedy Approach.
Initialize maximum profit, maxProfit = 0
Create an empty queue, Q.
Create a dummy node of decision tree and enqueue it to Q. Profit and weight of dummy node are 0.
Do following while Q is not empty.Extract an item from Q. Let the extracted item be u.Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit.Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q.Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes.
Extract an item from Q. Let the extracted item be u.
Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit.
Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q.
Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes.
Illustration:
Input:
// First thing in every pair is weight of item
// and second thing is value of item
Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100},
{5, 95}, {3, 30}};
Knapsack Capacity W = 10
Output:
The maximum possible profit = 235
Below diagram shows illustration. Items are
considered sorted by value/weight.
Note : The image doesn't strictly follow the
algorithm/code as there is no dummy node in the
image.
Following is C++ implementation of above idea.
// C++ program to solve knapsack problem using// branch and bound#include <bits/stdc++.h>using namespace std; // Structure for Item which store weight and corresponding// value of Itemstruct Item{ float weight; int value;}; // Node structure to store information of decision// treestruct Node{ // level --> Level of node in decision tree (or index // in arr[] // profit --> Profit of nodes on path from root to this // node (including this node) // bound ---> Upper bound of maximum profit in subtree // of this node/ int level, profit, bound; float weight;}; // Comparison function to sort Item according to// val/weight ratiobool cmp(Item a, Item b){ double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2;} // Returns bound of profit in subtree rooted with u.// This function mainly uses Greedy solution to find// an upper bound on maximum profit.int bound(Node u, int n, int W, Item arr[]){ // if weight overcomes the knapsack capacity, return // 0 as expected bound if (u.weight >= W) return 0; // initialize bound on profit by current profit int profit_bound = u.profit; // start including items from index 1 more to current // item index int j = u.level + 1; int totweight = u.weight; // checking index condition and knapsack capacity // condition while ((j < n) && (totweight + arr[j].weight <= W)) { totweight += arr[j].weight; profit_bound += arr[j].value; j++; } // If k is not n, include last item partially for // upper bound on profit if (j < n) profit_bound += (W - totweight) * arr[j].value / arr[j].weight; return profit_bound;} // Returns maximum profit we can get with capacity Wint knapsack(int W, Item arr[], int n){ // sorting Item on basis of value per unit // weight. sort(arr, arr + n, cmp); // make a queue for traversing the node queue<Node> Q; Node u, v; // dummy node at starting u.level = -1; u.profit = u.weight = 0; Q.push(u); // One by one extract an item from decision tree // compute profit of all children of extracted item // and keep saving maxProfit int maxProfit = 0; while (!Q.empty()) { // Dequeue a node u = Q.front(); Q.pop(); // If it is starting node, assign level 0 if (u.level == -1) v.level = 0; // If there is nothing on next level if (u.level == n-1) continue; // Else if not last node, then increment level, // and compute profit of children nodes. v.level = u.level + 1; // Taking current level's item add current // level's weight and value to node u's // weight and value v.weight = u.weight + arr[v.level].weight; v.profit = u.profit + arr[v.level].value; // If cumulated weight is less than W and // profit is greater than previous profit, // update maxprofit if (v.weight <= W && v.profit > maxProfit) maxProfit = v.profit; // Get the upper bound on profit to decide // whether to add v to Q or not. v.bound = bound(v, n, W, arr); // If bound value is greater than profit, // then only push into queue for further // consideration if (v.bound > maxProfit) Q.push(v); // Do the same thing, but Without taking // the item in knapsack v.weight = u.weight; v.profit = u.profit; v.bound = bound(v, n, W, arr); if (v.bound > maxProfit) Q.push(v); } return maxProfit;} // driver program to test above functionint main(){ int W = 10; // Weight of knapsack Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100}, {5, 95}, {3, 30}}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum possible profit = " << knapsack(W, arr, n); return 0;}
Output :
Maximum possible profit = 235
This article is contributed Utkarsh Trivedi. If you likeGeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
SherifTarek
nidhi_biet
knapsack
Branch and Bound
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
0/1 Knapsack using Least Cost Branch and Bound
Travelling Salesman Problem (TSP) using Reduced Matrix Method
Classification of Algorithms with Examples
Generate Binary Strings of length N using Branch and Bound
Deutsche Bank Interview Experience (2021-22 )
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Calculator using Classes in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 122,
"s": 52,
"text": "We strongly recommend to refer below post as a prerequisite for this."
},
{
"code": null,
"e": 180,
"s": 122,
"text": "Branch and Bound | Set 1 (Introduction with 0/1 Knapsack)"
},
{
"code": null,
"e": 342,
"s": 180,
"text": "We discussed different approaches to solve above problem and saw that the Branch and Bound solution is the best suited method when item weights are not integers."
},
{
"code": null,
"e": 436,
"s": 342,
"text": "In this post implementation of Branch and Bound method for 0/1 knapsack problem is discussed."
},
{
"code": null,
"e": 875,
"s": 436,
"text": "How to find bound for every node for 0/1 Knapsack?The idea is to use the fact that the Greedy approach provides the best solution for Fractional Knapsack problem.To check if a particular node can give us a better solution or not, we compute the optimal solution (through the node) using Greedy approach. If the solution computed by Greedy approach itself is more than the best so far, then we can’t get a better solution through the node."
},
{
"code": null,
"e": 895,
"s": 875,
"text": "Complete Algorithm:"
},
{
"code": null,
"e": 1645,
"s": 895,
"text": "Sort all items in decreasing order of ratio of value per unit weight so that an upper bound can be computed using Greedy Approach.Initialize maximum profit, maxProfit = 0Create an empty queue, Q.Create a dummy node of decision tree and enqueue it to Q. Profit and weight of dummy node are 0.Do following while Q is not empty.Extract an item from Q. Let the extracted item be u.Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit.Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q.Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes."
},
{
"code": null,
"e": 1776,
"s": 1645,
"text": "Sort all items in decreasing order of ratio of value per unit weight so that an upper bound can be computed using Greedy Approach."
},
{
"code": null,
"e": 1817,
"s": 1776,
"text": "Initialize maximum profit, maxProfit = 0"
},
{
"code": null,
"e": 1843,
"s": 1817,
"text": "Create an empty queue, Q."
},
{
"code": null,
"e": 1940,
"s": 1843,
"text": "Create a dummy node of decision tree and enqueue it to Q. Profit and weight of dummy node are 0."
},
{
"code": null,
"e": 2399,
"s": 1940,
"text": "Do following while Q is not empty.Extract an item from Q. Let the extracted item be u.Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit.Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q.Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes."
},
{
"code": null,
"e": 2452,
"s": 2399,
"text": "Extract an item from Q. Let the extracted item be u."
},
{
"code": null,
"e": 2548,
"s": 2452,
"text": "Compute profit of next level node. If the profit is more than maxProfit, then update maxProfit."
},
{
"code": null,
"e": 2646,
"s": 2548,
"text": "Compute bound of next level node. If bound is more than maxProfit, then add next level node to Q."
},
{
"code": null,
"e": 2827,
"s": 2646,
"text": "Consider the case when next level node is not considered as part of solution and add a node to queue with level as next, but weight and profit without considering next level nodes."
},
{
"code": null,
"e": 2841,
"s": 2827,
"text": "Illustration:"
},
{
"code": null,
"e": 3268,
"s": 2841,
"text": "Input:\n// First thing in every pair is weight of item\n// and second thing is value of item\nItem arr[] = {{2, 40}, {3.14, 50}, {1.98, 100},\n {5, 95}, {3, 30}};\nKnapsack Capacity W = 10\n\nOutput:\nThe maximum possible profit = 235\n\nBelow diagram shows illustration. Items are \nconsidered sorted by value/weight.\n\n\n\nNote : The image doesn't strictly follow the \nalgorithm/code as there is no dummy node in the\nimage.\n"
},
{
"code": null,
"e": 3315,
"s": 3268,
"text": "Following is C++ implementation of above idea."
},
{
"code": "// C++ program to solve knapsack problem using// branch and bound#include <bits/stdc++.h>using namespace std; // Structure for Item which store weight and corresponding// value of Itemstruct Item{ float weight; int value;}; // Node structure to store information of decision// treestruct Node{ // level --> Level of node in decision tree (or index // in arr[] // profit --> Profit of nodes on path from root to this // node (including this node) // bound ---> Upper bound of maximum profit in subtree // of this node/ int level, profit, bound; float weight;}; // Comparison function to sort Item according to// val/weight ratiobool cmp(Item a, Item b){ double r1 = (double)a.value / a.weight; double r2 = (double)b.value / b.weight; return r1 > r2;} // Returns bound of profit in subtree rooted with u.// This function mainly uses Greedy solution to find// an upper bound on maximum profit.int bound(Node u, int n, int W, Item arr[]){ // if weight overcomes the knapsack capacity, return // 0 as expected bound if (u.weight >= W) return 0; // initialize bound on profit by current profit int profit_bound = u.profit; // start including items from index 1 more to current // item index int j = u.level + 1; int totweight = u.weight; // checking index condition and knapsack capacity // condition while ((j < n) && (totweight + arr[j].weight <= W)) { totweight += arr[j].weight; profit_bound += arr[j].value; j++; } // If k is not n, include last item partially for // upper bound on profit if (j < n) profit_bound += (W - totweight) * arr[j].value / arr[j].weight; return profit_bound;} // Returns maximum profit we can get with capacity Wint knapsack(int W, Item arr[], int n){ // sorting Item on basis of value per unit // weight. sort(arr, arr + n, cmp); // make a queue for traversing the node queue<Node> Q; Node u, v; // dummy node at starting u.level = -1; u.profit = u.weight = 0; Q.push(u); // One by one extract an item from decision tree // compute profit of all children of extracted item // and keep saving maxProfit int maxProfit = 0; while (!Q.empty()) { // Dequeue a node u = Q.front(); Q.pop(); // If it is starting node, assign level 0 if (u.level == -1) v.level = 0; // If there is nothing on next level if (u.level == n-1) continue; // Else if not last node, then increment level, // and compute profit of children nodes. v.level = u.level + 1; // Taking current level's item add current // level's weight and value to node u's // weight and value v.weight = u.weight + arr[v.level].weight; v.profit = u.profit + arr[v.level].value; // If cumulated weight is less than W and // profit is greater than previous profit, // update maxprofit if (v.weight <= W && v.profit > maxProfit) maxProfit = v.profit; // Get the upper bound on profit to decide // whether to add v to Q or not. v.bound = bound(v, n, W, arr); // If bound value is greater than profit, // then only push into queue for further // consideration if (v.bound > maxProfit) Q.push(v); // Do the same thing, but Without taking // the item in knapsack v.weight = u.weight; v.profit = u.profit; v.bound = bound(v, n, W, arr); if (v.bound > maxProfit) Q.push(v); } return maxProfit;} // driver program to test above functionint main(){ int W = 10; // Weight of knapsack Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100}, {5, 95}, {3, 30}}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum possible profit = \" << knapsack(W, arr, n); return 0;}",
"e": 7364,
"s": 3315,
"text": null
},
{
"code": null,
"e": 7373,
"s": 7364,
"text": "Output :"
},
{
"code": null,
"e": 7403,
"s": 7373,
"text": "Maximum possible profit = 235"
},
{
"code": null,
"e": 7668,
"s": 7403,
"text": "This article is contributed Utkarsh Trivedi. If you likeGeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7680,
"s": 7668,
"text": "SherifTarek"
},
{
"code": null,
"e": 7691,
"s": 7680,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7700,
"s": 7691,
"text": "knapsack"
},
{
"code": null,
"e": 7717,
"s": 7700,
"text": "Branch and Bound"
},
{
"code": null,
"e": 7815,
"s": 7717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7843,
"s": 7815,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 7890,
"s": 7843,
"text": "0/1 Knapsack using Least Cost Branch and Bound"
},
{
"code": null,
"e": 7952,
"s": 7890,
"text": "Travelling Salesman Problem (TSP) using Reduced Matrix Method"
},
{
"code": null,
"e": 7995,
"s": 7952,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 8054,
"s": 7995,
"text": "Generate Binary Strings of length N using Branch and Bound"
},
{
"code": null,
"e": 8100,
"s": 8054,
"text": "Deutsche Bank Interview Experience (2021-22 )"
},
{
"code": null,
"e": 8149,
"s": 8100,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 8174,
"s": 8149,
"text": "DSA Sheet by Love Babbar"
}
] |
Python Program for Sum of squares of first n natural numbers | 03 Dec, 2018
Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2.
Examples:
Input : N = 4
Output : 30
12 + 22 + 32 + 42
= 1 + 4 + 9 + 16
= 30
Input : N = 5
Output : 55
Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum.
# Python3 Program to# find sum of square# of first n natural # numbers # Return the sum of# square of first n# natural numbersdef squaresum(n) : # Iterate i from 1 # and n finding # square of i and # add to sum. sm = 0 for i in range(1, n+1) : sm = sm + (i * i) return sm # Driven Programn = 4print(squaresum(n)) # This code is contributed by Nikita Tiwari.*/
Output:
30
Method 2: O(1)
Proof:
We know,
(k + 1)3 = k3 + 3 * k2 + 3 * k + 1
We can write the above identity for k from 1 to n:
23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)
33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)
43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)
53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)
...
n3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)
(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)
Putting equation (n - 1) in equation n,
(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1
= (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1
By putting all equation, we get
(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1
n3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n
n3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2
n * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2
n * (n + 1) * (2 * n + 1)/6 = Σ k2
# Python3 Program to# find sum of square # of first n natural # numbers # Return the sum of # square of first n# natural numbersdef squaresum(n) : return (n * (n + 1) * (2 * n + 1)) // 6 # Driven Programn = 4print(squaresum(n)) #This code is contributed by Nikita Tiwari.
Output:
30
Avoiding early overflow:For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2.
# Python Program to find sum of square of first# n natural numbers. This program avoids# overflow upto some extent for large value# of n.y def squaresum(n): return (n * (n + 1) / 2) * (2 * n + 1) / 3 # main()n = 4print(squaresum(n)); # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
30
Please refer complete article on Sum of squares of first n natural numbers for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python
Python Program for Bubble Sort
Python | Check if a variable is string | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 129,
"s": 54,
"text": "Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2."
},
{
"code": null,
"e": 139,
"s": 129,
"text": "Examples:"
},
{
"code": null,
"e": 233,
"s": 139,
"text": "Input : N = 4\nOutput : 30\n12 + 22 + 32 + 42\n= 1 + 4 + 9 + 16\n= 30\n\nInput : N = 5\nOutput : 55\n"
},
{
"code": null,
"e": 331,
"s": 233,
"text": "Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 <= i <= n, find i2 to sum."
},
{
"code": "# Python3 Program to# find sum of square# of first n natural # numbers # Return the sum of# square of first n# natural numbersdef squaresum(n) : # Iterate i from 1 # and n finding # square of i and # add to sum. sm = 0 for i in range(1, n+1) : sm = sm + (i * i) return sm # Driven Programn = 4print(squaresum(n)) # This code is contributed by Nikita Tiwari.*/",
"e": 734,
"s": 331,
"text": null
},
{
"code": null,
"e": 742,
"s": 734,
"text": "Output:"
},
{
"code": null,
"e": 746,
"s": 742,
"text": "30\n"
},
{
"code": null,
"e": 761,
"s": 746,
"text": "Method 2: O(1)"
},
{
"code": null,
"e": 768,
"s": 761,
"text": "Proof:"
},
{
"code": null,
"e": 1814,
"s": 768,
"text": "We know,\n(k + 1)3 = k3 + 3 * k2 + 3 * k + 1\nWe can write the above identity for k from 1 to n:\n23 = 13 + 3 * 12 + 3 * 1 + 1 ......... (1)\n33 = 23 + 3 * 22 + 3 * 2 + 1 ......... (2)\n43 = 33 + 3 * 32 + 3 * 3 + 1 ......... (3)\n53 = 43 + 3 * 42 + 3 * 4 + 1 ......... (4)\n...\nn3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 ......... (n - 1)\n(n + 1)3 = n3 + 3 * n2 + 3 * n + 1 ......... (n)\n\nPutting equation (n - 1) in equation n,\n(n + 1)3 = (n - 1)3 + 3 * (n - 1)2 + 3 * (n - 1) + 1 + 3 * n2 + 3 * n + 1\n = (n - 1)3 + 3 * (n2 + (n - 1)2) + 3 * ( n + (n - 1) ) + 1 + 1\n\nBy putting all equation, we get\n(n + 1)3 = 13 + 3 * Σ k2 + 3 * Σ k + Σ 1\nn3 + 3 * n2 + 3 * n + 1 = 1 + 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 3 * n = 3 * Σ k2 + 3 * (n * (n + 1))/2 + n\nn3 + 3 * n2 + 2 * n - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n2 + 3 * n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2) - 3 * (n * (n + 1))/2 = 3 * Σ k2\nn * (n + 1) * (n + 2 - 3/2) = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/2 = 3 * Σ k2\nn * (n + 1) * (2 * n + 1)/6 = Σ k2\n"
},
{
"code": "# Python3 Program to# find sum of square # of first n natural # numbers # Return the sum of # square of first n# natural numbersdef squaresum(n) : return (n * (n + 1) * (2 * n + 1)) // 6 # Driven Programn = 4print(squaresum(n)) #This code is contributed by Nikita Tiwari. ",
"e": 2155,
"s": 1814,
"text": null
},
{
"code": null,
"e": 2163,
"s": 2155,
"text": "Output:"
},
{
"code": null,
"e": 2167,
"s": 2163,
"text": "30\n"
},
{
"code": null,
"e": 2353,
"s": 2167,
"text": "Avoiding early overflow:For large n, the value of (n * (n + 1) * (2 * n + 1)) would overflow. We can avoid overflow up to some extent using the fact that n*(n+1) must be divisible by 2."
},
{
"code": "# Python Program to find sum of square of first# n natural numbers. This program avoids# overflow upto some extent for large value# of n.y def squaresum(n): return (n * (n + 1) / 2) * (2 * n + 1) / 3 # main()n = 4print(squaresum(n)); # Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 2639,
"s": 2353,
"text": null
},
{
"code": null,
"e": 2647,
"s": 2639,
"text": "Output:"
},
{
"code": null,
"e": 2651,
"s": 2647,
"text": "30\n"
},
{
"code": null,
"e": 2744,
"s": 2651,
"text": "Please refer complete article on Sum of squares of first n natural numbers for more details!"
},
{
"code": null,
"e": 2760,
"s": 2744,
"text": "Python Programs"
},
{
"code": null,
"e": 2858,
"s": 2760,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2892,
"s": 2858,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2933,
"s": 2892,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 2988,
"s": 2933,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 3034,
"s": 2988,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 3067,
"s": 3034,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 3106,
"s": 3067,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 3143,
"s": 3106,
"text": "Python | Convert a list into a tuple"
},
{
"code": null,
"e": 3188,
"s": 3143,
"text": "Add a key:value pair to dictionary in Python"
},
{
"code": null,
"e": 3219,
"s": 3188,
"text": "Python Program for Bubble Sort"
}
] |
R – Factors | 27 Oct, 2021
Factors in R Programming Language are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels.
They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers and care must be taken while using them as strings. The factor accepts only a restricted number of distinct values. For example, a data field such as gender may contain values only from female, male, or transgender.
In the above example, all the possible cases are known beforehand and are predefined. These distinct values are known as levels. After a factor is created it only consists of levels that are by default sorted alphabetically.
x: It is the vector that needs to be converted into a factor.
Levels: It is a set of distinct values which are given to the input vector x.
Labels: It is a character vector corresponding to the number of labels.
Exclude: This will mention all the values you want to exclude.
Ordered: This logical attribute decides whether the levels are ordered.
nmax: It will decide the upper limit for the maximum number of levels.
The command used to create or modify a factor in R language is – factor() with a vector as input. The two steps to creating a factor are:
Creating a vector
Converting the vector created into a factor using function factor()
Examples: Let us create a factor gender with levels female, male and transgender.
R
# Creating a vectorx < -c("female", "male", "male", "female")print(x) # Converting the vector x into a factor# named gendergender < -factor(x)print(gender)
Output:
[1] "female" "male" "male" "female"
[1] female male male female
Levels: female male
Levels can also be predefined by the programmer.
R
# Creating a factor with levels defined by programmergender <- factor(c("female", "male", "male", "female"), levels = c("female", "transgender", "male"));gender
Output:
[1] female male male female
Levels: female transgender male
Further one can check the levels of a factor by using function levels().
The function is.factor() is used to check whether the variable is a factor and returns “TRUE” if it is a factor.
R
gender <- factor(c("female", "male", "male", "female"));print(is.factor(gender))
Output:
[1] TRUE
Function class() is also used to check whether the variable is a factor and if true returns “factor”.
R
gender <- factor(c("female", "male", "male", "female"));class(gender)
Output:
[1] "factor"
Like we access elements of a vector, the same way we access the elements of a factor. If gender is a factor then gender[i] would mean accessing ith element in the factor.
Example:
R
gender <- factor(c("female", "male", "male", "female"));gender[3]
Output:
[1] male
Levels: female male
More than one element can be accessed at a time.
Example:
R
gender <- factor(c("female", "male", "male", "female"));gender[c(2, 4)]
Output:
[1] male female
Levels: female male
Example:
R
gender <- factor(c("female", "male", "male", "female" ));gender[-3]
Output:
[1] female male female
Levels: female male
After a factor is formed, its components can be modified but the new values which need to be assigned must be at the predefined level.
Example:
R
gender <- factor(c("female", "male", "male", "female" ));gender[2]<-"female"gender
Output:
[1] female female male female
Levels: female male
For selecting all the elements of the factor gender except ith element, gender[-i] should be used. So if you want to modify a factor and add value out of predefines levels, then first modify levels.
Example:
R
gender <- factor(c("female", "male", "male", "female" )); # add new levellevels(gender) <- c(levels(gender), "other") gender[3] <- "other"gender
Output:
[1] female male other female
Levels: female male other
The Data frame is similar to a 2D array with the columns containing all the values of one variable and the rows having one set of values from every column. There are four things to remember about data frames:
column names are compulsory and cannot be empty.
Unique names should be assigned to each row.
The data frame’s data can be only of three types- factor, numeric, and character type.
The same number of data items must be present in each column.
In R language when we create a data frame, its column is categorical data and hence a factor is automatically created on it.We can create a data frame and check if its column is a factor.
Example:
R
age <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c("male", "male", "transgender", "female", "male", "female", "transgender")employee<- data.frame(age, salary, gender) print(employee) print(is.factor(employee$gender))
Output:
age salary gender
1 40 103200 male
2 49 106200 male
3 48 150200 transgender
4 40 10606 female
5 67 10390 male
6 52 14070 female
7 53 10220 transgender
[1] TRUE
anikakapoor
kumar_satyam
R Data-types
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "Factors in R Programming Language are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. "
},
{
"code": null,
"e": 561,
"s": 190,
"text": "They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers and care must be taken while using them as strings. The factor accepts only a restricted number of distinct values. For example, a data field such as gender may contain values only from female, male, or transgender."
},
{
"code": null,
"e": 788,
"s": 561,
"text": "In the above example, all the possible cases are known beforehand and are predefined. These distinct values are known as levels. After a factor is created it only consists of levels that are by default sorted alphabetically. "
},
{
"code": null,
"e": 850,
"s": 788,
"text": "x: It is the vector that needs to be converted into a factor."
},
{
"code": null,
"e": 928,
"s": 850,
"text": "Levels: It is a set of distinct values which are given to the input vector x."
},
{
"code": null,
"e": 1000,
"s": 928,
"text": "Labels: It is a character vector corresponding to the number of labels."
},
{
"code": null,
"e": 1063,
"s": 1000,
"text": "Exclude: This will mention all the values you want to exclude."
},
{
"code": null,
"e": 1135,
"s": 1063,
"text": "Ordered: This logical attribute decides whether the levels are ordered."
},
{
"code": null,
"e": 1206,
"s": 1135,
"text": "nmax: It will decide the upper limit for the maximum number of levels."
},
{
"code": null,
"e": 1346,
"s": 1206,
"text": "The command used to create or modify a factor in R language is – factor() with a vector as input. The two steps to creating a factor are: "
},
{
"code": null,
"e": 1364,
"s": 1346,
"text": "Creating a vector"
},
{
"code": null,
"e": 1432,
"s": 1364,
"text": "Converting the vector created into a factor using function factor()"
},
{
"code": null,
"e": 1516,
"s": 1432,
"text": "Examples: Let us create a factor gender with levels female, male and transgender. "
},
{
"code": null,
"e": 1518,
"s": 1516,
"text": "R"
},
{
"code": "# Creating a vectorx < -c(\"female\", \"male\", \"male\", \"female\")print(x) # Converting the vector x into a factor# named gendergender < -factor(x)print(gender)",
"e": 1674,
"s": 1518,
"text": null
},
{
"code": null,
"e": 1683,
"s": 1674,
"text": "Output: "
},
{
"code": null,
"e": 1775,
"s": 1683,
"text": "[1] \"female\" \"male\" \"male\" \"female\"\n[1] female male male female\nLevels: female male"
},
{
"code": null,
"e": 1825,
"s": 1775,
"text": "Levels can also be predefined by the programmer. "
},
{
"code": null,
"e": 1827,
"s": 1825,
"text": "R"
},
{
"code": "# Creating a factor with levels defined by programmergender <- factor(c(\"female\", \"male\", \"male\", \"female\"), levels = c(\"female\", \"transgender\", \"male\"));gender",
"e": 1997,
"s": 1827,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "Output: "
},
{
"code": null,
"e": 2070,
"s": 2006,
"text": "[1] female male male female\nLevels: female transgender male"
},
{
"code": null,
"e": 2144,
"s": 2070,
"text": "Further one can check the levels of a factor by using function levels(). "
},
{
"code": null,
"e": 2258,
"s": 2144,
"text": "The function is.factor() is used to check whether the variable is a factor and returns “TRUE” if it is a factor. "
},
{
"code": null,
"e": 2260,
"s": 2258,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\"));print(is.factor(gender))",
"e": 2341,
"s": 2260,
"text": null
},
{
"code": null,
"e": 2350,
"s": 2341,
"text": "Output: "
},
{
"code": null,
"e": 2359,
"s": 2350,
"text": "[1] TRUE"
},
{
"code": null,
"e": 2462,
"s": 2359,
"text": "Function class() is also used to check whether the variable is a factor and if true returns “factor”. "
},
{
"code": null,
"e": 2464,
"s": 2462,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\"));class(gender)",
"e": 2534,
"s": 2464,
"text": null
},
{
"code": null,
"e": 2543,
"s": 2534,
"text": "Output: "
},
{
"code": null,
"e": 2557,
"s": 2543,
"text": "[1] \"factor\" "
},
{
"code": null,
"e": 2729,
"s": 2557,
"text": "Like we access elements of a vector, the same way we access the elements of a factor. If gender is a factor then gender[i] would mean accessing ith element in the factor. "
},
{
"code": null,
"e": 2740,
"s": 2729,
"text": "Example: "
},
{
"code": null,
"e": 2742,
"s": 2740,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\"));gender[3]",
"e": 2808,
"s": 2742,
"text": null
},
{
"code": null,
"e": 2817,
"s": 2808,
"text": "Output: "
},
{
"code": null,
"e": 2846,
"s": 2817,
"text": "[1] male\nLevels: female male"
},
{
"code": null,
"e": 2896,
"s": 2846,
"text": "More than one element can be accessed at a time. "
},
{
"code": null,
"e": 2906,
"s": 2896,
"text": "Example: "
},
{
"code": null,
"e": 2908,
"s": 2906,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\"));gender[c(2, 4)]",
"e": 2980,
"s": 2908,
"text": null
},
{
"code": null,
"e": 2989,
"s": 2980,
"text": "Output: "
},
{
"code": null,
"e": 3027,
"s": 2989,
"text": "[1] male female\nLevels: female male"
},
{
"code": null,
"e": 3037,
"s": 3027,
"text": "Example: "
},
{
"code": null,
"e": 3039,
"s": 3037,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\" ));gender[-3]",
"e": 3108,
"s": 3039,
"text": null
},
{
"code": null,
"e": 3117,
"s": 3108,
"text": "Output: "
},
{
"code": null,
"e": 3162,
"s": 3117,
"text": "[1] female male female\nLevels: female male"
},
{
"code": null,
"e": 3298,
"s": 3162,
"text": "After a factor is formed, its components can be modified but the new values which need to be assigned must be at the predefined level. "
},
{
"code": null,
"e": 3309,
"s": 3298,
"text": "Example: "
},
{
"code": null,
"e": 3311,
"s": 3309,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\" ));gender[2]<-\"female\"gender",
"e": 3395,
"s": 3311,
"text": null
},
{
"code": null,
"e": 3404,
"s": 3395,
"text": "Output: "
},
{
"code": null,
"e": 3456,
"s": 3404,
"text": "[1] female female male female\nLevels: female male"
},
{
"code": null,
"e": 3656,
"s": 3456,
"text": "For selecting all the elements of the factor gender except ith element, gender[-i] should be used. So if you want to modify a factor and add value out of predefines levels, then first modify levels. "
},
{
"code": null,
"e": 3667,
"s": 3656,
"text": "Example: "
},
{
"code": null,
"e": 3669,
"s": 3667,
"text": "R"
},
{
"code": "gender <- factor(c(\"female\", \"male\", \"male\", \"female\" )); # add new levellevels(gender) <- c(levels(gender), \"other\") gender[3] <- \"other\"gender",
"e": 3817,
"s": 3669,
"text": null
},
{
"code": null,
"e": 3826,
"s": 3817,
"text": "Output: "
},
{
"code": null,
"e": 3885,
"s": 3826,
"text": "[1] female male other female\nLevels: female male other "
},
{
"code": null,
"e": 4096,
"s": 3885,
"text": "The Data frame is similar to a 2D array with the columns containing all the values of one variable and the rows having one set of values from every column. There are four things to remember about data frames: "
},
{
"code": null,
"e": 4145,
"s": 4096,
"text": "column names are compulsory and cannot be empty."
},
{
"code": null,
"e": 4190,
"s": 4145,
"text": "Unique names should be assigned to each row."
},
{
"code": null,
"e": 4277,
"s": 4190,
"text": "The data frame’s data can be only of three types- factor, numeric, and character type."
},
{
"code": null,
"e": 4339,
"s": 4277,
"text": "The same number of data items must be present in each column."
},
{
"code": null,
"e": 4528,
"s": 4339,
"text": "In R language when we create a data frame, its column is categorical data and hence a factor is automatically created on it.We can create a data frame and check if its column is a factor. "
},
{
"code": null,
"e": 4539,
"s": 4528,
"text": "Example: "
},
{
"code": null,
"e": 4541,
"s": 4539,
"text": "R"
},
{
"code": "age <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220)gender <- c(\"male\", \"male\", \"transgender\", \"female\", \"male\", \"female\", \"transgender\")employee<- data.frame(age, salary, gender) print(employee) print(is.factor(employee$gender))",
"e": 4841,
"s": 4541,
"text": null
},
{
"code": null,
"e": 4850,
"s": 4841,
"text": "Output: "
},
{
"code": null,
"e": 5059,
"s": 4850,
"text": " age salary gender\n1 40 103200 male\n2 49 106200 male\n3 48 150200 transgender\n4 40 10606 female\n5 67 10390 male\n6 52 14070 female\n7 53 10220 transgender\n[1] TRUE"
},
{
"code": null,
"e": 5071,
"s": 5059,
"text": "anikakapoor"
},
{
"code": null,
"e": 5084,
"s": 5071,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5097,
"s": 5084,
"text": "R Data-types"
},
{
"code": null,
"e": 5108,
"s": 5097,
"text": "R Language"
},
{
"code": null,
"e": 5206,
"s": 5108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5251,
"s": 5206,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 5303,
"s": 5251,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5361,
"s": 5303,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 5413,
"s": 5361,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 5471,
"s": 5413,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 5503,
"s": 5471,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 5566,
"s": 5503,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 5601,
"s": 5566,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 5645,
"s": 5601,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
Nested Structure in Golang | 13 Aug, 2019
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure. A structure which is the field of another structure is known as Nested Structure. Or in other words, a structure within another structure is known as a Nested Structure.
Syntax:
type struct_name_1 struct{
// Fields
}
type struct_name_2 struct{
variable_name struct_name_1
}
Let us discuss this concept with the help of the examples:
Example 1:
// Golang program to illustrate// the nested structurepackage main import "fmt" // Creating structuretype Author struct { name string branch string year int} // Creating nested structuretype HR struct { // structure as a field details Author} func main() { // Initializing the fields // of the structure result := HR{ details: Author{"Sona", "ECE", 2013}, } // Display the values fmt.Println("\nDetails of Author") fmt.Println(result)}
Output:
Details of Author
{{Sona ECE 2013}}
Example 2:
// Golang program to illustrate// the nested structurepackage main import "fmt" // Creating structuretype Student struct { name string branch string year int} // Creating nested structuretype Teacher struct { name string subject string exp int details Student} func main() { // Initializing the fields // of the structure result := Teacher{ name: "Suman", subject: "Java", exp: 5, details: Student{"Bongo", "CSE", 2}, } // Display the values fmt.Println("Details of the Teacher") fmt.Println("Teacher's name: ", result.name) fmt.Println("Subject: ", result.subject) fmt.Println("Experience: ", result.exp) fmt.Println("\nDetails of Student") fmt.Println("Student's name: ", result.details.name) fmt.Println("Student's branch name: ", result.details.branch) fmt.Println("Year: ", result.details.year)}
Output:
Details of the Teacher
Teacher's name: Suman
Subject: Java
Experience: 5
Details of Student
Student's name: Bongo
Student's branch name: CSE
Year: 2
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 473,
"s": 28,
"text": "A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure. A structure which is the field of another structure is known as Nested Structure. Or in other words, a structure within another structure is known as a Nested Structure."
},
{
"code": null,
"e": 481,
"s": 473,
"text": "Syntax:"
},
{
"code": null,
"e": 585,
"s": 481,
"text": "type struct_name_1 struct{\n // Fields\n} \ntype struct_name_2 struct{\n variable_name struct_name_1\n\n}\n"
},
{
"code": null,
"e": 644,
"s": 585,
"text": "Let us discuss this concept with the help of the examples:"
},
{
"code": null,
"e": 655,
"s": 644,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// the nested structurepackage main import \"fmt\" // Creating structuretype Author struct { name string branch string year int} // Creating nested structuretype HR struct { // structure as a field details Author} func main() { // Initializing the fields // of the structure result := HR{ details: Author{\"Sona\", \"ECE\", 2013}, } // Display the values fmt.Println(\"\\nDetails of Author\") fmt.Println(result)}",
"e": 1154,
"s": 655,
"text": null
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "Output:"
},
{
"code": null,
"e": 1199,
"s": 1162,
"text": "Details of Author\n{{Sona ECE 2013}}\n"
},
{
"code": null,
"e": 1210,
"s": 1199,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// the nested structurepackage main import \"fmt\" // Creating structuretype Student struct { name string branch string year int} // Creating nested structuretype Teacher struct { name string subject string exp int details Student} func main() { // Initializing the fields // of the structure result := Teacher{ name: \"Suman\", subject: \"Java\", exp: 5, details: Student{\"Bongo\", \"CSE\", 2}, } // Display the values fmt.Println(\"Details of the Teacher\") fmt.Println(\"Teacher's name: \", result.name) fmt.Println(\"Subject: \", result.subject) fmt.Println(\"Experience: \", result.exp) fmt.Println(\"\\nDetails of Student\") fmt.Println(\"Student's name: \", result.details.name) fmt.Println(\"Student's branch name: \", result.details.branch) fmt.Println(\"Year: \", result.details.year)}",
"e": 2127,
"s": 1210,
"text": null
},
{
"code": null,
"e": 2135,
"s": 2127,
"text": "Output:"
},
{
"code": null,
"e": 2292,
"s": 2135,
"text": "Details of the Teacher\nTeacher's name: Suman\nSubject: Java\nExperience: 5\n\nDetails of Student\nStudent's name: Bongo\nStudent's branch name: CSE\nYear: 2\n"
},
{
"code": null,
"e": 2299,
"s": 2292,
"text": "Golang"
},
{
"code": null,
"e": 2311,
"s": 2299,
"text": "Go Language"
},
{
"code": null,
"e": 2409,
"s": 2311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2461,
"s": 2409,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 2507,
"s": 2461,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 2557,
"s": 2507,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 2608,
"s": 2557,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 2655,
"s": 2608,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 2667,
"s": 2655,
"text": "Golang Maps"
},
{
"code": null,
"e": 2693,
"s": 2667,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 2714,
"s": 2693,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2768,
"s": 2714,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
HTML5 | MathML <math> tag | 19 Aug, 2021
The MathML <math> tag in HTML5 is the most prioritize element. Whatever MathML element you want to use they should wrapped inside of the <math> tag.Syntax:
<math> child elements </math>
Attributes: The tag accepts some attributes which are listed below:
class|id|style: This attribute is used to hold the styles of the child elements.
dir: This attributes holds the direction value. It holds two types of direction values ltr for left to right and rtl for right to left.
href: This attribute is used to hold any hyperlink to a specified URL.
mathbackground: This attribute holds the value of the math expressions background color.
mathcolor: This attribute holds the color of the math expressions.
display: This attribute holds the value of rendering of HTML element. There can be two value block which means that this element will be displayed outside the current span of text, inline which means that this element will be displayed inside the current span of text.
mode: Express the display attribute, possible values are display and inline.
overflow: It holds the value how the expression will behave. The default value is the linebreak and other possible values are scroll, elide, truncate, and scale.
Below example illustrates the MathML <math> tag in HTML5:Example:
html
<!DOCTYPE html><html> <head> <title>HTML5 MathML math tag</title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h3>HTML5 MathML <math> tag</h3> <math> <mrow> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <msup> <mi>y</mi> <mn>2</mn> </msup> </mrow> <mo>=</mo> <msup> <mi>z</mi> <mn>2</mn> </msup> </mrow> </math> </center></body> </html>
Output:
Supported Browsers: The browsers supported by HTML5 MathML <math> tag are listed below:
Firefox
Safari
ysachin2314
HTML-MathML
HTML-Tags
HTML5
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": "\n19 Aug, 2021"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "The MathML <math> tag in HTML5 is the most prioritize element. Whatever MathML element you want to use they should wrapped inside of the <math> tag.Syntax: "
},
{
"code": null,
"e": 216,
"s": 186,
"text": "<math> child elements </math>"
},
{
"code": null,
"e": 286,
"s": 216,
"text": "Attributes: The tag accepts some attributes which are listed below: "
},
{
"code": null,
"e": 367,
"s": 286,
"text": "class|id|style: This attribute is used to hold the styles of the child elements."
},
{
"code": null,
"e": 503,
"s": 367,
"text": "dir: This attributes holds the direction value. It holds two types of direction values ltr for left to right and rtl for right to left."
},
{
"code": null,
"e": 574,
"s": 503,
"text": "href: This attribute is used to hold any hyperlink to a specified URL."
},
{
"code": null,
"e": 663,
"s": 574,
"text": "mathbackground: This attribute holds the value of the math expressions background color."
},
{
"code": null,
"e": 730,
"s": 663,
"text": "mathcolor: This attribute holds the color of the math expressions."
},
{
"code": null,
"e": 999,
"s": 730,
"text": "display: This attribute holds the value of rendering of HTML element. There can be two value block which means that this element will be displayed outside the current span of text, inline which means that this element will be displayed inside the current span of text."
},
{
"code": null,
"e": 1076,
"s": 999,
"text": "mode: Express the display attribute, possible values are display and inline."
},
{
"code": null,
"e": 1238,
"s": 1076,
"text": "overflow: It holds the value how the expression will behave. The default value is the linebreak and other possible values are scroll, elide, truncate, and scale."
},
{
"code": null,
"e": 1306,
"s": 1238,
"text": "Below example illustrates the MathML <math> tag in HTML5:Example: "
},
{
"code": null,
"e": 1311,
"s": 1306,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML5 MathML math tag</title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3>HTML5 MathML <math> tag</h3> <math> <mrow> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <msup> <mi>y</mi> <mn>2</mn> </msup> </mrow> <mo>=</mo> <msup> <mi>z</mi> <mn>2</mn> </msup> </mrow> </math> </center></body> </html>",
"e": 2079,
"s": 1311,
"text": null
},
{
"code": null,
"e": 2089,
"s": 2079,
"text": "Output: "
},
{
"code": null,
"e": 2179,
"s": 2089,
"text": "Supported Browsers: The browsers supported by HTML5 MathML <math> tag are listed below: "
},
{
"code": null,
"e": 2187,
"s": 2179,
"text": "Firefox"
},
{
"code": null,
"e": 2194,
"s": 2187,
"text": "Safari"
},
{
"code": null,
"e": 2208,
"s": 2196,
"text": "ysachin2314"
},
{
"code": null,
"e": 2220,
"s": 2208,
"text": "HTML-MathML"
},
{
"code": null,
"e": 2230,
"s": 2220,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2236,
"s": 2230,
"text": "HTML5"
},
{
"code": null,
"e": 2241,
"s": 2236,
"text": "HTML"
},
{
"code": null,
"e": 2258,
"s": 2241,
"text": "Web Technologies"
},
{
"code": null,
"e": 2263,
"s": 2258,
"text": "HTML"
}
] |
Difference between Thread.start() and Thread.run() in Java | 23 Jan, 2019
In Java’s multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods:
New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no new thread will be created and run() method will be executed as a normal method call on the current calling thread itself and no multi-threading will take place.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}Output:Current thread name: Thread-0
run() method called
As we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}Output:Current thread name: main
run() method called
As we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call.Multiple invocation: In Java’s multi-threading concept, another most important difference between start() and run() method is that we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method can be called multiple times as it is just a normal method calling.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}Output:Current thread name: Thread-0
run() method called
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at GeeksforGeeks.main(File.java:11)
As we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}Output:Current thread name: main
run() method called
Current thread name: main
run() method called
As we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself.Summarystart()run()Creates a new thread and the run() method is executed on the newly created thread.No new thread is created and the run() method is executed on the calling thread itself.Can’t be invoked more than one time otherwise throws java.lang.IllegalStateExceptionMultiple invocation is possibleDefined in java.lang.Thread class.Defined in java.lang.Runnable interface and must be overriden in the implementing class.My Personal Notes
arrow_drop_upSave
New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no new thread will be created and run() method will be executed as a normal method call on the current calling thread itself and no multi-threading will take place.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}Output:Current thread name: Thread-0
run() method called
As we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}Output:Current thread name: main
run() method called
As we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call.
class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}
Current thread name: Thread-0
run() method called
As we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:
class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}
Current thread name: main
run() method called
As we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call.
Multiple invocation: In Java’s multi-threading concept, another most important difference between start() and run() method is that we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method can be called multiple times as it is just a normal method calling.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}Output:Current thread name: Thread-0
run() method called
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at GeeksforGeeks.main(File.java:11)
As we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}Output:Current thread name: main
run() method called
Current thread name: main
run() method called
As we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself.Summarystart()run()Creates a new thread and the run() method is executed on the newly created thread.No new thread is created and the run() method is executed on the calling thread itself.Can’t be invoked more than one time otherwise throws java.lang.IllegalStateExceptionMultiple invocation is possibleDefined in java.lang.Thread class.Defined in java.lang.Runnable interface and must be overriden in the implementing class.My Personal Notes
arrow_drop_upSave
class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}
Output:
Current thread name: Thread-0
run() method called
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at GeeksforGeeks.main(File.java:11)
As we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:
class MyThread extends Thread { public void run() { System.out.println("Current thread name: " + Thread.currentThread().getName()); System.out.println("run() method called"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}
Current thread name: main
run() method called
Current thread name: main
run() method called
As we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself.
Java-Functions
Java-Multithreading
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "In Java’s multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods:"
},
{
"code": null,
"e": 4190,
"s": 228,
"text": "New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no new thread will be created and run() method will be executed as a normal method call on the current calling thread itself and no multi-threading will take place.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}Output:Current thread name: Thread-0\nrun() method called\nAs we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}Output:Current thread name: main\nrun() method called\nAs we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call.Multiple invocation: In Java’s multi-threading concept, another most important difference between start() and run() method is that we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method can be called multiple times as it is just a normal method calling.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}Output:Current thread name: Thread-0\nrun() method called\nException in thread \"main\" java.lang.IllegalThreadStateException\n at java.lang.Thread.start(Thread.java:708)\n at GeeksforGeeks.main(File.java:11)\nAs we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}Output:Current thread name: main\nrun() method called\nCurrent thread name: main\nrun() method called\nAs we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself.Summarystart()run()Creates a new thread and the run() method is executed on the newly created thread.No new thread is created and the run() method is executed on the calling thread itself.Can’t be invoked more than one time otherwise throws java.lang.IllegalStateExceptionMultiple invocation is possibleDefined in java.lang.Thread class.Defined in java.lang.Runnable interface and must be overriden in the implementing class.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5983,
"s": 4190,
"text": "New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no new thread will be created and run() method will be executed as a normal method call on the current calling thread itself and no multi-threading will take place.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}Output:Current thread name: Thread-0\nrun() method called\nAs we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}Output:Current thread name: main\nrun() method called\nAs we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call."
},
{
"code": "class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); }}",
"e": 6340,
"s": 5983,
"text": null
},
{
"code": null,
"e": 6391,
"s": 6340,
"text": "Current thread name: Thread-0\nrun() method called\n"
},
{
"code": null,
"e": 6710,
"s": 6391,
"text": "As we can see in the above example, when we call the start() method of our thread class instance, a new thread is created with default name Thread-0 and then run() method is called and everything inside it is executed on the newly created thread.Now, let us try to call run() method directly instead of start() method:"
},
{
"code": "class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); }}",
"e": 7067,
"s": 6710,
"text": null
},
{
"code": null,
"e": 7114,
"s": 7067,
"text": "Current thread name: main\nrun() method called\n"
},
{
"code": null,
"e": 7395,
"s": 7114,
"text": "As we can see in the above example, when we called the run() method of our MyThread class, no new thread is created and the run() method is executed on the current thread i.e. main thread. Hence, no multi-threading took place. The run() method is called as a normal function call."
},
{
"code": null,
"e": 9565,
"s": 7395,
"text": "Multiple invocation: In Java’s multi-threading concept, another most important difference between start() and run() method is that we can’t call the start() method twice otherwise it will throw an IllegalStateException whereas run() method can be called multiple times as it is just a normal method calling.Let us understand it with an example:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}Output:Current thread name: Thread-0\nrun() method called\nException in thread \"main\" java.lang.IllegalThreadStateException\n at java.lang.Thread.start(Thread.java:708)\n at GeeksforGeeks.main(File.java:11)\nAs we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}Output:Current thread name: main\nrun() method called\nCurrent thread name: main\nrun() method called\nAs we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself.Summarystart()run()Creates a new thread and the run() method is executed on the newly created thread.No new thread is created and the run() method is executed on the calling thread itself.Can’t be invoked more than one time otherwise throws java.lang.IllegalStateExceptionMultiple invocation is possibleDefined in java.lang.Thread class.Defined in java.lang.Runnable interface and must be overriden in the implementing class.My Personal Notes\narrow_drop_upSave"
},
{
"code": "class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.start(); t.start(); }}",
"e": 9942,
"s": 9565,
"text": null
},
{
"code": null,
"e": 9950,
"s": 9942,
"text": "Output:"
},
{
"code": null,
"e": 10153,
"s": 9950,
"text": "Current thread name: Thread-0\nrun() method called\nException in thread \"main\" java.lang.IllegalThreadStateException\n at java.lang.Thread.start(Thread.java:708)\n at GeeksforGeeks.main(File.java:11)\n"
},
{
"code": null,
"e": 10307,
"s": 10153,
"text": "As we can see in the above example, calling start() method again raises java.lang.IllegalThreadStateException.Now, let us try to call run() method twice:"
},
{
"code": "class MyThread extends Thread { public void run() { System.out.println(\"Current thread name: \" + Thread.currentThread().getName()); System.out.println(\"run() method called\"); }} class GeeksforGeeks { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); t.run(); }}",
"e": 10678,
"s": 10307,
"text": null
},
{
"code": null,
"e": 10771,
"s": 10678,
"text": "Current thread name: main\nrun() method called\nCurrent thread name: main\nrun() method called\n"
},
{
"code": null,
"e": 10930,
"s": 10771,
"text": "As we can see in the above example, calling run() method twice doesn’t raise any exception and it is executed twice as expected but on the main thread itself."
},
{
"code": null,
"e": 10945,
"s": 10930,
"text": "Java-Functions"
},
{
"code": null,
"e": 10965,
"s": 10945,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 10984,
"s": 10965,
"text": "Difference Between"
},
{
"code": null,
"e": 10989,
"s": 10984,
"text": "Java"
},
{
"code": null,
"e": 10994,
"s": 10989,
"text": "Java"
}
] |
Top 10 Highest Paying IT Certifications in 2020 | 18 Jul, 2020
What is the best way to prove that you know something? That’s easy, obtain a certification on your specialty from a reputed source so that you have a credential to prove what you say. Certifications are very useful as they can boost your value in the market, lead to higher salary offers and provide a tangible proof of your competency and knowledge in a subject.
So in this article, we have shared the Top 10 highest paying certifications in 2020. These certifications were originally reported by Global Knowledge, which is a famous IT and business skills training provider. The estimated salaries after obtaining each certification are a result of cumulative hard work, having the relevant skills, as well as a certification demonstrating those skills. So let’s see these certifications now!
A Google Certified Professional Cloud Architect is a person who can handle Google Cloud Technologies. This cloud architect can design and handle scalable and secure cloud technologies to provide value addition for their company. To pass the exam for becoming a Google Certified Professional Cloud Architect, you need to be able to design and plan cloud solution architecture and make sure your designs are compliant with the security policies. Moreover, you need to demonstrate enough talent to handle the implementations of cloud architecture that are optimal for business processes.
This multiple-choice exam has a length of 2 hours with a registration fee of 200 USD. You can take the exam in English or Japanese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have at least 3 years of industry experience with 1 year exclusively dedicated to the management and handling of Google Cloud Technologies.
The Amazon Web Services Certified Solutions Architect is a person who is experienced as a Solutions Architect and well versed in creating fault-tolerant, scalable and cost-efficient systems on Amazon Web Services. If you want to clear the AWS Certified Solutions Architect exam in order to obtain this certification, you should be knowledgeable about the networking, computing, storage, and database AWS services. Moreover, you should have an understanding of the architectural principles, security features, and network technologies in creating systems on the AWS Cloud.
This multiple-choice exam has a length of 130 minutes with a registration fee of 150 USD. You can take the exam in English, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have some hands-on industry experience to pass this exam with flying colors.
The Certified Information Security Manager (CISM) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience in IT program development and management, risk management, incident management, information security governance, etc. This basically aims to move your career from the technical IT side to the management side of things. The Certified Information Security Manager (CISM) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of Information Risk Management, Information Security Governance, Information Security Program Development and Information Security Incident Management.
This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months.
The Certified in Risk and Information Systems Control (CRISC) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience in managing and handling Information Technology risks after identifying them and implementing information systems. The Certified in Risk and Information Systems Control (CRISC) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of IT Risk Assessment, IT Risk control, monitoring and reporting, IT Risk Response and Mitigation as well as IT Risk Identification.
This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months.
If you are a Project Manager then this Project Management Professional certification is for you. And even if that is not your official designation, if you have completed projects successfully, still the Project Management Professional certification informs everyone that you are proficient in managing projects. This certification is offered by the Project Management Institute and you need to have a four-year degree, three years experience in leading projects and 35 hours spend in project management education or training or otherwise the CAPM Certification.
This multiple-choice exam has 200 questions with a registration fee of 405 USD for those that are members of PMI and 555 USD for non-members. The exam has 5 domains namely Initiating, Planning, Executing, Monitoring and Controlling, and Closing for Projects.
The Certified Information Systems Security Professional (CISSP) certification is provided by the International Information System Security Certification Consortium, or (ISC)2. This is a nonprofit organization that is also called the “world’s largest IT security organization”! The CISSP is basically for security professionals such as Chief Information Security Officer, Security Systems Engineer, Security Analyst, Security Manager, etc. so that they can demonstrate their mastery over their field.
This multiple-choice exam has a length of 3 hours with around 100 to 150 questions. You need to score 700 out of 1000 points to achieve a passing grade and you can take the exam in English only. Moreover, you need at least 5 years of full-time work experience where you are in a paid position in 2 or more of the 8 domains of the CISSP Common Body of Knowledge. These domains include Identity and Access Management, Security Assessment and Testing, Security and Risk Management, Architecture and Engineering, Asset Security, Security Operations, Security Communication and Network Security, and Software Development Security.
The Certified Information Systems Auditor (CISA) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience for those who audit, monitor, control, and otherwise manage the IT and business systems of any organization. The Certified Information Systems Auditor (CISA) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of Governance and Management of IT, Protection of Information Assets, Information System Auditing process, Information System Operations, and Business Resilience, and Information systems Acquisition.
This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months.
The Amazon Web Services Certified Cloud Practitioner is a person who has an adequate understanding of the AWS cloud in general, which is obtained through usage. If you want to clear this exam in order to obtain this certification, you should be knowledgeable about the AWS cloud architecture, global infrastructure, value proposition, security model, important services, etc. In fact, if you want to earn an Associate or Specialty certification in Amazon Web Services, then the Certified Cloud Practitioner is a very important beginner certification.
This multiple-choice exam has a length of 90 minutes with a registration fee of 100 USD. You can take the exam in English, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have a minimum of six months’ experience with the Amazon Cloud Services in any capacity.
The VMware Certified Professional – Data Center Virtualization certification is offered by VMware to candidates so that they can demonstrate their expertise in the vSphere V6.7 infrastructure and prove that they can handle implementation, management and troubleshooting easily. It’s best if professionals have some VCP certifications if they want to attempt this exam, otherwise they need to gain experience with vSphere 6.7, attend VMware vSphere training courses, pass one of the foundation exams and then pass one of the Professional Data Center Virtualization Exams.
This single and multiple-choice exam has a length of 120 minutes with 85 questions and a passing score of 300. You can take the exam in English, and Japanese while the exam format is a proctored exam. The exam price is 250 USD.
The ITIL originally stood for Information Technology Infrastructure Library and it specifies IT service management (ITSM) practises that bridge the gap between IT services and business requirements. This ITIL Foundation certification allows professionals to demonstrate their knowledge of the ITIL framework and Service Management along with various concepts from Agile, Lean, DevOps, etc. and why they are necessary in business. Basically, the ITIL certification shows mastery over the total development model of tech products and services which includes their creation, delivery and continuous improvement in the future.
This multiple-choice exam has a length of 60 minutes with overall 40 questions. You need to obtain at least 26 marks out of 40 to pass the exam, which is 65%. The exam can take the exam in English and Japanese language with a cost of 314 USD in America.
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Learn Data Science in 10 weeks?
DSA Sheet by Love Babbar
Top Programming Languages For Competitive Programming
A Freshers Guide To Programming
Writing a Windows batch script
Top 8 Python Libraries for Data Visualization
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Genetic Algorithms
What is Data Structure: Types, Classifications and Applications
7 Highest Paying Programming Languages For Freelancers in 2022 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jul, 2020"
},
{
"code": null,
"e": 418,
"s": 54,
"text": "What is the best way to prove that you know something? That’s easy, obtain a certification on your specialty from a reputed source so that you have a credential to prove what you say. Certifications are very useful as they can boost your value in the market, lead to higher salary offers and provide a tangible proof of your competency and knowledge in a subject."
},
{
"code": null,
"e": 848,
"s": 418,
"text": "So in this article, we have shared the Top 10 highest paying certifications in 2020. These certifications were originally reported by Global Knowledge, which is a famous IT and business skills training provider. The estimated salaries after obtaining each certification are a result of cumulative hard work, having the relevant skills, as well as a certification demonstrating those skills. So let’s see these certifications now!"
},
{
"code": null,
"e": 1433,
"s": 848,
"text": "A Google Certified Professional Cloud Architect is a person who can handle Google Cloud Technologies. This cloud architect can design and handle scalable and secure cloud technologies to provide value addition for their company. To pass the exam for becoming a Google Certified Professional Cloud Architect, you need to be able to design and plan cloud solution architecture and make sure your designs are compliant with the security policies. Moreover, you need to demonstrate enough talent to handle the implementations of cloud architecture that are optimal for business processes."
},
{
"code": null,
"e": 1859,
"s": 1433,
"text": "This multiple-choice exam has a length of 2 hours with a registration fee of 200 USD. You can take the exam in English or Japanese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have at least 3 years of industry experience with 1 year exclusively dedicated to the management and handling of Google Cloud Technologies."
},
{
"code": null,
"e": 2431,
"s": 1859,
"text": "The Amazon Web Services Certified Solutions Architect is a person who is experienced as a Solutions Architect and well versed in creating fault-tolerant, scalable and cost-efficient systems on Amazon Web Services. If you want to clear the AWS Certified Solutions Architect exam in order to obtain this certification, you should be knowledgeable about the networking, computing, storage, and database AWS services. Moreover, you should have an understanding of the architectural principles, security features, and network technologies in creating systems on the AWS Cloud."
},
{
"code": null,
"e": 2828,
"s": 2431,
"text": "This multiple-choice exam has a length of 130 minutes with a registration fee of 150 USD. You can take the exam in English, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have some hands-on industry experience to pass this exam with flying colors."
},
{
"code": null,
"e": 3566,
"s": 2828,
"text": "The Certified Information Security Manager (CISM) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience in IT program development and management, risk management, incident management, information security governance, etc. This basically aims to move your career from the technical IT side to the management side of things. The Certified Information Security Manager (CISM) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of Information Risk Management, Information Security Governance, Information Security Program Development and Information Security Incident Management."
},
{
"code": null,
"e": 3965,
"s": 3566,
"text": "This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months."
},
{
"code": null,
"e": 4604,
"s": 3965,
"text": "The Certified in Risk and Information Systems Control (CRISC) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience in managing and handling Information Technology risks after identifying them and implementing information systems. The Certified in Risk and Information Systems Control (CRISC) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of IT Risk Assessment, IT Risk control, monitoring and reporting, IT Risk Response and Mitigation as well as IT Risk Identification."
},
{
"code": null,
"e": 5003,
"s": 4604,
"text": "This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months."
},
{
"code": null,
"e": 5565,
"s": 5003,
"text": "If you are a Project Manager then this Project Management Professional certification is for you. And even if that is not your official designation, if you have completed projects successfully, still the Project Management Professional certification informs everyone that you are proficient in managing projects. This certification is offered by the Project Management Institute and you need to have a four-year degree, three years experience in leading projects and 35 hours spend in project management education or training or otherwise the CAPM Certification."
},
{
"code": null,
"e": 5824,
"s": 5565,
"text": "This multiple-choice exam has 200 questions with a registration fee of 405 USD for those that are members of PMI and 555 USD for non-members. The exam has 5 domains namely Initiating, Planning, Executing, Monitoring and Controlling, and Closing for Projects."
},
{
"code": null,
"e": 6324,
"s": 5824,
"text": "The Certified Information Systems Security Professional (CISSP) certification is provided by the International Information System Security Certification Consortium, or (ISC)2. This is a nonprofit organization that is also called the “world’s largest IT security organization”! The CISSP is basically for security professionals such as Chief Information Security Officer, Security Systems Engineer, Security Analyst, Security Manager, etc. so that they can demonstrate their mastery over their field."
},
{
"code": null,
"e": 6951,
"s": 6324,
"text": "This multiple-choice exam has a length of 3 hours with around 100 to 150 questions. You need to score 700 out of 1000 points to achieve a passing grade and you can take the exam in English only. Moreover, you need at least 5 years of full-time work experience where you are in a paid position in 2 or more of the 8 domains of the CISSP Common Body of Knowledge. These domains include Identity and Access Management, Security Assessment and Testing, Security and Risk Management, Architecture and Engineering, Asset Security, Security Operations, Security Communication and Network Security, and Software Development Security."
},
{
"code": null,
"e": 7626,
"s": 6951,
"text": "The Certified Information Systems Auditor (CISA) certification is provided by ISACA which is an international professional association with a focus on IT governance. This certification demonstrates experience for those who audit, monitor, control, and otherwise manage the IT and business systems of any organization. The Certified Information Systems Auditor (CISA) certification is extremely helpful in proving your expertise or demonstrating your knowledge in the realms of Governance and Management of IT, Protection of Information Assets, Information System Auditing process, Information System Operations, and Business Resilience, and Information systems Acquisition."
},
{
"code": null,
"e": 8025,
"s": 7626,
"text": "This exam has a registration fee of 575 USD for those that are members of ISACA and 760 USD for non-members. You can take the exam in English, French, German, Italian, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. Also, your eligibility for the exam is checked when you apply for the exam registration and it is valid for twelve months."
},
{
"code": null,
"e": 8576,
"s": 8025,
"text": "The Amazon Web Services Certified Cloud Practitioner is a person who has an adequate understanding of the AWS cloud in general, which is obtained through usage. If you want to clear this exam in order to obtain this certification, you should be knowledgeable about the AWS cloud architecture, global infrastructure, value proposition, security model, important services, etc. In fact, if you want to earn an Associate or Specialty certification in Amazon Web Services, then the Certified Cloud Practitioner is a very important beginner certification."
},
{
"code": null,
"e": 8984,
"s": 8576,
"text": "This multiple-choice exam has a length of 90 minutes with a registration fee of 100 USD. You can take the exam in English, Korean, Japanese, and Simplified Chinese language with an option for an online exam or onsite exam as well. While you don’t need any prerequisites for taking this exam, it is recommended that you have a minimum of six months’ experience with the Amazon Cloud Services in any capacity."
},
{
"code": null,
"e": 9555,
"s": 8984,
"text": "The VMware Certified Professional – Data Center Virtualization certification is offered by VMware to candidates so that they can demonstrate their expertise in the vSphere V6.7 infrastructure and prove that they can handle implementation, management and troubleshooting easily. It’s best if professionals have some VCP certifications if they want to attempt this exam, otherwise they need to gain experience with vSphere 6.7, attend VMware vSphere training courses, pass one of the foundation exams and then pass one of the Professional Data Center Virtualization Exams."
},
{
"code": null,
"e": 9783,
"s": 9555,
"text": "This single and multiple-choice exam has a length of 120 minutes with 85 questions and a passing score of 300. You can take the exam in English, and Japanese while the exam format is a proctored exam. The exam price is 250 USD."
},
{
"code": null,
"e": 10406,
"s": 9783,
"text": "The ITIL originally stood for Information Technology Infrastructure Library and it specifies IT service management (ITSM) practises that bridge the gap between IT services and business requirements. This ITIL Foundation certification allows professionals to demonstrate their knowledge of the ITIL framework and Service Management along with various concepts from Agile, Lean, DevOps, etc. and why they are necessary in business. Basically, the ITIL certification shows mastery over the total development model of tech products and services which includes their creation, delivery and continuous improvement in the future."
},
{
"code": null,
"e": 10660,
"s": 10406,
"text": "This multiple-choice exam has a length of 60 minutes with overall 40 questions. You need to obtain at least 26 marks out of 40 to pass the exam, which is 65%. The exam can take the exam in English and Japanese language with a cost of 314 USD in America."
},
{
"code": null,
"e": 10666,
"s": 10660,
"text": "GBlog"
},
{
"code": null,
"e": 10764,
"s": 10666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10803,
"s": 10764,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 10828,
"s": 10803,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 10882,
"s": 10828,
"text": "Top Programming Languages For Competitive Programming"
},
{
"code": null,
"e": 10914,
"s": 10882,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 10945,
"s": 10914,
"text": "Writing a Windows batch script"
},
{
"code": null,
"e": 10991,
"s": 10945,
"text": "Top 8 Python Libraries for Data Visualization"
},
{
"code": null,
"e": 11046,
"s": 10991,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 11065,
"s": 11046,
"text": "Genetic Algorithms"
},
{
"code": null,
"e": 11129,
"s": 11065,
"text": "What is Data Structure: Types, Classifications and Applications"
}
] |
MVC Framework - Exception Handling | In ASP.NET, error handling is done using the standard try catch approach or using application events. ASP.NET MVC comes with built-in support for exception handling using a feature known as exception filters. We are going to learn two approaches here: one with overriding the onException method and another by defining the HandleError filters.
This approach is used when we want to handle all the exceptions across the Action methods at the controller level.
To understand this approach, create an MVC application (follow the steps covered in previous chapters). Now add a new Controller class and add the following code which overrides the onException method and explicitly throws an error in our Action method −
Now let us create a common View named Error which will be shown to the user when any exception happens in the application. Inside the Views folder, create a new folder called Shared and add a new View named Error.
Copy the following code inside the newly created Error.cshtml −
If you try to run the application now, it will give the following result. The above code renders the Error View when any exception occurs in any of the action methods within this controller.
The advantage of this approach is that multiple actions within the same controller can share this error handling logic. However, the disadvantage is that we cannot use the same error handling logic across multiple controllers.
The HandleError Attribute is one of the action filters that we studied in Filters and Action Filters chapter. The HandleErrorAttribute is the default implementation of IExceptionFilter. This filter handles all the exceptions raised by controller actions, filters, and views.
To use this feature, first of all turn on the customErrors section in web.config. Open the web.config and place the following code inside system.web and set its value as On.
<customErrors mode = "On"/>
We already have the Error View created inside the Shared folder under Views. This time change the code of this View file to the following, to strongly-type it with the HandleErrorInfo model (which is present under System.Web.MVC).
@model System.Web.Mvc.HandleErrorInfo
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<h2>Exception details</h2>
<p>
Controller: @Model.ControllerName <br>
Action: @Model.ActionName
Exception: @Model.Exception
</p>
</body>
</html>
Now place the following code in your controller file which specifies [HandleError] attribute at the Controller file.
using System;
using System.Data.Common;
using System.Web.Mvc;
namespace ExceptionHandlingMVC.Controllers {
[HandleError]
public class ExceptionHandlingController : Controller {
public ActionResult TestMethod() {
throw new Exception("Test Exception");
return View();
}
}
}
If you try to run the application now, you will get an error similar to shown in the following screenshot.
As you can see, this time the error contains more information about the Controller and Action related details. In this manner, the HandleError can be used at any level and across controllers to handle such errors. | [
{
"code": null,
"e": 2503,
"s": 2159,
"text": "In ASP.NET, error handling is done using the standard try catch approach or using application events. ASP.NET MVC comes with built-in support for exception handling using a feature known as exception filters. We are going to learn two approaches here: one with overriding the onException method and another by defining the HandleError filters."
},
{
"code": null,
"e": 2618,
"s": 2503,
"text": "This approach is used when we want to handle all the exceptions across the Action methods at the controller level."
},
{
"code": null,
"e": 2873,
"s": 2618,
"text": "To understand this approach, create an MVC application (follow the steps covered in previous chapters). Now add a new Controller class and add the following code which overrides the onException method and explicitly throws an error in our Action method −"
},
{
"code": null,
"e": 3087,
"s": 2873,
"text": "Now let us create a common View named Error which will be shown to the user when any exception happens in the application. Inside the Views folder, create a new folder called Shared and add a new View named Error."
},
{
"code": null,
"e": 3151,
"s": 3087,
"text": "Copy the following code inside the newly created Error.cshtml −"
},
{
"code": null,
"e": 3342,
"s": 3151,
"text": "If you try to run the application now, it will give the following result. The above code renders the Error View when any exception occurs in any of the action methods within this controller."
},
{
"code": null,
"e": 3569,
"s": 3342,
"text": "The advantage of this approach is that multiple actions within the same controller can share this error handling logic. However, the disadvantage is that we cannot use the same error handling logic across multiple controllers."
},
{
"code": null,
"e": 3844,
"s": 3569,
"text": "The HandleError Attribute is one of the action filters that we studied in Filters and Action Filters chapter. The HandleErrorAttribute is the default implementation of IExceptionFilter. This filter handles all the exceptions raised by controller actions, filters, and views."
},
{
"code": null,
"e": 4018,
"s": 3844,
"text": "To use this feature, first of all turn on the customErrors section in web.config. Open the web.config and place the following code inside system.web and set its value as On."
},
{
"code": null,
"e": 4047,
"s": 4018,
"text": "<customErrors mode = \"On\"/>\n"
},
{
"code": null,
"e": 4278,
"s": 4047,
"text": "We already have the Error View created inside the Shared folder under Views. This time change the code of this View file to the following, to strongly-type it with the HandleErrorInfo model (which is present under System.Web.MVC)."
},
{
"code": null,
"e": 4806,
"s": 4278,
"text": "@model System.Web.Mvc.HandleErrorInfo \n\n@{ \nLayout = null; \n} \n \n<!DOCTYPE html> \n<html> \n <head> \n <meta name = \"viewport\" content = \"width = device-width\" /> \n <title>Error</title> \n </head> \n \n <body> \n <h2> \n Sorry, an error occurred while processing your request. \n </h2> \n <h2>Exception details</h2> \n \n <p> \n Controller: @Model.ControllerName <br> \n Action: @Model.ActionName \n Exception: @Model.Exception \n </p> \n \n </body> \n</html> "
},
{
"code": null,
"e": 4923,
"s": 4806,
"text": "Now place the following code in your controller file which specifies [HandleError] attribute at the Controller file."
},
{
"code": null,
"e": 5254,
"s": 4923,
"text": "using System; \nusing System.Data.Common; \nusing System.Web.Mvc; \n\nnamespace ExceptionHandlingMVC.Controllers { \n [HandleError] \n public class ExceptionHandlingController : Controller { \n \n public ActionResult TestMethod() { \n throw new Exception(\"Test Exception\"); \n return View(); \n } \n } \n}"
},
{
"code": null,
"e": 5361,
"s": 5254,
"text": "If you try to run the application now, you will get an error similar to shown in the following screenshot."
}
] |
How to scroll to a particular element or skip the content in CSS ? | 16 Jun, 2022
Sometimes we need the user to click on a button or link and take them to an element present on the same HTML page. Also, this needs to take the user to the element without any reload. Lots of times, users tend to skip to the main content, like on a gaming Website. They might want to skip the instructions and want to play the game directly. So, basically, we want to scroll to a particular element or skip to content.
In this article, we will learn how to scroll to a particular element or skip to content in plain HTML and CSS only.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Scroll</title> <style> section:target { border: 2px solid blue; } .links-container { display: flex; justify-content: space-between; } </style></head> <body> <div class="links-container"> <!-- The href attribute of anchor tags point to the section IDs --> <!-- Note that href has to point to IDs and not to classes as IDs are unique in HTML--> <a href="#id1">Go to Section 1</a> <a href="#id2">Go to Section 2</a> <a href="#id3">Go to Section 3</a> <a href="#id4">Go to Section 4</a> </div> <!-- We need to specify unique IDs for each section/div/element we want the user to scroll to --> <section id="id1"> <h1>Section 1</h1> </section> <section id="id2"> <h1>Section 2</h1> </section> <section id="id3"> <h1>Section 3</h1> </section> <section id="id4"> <h1>Section 4</h1> </section></body> </html>
Output: Our HTML will look like this in a browser window.
Example 2: Let’s now go ahead and add some styles so that we can have the sections placed far away from each other.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <style> /* Some basic styling for testing our functionality */ .links-container { display: flex; justify-content: space-between; } .sections { display: flex; flex-direction: column; place-items: center; gap: 100rem; } </style></head> <body> <div class="links-container"> <!-- The href attribute of anchor tags point to the section IDs --> <a href="#id1">Go to Section 1</a> <a href="#id2">Go to Section 2</a> <a href="#id3">Go to Section 3</a> <a href="#id4">Go to Section 4</a> </div> <!-- We need to specify IDs for each section/div/element we want the user to scroll to --> <div class="sections"> <section id="id1"> <h1>Section 1</h1> </section> <section id="id2"> <h1>Section 2</h1> </section> <section id="id3"> <h1>Section 3</h1> </section> <section id="id4"> <h1>Section 4</h1> </section> </div></body> </html>
Output: Now, when we open our HTML file in a browser, we can see the functionality working when we click on any of the links, i.e. Go to Section 1, Go to Section 2, etc.
Although we are skipping content, the behavior is still not smooth. You can observe that when we click on the links, we go directly to the desired section. But we can make it scroll smoothly to the desired section as well.
To do this, we can use the following line in our code:
scroll-behavior: smooth;
There are other scroll behaviours also defined in HTML, you can go here for details about them. Here, we will be using smooth behaviour. Here, we will use scrolling to the particular section that we want to go, just by clicking once on the link.
The final code will look like this altogether: Example 3:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Scroll</title> <style> html { /* This property makes the html page to scroll smoothly */ /* If you want to directly move to the section without scrolling, remove this scroll-behavior property*/ scroll-behavior: smooth; } /* Some basic styling for testing our functionality */ .links-container { display: flex; justify-content: space-between; } .sections { display: flex; flex-direction: column; place-items: center; gap: 100rem; } </style></head> <body> <div class="links-container"> <!-- The href attribute of anchor tags point to the section IDs --> <a href="#id1">Go to Section 1</a> <a href="#id2">Go to Section 2</a> <a href="#id3">Go to Section 3</a> <a href="#id4">Go to Section 4</a> </div> <!-- We need to specify IDs for each section/div/element we want the user to scroll to --> <div class="sections"> <section id="id1"> <h1>Section 1</h1> </section> <section id="id2"> <h1>Section 2</h1> </section> <section id="id3"> <h1>Section 3</h1> </section> <section id="id4"> <h1>Section 4</h1> </section> </div></body> </html>
Output: As you can see in the output, we are smoothly scrolling to the sections and skipping the contents as well.
sumitgumber28
CSS-Properties
CSS-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 447,
"s": 28,
"text": "Sometimes we need the user to click on a button or link and take them to an element present on the same HTML page. Also, this needs to take the user to the element without any reload. Lots of times, users tend to skip to the main content, like on a gaming Website. They might want to skip the instructions and want to play the game directly. So, basically, we want to scroll to a particular element or skip to content."
},
{
"code": null,
"e": 563,
"s": 447,
"text": "In this article, we will learn how to scroll to a particular element or skip to content in plain HTML and CSS only."
},
{
"code": null,
"e": 574,
"s": 563,
"text": "Example 1:"
},
{
"code": null,
"e": 579,
"s": 574,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Scroll</title> <style> section:target { border: 2px solid blue; } .links-container { display: flex; justify-content: space-between; } </style></head> <body> <div class=\"links-container\"> <!-- The href attribute of anchor tags point to the section IDs --> <!-- Note that href has to point to IDs and not to classes as IDs are unique in HTML--> <a href=\"#id1\">Go to Section 1</a> <a href=\"#id2\">Go to Section 2</a> <a href=\"#id3\">Go to Section 3</a> <a href=\"#id4\">Go to Section 4</a> </div> <!-- We need to specify unique IDs for each section/div/element we want the user to scroll to --> <section id=\"id1\"> <h1>Section 1</h1> </section> <section id=\"id2\"> <h1>Section 2</h1> </section> <section id=\"id3\"> <h1>Section 3</h1> </section> <section id=\"id4\"> <h1>Section 4</h1> </section></body> </html>",
"e": 1814,
"s": 579,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1814,
"text": "Output: Our HTML will look like this in a browser window."
},
{
"code": null,
"e": 1988,
"s": 1872,
"text": "Example 2: Let’s now go ahead and add some styles so that we can have the sections placed far away from each other."
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <style> /* Some basic styling for testing our functionality */ .links-container { display: flex; justify-content: space-between; } .sections { display: flex; flex-direction: column; place-items: center; gap: 100rem; } </style></head> <body> <div class=\"links-container\"> <!-- The href attribute of anchor tags point to the section IDs --> <a href=\"#id1\">Go to Section 1</a> <a href=\"#id2\">Go to Section 2</a> <a href=\"#id3\">Go to Section 3</a> <a href=\"#id4\">Go to Section 4</a> </div> <!-- We need to specify IDs for each section/div/element we want the user to scroll to --> <div class=\"sections\"> <section id=\"id1\"> <h1>Section 1</h1> </section> <section id=\"id2\"> <h1>Section 2</h1> </section> <section id=\"id3\"> <h1>Section 3</h1> </section> <section id=\"id4\"> <h1>Section 4</h1> </section> </div></body> </html>",
"e": 3315,
"s": 1993,
"text": null
},
{
"code": null,
"e": 3485,
"s": 3315,
"text": "Output: Now, when we open our HTML file in a browser, we can see the functionality working when we click on any of the links, i.e. Go to Section 1, Go to Section 2, etc."
},
{
"code": null,
"e": 3708,
"s": 3485,
"text": "Although we are skipping content, the behavior is still not smooth. You can observe that when we click on the links, we go directly to the desired section. But we can make it scroll smoothly to the desired section as well."
},
{
"code": null,
"e": 3763,
"s": 3708,
"text": "To do this, we can use the following line in our code:"
},
{
"code": null,
"e": 3788,
"s": 3763,
"text": "scroll-behavior: smooth;"
},
{
"code": null,
"e": 4034,
"s": 3788,
"text": "There are other scroll behaviours also defined in HTML, you can go here for details about them. Here, we will be using smooth behaviour. Here, we will use scrolling to the particular section that we want to go, just by clicking once on the link."
},
{
"code": null,
"e": 4092,
"s": 4034,
"text": "The final code will look like this altogether: Example 3:"
},
{
"code": null,
"e": 4097,
"s": 4092,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Scroll</title> <style> html { /* This property makes the html page to scroll smoothly */ /* If you want to directly move to the section without scrolling, remove this scroll-behavior property*/ scroll-behavior: smooth; } /* Some basic styling for testing our functionality */ .links-container { display: flex; justify-content: space-between; } .sections { display: flex; flex-direction: column; place-items: center; gap: 100rem; } </style></head> <body> <div class=\"links-container\"> <!-- The href attribute of anchor tags point to the section IDs --> <a href=\"#id1\">Go to Section 1</a> <a href=\"#id2\">Go to Section 2</a> <a href=\"#id3\">Go to Section 3</a> <a href=\"#id4\">Go to Section 4</a> </div> <!-- We need to specify IDs for each section/div/element we want the user to scroll to --> <div class=\"sections\"> <section id=\"id1\"> <h1>Section 1</h1> </section> <section id=\"id2\"> <h1>Section 2</h1> </section> <section id=\"id3\"> <h1>Section 3</h1> </section> <section id=\"id4\"> <h1>Section 4</h1> </section> </div></body> </html>",
"e": 5723,
"s": 4097,
"text": null
},
{
"code": null,
"e": 5838,
"s": 5723,
"text": "Output: As you can see in the output, we are smoothly scrolling to the sections and skipping the contents as well."
},
{
"code": null,
"e": 5852,
"s": 5838,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5867,
"s": 5852,
"text": "CSS-Properties"
},
{
"code": null,
"e": 5881,
"s": 5867,
"text": "CSS-Questions"
},
{
"code": null,
"e": 5891,
"s": 5881,
"text": "HTML-Tags"
},
{
"code": null,
"e": 5898,
"s": 5891,
"text": "Picked"
},
{
"code": null,
"e": 5902,
"s": 5898,
"text": "CSS"
},
{
"code": null,
"e": 5907,
"s": 5902,
"text": "HTML"
},
{
"code": null,
"e": 5924,
"s": 5907,
"text": "Web Technologies"
},
{
"code": null,
"e": 5929,
"s": 5924,
"text": "HTML"
},
{
"code": null,
"e": 6027,
"s": 5929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6066,
"s": 6027,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 6105,
"s": 6066,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 6144,
"s": 6105,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 6181,
"s": 6144,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 6210,
"s": 6181,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 6234,
"s": 6210,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6287,
"s": 6234,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 6347,
"s": 6287,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6408,
"s": 6347,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
ReactJS checked Attribute | 25 May, 2021
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component.
In this article, we will know how to use checked or defaultChecked attribute in checkbox input in React.js.
The checked attribute can be used with a checkbox or RadioButton element.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure: It will look like the following.
Example 1: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'; // Defining our App Componentconst App = () => { // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> Input: <input type='checkbox' checked={true} /> </div> </>;} // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 2: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'; // Defining our App Componentconst App = () => { // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> Input: <input type='radio' checked={true} /> </div> </>;} // Exporting your Default App Componentexport default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference:https://reactjs.org/docs/dom-elements.html#checked
ReactJS Attributes
ReactJS DOM Elements
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component."
},
{
"code": null,
"e": 365,
"s": 257,
"text": "In this article, we will know how to use checked or defaultChecked attribute in checkbox input in React.js."
},
{
"code": null,
"e": 440,
"s": 365,
"text": "The checked attribute can be used with a checkbox or RadioButton element. "
},
{
"code": null,
"e": 490,
"s": 440,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 585,
"s": 490,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 649,
"s": 585,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 681,
"s": 649,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 794,
"s": 681,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 894,
"s": 794,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 908,
"s": 894,
"text": "cd foldername"
},
{
"code": null,
"e": 960,
"s": 908,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1092,
"s": 960,
"text": "Example 1: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1099,
"s": 1092,
"text": "App.js"
},
{
"code": "import React from 'react'; // Defining our App Componentconst App = () => { // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> Input: <input type='checkbox' checked={true} /> </div> </>;} // Exporting your Default App Componentexport default App",
"e": 1384,
"s": 1099,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1384,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1507,
"s": 1497,
"text": "npm start"
},
{
"code": null,
"e": 1607,
"s": 1507,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output: "
},
{
"code": null,
"e": 1739,
"s": 1607,
"text": "Example 2: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1750,
"s": 1739,
"text": "Javascript"
},
{
"code": "import React from 'react'; // Defining our App Componentconst App = () => { // Returning our JSX code return <> <div> <h1>GeeksforGeeks</h1> Input: <input type='radio' checked={true} /> </div> </>;} // Exporting your Default App Componentexport default App",
"e": 2032,
"s": 1750,
"text": null
},
{
"code": null,
"e": 2145,
"s": 2032,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2155,
"s": 2145,
"text": "npm start"
},
{
"code": null,
"e": 2254,
"s": 2155,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2315,
"s": 2254,
"text": "Reference:https://reactjs.org/docs/dom-elements.html#checked"
},
{
"code": null,
"e": 2334,
"s": 2315,
"text": "ReactJS Attributes"
},
{
"code": null,
"e": 2355,
"s": 2334,
"text": "ReactJS DOM Elements"
},
{
"code": null,
"e": 2363,
"s": 2355,
"text": "ReactJS"
},
{
"code": null,
"e": 2380,
"s": 2363,
"text": "Web Technologies"
},
{
"code": null,
"e": 2478,
"s": 2380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2516,
"s": 2478,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2543,
"s": 2516,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2582,
"s": 2543,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2634,
"s": 2582,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2673,
"s": 2634,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2735,
"s": 2673,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2768,
"s": 2735,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2829,
"s": 2768,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2879,
"s": 2829,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Print Postorder traversal from given Inorder and Preorder traversals | 21 Jun, 2022
Given Inorder and Preorder traversals of a binary tree, print Postorder traversal.
Example:
Input:
Inorder traversal in[] = {4, 2, 5, 1, 3, 6}
Preorder traversal pre[] = {1, 2, 4, 5, 3, 6}
Output:
Postorder traversal is {4, 5, 2, 6, 3, 1}
Traversals in the above example represents following tree
1
/ \
2 3
/ \ \
4 5 6
A naive method is to first construct the tree, then use a simple recursive method to print postorder traversal of the constructed tree.
We can print postorder traversal without constructing the tree. The idea is, root is always the first item in preorder traversal and it must be the last item in postorder traversal. We first recursively print left subtree, then recursively print right subtree. Finally, print root.
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.
To find boundaries of left and right subtrees in pre[] and in[], we search root in in[], all elements before root in in[] are elements of left subtree, and all elements after root are elements of right subtree. In pre[], all elements after index of root in in[] are elements of right subtree. And elements before index (including the element at index and excluding the first element) are elements of left subtree.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to print postorder traversal// from preorder and inorder traversals#include <iostream>using namespace std; // A utility function to search x in arr[] of size nint search(int arr[], int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from given// inorder and preorder traversalsvoid printPostOrder(int in[], int pre[], int n){ // The first element in pre[] is always root, search it // in in[] to find left and right subtrees int root = search(in, pre[0], n); // If left subtree is not empty, print left subtree if (root != 0) printPostOrder(in, pre + 1, root); // If right subtree is not empty, print right subtree if (root != n - 1) printPostOrder(in + root + 1, pre + root + 1, n - root - 1); // Print root cout << pre[0] << " ";} // Driver program to test above functionsint main(){ int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = sizeof(in) / sizeof(in[0]); cout << "Postorder traversal " << endl; printPostOrder(in, pre, n); return 0;}
// Java program to print postorder// traversal from preorder and// inorder traversalsimport java.util.Arrays; class GFG{ // A utility function to search x in arr[] of size nstatic int search(int arr[], int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsstatic void printPostOrder(int in1[], int pre[], int n){ // The first element in pre[] is // always root, search it in in[] // to find left and right subtrees int root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree if (root != 0) printPostOrder(in1, Arrays.copyOfRange(pre, 1, n), root); // If right subtree is not empty, // print right subtree if (root != n - 1) printPostOrder(Arrays.copyOfRange(in1, root+1, n), Arrays.copyOfRange(pre, 1+root, n), n - root - 1); // Print root System.out.print( pre[0] + " ");} // Driver codepublic static void main(String args[]){ int in1[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = in1.length; System.out.println("Postorder traversal " ); printPostOrder(in1, pre, n);}}// This code is contributed by Arnab Kundu
# Python3 program to print postorder# traversal from preorder and inorder# traversals # A utility function to search x in# arr[] of size ndef search(arr, x, n): for i in range(n): if (arr[i] == x): return i return -1 # Prints postorder traversal from# given inorder and preorder traversalsdef printPostOrder(In, pre, n): # The first element in pre[] is always # root, search it in in[] to find left # and right subtrees root = search(In, pre[0], n) # If left subtree is not empty, # print left subtree if (root != 0): printPostOrder(In, pre[1:n], root) # If right subtree is not empty, # print right subtree if (root != n - 1): printPostOrder(In[root + 1 : n], pre[root + 1 : n], n - root - 1) # Print root print(pre[0], end = " ") # Driver codeIn = [ 4, 2, 5, 1, 3, 6 ]pre = [ 1, 2, 4, 5, 3, 6 ]n = len(In) print("Postorder traversal ") printPostOrder(In, pre, n) # This code is contributed by avanitrachhadiya2155
// C# program to print postorder// traversal from preorder and// inorder traversalsusing System; class GFG{ // A utility function to search x// in []arr of size nstatic int search(int []arr, int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsstatic void printPostOrder(int []in1, int []pre, int n){ // The first element in pre[] is // always root, search it in in[] // to find left and right subtrees int root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree int []ar; if (root != 0) { ar = new int[n - 1]; Array.Copy(pre, 1, ar, 0, n - 1); printPostOrder(in1, ar, root); } // If right subtree is not empty, // print right subtree if (root != n - 1) { ar = new int[n - (root + 1)]; Array.Copy(in1, root + 1, ar, 0, n - (root + 1)); int []ar1 = new int[n - (root + 1)]; Array.Copy(pre, root + 1, ar1, 0, n - (root + 1)); printPostOrder(ar, ar1, n - root - 1); } // Print root Console.Write(pre[0] + " ");} // Driver codepublic static void Main(String []args){ int []in1 = { 4, 2, 5, 1, 3, 6 }; int []pre = { 1, 2, 4, 5, 3, 6 }; int n = in1.Length; Console.WriteLine("Postorder traversal " ); printPostOrder(in1, pre, n);}} // This code is contributed by 29AjayKumar
<script> // javascript program to print postorder// traversal from preorder and// inorder traversals // A utility function to search x in arr of size nfunction search(arr , x , n){ for (var i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsfunction printPostOrder( in1, pre , n){ // The first element in pre is // always root, search it in in // to find left and right subtrees var root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree if (root != 0) printPostOrder(in1, pre.slice(1, n), root); // If right subtree is not empty, // print right subtree if (root != n - 1) printPostOrder(in1.slice(root+1, n), pre.slice(1+root, n), n - root - 1); // Print root document.write( pre[0] + " ");} // Driver codevar in1 = [ 4, 2, 5, 1, 3, 6 ];var pre = [ 1, 2, 4, 5, 3, 6 ];var n = in1.length;document.write("Postorder traversal <br>" );printPostOrder(in1, pre, n); // This code contributed by shikhasingrajput</script>
Postorder traversal
4 5 2 6 3 1
Implementation:
C++
Java
C#
Javascript
// C++ program to print Postorder// traversal from given Inorder// and Preorder traversals.#include <iostream>using namespace std; int preIndex = 0; int search(int arr[], int startIn,int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;}void printPost(int arr[], int pre[],int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd,pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal cout << arr[inIndex] << " ";} // Driver codeint main(){ int arr[] = {4, 2, 5, 1, 3, 6}; int pre[] = {1, 2, 4, 5, 3, 6}; int len = sizeof(arr)/sizeof(arr[0]); printPost(arr, pre, 0, len - 1);} // This code is contributed by SHUBHAMSINGH10
// Java program to print Postorder traversal from given Inorder// and Preorder traversals. public class PrintPost { static int preIndex = 0; void printPost(int[] in, int[] pre, int inStrt, int inEnd) { if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = search(in, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(in, pre, inStrt, inIndex - 1); // traverse right tree printPost(in, pre, inIndex + 1, inEnd); // print root node at the end of traversal System.out.print(in[inIndex] + " "); } int search(int[] in, int startIn, int endIn, int data) { int i = 0; for (i = startIn; i < endIn; i++) if (in[i] == data) return i; return i; } // Driver code public static void main(String ars[]) { int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int len = in.length; PrintPost tree = new PrintPost(); tree.printPost(in, pre, 0, len - 1); }}
// C# program to print Postorder// traversal from given Inorder// and Preorder traversals.using System; class GFG{public static int preIndex = 0;public virtual void printPost(int[] arr, int[] pre, int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal Console.Write(arr[inIndex] + " ");} public virtual int search(int[] arr, int startIn, int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;} // Driver codepublic static void Main(string[] ars){ int[] arr = new int[] {4, 2, 5, 1, 3, 6}; int[] pre = new int[] {1, 2, 4, 5, 3, 6}; int len = arr.Length; GFG tree = new GFG(); tree.printPost(arr, pre, 0, len - 1);}} // This code is contributed by Shrikant13
<script> // JavaScript program to print Postorder // traversal from given Inorder // and Preorder traversals. class GFG { constructor() { this.preIndex = 0; } printPost(arr, pre, inStrt, inEnd) { if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. var inIndex = this.search(arr, inStrt, inEnd, pre[this.preIndex++]); // traverse left tree this.printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree this.printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal document.write(arr[inIndex] + " "); } search(arr, startIn, endIn, data) { var i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i; } } // Driver code var arr = [4, 2, 5, 1, 3, 6]; var pre = [1, 2, 4, 5, 3, 6]; var len = arr.length; var tree = new GFG(); tree.printPost(arr, pre, 0, len - 1); </script>
4 5 2 6 3 1
Time Complexity: The above function visits every node in array. For every visit, it calls search which takes O(n) time. Therefore, overall time complexity of the function is O(n2)
Implementation: The above solution can be optimized using hashing. We use a HashMap to store elements and their indexes so that we can quickly find index of an element.
C++
Java
Python3
C#
Javascript
// C++ program to print Postorder traversal from// given Inorder and Preorder traversals.#include<bits/stdc++.h>using namespace std; int preIndex = 0;void printPost(int in[], int pre[], int inStrt, int inEnd, map<int, int> hm){ if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = hm[pre[preIndex++]]; // traverse left tree printPost(in, pre, inStrt, inIndex - 1, hm); // traverse right tree printPost(in, pre, inIndex + 1, inEnd, hm); // print root node at the end of traversal cout << in[inIndex] << " ";} void printPostMain(int in[], int pre[],int n){ map<int,int> hm ; for (int i = 0; i < n; i++) hm[in[i]] = i; printPost(in, pre, 0, n - 1, hm);} // Driver codeint main(){ int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = sizeof(pre)/sizeof(pre[0]); printPostMain(in, pre, n); return 0;} // This code is contributed by Arnab Kundu
// Java program to print Postorder traversal from// given Inorder and Preorder traversals.import java.util.*; public class PrintPost { static int preIndex = 0; void printPost(int[] in, int[] pre, int inStrt, int inEnd, HashMap<Integer, Integer> hm) { if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = hm.get(pre[preIndex++]); // traverse left tree printPost(in, pre, inStrt, inIndex - 1, hm); // traverse right tree printPost(in, pre, inIndex + 1, inEnd, hm); // print root node at the end of traversal System.out.print(in[inIndex] + " "); } void printPostMain(int[] in, int[] pre) { int n = pre.length; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i=0; i<n; i++) hm.put(in[i], i); printPost(in, pre, 0, n-1, hm); } // Driver code public static void main(String ars[]) { int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; PrintPost tree = new PrintPost(); tree.printPostMain(in, pre); }}
# Python3 program to print Postorder traversal from# given Inorder and Preorder traversals. def printPost(inn, pre, inStrt, inEnd): global preIndex, hm if (inStrt > inEnd): return # Find index of next item in preorder traversal in # inorder. inIndex = hm[pre[preIndex]] preIndex += 1 # traverse left tree printPost(inn, pre, inStrt, inIndex - 1) # traverse right tree printPost(inn, pre, inIndex + 1, inEnd) # print root node at the end of traversal print(inn[inIndex], end = " ") def printPostMain(inn, pre, n): for i in range(n): hm[inn[i]] = i printPost(inn, pre, 0, n - 1) # Driver codeif __name__ == '__main__': hm = {} preIndex = 0 inn = [4, 2, 5, 1, 3, 6] pre = [1, 2, 4, 5, 3, 6] n = len(pre) printPostMain(inn, pre, n) # This code is contributed by mohit kumar 29
// C# program to print Postorder// traversal from given Inorder// and Preorder traversals.using System; class GFG{public static int preIndex = 0;public virtual void printPost(int[] arr, int[] pre, int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the // end of traversal Console.Write(arr[inIndex] + " ");} public virtual int search(int[] arr, int startIn, int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;} // Driver codepublic static void Main(string[] ars){ int[] arr = new int[] {4, 2, 5, 1, 3, 6}; int[] pre = new int[] {1, 2, 4, 5, 3, 6}; int len = arr.Length; GFG tree = new GFG(); tree.printPost(arr, pre, 0, len - 1);}} // This code is contributed by Shrikant13
<script> // Javascript program to print// Postorder traversal from given// Inorder and Preorder traversals.let preIndex = 0; function printPost(In, pre, inStrt, inEnd, hm){ if (inStrt > inEnd) return; // Find index of next item in // preorder traversal in inorder. let inIndex = hm.get(pre[preIndex++]); // Traverse left tree printPost(In, pre, inStrt, inIndex - 1, hm); // Traverse right tree printPost(In, pre, inIndex + 1, inEnd, hm); // Print root node at the end of traversal document.write(In[inIndex] + " ");} function printPostMain(In, pre){ let n = pre.length; let hm = new Map(); for(let i = 0; i < n; i++) hm.set(In[i], i); printPost(In, pre, 0, n - 1, hm);} // Driver codelet In = [ 4, 2, 5, 1, 3, 6 ];let pre = [ 1, 2, 4, 5, 3, 6 ]; printPostMain(In, pre); // This code is contributed by unknown2108 </script>
4 5 2 6 3 1
Time complexity: O(n)
sainathcvs
shrikanth13
andrew1234
29AjayKumar
SHUBHAMSINGH10
mohit kumar 29
avanitrachhadiya2155
khushboogoyal499
unknown2108
rdtank
shikhasingrajput
sagartomar9927
simmytarika5
surinderdawra388
hardikkoriintern
Amazon
Java-HashMap
Payu
Tree
Amazon
Payu
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Given Inorder and Preorder traversals of a binary tree, print Postorder traversal."
},
{
"code": null,
"e": 144,
"s": 135,
"text": "Example:"
},
{
"code": null,
"e": 292,
"s": 144,
"text": "Input:\nInorder traversal in[] = {4, 2, 5, 1, 3, 6}\nPreorder traversal pre[] = {1, 2, 4, 5, 3, 6}\n\nOutput:\nPostorder traversal is {4, 5, 2, 6, 3, 1}"
},
{
"code": null,
"e": 351,
"s": 292,
"text": "Traversals in the above example represents following tree "
},
{
"code": null,
"e": 427,
"s": 351,
"text": " 1\n / \\ \n 2 3\n / \\ \\\n 4 5 6"
},
{
"code": null,
"e": 563,
"s": 427,
"text": "A naive method is to first construct the tree, then use a simple recursive method to print postorder traversal of the constructed tree."
},
{
"code": null,
"e": 846,
"s": 563,
"text": "We can print postorder traversal without constructing the tree. The idea is, root is always the first item in preorder traversal and it must be the last item in postorder traversal. We first recursively print left subtree, then recursively print right subtree. Finally, print root. "
},
{
"code": null,
"e": 855,
"s": 846,
"text": "Chapters"
},
{
"code": null,
"e": 882,
"s": 855,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 932,
"s": 882,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 955,
"s": 932,
"text": "captions off, selected"
},
{
"code": null,
"e": 963,
"s": 955,
"text": "English"
},
{
"code": null,
"e": 987,
"s": 963,
"text": "This is a modal window."
},
{
"code": null,
"e": 1056,
"s": 987,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1078,
"s": 1056,
"text": "End of dialog window."
},
{
"code": null,
"e": 1492,
"s": 1078,
"text": "To find boundaries of left and right subtrees in pre[] and in[], we search root in in[], all elements before root in in[] are elements of left subtree, and all elements after root are elements of right subtree. In pre[], all elements after index of root in in[] are elements of right subtree. And elements before index (including the element at index and excluding the first element) are elements of left subtree."
},
{
"code": null,
"e": 1508,
"s": 1492,
"text": "Implementation:"
},
{
"code": null,
"e": 1512,
"s": 1508,
"text": "C++"
},
{
"code": null,
"e": 1517,
"s": 1512,
"text": "Java"
},
{
"code": null,
"e": 1525,
"s": 1517,
"text": "Python3"
},
{
"code": null,
"e": 1528,
"s": 1525,
"text": "C#"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": "Javascript"
},
{
"code": "// C++ program to print postorder traversal// from preorder and inorder traversals#include <iostream>using namespace std; // A utility function to search x in arr[] of size nint search(int arr[], int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from given// inorder and preorder traversalsvoid printPostOrder(int in[], int pre[], int n){ // The first element in pre[] is always root, search it // in in[] to find left and right subtrees int root = search(in, pre[0], n); // If left subtree is not empty, print left subtree if (root != 0) printPostOrder(in, pre + 1, root); // If right subtree is not empty, print right subtree if (root != n - 1) printPostOrder(in + root + 1, pre + root + 1, n - root - 1); // Print root cout << pre[0] << \" \";} // Driver program to test above functionsint main(){ int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = sizeof(in) / sizeof(in[0]); cout << \"Postorder traversal \" << endl; printPostOrder(in, pre, n); return 0;}",
"e": 2668,
"s": 1539,
"text": null
},
{
"code": "// Java program to print postorder// traversal from preorder and// inorder traversalsimport java.util.Arrays; class GFG{ // A utility function to search x in arr[] of size nstatic int search(int arr[], int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsstatic void printPostOrder(int in1[], int pre[], int n){ // The first element in pre[] is // always root, search it in in[] // to find left and right subtrees int root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree if (root != 0) printPostOrder(in1, Arrays.copyOfRange(pre, 1, n), root); // If right subtree is not empty, // print right subtree if (root != n - 1) printPostOrder(Arrays.copyOfRange(in1, root+1, n), Arrays.copyOfRange(pre, 1+root, n), n - root - 1); // Print root System.out.print( pre[0] + \" \");} // Driver codepublic static void main(String args[]){ int in1[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = in1.length; System.out.println(\"Postorder traversal \" ); printPostOrder(in1, pre, n);}}// This code is contributed by Arnab Kundu",
"e": 3956,
"s": 2668,
"text": null
},
{
"code": "# Python3 program to print postorder# traversal from preorder and inorder# traversals # A utility function to search x in# arr[] of size ndef search(arr, x, n): for i in range(n): if (arr[i] == x): return i return -1 # Prints postorder traversal from# given inorder and preorder traversalsdef printPostOrder(In, pre, n): # The first element in pre[] is always # root, search it in in[] to find left # and right subtrees root = search(In, pre[0], n) # If left subtree is not empty, # print left subtree if (root != 0): printPostOrder(In, pre[1:n], root) # If right subtree is not empty, # print right subtree if (root != n - 1): printPostOrder(In[root + 1 : n], pre[root + 1 : n], n - root - 1) # Print root print(pre[0], end = \" \") # Driver codeIn = [ 4, 2, 5, 1, 3, 6 ]pre = [ 1, 2, 4, 5, 3, 6 ]n = len(In) print(\"Postorder traversal \") printPostOrder(In, pre, n) # This code is contributed by avanitrachhadiya2155",
"e": 5003,
"s": 3956,
"text": null
},
{
"code": "// C# program to print postorder// traversal from preorder and// inorder traversalsusing System; class GFG{ // A utility function to search x// in []arr of size nstatic int search(int []arr, int x, int n){ for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsstatic void printPostOrder(int []in1, int []pre, int n){ // The first element in pre[] is // always root, search it in in[] // to find left and right subtrees int root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree int []ar; if (root != 0) { ar = new int[n - 1]; Array.Copy(pre, 1, ar, 0, n - 1); printPostOrder(in1, ar, root); } // If right subtree is not empty, // print right subtree if (root != n - 1) { ar = new int[n - (root + 1)]; Array.Copy(in1, root + 1, ar, 0, n - (root + 1)); int []ar1 = new int[n - (root + 1)]; Array.Copy(pre, root + 1, ar1, 0, n - (root + 1)); printPostOrder(ar, ar1, n - root - 1); } // Print root Console.Write(pre[0] + \" \");} // Driver codepublic static void Main(String []args){ int []in1 = { 4, 2, 5, 1, 3, 6 }; int []pre = { 1, 2, 4, 5, 3, 6 }; int n = in1.Length; Console.WriteLine(\"Postorder traversal \" ); printPostOrder(in1, pre, n);}} // This code is contributed by 29AjayKumar",
"e": 6545,
"s": 5003,
"text": null
},
{
"code": "<script> // javascript program to print postorder// traversal from preorder and// inorder traversals // A utility function to search x in arr of size nfunction search(arr , x , n){ for (var i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} // Prints postorder traversal from// given inorder and preorder traversalsfunction printPostOrder( in1, pre , n){ // The first element in pre is // always root, search it in in // to find left and right subtrees var root = search(in1, pre[0], n); // If left subtree is not empty, // print left subtree if (root != 0) printPostOrder(in1, pre.slice(1, n), root); // If right subtree is not empty, // print right subtree if (root != n - 1) printPostOrder(in1.slice(root+1, n), pre.slice(1+root, n), n - root - 1); // Print root document.write( pre[0] + \" \");} // Driver codevar in1 = [ 4, 2, 5, 1, 3, 6 ];var pre = [ 1, 2, 4, 5, 3, 6 ];var n = in1.length;document.write(\"Postorder traversal <br>\" );printPostOrder(in1, pre, n); // This code contributed by shikhasingrajput</script>",
"e": 7679,
"s": 6545,
"text": null
},
{
"code": null,
"e": 7713,
"s": 7679,
"text": "Postorder traversal \n4 5 2 6 3 1 "
},
{
"code": null,
"e": 7729,
"s": 7713,
"text": "Implementation:"
},
{
"code": null,
"e": 7733,
"s": 7729,
"text": "C++"
},
{
"code": null,
"e": 7738,
"s": 7733,
"text": "Java"
},
{
"code": null,
"e": 7741,
"s": 7738,
"text": "C#"
},
{
"code": null,
"e": 7752,
"s": 7741,
"text": "Javascript"
},
{
"code": "// C++ program to print Postorder// traversal from given Inorder// and Preorder traversals.#include <iostream>using namespace std; int preIndex = 0; int search(int arr[], int startIn,int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;}void printPost(int arr[], int pre[],int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd,pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal cout << arr[inIndex] << \" \";} // Driver codeint main(){ int arr[] = {4, 2, 5, 1, 3, 6}; int pre[] = {1, 2, 4, 5, 3, 6}; int len = sizeof(arr)/sizeof(arr[0]); printPost(arr, pre, 0, len - 1);} // This code is contributed by SHUBHAMSINGH10",
"e": 8779,
"s": 7752,
"text": null
},
{
"code": "// Java program to print Postorder traversal from given Inorder// and Preorder traversals. public class PrintPost { static int preIndex = 0; void printPost(int[] in, int[] pre, int inStrt, int inEnd) { if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = search(in, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(in, pre, inStrt, inIndex - 1); // traverse right tree printPost(in, pre, inIndex + 1, inEnd); // print root node at the end of traversal System.out.print(in[inIndex] + \" \"); } int search(int[] in, int startIn, int endIn, int data) { int i = 0; for (i = startIn; i < endIn; i++) if (in[i] == data) return i; return i; } // Driver code public static void main(String ars[]) { int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int len = in.length; PrintPost tree = new PrintPost(); tree.printPost(in, pre, 0, len - 1); }}",
"e": 9919,
"s": 8779,
"text": null
},
{
"code": "// C# program to print Postorder// traversal from given Inorder// and Preorder traversals.using System; class GFG{public static int preIndex = 0;public virtual void printPost(int[] arr, int[] pre, int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal Console.Write(arr[inIndex] + \" \");} public virtual int search(int[] arr, int startIn, int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;} // Driver codepublic static void Main(string[] ars){ int[] arr = new int[] {4, 2, 5, 1, 3, 6}; int[] pre = new int[] {1, 2, 4, 5, 3, 6}; int len = arr.Length; GFG tree = new GFG(); tree.printPost(arr, pre, 0, len - 1);}} // This code is contributed by Shrikant13",
"e": 11118,
"s": 9919,
"text": null
},
{
"code": "<script> // JavaScript program to print Postorder // traversal from given Inorder // and Preorder traversals. class GFG { constructor() { this.preIndex = 0; } printPost(arr, pre, inStrt, inEnd) { if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. var inIndex = this.search(arr, inStrt, inEnd, pre[this.preIndex++]); // traverse left tree this.printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree this.printPost(arr, pre, inIndex + 1, inEnd); // print root node at the end of traversal document.write(arr[inIndex] + \" \"); } search(arr, startIn, endIn, data) { var i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i; } } // Driver code var arr = [4, 2, 5, 1, 3, 6]; var pre = [1, 2, 4, 5, 3, 6]; var len = arr.length; var tree = new GFG(); tree.printPost(arr, pre, 0, len - 1); </script>",
"e": 12306,
"s": 11118,
"text": null
},
{
"code": null,
"e": 12318,
"s": 12306,
"text": "4 5 2 6 3 1"
},
{
"code": null,
"e": 12500,
"s": 12320,
"text": "Time Complexity: The above function visits every node in array. For every visit, it calls search which takes O(n) time. Therefore, overall time complexity of the function is O(n2)"
},
{
"code": null,
"e": 12670,
"s": 12500,
"text": "Implementation: The above solution can be optimized using hashing. We use a HashMap to store elements and their indexes so that we can quickly find index of an element. "
},
{
"code": null,
"e": 12674,
"s": 12670,
"text": "C++"
},
{
"code": null,
"e": 12679,
"s": 12674,
"text": "Java"
},
{
"code": null,
"e": 12687,
"s": 12679,
"text": "Python3"
},
{
"code": null,
"e": 12690,
"s": 12687,
"text": "C#"
},
{
"code": null,
"e": 12701,
"s": 12690,
"text": "Javascript"
},
{
"code": "// C++ program to print Postorder traversal from// given Inorder and Preorder traversals.#include<bits/stdc++.h>using namespace std; int preIndex = 0;void printPost(int in[], int pre[], int inStrt, int inEnd, map<int, int> hm){ if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = hm[pre[preIndex++]]; // traverse left tree printPost(in, pre, inStrt, inIndex - 1, hm); // traverse right tree printPost(in, pre, inIndex + 1, inEnd, hm); // print root node at the end of traversal cout << in[inIndex] << \" \";} void printPostMain(int in[], int pre[],int n){ map<int,int> hm ; for (int i = 0; i < n; i++) hm[in[i]] = i; printPost(in, pre, 0, n - 1, hm);} // Driver codeint main(){ int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; int n = sizeof(pre)/sizeof(pre[0]); printPostMain(in, pre, n); return 0;} // This code is contributed by Arnab Kundu",
"e": 13719,
"s": 12701,
"text": null
},
{
"code": "// Java program to print Postorder traversal from// given Inorder and Preorder traversals.import java.util.*; public class PrintPost { static int preIndex = 0; void printPost(int[] in, int[] pre, int inStrt, int inEnd, HashMap<Integer, Integer> hm) { if (inStrt > inEnd) return; // Find index of next item in preorder traversal in // inorder. int inIndex = hm.get(pre[preIndex++]); // traverse left tree printPost(in, pre, inStrt, inIndex - 1, hm); // traverse right tree printPost(in, pre, inIndex + 1, inEnd, hm); // print root node at the end of traversal System.out.print(in[inIndex] + \" \"); } void printPostMain(int[] in, int[] pre) { int n = pre.length; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for (int i=0; i<n; i++) hm.put(in[i], i); printPost(in, pre, 0, n-1, hm); } // Driver code public static void main(String ars[]) { int in[] = { 4, 2, 5, 1, 3, 6 }; int pre[] = { 1, 2, 4, 5, 3, 6 }; PrintPost tree = new PrintPost(); tree.printPostMain(in, pre); }}",
"e": 14927,
"s": 13719,
"text": null
},
{
"code": "# Python3 program to print Postorder traversal from# given Inorder and Preorder traversals. def printPost(inn, pre, inStrt, inEnd): global preIndex, hm if (inStrt > inEnd): return # Find index of next item in preorder traversal in # inorder. inIndex = hm[pre[preIndex]] preIndex += 1 # traverse left tree printPost(inn, pre, inStrt, inIndex - 1) # traverse right tree printPost(inn, pre, inIndex + 1, inEnd) # print root node at the end of traversal print(inn[inIndex], end = \" \") def printPostMain(inn, pre, n): for i in range(n): hm[inn[i]] = i printPost(inn, pre, 0, n - 1) # Driver codeif __name__ == '__main__': hm = {} preIndex = 0 inn = [4, 2, 5, 1, 3, 6] pre = [1, 2, 4, 5, 3, 6] n = len(pre) printPostMain(inn, pre, n) # This code is contributed by mohit kumar 29",
"e": 15782,
"s": 14927,
"text": null
},
{
"code": "// C# program to print Postorder// traversal from given Inorder// and Preorder traversals.using System; class GFG{public static int preIndex = 0;public virtual void printPost(int[] arr, int[] pre, int inStrt, int inEnd){ if (inStrt > inEnd) { return; } // Find index of next item in preorder // traversal in inorder. int inIndex = search(arr, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(arr, pre, inStrt, inIndex - 1); // traverse right tree printPost(arr, pre, inIndex + 1, inEnd); // print root node at the // end of traversal Console.Write(arr[inIndex] + \" \");} public virtual int search(int[] arr, int startIn, int endIn, int data){ int i = 0; for (i = startIn; i < endIn; i++) { if (arr[i] == data) { return i; } } return i;} // Driver codepublic static void Main(string[] ars){ int[] arr = new int[] {4, 2, 5, 1, 3, 6}; int[] pre = new int[] {1, 2, 4, 5, 3, 6}; int len = arr.Length; GFG tree = new GFG(); tree.printPost(arr, pre, 0, len - 1);}} // This code is contributed by Shrikant13",
"e": 16987,
"s": 15782,
"text": null
},
{
"code": "<script> // Javascript program to print// Postorder traversal from given// Inorder and Preorder traversals.let preIndex = 0; function printPost(In, pre, inStrt, inEnd, hm){ if (inStrt > inEnd) return; // Find index of next item in // preorder traversal in inorder. let inIndex = hm.get(pre[preIndex++]); // Traverse left tree printPost(In, pre, inStrt, inIndex - 1, hm); // Traverse right tree printPost(In, pre, inIndex + 1, inEnd, hm); // Print root node at the end of traversal document.write(In[inIndex] + \" \");} function printPostMain(In, pre){ let n = pre.length; let hm = new Map(); for(let i = 0; i < n; i++) hm.set(In[i], i); printPost(In, pre, 0, n - 1, hm);} // Driver codelet In = [ 4, 2, 5, 1, 3, 6 ];let pre = [ 1, 2, 4, 5, 3, 6 ]; printPostMain(In, pre); // This code is contributed by unknown2108 </script>",
"e": 17889,
"s": 16987,
"text": null
},
{
"code": null,
"e": 17902,
"s": 17889,
"text": "4 5 2 6 3 1 "
},
{
"code": null,
"e": 17925,
"s": 17902,
"text": "Time complexity: O(n) "
},
{
"code": null,
"e": 17936,
"s": 17925,
"text": "sainathcvs"
},
{
"code": null,
"e": 17948,
"s": 17936,
"text": "shrikanth13"
},
{
"code": null,
"e": 17959,
"s": 17948,
"text": "andrew1234"
},
{
"code": null,
"e": 17971,
"s": 17959,
"text": "29AjayKumar"
},
{
"code": null,
"e": 17986,
"s": 17971,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 18001,
"s": 17986,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 18022,
"s": 18001,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 18039,
"s": 18022,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 18051,
"s": 18039,
"text": "unknown2108"
},
{
"code": null,
"e": 18058,
"s": 18051,
"text": "rdtank"
},
{
"code": null,
"e": 18075,
"s": 18058,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 18090,
"s": 18075,
"text": "sagartomar9927"
},
{
"code": null,
"e": 18103,
"s": 18090,
"text": "simmytarika5"
},
{
"code": null,
"e": 18120,
"s": 18103,
"text": "surinderdawra388"
},
{
"code": null,
"e": 18137,
"s": 18120,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 18144,
"s": 18137,
"text": "Amazon"
},
{
"code": null,
"e": 18157,
"s": 18144,
"text": "Java-HashMap"
},
{
"code": null,
"e": 18162,
"s": 18157,
"text": "Payu"
},
{
"code": null,
"e": 18167,
"s": 18162,
"text": "Tree"
},
{
"code": null,
"e": 18174,
"s": 18167,
"text": "Amazon"
},
{
"code": null,
"e": 18179,
"s": 18174,
"text": "Payu"
},
{
"code": null,
"e": 18184,
"s": 18179,
"text": "Tree"
}
] |
How to Download and Install Shotcut Video Editor on Windows? | 15 May, 2022
Shotcut is an open-source and cross-platform video editing software. It is developed by MLT Multimedia Framework. It is easy to use especially for the beginner who wants to learn video editing because it is free to use, provides a simple interface, and can work with any format of video, audio, or photo media. It is written in C, C++ languages and is available for all operating systems like Linux, macOS, Windows, etc. It does not depend upon the system codecs and can also run as a portable app from an external drive. It also performs an integrity check of an audio/video file. In this article, we will learn how to install Shotcut in Windows.
Follow the below steps to install Shotcut on Windows:
Step 1: Visit the official website using the URL https://shotcut.org/ with the help of any web browser to download Shotcut for Windows.
Step 2: Click on the Click to Download button.
Step 3: Next web page open, now click on Windows Installer and the file automatically started downloading.
Step 4: Now find the executable file in the Downloads folder of your system and open it.
Step 5: It will prompt confirmation to make changes to your system. Click on Yes.
Step 6: Next step is the License Agreement, so click on the I Agree button.
Step 7: Next step is the installing location. Now choose the drive which you want to install the Shotcut and that will have sufficient memory space for installation. By default, it installs in C drive. It required approximately 289.1 MB of memory space. Click on the Next button.
Step 8: Next screen is of choosing installation options, all options are not marked you can mark according to your requirement. Like if you want your software on the Desktop screen then mark Create Desktop Shortcut (Icon) option, if you want to remove old program files then mark Remove Old Program Files and then click on the Install button.
Step 9: After the installation process will start and will a few minutes to complete the installation.
Step 10: Setup is completed, now click on the Close button.
Now the Shotcut is successfully installed and an icon is created on the desktop.
Run the software to create a new project.
So this is how we install Shotcut in the Windows system.
lastbitcoder
how-to-install
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2022"
},
{
"code": null,
"e": 676,
"s": 28,
"text": "Shotcut is an open-source and cross-platform video editing software. It is developed by MLT Multimedia Framework. It is easy to use especially for the beginner who wants to learn video editing because it is free to use, provides a simple interface, and can work with any format of video, audio, or photo media. It is written in C, C++ languages and is available for all operating systems like Linux, macOS, Windows, etc. It does not depend upon the system codecs and can also run as a portable app from an external drive. It also performs an integrity check of an audio/video file. In this article, we will learn how to install Shotcut in Windows."
},
{
"code": null,
"e": 730,
"s": 676,
"text": "Follow the below steps to install Shotcut on Windows:"
},
{
"code": null,
"e": 866,
"s": 730,
"text": "Step 1: Visit the official website using the URL https://shotcut.org/ with the help of any web browser to download Shotcut for Windows."
},
{
"code": null,
"e": 913,
"s": 866,
"text": "Step 2: Click on the Click to Download button."
},
{
"code": null,
"e": 1020,
"s": 913,
"text": "Step 3: Next web page open, now click on Windows Installer and the file automatically started downloading."
},
{
"code": null,
"e": 1109,
"s": 1020,
"text": "Step 4: Now find the executable file in the Downloads folder of your system and open it."
},
{
"code": null,
"e": 1191,
"s": 1109,
"text": "Step 5: It will prompt confirmation to make changes to your system. Click on Yes."
},
{
"code": null,
"e": 1269,
"s": 1193,
"text": "Step 6: Next step is the License Agreement, so click on the I Agree button."
},
{
"code": null,
"e": 1549,
"s": 1269,
"text": "Step 7: Next step is the installing location. Now choose the drive which you want to install the Shotcut and that will have sufficient memory space for installation. By default, it installs in C drive. It required approximately 289.1 MB of memory space. Click on the Next button."
},
{
"code": null,
"e": 1892,
"s": 1549,
"text": "Step 8: Next screen is of choosing installation options, all options are not marked you can mark according to your requirement. Like if you want your software on the Desktop screen then mark Create Desktop Shortcut (Icon) option, if you want to remove old program files then mark Remove Old Program Files and then click on the Install button."
},
{
"code": null,
"e": 1995,
"s": 1892,
"text": "Step 9: After the installation process will start and will a few minutes to complete the installation."
},
{
"code": null,
"e": 2055,
"s": 1995,
"text": "Step 10: Setup is completed, now click on the Close button."
},
{
"code": null,
"e": 2136,
"s": 2055,
"text": "Now the Shotcut is successfully installed and an icon is created on the desktop."
},
{
"code": null,
"e": 2178,
"s": 2136,
"text": "Run the software to create a new project."
},
{
"code": null,
"e": 2235,
"s": 2178,
"text": "So this is how we install Shotcut in the Windows system."
},
{
"code": null,
"e": 2248,
"s": 2235,
"text": "lastbitcoder"
},
{
"code": null,
"e": 2263,
"s": 2248,
"text": "how-to-install"
},
{
"code": null,
"e": 2270,
"s": 2263,
"text": "How To"
},
{
"code": null,
"e": 2289,
"s": 2270,
"text": "Installation Guide"
}
] |
Log Injection | 01 Jul, 2022
Log Injection is a very simple to carry out attack aimed at web applications. For the attacker its very simple to perform the attack. However, for the target web application or its administrator its very difficult to identify the scope of the attack performed and its impact.
Web applications or any applications for the case, store huge amount of logs in the backend. They may be
Crash logs : Information about when the application got crashed, reason behind the crash, affected users etc.,Error/Exception logs : Details like exception thrown from code, Stacktrace of the thrown exception.Access logs : Access logs hold information about different end points accessed by a user in the system with time details.GC logs : Usually stored by Java to keep track of Garbage collection.Monitoring logs : Its useful when a user tries to do a suspicious activity on your site, you could detect it and send a mail to yourself to get notified or log it for future records.Apart from these, there are many categories of application logs. These logs are very useful and absolutely necessary to debug application issues, audit and control, application performance monitoring, troubleshooting etc.,These generated logs might be written to a disk, raised as an alert mail, pushed to a third party storage service or simply written to a set of files based on the criticalness of the generated log data and/or based on the volume of data that is generated.When not handled properly, even logs could be manipulated in the web application. Let’s say you have an endpoint like below,https://www.testsite.com/logDOSAttemptByUser?userName=user1
This API will log the user names of users who are trying a DOS Attack in your site.And in the backend, you have something like,List suspiciousAccountsLogged = new ArrayList();
suspiciousAccountsLogged = parseUserNamesFromLogs();
if(suspiciousAccountsLogged.size > 0)
{
for(String userName : suspiciousAccountsLogged)
{
doBlockUserForDOSAttempt(userName);
}
}
The idea is to block users who are trying to perform a DOS Attack on your site. You may find this based on the number of requests your servers have received from the particular user in a unit of time. Like above, there may be an automated way to process logs after sometime and flush data.Since the endpoint /logDOSAttemptByUser might be visible to the external world, it has the possibility of getting exploited. An attacker could modify the userName parameter of the request like below,https://www.testsite.com/logDOSAttemptByUser?userName=user2
and the system could block an credible user (user2) who haven’t tried any DOS Attempt on your site, but since the logs have been injected, the system will block the user.Even if the logs are processed manually, it will be very cumbersome to differntiate valid logs from the injected ones and may be impossible at some cases. Log details being untrustworthy will result in serious problems.It is also possible to confuse the administrator with modified log messages like below.,https://www.testsite.com/logUsageLimitReached?msg=UsageReached
This could be modified as,https://www.testsite.com/logUsageLimitReached?msg=UsageReached+"\n INFO : Looks like problem with our calculation"
and logs would be generated as,INFO : UsageReached
INFO : Looks like problem with our calculation.
SolutionsInstead of directly passing messages via parameters, log codes could be passed. However it is still exploitable.Don’t use API Calls to log actions, as there API’s will be visible in browser network calls.In case of a need, pass user ids or publicly non identifiable values as parameters in logging endpoints.Use proper error codes and identifiable error messages.My Personal Notes
arrow_drop_upSave
Crash logs : Information about when the application got crashed, reason behind the crash, affected users etc.,
Error/Exception logs : Details like exception thrown from code, Stacktrace of the thrown exception.
Access logs : Access logs hold information about different end points accessed by a user in the system with time details.
GC logs : Usually stored by Java to keep track of Garbage collection.
Monitoring logs : Its useful when a user tries to do a suspicious activity on your site, you could detect it and send a mail to yourself to get notified or log it for future records.
Apart from these, there are many categories of application logs. These logs are very useful and absolutely necessary to debug application issues, audit and control, application performance monitoring, troubleshooting etc.,
These generated logs might be written to a disk, raised as an alert mail, pushed to a third party storage service or simply written to a set of files based on the criticalness of the generated log data and/or based on the volume of data that is generated.
When not handled properly, even logs could be manipulated in the web application. Let’s say you have an endpoint like below,
https://www.testsite.com/logDOSAttemptByUser?userName=user1
This API will log the user names of users who are trying a DOS Attack in your site.
And in the backend, you have something like,
List suspiciousAccountsLogged = new ArrayList();
suspiciousAccountsLogged = parseUserNamesFromLogs();
if(suspiciousAccountsLogged.size > 0)
{
for(String userName : suspiciousAccountsLogged)
{
doBlockUserForDOSAttempt(userName);
}
}
The idea is to block users who are trying to perform a DOS Attack on your site. You may find this based on the number of requests your servers have received from the particular user in a unit of time. Like above, there may be an automated way to process logs after sometime and flush data.
Since the endpoint /logDOSAttemptByUser might be visible to the external world, it has the possibility of getting exploited. An attacker could modify the userName parameter of the request like below,
https://www.testsite.com/logDOSAttemptByUser?userName=user2
and the system could block an credible user (user2) who haven’t tried any DOS Attempt on your site, but since the logs have been injected, the system will block the user.
Even if the logs are processed manually, it will be very cumbersome to differntiate valid logs from the injected ones and may be impossible at some cases. Log details being untrustworthy will result in serious problems.
It is also possible to confuse the administrator with modified log messages like below.,
https://www.testsite.com/logUsageLimitReached?msg=UsageReached
This could be modified as,
https://www.testsite.com/logUsageLimitReached?msg=UsageReached+"\n INFO : Looks like problem with our calculation"
and logs would be generated as,
INFO : UsageReached
INFO : Looks like problem with our calculation.
Solutions
Instead of directly passing messages via parameters, log codes could be passed. However it is still exploitable.
Don’t use API Calls to log actions, as there API’s will be visible in browser network calls.
In case of a need, pass user ids or publicly non identifiable values as parameters in logging endpoints.
Use proper error codes and identifiable error messages.
harshmaster07705
Information-Security
Technical Scripter 2018
vulnerability
Articles
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 304,
"s": 28,
"text": "Log Injection is a very simple to carry out attack aimed at web applications. For the attacker its very simple to perform the attack. However, for the target web application or its administrator its very difficult to identify the scope of the attack performed and its impact."
},
{
"code": null,
"e": 409,
"s": 304,
"text": "Web applications or any applications for the case, store huge amount of logs in the backend. They may be"
},
{
"code": null,
"e": 3760,
"s": 409,
"text": "Crash logs : Information about when the application got crashed, reason behind the crash, affected users etc.,Error/Exception logs : Details like exception thrown from code, Stacktrace of the thrown exception.Access logs : Access logs hold information about different end points accessed by a user in the system with time details.GC logs : Usually stored by Java to keep track of Garbage collection.Monitoring logs : Its useful when a user tries to do a suspicious activity on your site, you could detect it and send a mail to yourself to get notified or log it for future records.Apart from these, there are many categories of application logs. These logs are very useful and absolutely necessary to debug application issues, audit and control, application performance monitoring, troubleshooting etc.,These generated logs might be written to a disk, raised as an alert mail, pushed to a third party storage service or simply written to a set of files based on the criticalness of the generated log data and/or based on the volume of data that is generated.When not handled properly, even logs could be manipulated in the web application. Let’s say you have an endpoint like below,https://www.testsite.com/logDOSAttemptByUser?userName=user1\nThis API will log the user names of users who are trying a DOS Attack in your site.And in the backend, you have something like,List suspiciousAccountsLogged = new ArrayList();\nsuspiciousAccountsLogged = parseUserNamesFromLogs();\nif(suspiciousAccountsLogged.size > 0)\n{\n for(String userName : suspiciousAccountsLogged)\n {\n doBlockUserForDOSAttempt(userName);\n }\n}\nThe idea is to block users who are trying to perform a DOS Attack on your site. You may find this based on the number of requests your servers have received from the particular user in a unit of time. Like above, there may be an automated way to process logs after sometime and flush data.Since the endpoint /logDOSAttemptByUser might be visible to the external world, it has the possibility of getting exploited. An attacker could modify the userName parameter of the request like below,https://www.testsite.com/logDOSAttemptByUser?userName=user2\nand the system could block an credible user (user2) who haven’t tried any DOS Attempt on your site, but since the logs have been injected, the system will block the user.Even if the logs are processed manually, it will be very cumbersome to differntiate valid logs from the injected ones and may be impossible at some cases. Log details being untrustworthy will result in serious problems.It is also possible to confuse the administrator with modified log messages like below.,https://www.testsite.com/logUsageLimitReached?msg=UsageReached\nThis could be modified as,https://www.testsite.com/logUsageLimitReached?msg=UsageReached+\"\\n INFO : Looks like problem with our calculation\"\nand logs would be generated as,INFO : UsageReached\nINFO : Looks like problem with our calculation.\nSolutionsInstead of directly passing messages via parameters, log codes could be passed. However it is still exploitable.Don’t use API Calls to log actions, as there API’s will be visible in browser network calls.In case of a need, pass user ids or publicly non identifiable values as parameters in logging endpoints.Use proper error codes and identifiable error messages.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 3871,
"s": 3760,
"text": "Crash logs : Information about when the application got crashed, reason behind the crash, affected users etc.,"
},
{
"code": null,
"e": 3971,
"s": 3871,
"text": "Error/Exception logs : Details like exception thrown from code, Stacktrace of the thrown exception."
},
{
"code": null,
"e": 4093,
"s": 3971,
"text": "Access logs : Access logs hold information about different end points accessed by a user in the system with time details."
},
{
"code": null,
"e": 4163,
"s": 4093,
"text": "GC logs : Usually stored by Java to keep track of Garbage collection."
},
{
"code": null,
"e": 4346,
"s": 4163,
"text": "Monitoring logs : Its useful when a user tries to do a suspicious activity on your site, you could detect it and send a mail to yourself to get notified or log it for future records."
},
{
"code": null,
"e": 4569,
"s": 4346,
"text": "Apart from these, there are many categories of application logs. These logs are very useful and absolutely necessary to debug application issues, audit and control, application performance monitoring, troubleshooting etc.,"
},
{
"code": null,
"e": 4825,
"s": 4569,
"text": "These generated logs might be written to a disk, raised as an alert mail, pushed to a third party storage service or simply written to a set of files based on the criticalness of the generated log data and/or based on the volume of data that is generated."
},
{
"code": null,
"e": 4950,
"s": 4825,
"text": "When not handled properly, even logs could be manipulated in the web application. Let’s say you have an endpoint like below,"
},
{
"code": null,
"e": 5011,
"s": 4950,
"text": "https://www.testsite.com/logDOSAttemptByUser?userName=user1\n"
},
{
"code": null,
"e": 5095,
"s": 5011,
"text": "This API will log the user names of users who are trying a DOS Attack in your site."
},
{
"code": null,
"e": 5140,
"s": 5095,
"text": "And in the backend, you have something like,"
},
{
"code": null,
"e": 5387,
"s": 5140,
"text": "List suspiciousAccountsLogged = new ArrayList();\nsuspiciousAccountsLogged = parseUserNamesFromLogs();\nif(suspiciousAccountsLogged.size > 0)\n{\n for(String userName : suspiciousAccountsLogged)\n {\n doBlockUserForDOSAttempt(userName);\n }\n}\n"
},
{
"code": null,
"e": 5677,
"s": 5387,
"text": "The idea is to block users who are trying to perform a DOS Attack on your site. You may find this based on the number of requests your servers have received from the particular user in a unit of time. Like above, there may be an automated way to process logs after sometime and flush data."
},
{
"code": null,
"e": 5877,
"s": 5677,
"text": "Since the endpoint /logDOSAttemptByUser might be visible to the external world, it has the possibility of getting exploited. An attacker could modify the userName parameter of the request like below,"
},
{
"code": null,
"e": 5938,
"s": 5877,
"text": "https://www.testsite.com/logDOSAttemptByUser?userName=user2\n"
},
{
"code": null,
"e": 6109,
"s": 5938,
"text": "and the system could block an credible user (user2) who haven’t tried any DOS Attempt on your site, but since the logs have been injected, the system will block the user."
},
{
"code": null,
"e": 6329,
"s": 6109,
"text": "Even if the logs are processed manually, it will be very cumbersome to differntiate valid logs from the injected ones and may be impossible at some cases. Log details being untrustworthy will result in serious problems."
},
{
"code": null,
"e": 6418,
"s": 6329,
"text": "It is also possible to confuse the administrator with modified log messages like below.,"
},
{
"code": null,
"e": 6482,
"s": 6418,
"text": "https://www.testsite.com/logUsageLimitReached?msg=UsageReached\n"
},
{
"code": null,
"e": 6509,
"s": 6482,
"text": "This could be modified as,"
},
{
"code": null,
"e": 6625,
"s": 6509,
"text": "https://www.testsite.com/logUsageLimitReached?msg=UsageReached+\"\\n INFO : Looks like problem with our calculation\"\n"
},
{
"code": null,
"e": 6657,
"s": 6625,
"text": "and logs would be generated as,"
},
{
"code": null,
"e": 6726,
"s": 6657,
"text": "INFO : UsageReached\nINFO : Looks like problem with our calculation.\n"
},
{
"code": null,
"e": 6736,
"s": 6726,
"text": "Solutions"
},
{
"code": null,
"e": 6849,
"s": 6736,
"text": "Instead of directly passing messages via parameters, log codes could be passed. However it is still exploitable."
},
{
"code": null,
"e": 6942,
"s": 6849,
"text": "Don’t use API Calls to log actions, as there API’s will be visible in browser network calls."
},
{
"code": null,
"e": 7047,
"s": 6942,
"text": "In case of a need, pass user ids or publicly non identifiable values as parameters in logging endpoints."
},
{
"code": null,
"e": 7103,
"s": 7047,
"text": "Use proper error codes and identifiable error messages."
},
{
"code": null,
"e": 7120,
"s": 7103,
"text": "harshmaster07705"
},
{
"code": null,
"e": 7141,
"s": 7120,
"text": "Information-Security"
},
{
"code": null,
"e": 7165,
"s": 7141,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 7179,
"s": 7165,
"text": "vulnerability"
},
{
"code": null,
"e": 7188,
"s": 7179,
"text": "Articles"
},
{
"code": null,
"e": 7207,
"s": 7188,
"text": "Technical Scripter"
}
] |
Types of Server Virtualization in Computer Network | 17 Mar, 2022
Server Virtualization is the partitioning of a physical server into a number of small virtual servers, each running its own operating system. These operating systems are known as guest operating systems. These are running on another operating system known as the host operating system. Each guest running in this manner is unaware of any other guests running on the same host. Different virtualization techniques are employed to achieve this transparency.
Types of Server virtualization :
1. Hypervisor –
A Hypervisor or VMM(virtual machine monitor) is a layer that exists between the operating system and hardware. It provides the necessary services and features for the smooth running of multiple operating systems.
It identifies traps, responds to privileged CPU instructions, and handles queuing, dispatching, and returning the hardware requests. A host operating system also runs on top of the hypervisor to administer and manage the virtual machines.
2. Para Virtualization –
It is based on Hypervisor. Much of the emulation and trapping overhead in software implemented virtualization is handled in this model. The guest operating system is modified and recompiled before installation into the virtual machine. Due to the modification in the Guest operating system, performance is enhanced as the modified guest operating system communicates directly with the hypervisor and emulation overhead is removed.
Example: Xen primarily uses Paravirtualization, where a customized Linux environment is used to support the administrative environment known as domain 0.
Advantages:
Easier
Enhanced Performance
No emulation overhead
Limitations:
Requires modification to a guest operating system
3. Full Virtualization –
It is very much similar to Paravirtualization. It can emulate the underlying hardware when necessary. The hypervisor traps the machine operations used by the operating system to perform I/O or modify the system status. After trapping, these operations are emulated in software and the status codes are returned very much consistent with what the real hardware would deliver. This is why an unmodified operating system is able to run on top of the hypervisor.
Example: VMWare ESX server uses this method. A customized Linux version known as Service Console is used as the administrative operating system. It is not as fast as Paravirtualization.
Advantages:
No modification to the Guest operating system is required.
Limitations:
Complex
Slower due to emulation
Installation of the new device driver is difficult.
4. Hardware-Assisted Virtualization –
It is similar to Full Virtualization and Paravirtualization in terms of operation except that it requires hardware support. Much of the hypervisor overhead due to trapping and emulating I/O operations and status instructions executed within a guest OS is dealt with by relying on the hardware extensions of the x86 architecture.
Unmodified OS can be run as the hardware support for virtualization would be used to handle hardware access requests, privileged and protected operations, and to communicate with the virtual machine.
Examples: AMD – V Pacifica and Intel VT Vanderpool provide hardware support for virtualization.
Advantages:
No modification to a guest operating system is required.
Very less hypervisor overhead
Limitations:
Hardware support Required
5. Kernel level Virtualization –
Instead of using a hypervisor, it runs a separate version of the Linux kernel and sees the associated virtual machine as a user-space process on the physical host. This makes it easy to run multiple virtual machines on a single host. A device driver is used for communication between the main Linux kernel and the virtual machine. Processor support is required for virtualization ( Intel VT or AMD – v). A slightly modified QEMU process is used as the display and execution containers for the virtual machines. In many ways, kernel-level virtualization is a specialized form of server virtualization.
Examples: User – Mode Linux( UML ) and Kernel Virtual Machine( KVM )
Advantages:
No special administrative software is required.
Very less overhead
Limitations:
Hardware Support Required
6. System Level or OS Virtualization –
Runs multiple but logically distinct environments on a single instance of the operating system kernel. Also called shared kernel approach as all virtual machines share a common kernel of host operating system. Based on the change root concept “chroot”. chroot starts during bootup. The kernel uses root filesystems to load drivers and perform other early-stage system initialization tasks. It then switches to another root filesystem using chroot command to mount an on-disk file system as its final root filesystem and continue system initialization and configuration within that file system. The chroot mechanism of system-level virtualization is an extension of this concept. It enables the system to start virtual servers with their own set of processes that execute relative to their own filesystem root directories. The main difference between system-level and server virtualization is whether different operating systems can be run on different virtual systems. If all virtual servers must share the same copy of the operating system it is system-level virtualization and if different servers can have different operating systems ( including different versions of a single operating system) it is server virtualization.
Examples: FreeVPS, Linux Vserver, and OpenVZ are some examples.
Advantages:
Significantly lightweight than complete machines(including a kernel)
Can host many more virtual servers
Enhanced Security and isolation
Virtualizing an operating system usually has little to no overhead.
Live migration is possible with OS Virtualization.
It can also leverage dynamic container load balancing between nodes and clusters.
On OS virtualization, the file-level copy-on-write (CoW) method is possible, making it easier to back up data, more space-efficient, and easier to cache than block-level copy-on-write schemes.
Limitations:
Kernel or driver problems can take down all virtual servers.
Reference: Types of Server Virtualization
anikakapoor
vaibhavsinghtanwar
singghakshay
akashmomale19
Articles
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 511,
"s": 54,
"text": "Server Virtualization is the partitioning of a physical server into a number of small virtual servers, each running its own operating system. These operating systems are known as guest operating systems. These are running on another operating system known as the host operating system. Each guest running in this manner is unaware of any other guests running on the same host. Different virtualization techniques are employed to achieve this transparency. "
},
{
"code": null,
"e": 545,
"s": 511,
"text": "Types of Server virtualization : "
},
{
"code": null,
"e": 562,
"s": 545,
"text": "1. Hypervisor – "
},
{
"code": null,
"e": 776,
"s": 562,
"text": "A Hypervisor or VMM(virtual machine monitor) is a layer that exists between the operating system and hardware. It provides the necessary services and features for the smooth running of multiple operating systems. "
},
{
"code": null,
"e": 1015,
"s": 776,
"text": "It identifies traps, responds to privileged CPU instructions, and handles queuing, dispatching, and returning the hardware requests. A host operating system also runs on top of the hypervisor to administer and manage the virtual machines."
},
{
"code": null,
"e": 1041,
"s": 1015,
"text": "2. Para Virtualization – "
},
{
"code": null,
"e": 1473,
"s": 1041,
"text": "It is based on Hypervisor. Much of the emulation and trapping overhead in software implemented virtualization is handled in this model. The guest operating system is modified and recompiled before installation into the virtual machine. Due to the modification in the Guest operating system, performance is enhanced as the modified guest operating system communicates directly with the hypervisor and emulation overhead is removed. "
},
{
"code": null,
"e": 1628,
"s": 1473,
"text": "Example: Xen primarily uses Paravirtualization, where a customized Linux environment is used to support the administrative environment known as domain 0. "
},
{
"code": null,
"e": 1641,
"s": 1628,
"text": "Advantages: "
},
{
"code": null,
"e": 1648,
"s": 1641,
"text": "Easier"
},
{
"code": null,
"e": 1669,
"s": 1648,
"text": "Enhanced Performance"
},
{
"code": null,
"e": 1691,
"s": 1669,
"text": "No emulation overhead"
},
{
"code": null,
"e": 1704,
"s": 1691,
"text": "Limitations:"
},
{
"code": null,
"e": 1754,
"s": 1704,
"text": "Requires modification to a guest operating system"
},
{
"code": null,
"e": 1780,
"s": 1754,
"text": "3. Full Virtualization – "
},
{
"code": null,
"e": 2240,
"s": 1780,
"text": "It is very much similar to Paravirtualization. It can emulate the underlying hardware when necessary. The hypervisor traps the machine operations used by the operating system to perform I/O or modify the system status. After trapping, these operations are emulated in software and the status codes are returned very much consistent with what the real hardware would deliver. This is why an unmodified operating system is able to run on top of the hypervisor. "
},
{
"code": null,
"e": 2428,
"s": 2240,
"text": "Example: VMWare ESX server uses this method. A customized Linux version known as Service Console is used as the administrative operating system. It is not as fast as Paravirtualization. "
},
{
"code": null,
"e": 2441,
"s": 2428,
"text": "Advantages: "
},
{
"code": null,
"e": 2500,
"s": 2441,
"text": "No modification to the Guest operating system is required."
},
{
"code": null,
"e": 2513,
"s": 2500,
"text": "Limitations:"
},
{
"code": null,
"e": 2521,
"s": 2513,
"text": "Complex"
},
{
"code": null,
"e": 2545,
"s": 2521,
"text": "Slower due to emulation"
},
{
"code": null,
"e": 2597,
"s": 2545,
"text": "Installation of the new device driver is difficult."
},
{
"code": null,
"e": 2636,
"s": 2597,
"text": "4. Hardware-Assisted Virtualization – "
},
{
"code": null,
"e": 2966,
"s": 2636,
"text": "It is similar to Full Virtualization and Paravirtualization in terms of operation except that it requires hardware support. Much of the hypervisor overhead due to trapping and emulating I/O operations and status instructions executed within a guest OS is dealt with by relying on the hardware extensions of the x86 architecture. "
},
{
"code": null,
"e": 3167,
"s": 2966,
"text": "Unmodified OS can be run as the hardware support for virtualization would be used to handle hardware access requests, privileged and protected operations, and to communicate with the virtual machine. "
},
{
"code": null,
"e": 3264,
"s": 3167,
"text": "Examples: AMD – V Pacifica and Intel VT Vanderpool provide hardware support for virtualization. "
},
{
"code": null,
"e": 3277,
"s": 3264,
"text": "Advantages: "
},
{
"code": null,
"e": 3334,
"s": 3277,
"text": "No modification to a guest operating system is required."
},
{
"code": null,
"e": 3364,
"s": 3334,
"text": "Very less hypervisor overhead"
},
{
"code": null,
"e": 3377,
"s": 3364,
"text": "Limitations:"
},
{
"code": null,
"e": 3403,
"s": 3377,
"text": "Hardware support Required"
},
{
"code": null,
"e": 3437,
"s": 3403,
"text": "5. Kernel level Virtualization – "
},
{
"code": null,
"e": 4039,
"s": 3437,
"text": "Instead of using a hypervisor, it runs a separate version of the Linux kernel and sees the associated virtual machine as a user-space process on the physical host. This makes it easy to run multiple virtual machines on a single host. A device driver is used for communication between the main Linux kernel and the virtual machine. Processor support is required for virtualization ( Intel VT or AMD – v). A slightly modified QEMU process is used as the display and execution containers for the virtual machines. In many ways, kernel-level virtualization is a specialized form of server virtualization. "
},
{
"code": null,
"e": 4109,
"s": 4039,
"text": "Examples: User – Mode Linux( UML ) and Kernel Virtual Machine( KVM ) "
},
{
"code": null,
"e": 4122,
"s": 4109,
"text": "Advantages: "
},
{
"code": null,
"e": 4170,
"s": 4122,
"text": "No special administrative software is required."
},
{
"code": null,
"e": 4189,
"s": 4170,
"text": "Very less overhead"
},
{
"code": null,
"e": 4202,
"s": 4189,
"text": "Limitations:"
},
{
"code": null,
"e": 4228,
"s": 4202,
"text": "Hardware Support Required"
},
{
"code": null,
"e": 4268,
"s": 4228,
"text": "6. System Level or OS Virtualization – "
},
{
"code": null,
"e": 5496,
"s": 4268,
"text": "Runs multiple but logically distinct environments on a single instance of the operating system kernel. Also called shared kernel approach as all virtual machines share a common kernel of host operating system. Based on the change root concept “chroot”. chroot starts during bootup. The kernel uses root filesystems to load drivers and perform other early-stage system initialization tasks. It then switches to another root filesystem using chroot command to mount an on-disk file system as its final root filesystem and continue system initialization and configuration within that file system. The chroot mechanism of system-level virtualization is an extension of this concept. It enables the system to start virtual servers with their own set of processes that execute relative to their own filesystem root directories. The main difference between system-level and server virtualization is whether different operating systems can be run on different virtual systems. If all virtual servers must share the same copy of the operating system it is system-level virtualization and if different servers can have different operating systems ( including different versions of a single operating system) it is server virtualization. "
},
{
"code": null,
"e": 5561,
"s": 5496,
"text": "Examples: FreeVPS, Linux Vserver, and OpenVZ are some examples. "
},
{
"code": null,
"e": 5574,
"s": 5561,
"text": "Advantages: "
},
{
"code": null,
"e": 5643,
"s": 5574,
"text": "Significantly lightweight than complete machines(including a kernel)"
},
{
"code": null,
"e": 5678,
"s": 5643,
"text": "Can host many more virtual servers"
},
{
"code": null,
"e": 5710,
"s": 5678,
"text": "Enhanced Security and isolation"
},
{
"code": null,
"e": 5778,
"s": 5710,
"text": "Virtualizing an operating system usually has little to no overhead."
},
{
"code": null,
"e": 5829,
"s": 5778,
"text": "Live migration is possible with OS Virtualization."
},
{
"code": null,
"e": 5911,
"s": 5829,
"text": "It can also leverage dynamic container load balancing between nodes and clusters."
},
{
"code": null,
"e": 6104,
"s": 5911,
"text": "On OS virtualization, the file-level copy-on-write (CoW) method is possible, making it easier to back up data, more space-efficient, and easier to cache than block-level copy-on-write schemes."
},
{
"code": null,
"e": 6117,
"s": 6104,
"text": "Limitations:"
},
{
"code": null,
"e": 6178,
"s": 6117,
"text": "Kernel or driver problems can take down all virtual servers."
},
{
"code": null,
"e": 6221,
"s": 6178,
"text": "Reference: Types of Server Virtualization "
},
{
"code": null,
"e": 6235,
"s": 6223,
"text": "anikakapoor"
},
{
"code": null,
"e": 6254,
"s": 6235,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 6267,
"s": 6254,
"text": "singghakshay"
},
{
"code": null,
"e": 6281,
"s": 6267,
"text": "akashmomale19"
},
{
"code": null,
"e": 6290,
"s": 6281,
"text": "Articles"
},
{
"code": null,
"e": 6308,
"s": 6290,
"text": "Computer Networks"
},
{
"code": null,
"e": 6326,
"s": 6308,
"text": "Computer Networks"
}
] |
GATE | GATE-CS-2017 (Set 1) | Question 34 | 01 Oct, 2021
Consider the following context-free grammar over the alphabet ∑ = {a, b, c} with S as the start symbol:
S → abScT | abcT
T → bT | b
Which of the following represents the language generated by the above grammar?(A) {(ab)n(cb)n | n >= 1 }(B) {(abncbm1cbm2...cbmn | n, m1, m2, ....., mn >= 1 }(C) {(ab)n(cbm)n | n >= 1 }(D) {(ab)n(cbn)m | m, n >= 1 }Answer: (B)Explanation: Let’s generate a string from given grammar :
S → abScT→ ab abScT cT→ abab abcT cTcT→ abababc bT cTcT→ abababcb bT cTcT→ abababcbb bT cTcT→ abababcbbbb cTcT→ abababcbbbbc b cT→ abababcbbbbcbc bT→ abababcbbbbcbcbb
This string can rule out all wrong options. Now let’s try to analyse this string.
→ abababcbbbbcbcbb
→ {(abncbm1cbm2...cbmn | n, m1, m2, ....., mn >= 1 }
We can clearly rule out option (A), (C) and (D) with help of the string generated by given grammar.
Only option (B) is correct.
GATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATEWatch 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:0047:05 / 1:02:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zAzS1PzU0NQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 1996 | Question 63
GATE | Gate IT 2005 | Question 52
GATE | GATE CS 2012 | Question 18
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "Consider the following context-free grammar over the alphabet ∑ = {a, b, c} with S as the start symbol:"
},
{
"code": null,
"e": 161,
"s": 132,
"text": "S → abScT | abcT\nT → bT | b\n"
},
{
"code": null,
"e": 445,
"s": 161,
"text": "Which of the following represents the language generated by the above grammar?(A) {(ab)n(cb)n | n >= 1 }(B) {(abncbm1cbm2...cbmn | n, m1, m2, ....., mn >= 1 }(C) {(ab)n(cbm)n | n >= 1 }(D) {(ab)n(cbn)m | m, n >= 1 }Answer: (B)Explanation: Let’s generate a string from given grammar :"
},
{
"code": null,
"e": 612,
"s": 445,
"text": "S → abScT→ ab abScT cT→ abab abcT cTcT→ abababc bT cTcT→ abababcb bT cTcT→ abababcbb bT cTcT→ abababcbbbb cTcT→ abababcbbbbc b cT→ abababcbbbbcbc bT→ abababcbbbbcbcbb"
},
{
"code": null,
"e": 694,
"s": 612,
"text": "This string can rule out all wrong options. Now let’s try to analyse this string."
},
{
"code": null,
"e": 713,
"s": 694,
"text": "→ abababcbbbbcbcbb"
},
{
"code": null,
"e": 766,
"s": 713,
"text": "→ {(abncbm1cbm2...cbmn | n, m1, m2, ....., mn >= 1 }"
},
{
"code": null,
"e": 866,
"s": 766,
"text": "We can clearly rule out option (A), (C) and (D) with help of the string generated by given grammar."
},
{
"code": null,
"e": 894,
"s": 866,
"text": "Only option (B) is correct."
},
{
"code": null,
"e": 1858,
"s": 894,
"text": "GATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATEWatch 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:0047:05 / 1:02:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=zAzS1PzU0NQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 1879,
"s": 1858,
"text": "GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 1905,
"s": 1879,
"text": "GATE-GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 1910,
"s": 1905,
"text": "GATE"
},
{
"code": null,
"e": 2008,
"s": 1910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2112,
"s": 2050,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2154,
"s": 2112,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 2196,
"s": 2154,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 2230,
"s": 2196,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 2264,
"s": 2230,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 2298,
"s": 2264,
"text": "GATE | Gate IT 2005 | Question 52"
},
{
"code": null,
"e": 2332,
"s": 2298,
"text": "GATE | GATE CS 2012 | Question 18"
},
{
"code": null,
"e": 2366,
"s": 2332,
"text": "GATE | GATE CS 2008 | Question 40"
}
] |
Convert CSV to Excel using Pandas in Python | 22 Feb, 2022
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax:
final = pd.ExcelWriter('GFG.xlsx')
Example:Sample CSV File:
Python3
import pandas as pd # Reading the csv filedf_new = pd.read_csv('Names.csv') # saving xlsx fileGFG = pd.ExcelWriter('Names.xlsx')df_new.to_excel(GFG, index=False) GFG.save()
Output:
The read_* functions are used to read data to pandas, the to_* methods are used to store data. The to_excel() method stores the data as an excel file. In the example here, the sheet_name is named passengers instead of the default Sheet1. By setting index=False the row index labels are not saved in the spreadsheet.
Python3
import pandas as pd # The read_csv is reading the csv file into Dataframe df = pd.read_csv("./weather_data.csv") # then to_excel method converting the .csv file to .xlsx file. df.to_excel("weather.xlsx", sheet_name="Testing", index=False) # This will make a new "weather.xlsx" file in your working directory.# This code is contributed by Vidit Varshney
viditvarshney
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 356,
"s": 52,
"text": "Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: "
},
{
"code": null,
"e": 391,
"s": 356,
"text": "final = pd.ExcelWriter('GFG.xlsx')"
},
{
"code": null,
"e": 417,
"s": 391,
"text": "Example:Sample CSV File: "
},
{
"code": null,
"e": 427,
"s": 419,
"text": "Python3"
},
{
"code": "import pandas as pd # Reading the csv filedf_new = pd.read_csv('Names.csv') # saving xlsx fileGFG = pd.ExcelWriter('Names.xlsx')df_new.to_excel(GFG, index=False) GFG.save()",
"e": 601,
"s": 427,
"text": null
},
{
"code": null,
"e": 610,
"s": 601,
"text": "Output: "
},
{
"code": null,
"e": 926,
"s": 610,
"text": "The read_* functions are used to read data to pandas, the to_* methods are used to store data. The to_excel() method stores the data as an excel file. In the example here, the sheet_name is named passengers instead of the default Sheet1. By setting index=False the row index labels are not saved in the spreadsheet."
},
{
"code": null,
"e": 934,
"s": 926,
"text": "Python3"
},
{
"code": "import pandas as pd # The read_csv is reading the csv file into Dataframe df = pd.read_csv(\"./weather_data.csv\") # then to_excel method converting the .csv file to .xlsx file. df.to_excel(\"weather.xlsx\", sheet_name=\"Testing\", index=False) # This will make a new \"weather.xlsx\" file in your working directory.# This code is contributed by Vidit Varshney",
"e": 1287,
"s": 934,
"text": null
},
{
"code": null,
"e": 1301,
"s": 1287,
"text": "viditvarshney"
},
{
"code": null,
"e": 1308,
"s": 1301,
"text": "Picked"
},
{
"code": null,
"e": 1322,
"s": 1308,
"text": "Python-pandas"
},
{
"code": null,
"e": 1329,
"s": 1322,
"text": "Python"
}
] |
Python – Itertools.takewhile() | 19 Feb, 2020
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile().
Note: For more information, refer to Python Itertools
This allows considering an item from the iterable until the specified predicate becomes false for the first time. The iterable is a list or string in most of the cases. As the name suggests it “take” the element from the sequence “while” the predicate is “true”. This function come under the category “terminating iterators”. The output cannot be used directly and has to be converted to another iterable form. Mostly they are converted into lists.
Syntax:
takewhile(predicate, iterable)
The predicate is either a built-in function or a user-defined function. It can be even lambda functions.
The general implementation of this function using simple if-else is given below.
def takewhile(predicate, iterable):
for i in iterable:
if predicate(i):
return(i)
else:
break
The function takewhile() takes a predicate and an iterable as arguments. The iterable is iterated to check each of its elements. If the elements on the specified predicate, evaluates to true, it is returned. Otherwise, the loop is terminated.
Example 1: Lists and takewhile()Consider a list of integers. We need only the even numbers in the output. Look at the code below to see what happens if we use takewhile().
from itertools import takewhile # function to check whether # number is evendef even_nos(x): return(x % 2 == 0) # iterable (list)li =[0, 2, 4, 8, 22, 34, 6, 67] # output listnew_li = list(takewhile(even_nos, li)) print(new_li)
[0, 2, 4, 8, 22, 34, 6]
Example 2: Strings and takewhile()Consider an alpha-numerical String. Now we need to take the elements as long as they are digits.
from itertools import takewhile # function to test the elementsdef test_func(x): print("Testing:", x) return(x.isdigit()) # using takewhile with for-loopfor i in takewhile(test_func, "11234erdg456"): print("Output :", i) print()
Output:
Testing: 1
Output : 1
Testing: 1
Output : 1
Testing: 2
Output : 2
Testing: 3
Output : 3
Testing: 4
Output : 4
Testing: e
The iterable can be directly passed also. It is not mandatory that they should be assigned to some variable before passing them to takewhile() function.
Example 3: lambda functions in takewhile()Consider the elements of the input String until a ‘s’ is encountered.
from itertools import takewhile # input stringst ="GeeksforGeeks" # consider elements until # 's' is encounteredli = list(takewhile(lambda x:x !='s', st)) print(li)
Output:
['G', 'e', 'e', 'k']
Example 4:Make a list of alphabets in random order and consider the elements until you encounter ‘e’ or ‘i’ or ‘u’.
import randomfrom itertools import takewhile # generating alphabets in random orderli = random.sample(range(97, 123), 26)li = list(map(chr, li)) print("The original list list is :")print(li) # consider the element until# 'e' or 'i' or 'o' is encounterednew_li = list(takewhile(lambda x:x not in ['e', 'i', 'o'], li)) print("\nThe new list is :")print(new_li)
The original list list is :[‘v’, ‘u’, ‘k’, ‘j’, ‘r’, ‘q’, ‘n’, ‘y’, ‘a’, ‘x’, ‘i’, ‘p’, ‘e’, ‘w’, ‘b’, ‘t’, ‘s’, ‘l’, ‘z’, ‘m’, ‘f’, ‘c’, ‘g’, ‘d’, ‘o’, ‘h’]
The new list is :[‘v’, ‘u’, ‘k’, ‘j’, ‘r’, ‘q’, ‘n’, ‘y’, ‘a’, ‘x’]
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 255,
"s": 28,
"text": "The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile()."
},
{
"code": null,
"e": 309,
"s": 255,
"text": "Note: For more information, refer to Python Itertools"
},
{
"code": null,
"e": 758,
"s": 309,
"text": "This allows considering an item from the iterable until the specified predicate becomes false for the first time. The iterable is a list or string in most of the cases. As the name suggests it “take” the element from the sequence “while” the predicate is “true”. This function come under the category “terminating iterators”. The output cannot be used directly and has to be converted to another iterable form. Mostly they are converted into lists."
},
{
"code": null,
"e": 766,
"s": 758,
"text": "Syntax:"
},
{
"code": null,
"e": 797,
"s": 766,
"text": "takewhile(predicate, iterable)"
},
{
"code": null,
"e": 902,
"s": 797,
"text": "The predicate is either a built-in function or a user-defined function. It can be even lambda functions."
},
{
"code": null,
"e": 983,
"s": 902,
"text": "The general implementation of this function using simple if-else is given below."
},
{
"code": null,
"e": 1118,
"s": 983,
"text": "def takewhile(predicate, iterable):\n for i in iterable:\n if predicate(i):\n return(i)\n else:\n break"
},
{
"code": null,
"e": 1361,
"s": 1118,
"text": "The function takewhile() takes a predicate and an iterable as arguments. The iterable is iterated to check each of its elements. If the elements on the specified predicate, evaluates to true, it is returned. Otherwise, the loop is terminated."
},
{
"code": null,
"e": 1533,
"s": 1361,
"text": "Example 1: Lists and takewhile()Consider a list of integers. We need only the even numbers in the output. Look at the code below to see what happens if we use takewhile()."
},
{
"code": "from itertools import takewhile # function to check whether # number is evendef even_nos(x): return(x % 2 == 0) # iterable (list)li =[0, 2, 4, 8, 22, 34, 6, 67] # output listnew_li = list(takewhile(even_nos, li)) print(new_li)",
"e": 1768,
"s": 1533,
"text": null
},
{
"code": null,
"e": 1793,
"s": 1768,
"text": "[0, 2, 4, 8, 22, 34, 6]\n"
},
{
"code": null,
"e": 1924,
"s": 1793,
"text": "Example 2: Strings and takewhile()Consider an alpha-numerical String. Now we need to take the elements as long as they are digits."
},
{
"code": "from itertools import takewhile # function to test the elementsdef test_func(x): print(\"Testing:\", x) return(x.isdigit()) # using takewhile with for-loopfor i in takewhile(test_func, \"11234erdg456\"): print(\"Output :\", i) print()",
"e": 2180,
"s": 1924,
"text": null
},
{
"code": null,
"e": 2188,
"s": 2180,
"text": "Output:"
},
{
"code": null,
"e": 2315,
"s": 2188,
"text": "Testing: 1\nOutput : 1\n\nTesting: 1\nOutput : 1\n\nTesting: 2\nOutput : 2\n\nTesting: 3\nOutput : 3\n\nTesting: 4\nOutput : 4\n\nTesting: e\n"
},
{
"code": null,
"e": 2468,
"s": 2315,
"text": "The iterable can be directly passed also. It is not mandatory that they should be assigned to some variable before passing them to takewhile() function."
},
{
"code": null,
"e": 2580,
"s": 2468,
"text": "Example 3: lambda functions in takewhile()Consider the elements of the input String until a ‘s’ is encountered."
},
{
"code": "from itertools import takewhile # input stringst =\"GeeksforGeeks\" # consider elements until # 's' is encounteredli = list(takewhile(lambda x:x !='s', st)) print(li)",
"e": 2748,
"s": 2580,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2748,
"text": "Output:"
},
{
"code": null,
"e": 2778,
"s": 2756,
"text": "['G', 'e', 'e', 'k']\n"
},
{
"code": null,
"e": 2894,
"s": 2778,
"text": "Example 4:Make a list of alphabets in random order and consider the elements until you encounter ‘e’ or ‘i’ or ‘u’."
},
{
"code": "import randomfrom itertools import takewhile # generating alphabets in random orderli = random.sample(range(97, 123), 26)li = list(map(chr, li)) print(\"The original list list is :\")print(li) # consider the element until# 'e' or 'i' or 'o' is encounterednew_li = list(takewhile(lambda x:x not in ['e', 'i', 'o'], li)) print(\"\\nThe new list is :\")print(new_li)",
"e": 3280,
"s": 2894,
"text": null
},
{
"code": null,
"e": 3438,
"s": 3280,
"text": "The original list list is :[‘v’, ‘u’, ‘k’, ‘j’, ‘r’, ‘q’, ‘n’, ‘y’, ‘a’, ‘x’, ‘i’, ‘p’, ‘e’, ‘w’, ‘b’, ‘t’, ‘s’, ‘l’, ‘z’, ‘m’, ‘f’, ‘c’, ‘g’, ‘d’, ‘o’, ‘h’]"
},
{
"code": null,
"e": 3506,
"s": 3438,
"text": "The new list is :[‘v’, ‘u’, ‘k’, ‘j’, ‘r’, ‘q’, ‘n’, ‘y’, ‘a’, ‘x’]"
},
{
"code": null,
"e": 3523,
"s": 3506,
"text": "Python-itertools"
},
{
"code": null,
"e": 3530,
"s": 3523,
"text": "Python"
}
] |
Shell Script To Count Number of Words, Characters, White Spaces, and Special Symbols | 20 Apr, 2021
In this article, we are going to see how to count the number of words, characters, whitespace and special symbol in a text file/ input string. Given a text file and tour task is to count the number of words, characters, whitespace and special symbol. So there are many methods and tool that we can use to accomplish our task. For better understanding let’s take an example:
Example:
Input text: GeeksforGeeks are best!
Output :
Number of Words = 3
Number of Characters = 24
Number of White Spaces =2
Number of Special Symbols = 2
Explanation:
words are { "GeeksforGeeks", "are", "best!!"}
Characters include number of white spaces(Space),special symbols and letter.
White Spaces are just spaces {' ',' '}
And Special Symbol are {'!','!'}
Using wc command. wc command is used to know the number of lines, word count, byte and characters count etc.
Count the number of words using wc -w. Here, “-w” indicates that we are counting words.
Count the number of characters using wc -c. Here, “-c” indicates that we are counting each character including white spaces.
Count the number of white spaces in a string using the following syntax:
Syntax: expr length “$text” – length `echo “$text” | sed “s/ //g”`
Sed command is used to manipulate text, it stands for stream editor. Here, we are using sed to find the whites paces using sed “s/replace this with the whitespace//g”. In this syntax sed s refer as substitute and g as globalism and this syntax will search and replace every whitespace in entire text.
Count all the special characters using following regular expression.
Syntax: expr length “${text//[^\~!@#$&*()]/}”
Shell Script:
#! /bin/bash
echo "Enter a String"
# Taking input from user
read text
# Counting words
word=$(echo -n "$text" | wc -w)
# Counting characters
char=$(echo -n "$text" | wc -c)
# Counting Number of white spaces (Here,specificly " ")
# sed "s/ change this to whitespace//g"
space=$(expr length "$text" - length `echo "$text" | sed "s/ //g"`)
# Counting special characters
special=$(expr length "${text//[^\~!@#$&*()]/}")
# Output
echo "Number of Words = $word"
echo "Number of Characters = $char"
echo "Number of White Spaces = $space"
echo "Number of Special symbols = $special"
Output:
Output
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 402,
"s": 28,
"text": "In this article, we are going to see how to count the number of words, characters, whitespace and special symbol in a text file/ input string. Given a text file and tour task is to count the number of words, characters, whitespace and special symbol. So there are many methods and tool that we can use to accomplish our task. For better understanding let’s take an example:"
},
{
"code": null,
"e": 772,
"s": 402,
"text": "Example:\nInput text: GeeksforGeeks are best!\n\nOutput :\nNumber of Words = 3\nNumber of Characters = 24\nNumber of White Spaces =2\nNumber of Special Symbols = 2\n\nExplanation:\nwords are { \"GeeksforGeeks\", \"are\", \"best!!\"}\nCharacters include number of white spaces(Space),special symbols and letter.\nWhite Spaces are just spaces {' ',' '}\nAnd Special Symbol are {'!','!'}"
},
{
"code": null,
"e": 881,
"s": 772,
"text": "Using wc command. wc command is used to know the number of lines, word count, byte and characters count etc."
},
{
"code": null,
"e": 969,
"s": 881,
"text": "Count the number of words using wc -w. Here, “-w” indicates that we are counting words."
},
{
"code": null,
"e": 1094,
"s": 969,
"text": "Count the number of characters using wc -c. Here, “-c” indicates that we are counting each character including white spaces."
},
{
"code": null,
"e": 1167,
"s": 1094,
"text": "Count the number of white spaces in a string using the following syntax:"
},
{
"code": null,
"e": 1234,
"s": 1167,
"text": "Syntax: expr length “$text” – length `echo “$text” | sed “s/ //g”`"
},
{
"code": null,
"e": 1535,
"s": 1234,
"text": "Sed command is used to manipulate text, it stands for stream editor. Here, we are using sed to find the whites paces using sed “s/replace this with the whitespace//g”. In this syntax sed s refer as substitute and g as globalism and this syntax will search and replace every whitespace in entire text."
},
{
"code": null,
"e": 1604,
"s": 1535,
"text": "Count all the special characters using following regular expression."
},
{
"code": null,
"e": 1650,
"s": 1604,
"text": "Syntax: expr length “${text//[^\\~!@#$&*()]/}”"
},
{
"code": null,
"e": 1664,
"s": 1650,
"text": "Shell Script:"
},
{
"code": null,
"e": 2244,
"s": 1664,
"text": "#! /bin/bash\n\necho \"Enter a String\"\n# Taking input from user\nread text\n\n# Counting words\nword=$(echo -n \"$text\" | wc -w)\n# Counting characters\nchar=$(echo -n \"$text\" | wc -c)\n\n# Counting Number of white spaces (Here,specificly \" \")\n# sed \"s/ change this to whitespace//g\"\nspace=$(expr length \"$text\" - length `echo \"$text\" | sed \"s/ //g\"`)\n\n# Counting special characters\nspecial=$(expr length \"${text//[^\\~!@#$&*()]/}\")\n\n# Output\necho \"Number of Words = $word\"\necho \"Number of Characters = $char\"\necho \"Number of White Spaces = $space\"\necho \"Number of Special symbols = $special\""
},
{
"code": null,
"e": 2252,
"s": 2244,
"text": "Output:"
},
{
"code": null,
"e": 2260,
"s": 2252,
"text": "Output "
},
{
"code": null,
"e": 2267,
"s": 2260,
"text": "Picked"
},
{
"code": null,
"e": 2280,
"s": 2267,
"text": "Shell Script"
},
{
"code": null,
"e": 2291,
"s": 2280,
"text": "Linux-Unix"
}
] |
Python – Filter rows with only Alphabets from List of Lists | 02 Dec, 2020
Given Matrix, write a Python program to extract rows which only contains alphabets in its strings.
Examples:
Input : test_list = [[“gfg”, “is”, “best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]] Output : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]] Explanation : All strings with just alphabets are extracted.
Input : test_list = [[“gfg”, “is”, “!best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]] Output : [[‘love’, ‘gfg’]] Explanation : All strings with just alphabets are extracted.
Method #1: Using isalpha() + all() + list comprehension
In this, we check for all the alphabets using isalpha() and all() is used to ensure all the strings contain just the alphabets. The list comprehension is used to iterate through rows.
Python3
# Python3 code to demonstrate working of# Filter rows with only Alphabets# Using isalpha() + all() + list comprehension # initializing listtest_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"], ["Gfg is good"], ["love", "gfg"]] # printing original listsprint("The original list is : " + str(test_list)) # all() checks for all strings to contain alphabetsres = [sub for sub in test_list if all(ele.isalpha() for ele in sub)] # printing resultprint("Filtered Rows : " + str(res))
Output:
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]
Method #2 : Using filter() + lambda + join() + isalpha()
In this, we concatenate each string using join() and test if its all alphabets using isalpha(), and add if the verdict returns true.
Python3
# Python3 code to demonstrate working of# Filter rows with only Alphabets# Using filter() + lambda + join() + isalpha() # initializing listtest_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"], ["Gfg is good"], ["love", "gfg"]] # printing original listsprint("The original list is : " + str(test_list)) # join() used to concatenate stringsres = list(filter(lambda sub: ''.join( [ele for ele in sub]).isalpha(), test_list)) # printing resultprint("Filtered Rows : " + str(res))
Output:
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]
Python list-programs
Python string-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": "\n02 Dec, 2020"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "Given Matrix, write a Python program to extract rows which only contains alphabets in its strings."
},
{
"code": null,
"e": 137,
"s": 127,
"text": "Examples:"
},
{
"code": null,
"e": 352,
"s": 137,
"text": "Input : test_list = [[“gfg”, “is”, “best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]] Output : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]] Explanation : All strings with just alphabets are extracted. "
},
{
"code": null,
"e": 545,
"s": 352,
"text": "Input : test_list = [[“gfg”, “is”, “!best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]] Output : [[‘love’, ‘gfg’]] Explanation : All strings with just alphabets are extracted. "
},
{
"code": null,
"e": 601,
"s": 545,
"text": "Method #1: Using isalpha() + all() + list comprehension"
},
{
"code": null,
"e": 785,
"s": 601,
"text": "In this, we check for all the alphabets using isalpha() and all() is used to ensure all the strings contain just the alphabets. The list comprehension is used to iterate through rows."
},
{
"code": null,
"e": 793,
"s": 785,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Filter rows with only Alphabets# Using isalpha() + all() + list comprehension # initializing listtest_list = [[\"gfg\", \"is\", \"best\"], [\"Geeks4Geeks\", \"good\"], [\"Gfg is good\"], [\"love\", \"gfg\"]] # printing original listsprint(\"The original list is : \" + str(test_list)) # all() checks for all strings to contain alphabetsres = [sub for sub in test_list if all(ele.isalpha() for ele in sub)] # printing resultprint(\"Filtered Rows : \" + str(res))",
"e": 1293,
"s": 793,
"text": null
},
{
"code": null,
"e": 1301,
"s": 1293,
"text": "Output:"
},
{
"code": null,
"e": 1463,
"s": 1301,
"text": "The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]"
},
{
"code": null,
"e": 1520,
"s": 1463,
"text": "Method #2 : Using filter() + lambda + join() + isalpha()"
},
{
"code": null,
"e": 1653,
"s": 1520,
"text": "In this, we concatenate each string using join() and test if its all alphabets using isalpha(), and add if the verdict returns true."
},
{
"code": null,
"e": 1661,
"s": 1653,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Filter rows with only Alphabets# Using filter() + lambda + join() + isalpha() # initializing listtest_list = [[\"gfg\", \"is\", \"best\"], [\"Geeks4Geeks\", \"good\"], [\"Gfg is good\"], [\"love\", \"gfg\"]] # printing original listsprint(\"The original list is : \" + str(test_list)) # join() used to concatenate stringsres = list(filter(lambda sub: ''.join( [ele for ele in sub]).isalpha(), test_list)) # printing resultprint(\"Filtered Rows : \" + str(res))",
"e": 2163,
"s": 1661,
"text": null
},
{
"code": null,
"e": 2171,
"s": 2163,
"text": "Output:"
},
{
"code": null,
"e": 2333,
"s": 2171,
"text": "The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]"
},
{
"code": null,
"e": 2354,
"s": 2333,
"text": "Python list-programs"
},
{
"code": null,
"e": 2377,
"s": 2354,
"text": "Python string-programs"
},
{
"code": null,
"e": 2384,
"s": 2377,
"text": "Python"
},
{
"code": null,
"e": 2400,
"s": 2384,
"text": "Python Programs"
}
] |
Output of Java program | Set 5 | 11 Oct, 2021
Predict the output of following Java Programs.Program 1:
Java
// Main.javapublic class Main{ public static void gfg(String s) { System.out.println("String"); } public static void gfg(Object o) { System.out.println("Object"); } public static void main(String args[]) { gfg(null); }} //end class
Output:
String
Explanation : In case of method overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ is a more specific type than ‘java.lang.Object’. In this case the method which takes ‘String’ as a parameter is chosen. Program 2:
Java
// Main.javapublic class Main{ public static void gfg(String s) { System.out.println("String"); } public static void gfg(Object o) { System.out.println("Object"); } public static void gfg(Integer i) { System.out.println("Integer"); } public static void main(String args[]) { gfg(null); }} //end class
Output:
Compile Error at line 19.
Explanation: In this case of method Overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ and ‘java.lang.Integer’ is a more specific type than ‘java.lang.Object’,but between ‘java.lang.String’ and ‘java.lang.Integer’ none is more specific. In this case the Java is unable to decide which method to call. Program 3:
Java
// Main.javapublic class Main{ public static void main(String args[]) { String s1 = "abc"; String s2 = s1; s1 += "d"; System.out.println(s1 + " " + s2 + " " + (s1 == s2)); StringBuffer sb1 = new StringBuffer("abc"); StringBuffer sb2 = sb1; sb1.append("d"); System.out.println(sb1 + " " + sb2 + " " + (sb1 == sb2)); }} //end class
Output:
abcd abc false
abcd abcd true
Explanation : In Java, String is immutable and string buffer is mutable. So string s2 and s1 both pointing to the same string abc. And, after making the changes the string s1 points to abcd and s2 points to abc, hence false. While in string buffer, both sb1 and sb2 both point to the same object. Since string buffer are mutable, making changes in one string also make changes to the other string. So both string still pointing to the same object after making the changes to the object (here sb2).Program 4:
Java
// Main.javapublic class Main{ public static void main(String args[]) { short s = 0; int x = 07; int y = 08; int z = 112345; s += z; System.out.println("" + x + y + s); }} //end class
Output:
Compile Error at line 8
Explanation: 1. In Line 12 The “” in the println causes the numbers to be automatically cast as strings. So it doesn’t do addition, but appends together as string. 2. In Line11 the += does an automatic cast to a short. However the number 123456 can’t be contained within a short, so you end up with a negative value (-7616). (NOTE – short 2 bytes -32,768 to 32,767), Here the number 123456 doesn’t mean the Value of int z,it shows the length of the int value 3. Those other two are red herrings however as the code will never compile due to line 8. Any number beginning with zero is treated as an octal number (which is 0-7).This article is contributed by Pratik 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.
abyzeb95
sooda367
simmytarika5
Java-Output
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 113,
"s": 54,
"text": "Predict the output of following Java Programs.Program 1: "
},
{
"code": null,
"e": 118,
"s": 113,
"text": "Java"
},
{
"code": "// Main.javapublic class Main{ public static void gfg(String s) { System.out.println(\"String\"); } public static void gfg(Object o) { System.out.println(\"Object\"); } public static void main(String args[]) { gfg(null); }} //end class",
"e": 404,
"s": 118,
"text": null
},
{
"code": null,
"e": 412,
"s": 404,
"text": "Output:"
},
{
"code": null,
"e": 419,
"s": 412,
"text": "String"
},
{
"code": null,
"e": 671,
"s": 419,
"text": "Explanation : In case of method overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ is a more specific type than ‘java.lang.Object’. In this case the method which takes ‘String’ as a parameter is chosen. Program 2: "
},
{
"code": null,
"e": 676,
"s": 671,
"text": "Java"
},
{
"code": "// Main.javapublic class Main{ public static void gfg(String s) { System.out.println(\"String\"); } public static void gfg(Object o) { System.out.println(\"Object\"); } public static void gfg(Integer i) { System.out.println(\"Integer\"); } public static void main(String args[]) { gfg(null); }} //end class",
"e": 1047,
"s": 676,
"text": null
},
{
"code": null,
"e": 1057,
"s": 1047,
"text": "Output: "
},
{
"code": null,
"e": 1083,
"s": 1057,
"text": "Compile Error at line 19."
},
{
"code": null,
"e": 1433,
"s": 1083,
"text": "Explanation: In this case of method Overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ and ‘java.lang.Integer’ is a more specific type than ‘java.lang.Object’,but between ‘java.lang.String’ and ‘java.lang.Integer’ none is more specific. In this case the Java is unable to decide which method to call. Program 3: "
},
{
"code": null,
"e": 1438,
"s": 1433,
"text": "Java"
},
{
"code": "// Main.javapublic class Main{ public static void main(String args[]) { String s1 = \"abc\"; String s2 = s1; s1 += \"d\"; System.out.println(s1 + \" \" + s2 + \" \" + (s1 == s2)); StringBuffer sb1 = new StringBuffer(\"abc\"); StringBuffer sb2 = sb1; sb1.append(\"d\"); System.out.println(sb1 + \" \" + sb2 + \" \" + (sb1 == sb2)); }} //end class",
"e": 1835,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1845,
"s": 1835,
"text": "Output: "
},
{
"code": null,
"e": 1875,
"s": 1845,
"text": "abcd abc false\nabcd abcd true"
},
{
"code": null,
"e": 2385,
"s": 1875,
"text": "Explanation : In Java, String is immutable and string buffer is mutable. So string s2 and s1 both pointing to the same string abc. And, after making the changes the string s1 points to abcd and s2 points to abc, hence false. While in string buffer, both sb1 and sb2 both point to the same object. Since string buffer are mutable, making changes in one string also make changes to the other string. So both string still pointing to the same object after making the changes to the object (here sb2).Program 4: "
},
{
"code": null,
"e": 2390,
"s": 2385,
"text": "Java"
},
{
"code": "// Main.javapublic class Main{ public static void main(String args[]) { short s = 0; int x = 07; int y = 08; int z = 112345; s += z; System.out.println(\"\" + x + y + s); }} //end class",
"e": 2627,
"s": 2390,
"text": null
},
{
"code": null,
"e": 2637,
"s": 2627,
"text": "Output: "
},
{
"code": null,
"e": 2661,
"s": 2637,
"text": "Compile Error at line 8"
},
{
"code": null,
"e": 3709,
"s": 2661,
"text": "Explanation: 1. In Line 12 The “” in the println causes the numbers to be automatically cast as strings. So it doesn’t do addition, but appends together as string. 2. In Line11 the += does an automatic cast to a short. However the number 123456 can’t be contained within a short, so you end up with a negative value (-7616). (NOTE – short 2 bytes -32,768 to 32,767), Here the number 123456 doesn’t mean the Value of int z,it shows the length of the int value 3. Those other two are red herrings however as the code will never compile due to line 8. Any number beginning with zero is treated as an octal number (which is 0-7).This article is contributed by Pratik 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": 3718,
"s": 3709,
"text": "abyzeb95"
},
{
"code": null,
"e": 3727,
"s": 3718,
"text": "sooda367"
},
{
"code": null,
"e": 3740,
"s": 3727,
"text": "simmytarika5"
},
{
"code": null,
"e": 3752,
"s": 3740,
"text": "Java-Output"
},
{
"code": null,
"e": 3757,
"s": 3752,
"text": "Java"
},
{
"code": null,
"e": 3772,
"s": 3757,
"text": "Program Output"
},
{
"code": null,
"e": 3777,
"s": 3772,
"text": "Java"
}
] |
How To Make Density Plot in Python with Altair? | 17 May, 2021
Density plots are a variation of Histograms that are used to observe the distribution of a variable in data set over a continuous interval or a time period. The peaks of a Density Plot indicate where values are concentrated over an interval.
Compared to Histograms, Density Plots are better at determining the distribution shape because they’re not affected by the number of bins.
We can make a density plot in python using the libraries Pandas and Altair.
Altair-It is a statistical visualization library based on Vega and Vega-lite.
Pandas-It is an open-source data analysis and manipulation tool in Python.
Note: We will be using the ‘insurance.csv’ dataset which can be downloaded from Google Drive.
First, let’s import these libraries using-
Python3
import pandas as p # loading pandas libraryimport altair as a # loading altair library
Next, we load the data set on which we need to use the density plot.
Python3
data_set = 'insurance.csv' # dataset named = p.read_csv(data_set) # reading the datasaetd.head() # printing the first 5 data entries
Output:
As you can see, there are seven columns in the dataset. We shall use “charges” to make a density plot. To do, so we must first transform our data into density. This is done by using the transform_density() function. The parameters are the variable of interest and a name to indicate the transformed variable which is written as “as_=[‘Charges’, ‘density’]”. Bringing it together-
Python3
# loading a single column into# the data frame objectd = d[["charges"]] a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'], ).mark_area(color='green').encode( x="CHARGES:Q", y='DENSITY:Q', )
Output:
Output
Complete Script: Here is the code with all the steps at one place-
Python3
import pandas as p # loading pandas libraryimport altair as a # loading altair library # download dataset from https://drive.google.com/drive/folders/1Dddv1l9hpEPVWh_uuK9Iv1A1xUNy55v7?usp=sharing# OR replace name with your own dataset.data_set = 'insurance.csv'd = p.read_csv(data_set)d = d[["charges"]] a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'], ).mark_area(color='green').encode( x="CHARGES:Q", y='DENSITY:Q',)
Output:
Output
sweetyty
Python-Altair
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 270,
"s": 28,
"text": "Density plots are a variation of Histograms that are used to observe the distribution of a variable in data set over a continuous interval or a time period. The peaks of a Density Plot indicate where values are concentrated over an interval."
},
{
"code": null,
"e": 409,
"s": 270,
"text": "Compared to Histograms, Density Plots are better at determining the distribution shape because they’re not affected by the number of bins."
},
{
"code": null,
"e": 485,
"s": 409,
"text": "We can make a density plot in python using the libraries Pandas and Altair."
},
{
"code": null,
"e": 563,
"s": 485,
"text": "Altair-It is a statistical visualization library based on Vega and Vega-lite."
},
{
"code": null,
"e": 638,
"s": 563,
"text": "Pandas-It is an open-source data analysis and manipulation tool in Python."
},
{
"code": null,
"e": 732,
"s": 638,
"text": "Note: We will be using the ‘insurance.csv’ dataset which can be downloaded from Google Drive."
},
{
"code": null,
"e": 775,
"s": 732,
"text": "First, let’s import these libraries using-"
},
{
"code": null,
"e": 783,
"s": 775,
"text": "Python3"
},
{
"code": "import pandas as p # loading pandas libraryimport altair as a # loading altair library",
"e": 872,
"s": 783,
"text": null
},
{
"code": null,
"e": 941,
"s": 872,
"text": "Next, we load the data set on which we need to use the density plot."
},
{
"code": null,
"e": 949,
"s": 941,
"text": "Python3"
},
{
"code": "data_set = 'insurance.csv' # dataset named = p.read_csv(data_set) # reading the datasaetd.head() # printing the first 5 data entries",
"e": 1085,
"s": 949,
"text": null
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "Output:"
},
{
"code": null,
"e": 1473,
"s": 1093,
"text": "As you can see, there are seven columns in the dataset. We shall use “charges” to make a density plot. To do, so we must first transform our data into density. This is done by using the transform_density() function. The parameters are the variable of interest and a name to indicate the transformed variable which is written as “as_=[‘Charges’, ‘density’]”. Bringing it together-"
},
{
"code": null,
"e": 1481,
"s": 1473,
"text": "Python3"
},
{
"code": "# loading a single column into# the data frame objectd = d[[\"charges\"]] a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'], ).mark_area(color='green').encode( x=\"CHARGES:Q\", y='DENSITY:Q', )",
"e": 1722,
"s": 1481,
"text": null
},
{
"code": null,
"e": 1734,
"s": 1726,
"text": "Output:"
},
{
"code": null,
"e": 1743,
"s": 1736,
"text": "Output"
},
{
"code": null,
"e": 1812,
"s": 1745,
"text": "Complete Script: Here is the code with all the steps at one place-"
},
{
"code": null,
"e": 1822,
"s": 1814,
"text": "Python3"
},
{
"code": "import pandas as p # loading pandas libraryimport altair as a # loading altair library # download dataset from https://drive.google.com/drive/folders/1Dddv1l9hpEPVWh_uuK9Iv1A1xUNy55v7?usp=sharing# OR replace name with your own dataset.data_set = 'insurance.csv'd = p.read_csv(data_set)d = d[[\"charges\"]] a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'], ).mark_area(color='green').encode( x=\"CHARGES:Q\", y='DENSITY:Q',)",
"e": 2296,
"s": 1822,
"text": null
},
{
"code": null,
"e": 2304,
"s": 2296,
"text": "Output:"
},
{
"code": null,
"e": 2311,
"s": 2304,
"text": "Output"
},
{
"code": null,
"e": 2320,
"s": 2311,
"text": "sweetyty"
},
{
"code": null,
"e": 2334,
"s": 2320,
"text": "Python-Altair"
},
{
"code": null,
"e": 2341,
"s": 2334,
"text": "Python"
}
] |
How to use ThreadPoolExecutor in Python3 ? | 08 Oct, 2021
Prerequisite: Multithreading
Threading allows parallelism of code and Python language has two ways to achieve its 1st is via multiprocessing module and 2nd is via multithreading module. Multithreading is well suited to speed up I/O bound tasks like making a web request, or database operations, or reading/writing to a file. In contrast to this CPU intensive tasks like mathematical computational tasks are benefited the most using multiprocessing. This happens due to GIL (Global Interpreter Lock).
From Python 3.2 onwards a new class called ThreadPoolExecutor was introduced in Python in concurrent.futures module to efficiently manage and create threads. But wait if python already had a threading module inbuilt then why a new module was introduced. Let me answer this first.
Spawning new threads on the fly is not a problem when the number of threads is less, but it becomes really cumbersome to manage threads if we are dealing with many threads. Apart from this, it is computationally inefficient to create so many threads which will lead to a decline in throughput. An approach to keep up the throughput is to create & instantiate a pool of idle threads beforehand and reuse the threads from this pool until all the threads are exhausted. This way the overhead of creating new threads is reduced.
Also, the pool keeps track and manages the threads lifecycle and schedules them on the programmer’s behalf thus making the code much simpler and less buggy.
Syntax: concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix=”, initializer=None, initargs=())
Parameters:
max_workers: It is a number of Threads aka size of pool. From 3.8 onwards default value is min(32, os.cpu_count() + 4). Out of these 5 threads are preserved for I/O bound task.
thread_name_prefix : thread_name_prefix was added from python 3.6 onwards to give names to thread for easier debugging purpose.
initializer: initializer takes a callable which is invoked on start of each worker thread.
initargs: It’s a tuple of arguments passed to initializer.
ThreadPoolExecutor class exposes three methods to execute threads asynchronously. A detailed explanation is given below.
submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method.map(fn, *iterables, timeout = None, chunksize = 1) : It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value.shutdown(wait = True, *, cancel_futures = False): It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start.
submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method.
map(fn, *iterables, timeout = None, chunksize = 1) : It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value.
It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.
If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value.
shutdown(wait = True, *, cancel_futures = False): It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start.
It signals the executor to free up all resources when the futures are done executing.
It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.
wait=True makes the method not to return until execution of all threads is done and resources are freed up.
cancel_futures=True then the executor will cancel all the future threads that are yet to start.
Example 1:
The below code demonstrates the use of ThreadPoolExecutor, notice unlike with the threading module we do not have to explicitly call using a loop, keeping a track of thread using a list or wait for threads using join for synchronization, or releasing the resources after the threads are finished everything is taken under the hood by the constructor itself making the code compact and bug-free.
Python3
from concurrent.futures import ThreadPoolExecutorfrom time import sleep values = [3,4,5,6] def cube(x): print(f'Cube of {x}:{x*x*x}') if __name__ == '__main__': result =[] with ThreadPoolExecutor(max_workers=5) as exe: exe.submit(cube,2) # Maps the method 'cube' with a list of values. result = exe.map(cube,values) for r in result: print(r)
Output:
Output:
Cube of 2:8
Cube of 3:27
Cube of 4:64
Cube of 5:125
Cube of 6:216
Example 2:
The below code is fetching images over the internet by making an HTTP request, I am using the request library for the same. The first section of the code makes a one-to-one call to the API and i.e the download is slow, whereas the second section of the code makes a parallel request using threads to fetch API.
You can try all various parameters discussed above to see how it tunes the speedup for example if I make a thread pool of 6 instead of 3 the speedup is more significant.
Python3
import requestsimport timeimport concurrent.futures img_urls = [ 'https://media.geeksforgeeks.org/wp-content/uploads/20190623210949/download21.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211125/d11.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211655/d31.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212213/d4.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212607/d5.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623235904/d6.jpg',] t1 = time.perf_counter()def download_image(img_url): img_bytes = requests.get(img_url).content print("Downloading..") # Download images 1 by 1 => slowfor img in img_urls: download_image(img)t2 = time.perf_counter()print(f'Single Threaded Code Took :{t2 - t1} seconds') print('*'*50) t1 = time.perf_counter()def download_image(img_url): img_bytes = requests.get(img_url).content print("Downloading..") # Fetching images concurrently thus speeds up the download.with concurrent.futures.ThreadPoolExecutor(3) as executor: executor.map(download_image, img_urls) t2 = time.perf_counter()print(f'MultiThreaded Code Took:{t2 - t1} seconds')
Output:
Downloading..
Downloading..
Downloading..
Downloading..
Downloading..
Downloading..
Single Threaded Code Took :2.5529379630024778 seconds
**************************************************
Downloading..
Downloading..
Downloading..
Downloading..
Downloading..
Downloading..
MultiThreaded Code Took:0.5221083430078579 seconds
akshaysingh98088
anikaseth98
Python-multithreading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 82,
"s": 53,
"text": "Prerequisite: Multithreading"
},
{
"code": null,
"e": 553,
"s": 82,
"text": "Threading allows parallelism of code and Python language has two ways to achieve its 1st is via multiprocessing module and 2nd is via multithreading module. Multithreading is well suited to speed up I/O bound tasks like making a web request, or database operations, or reading/writing to a file. In contrast to this CPU intensive tasks like mathematical computational tasks are benefited the most using multiprocessing. This happens due to GIL (Global Interpreter Lock)."
},
{
"code": null,
"e": 833,
"s": 553,
"text": "From Python 3.2 onwards a new class called ThreadPoolExecutor was introduced in Python in concurrent.futures module to efficiently manage and create threads. But wait if python already had a threading module inbuilt then why a new module was introduced. Let me answer this first."
},
{
"code": null,
"e": 1358,
"s": 833,
"text": "Spawning new threads on the fly is not a problem when the number of threads is less, but it becomes really cumbersome to manage threads if we are dealing with many threads. Apart from this, it is computationally inefficient to create so many threads which will lead to a decline in throughput. An approach to keep up the throughput is to create & instantiate a pool of idle threads beforehand and reuse the threads from this pool until all the threads are exhausted. This way the overhead of creating new threads is reduced."
},
{
"code": null,
"e": 1515,
"s": 1358,
"text": "Also, the pool keeps track and manages the threads lifecycle and schedules them on the programmer’s behalf thus making the code much simpler and less buggy."
},
{
"code": null,
"e": 1632,
"s": 1515,
"text": "Syntax: concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix=”, initializer=None, initargs=())"
},
{
"code": null,
"e": 1644,
"s": 1632,
"text": "Parameters:"
},
{
"code": null,
"e": 1821,
"s": 1644,
"text": "max_workers: It is a number of Threads aka size of pool. From 3.8 onwards default value is min(32, os.cpu_count() + 4). Out of these 5 threads are preserved for I/O bound task."
},
{
"code": null,
"e": 1949,
"s": 1821,
"text": "thread_name_prefix : thread_name_prefix was added from python 3.6 onwards to give names to thread for easier debugging purpose."
},
{
"code": null,
"e": 2040,
"s": 1949,
"text": "initializer: initializer takes a callable which is invoked on start of each worker thread."
},
{
"code": null,
"e": 2099,
"s": 2040,
"text": "initargs: It’s a tuple of arguments passed to initializer."
},
{
"code": null,
"e": 2220,
"s": 2099,
"text": "ThreadPoolExecutor class exposes three methods to execute threads asynchronously. A detailed explanation is given below."
},
{
"code": null,
"e": 3229,
"s": 2220,
"text": "submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method.map(fn, *iterables, timeout = None, chunksize = 1) : It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value.shutdown(wait = True, *, cancel_futures = False): It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start."
},
{
"code": null,
"e": 3365,
"s": 3229,
"text": "submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method."
},
{
"code": null,
"e": 3800,
"s": 3365,
"text": "map(fn, *iterables, timeout = None, chunksize = 1) : It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value."
},
{
"code": null,
"e": 3962,
"s": 3800,
"text": "It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit."
},
{
"code": null,
"e": 4183,
"s": 3962,
"text": "If the iterables are very large, then having a chunk-size larger than 1 can improve performance when using ProcessPoolExecutor but with ThreadPoolExecutor it has no such advantage, ie it can be left to its default value."
},
{
"code": null,
"e": 4623,
"s": 4183,
"text": "shutdown(wait = True, *, cancel_futures = False): It signals the executor to free up all resources when the futures are done executing.It must be called before executor.submit() and executor.map() method else it would throw RuntimeError.wait=True makes the method not to return until execution of all threads is done and resources are freed up.cancel_futures=True then the executor will cancel all the future threads that are yet to start."
},
{
"code": null,
"e": 4709,
"s": 4623,
"text": "It signals the executor to free up all resources when the futures are done executing."
},
{
"code": null,
"e": 4812,
"s": 4709,
"text": "It must be called before executor.submit() and executor.map() method else it would throw RuntimeError."
},
{
"code": null,
"e": 4920,
"s": 4812,
"text": "wait=True makes the method not to return until execution of all threads is done and resources are freed up."
},
{
"code": null,
"e": 5016,
"s": 4920,
"text": "cancel_futures=True then the executor will cancel all the future threads that are yet to start."
},
{
"code": null,
"e": 5027,
"s": 5016,
"text": "Example 1:"
},
{
"code": null,
"e": 5422,
"s": 5027,
"text": "The below code demonstrates the use of ThreadPoolExecutor, notice unlike with the threading module we do not have to explicitly call using a loop, keeping a track of thread using a list or wait for threads using join for synchronization, or releasing the resources after the threads are finished everything is taken under the hood by the constructor itself making the code compact and bug-free."
},
{
"code": null,
"e": 5430,
"s": 5422,
"text": "Python3"
},
{
"code": "from concurrent.futures import ThreadPoolExecutorfrom time import sleep values = [3,4,5,6] def cube(x): print(f'Cube of {x}:{x*x*x}') if __name__ == '__main__': result =[] with ThreadPoolExecutor(max_workers=5) as exe: exe.submit(cube,2) # Maps the method 'cube' with a list of values. result = exe.map(cube,values) for r in result: print(r)",
"e": 5825,
"s": 5430,
"text": null
},
{
"code": null,
"e": 5833,
"s": 5825,
"text": "Output:"
},
{
"code": null,
"e": 5908,
"s": 5833,
"text": "Output: \nCube of 2:8\nCube of 3:27\nCube of 4:64\nCube of 5:125\nCube of 6:216"
},
{
"code": null,
"e": 5919,
"s": 5908,
"text": "Example 2:"
},
{
"code": null,
"e": 6230,
"s": 5919,
"text": "The below code is fetching images over the internet by making an HTTP request, I am using the request library for the same. The first section of the code makes a one-to-one call to the API and i.e the download is slow, whereas the second section of the code makes a parallel request using threads to fetch API."
},
{
"code": null,
"e": 6400,
"s": 6230,
"text": "You can try all various parameters discussed above to see how it tunes the speedup for example if I make a thread pool of 6 instead of 3 the speedup is more significant."
},
{
"code": null,
"e": 6408,
"s": 6400,
"text": "Python3"
},
{
"code": "import requestsimport timeimport concurrent.futures img_urls = [ 'https://media.geeksforgeeks.org/wp-content/uploads/20190623210949/download21.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211125/d11.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623211655/d31.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212213/d4.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623212607/d5.jpg', 'https://media.geeksforgeeks.org/wp-content/uploads/20190623235904/d6.jpg',] t1 = time.perf_counter()def download_image(img_url): img_bytes = requests.get(img_url).content print(\"Downloading..\") # Download images 1 by 1 => slowfor img in img_urls: download_image(img)t2 = time.perf_counter()print(f'Single Threaded Code Took :{t2 - t1} seconds') print('*'*50) t1 = time.perf_counter()def download_image(img_url): img_bytes = requests.get(img_url).content print(\"Downloading..\") # Fetching images concurrently thus speeds up the download.with concurrent.futures.ThreadPoolExecutor(3) as executor: executor.map(download_image, img_urls) t2 = time.perf_counter()print(f'MultiThreaded Code Took:{t2 - t1} seconds')",
"e": 7615,
"s": 6408,
"text": null
},
{
"code": null,
"e": 7623,
"s": 7615,
"text": "Output:"
},
{
"code": null,
"e": 7947,
"s": 7623,
"text": "Downloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nSingle Threaded Code Took :2.5529379630024778 seconds\n**************************************************\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nDownloading..\nMultiThreaded Code Took:0.5221083430078579 seconds"
},
{
"code": null,
"e": 7964,
"s": 7947,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 7976,
"s": 7964,
"text": "anikaseth98"
},
{
"code": null,
"e": 7998,
"s": 7976,
"text": "Python-multithreading"
},
{
"code": null,
"e": 8005,
"s": 7998,
"text": "Python"
}
] |
JavaScript String startsWith() Method | 06 Oct, 2021
Below is the example of the String startsWith() Method.
Example:
JavaScript
<script>function func() { var str = 'Geeks for Geeks'; var value = str.startsWith('Gee'); document.write(value);}func();</script>
Output:
true
The str.startsWith() method is used to check whether the given string starts with the characters of the specified string or not. Syntax:
str.startsWith( searchString , position )
Parameters: This method accepts two parameters as mentioned above and described below:
searchString: It is required parameter. It stores the string which needs to search.
start: It determines the position in the given string from where the searchString is to be searched. The default value is zero.
Return value This method returns the Boolean value true if the searchString is found else returns false.Examples for the above method are provided below:Example 1:
var str = 'It is a great day.';
var value = str.startsWith('It');
print(value);
Output:
true
In the above example, the method startsWith() checks whether the string str starts with It or not. Since the string starts with It therefore it returns true.Example 2:
var str = 'It is a great day.';
var value = str.startsWith('great');
print(value);
Output:
false
In this example, the method startsWith() checks whether the string str starts with great or not. Since great appears in the middle and not in the beginning of the string therefore it returns false.Example 3:
var str = 'It is a great day.'
var value = str.startsWith('great',8);
print(value);
Output:
true
In this example the method startsWith() checks whether the string str starts with great or not at the specified index 8. Since great appears at the given index in the string therefore it returns true.Below programs illustrate the startsWith() method in JavaScript:Program 1:
JavaScript
<script>// JavaScript to illustrate startsWith() method function func() { // Original string var str = 'It is a great day.'; // Checking the condition var value = str.startsWith('It'); document.write(value);}func();</script>
Output:
true
Program 2:
JavaScript
<script> // JavaScript to illustrate// startsWith() methodfunction func() { // Original string var str = 'It is a great day.'; var value = str.startsWith('great'); document.write(value);}func();</script>
Output:
false
Program 3:
JavaScript
<script> // JavaScript to illustrate// startsWith() methodfunction func() { // Original string var str = 'It is a great day.'; var value = str.startsWith('great', 8); document.write(value);} // Function callfunc(); </script>
Output:
true
Supported Browser:
Chrome 41 and above
Edge 12 and above
Opera 28 and above
Firefox 17 and above
Safari 9 and above
ysachin2314
JavaScript-Methods
javascript-string
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": "\n06 Oct, 2021"
},
{
"code": null,
"e": 86,
"s": 28,
"text": "Below is the example of the String startsWith() Method. "
},
{
"code": null,
"e": 97,
"s": 86,
"text": "Example: "
},
{
"code": null,
"e": 108,
"s": 97,
"text": "JavaScript"
},
{
"code": "<script>function func() { var str = 'Geeks for Geeks'; var value = str.startsWith('Gee'); document.write(value);}func();</script>",
"e": 247,
"s": 108,
"text": null
},
{
"code": null,
"e": 257,
"s": 247,
"text": "Output: "
},
{
"code": null,
"e": 262,
"s": 257,
"text": "true"
},
{
"code": null,
"e": 401,
"s": 262,
"text": "The str.startsWith() method is used to check whether the given string starts with the characters of the specified string or not. Syntax: "
},
{
"code": null,
"e": 443,
"s": 401,
"text": "str.startsWith( searchString , position )"
},
{
"code": null,
"e": 532,
"s": 443,
"text": "Parameters: This method accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 616,
"s": 532,
"text": "searchString: It is required parameter. It stores the string which needs to search."
},
{
"code": null,
"e": 744,
"s": 616,
"text": "start: It determines the position in the given string from where the searchString is to be searched. The default value is zero."
},
{
"code": null,
"e": 910,
"s": 744,
"text": "Return value This method returns the Boolean value true if the searchString is found else returns false.Examples for the above method are provided below:Example 1: "
},
{
"code": null,
"e": 991,
"s": 910,
"text": "var str = 'It is a great day.';\nvar value = str.startsWith('It'); \nprint(value);"
},
{
"code": null,
"e": 1001,
"s": 991,
"text": "Output: "
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "true"
},
{
"code": null,
"e": 1176,
"s": 1006,
"text": "In the above example, the method startsWith() checks whether the string str starts with It or not. Since the string starts with It therefore it returns true.Example 2: "
},
{
"code": null,
"e": 1259,
"s": 1176,
"text": "var str = 'It is a great day.';\nvar value = str.startsWith('great');\nprint(value);"
},
{
"code": null,
"e": 1269,
"s": 1259,
"text": "Output: "
},
{
"code": null,
"e": 1275,
"s": 1269,
"text": "false"
},
{
"code": null,
"e": 1485,
"s": 1275,
"text": "In this example, the method startsWith() checks whether the string str starts with great or not. Since great appears in the middle and not in the beginning of the string therefore it returns false.Example 3: "
},
{
"code": null,
"e": 1569,
"s": 1485,
"text": "var str = 'It is a great day.'\nvar value = str.startsWith('great',8);\nprint(value);"
},
{
"code": null,
"e": 1579,
"s": 1569,
"text": "Output: "
},
{
"code": null,
"e": 1584,
"s": 1579,
"text": "true"
},
{
"code": null,
"e": 1861,
"s": 1584,
"text": "In this example the method startsWith() checks whether the string str starts with great or not at the specified index 8. Since great appears at the given index in the string therefore it returns true.Below programs illustrate the startsWith() method in JavaScript:Program 1: "
},
{
"code": null,
"e": 1872,
"s": 1861,
"text": "JavaScript"
},
{
"code": "<script>// JavaScript to illustrate startsWith() method function func() { // Original string var str = 'It is a great day.'; // Checking the condition var value = str.startsWith('It'); document.write(value);}func();</script>",
"e": 2123,
"s": 1872,
"text": null
},
{
"code": null,
"e": 2133,
"s": 2123,
"text": "Output: "
},
{
"code": null,
"e": 2138,
"s": 2133,
"text": "true"
},
{
"code": null,
"e": 2151,
"s": 2138,
"text": "Program 2: "
},
{
"code": null,
"e": 2162,
"s": 2151,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript to illustrate// startsWith() methodfunction func() { // Original string var str = 'It is a great day.'; var value = str.startsWith('great'); document.write(value);}func();</script>",
"e": 2383,
"s": 2162,
"text": null
},
{
"code": null,
"e": 2393,
"s": 2383,
"text": "Output: "
},
{
"code": null,
"e": 2399,
"s": 2393,
"text": "false"
},
{
"code": null,
"e": 2412,
"s": 2399,
"text": "Program 3: "
},
{
"code": null,
"e": 2423,
"s": 2412,
"text": "JavaScript"
},
{
"code": "<script> // JavaScript to illustrate// startsWith() methodfunction func() { // Original string var str = 'It is a great day.'; var value = str.startsWith('great', 8); document.write(value);} // Function callfunc(); </script>",
"e": 2666,
"s": 2423,
"text": null
},
{
"code": null,
"e": 2676,
"s": 2666,
"text": "Output: "
},
{
"code": null,
"e": 2681,
"s": 2676,
"text": "true"
},
{
"code": null,
"e": 2700,
"s": 2681,
"text": "Supported Browser:"
},
{
"code": null,
"e": 2720,
"s": 2700,
"text": "Chrome 41 and above"
},
{
"code": null,
"e": 2738,
"s": 2720,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2757,
"s": 2738,
"text": "Opera 28 and above"
},
{
"code": null,
"e": 2778,
"s": 2757,
"text": "Firefox 17 and above"
},
{
"code": null,
"e": 2797,
"s": 2778,
"text": "Safari 9 and above"
},
{
"code": null,
"e": 2809,
"s": 2797,
"text": "ysachin2314"
},
{
"code": null,
"e": 2828,
"s": 2809,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2846,
"s": 2828,
"text": "javascript-string"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": "JavaScript"
},
{
"code": null,
"e": 2874,
"s": 2857,
"text": "Web Technologies"
}
] |
Java Program for Subset Sum Problem | DP-25 | 09 Jun, 2022
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.Example:
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
Following is naive recursive implementation that simply follows the recursive structure mentioned above.
Java
// A recursive solution for subset sum// problemclass GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than // sum, then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } /* Driver program to test above function */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println("Found a subset" + " with given sum"); else System.out.println("No subset with" + " given sum"); }} /* This code is contributed by Rajat Mishra */
Found a subset with given sum
Time Complexity: O(2^n)Auxiliary Space: O(1)
We can solve the problem in Pseudo-polynomial time using Dynamic programming.
Java
// A Dynamic Programming solution for subset// sum problemclass GFG { // Returns true if there is a subset of // set[] with sun equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i boolean subset[][] = new boolean[sum + 1][n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } /* Driver program to test above function */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println("Found a subset" + " with given sum"); else System.out.println("No subset with" + " given sum"); }} /* This code is contributed by Rajat Mishra */
Found a subset with given sum
Time Complexity: O(n*k) where k is sum of elements.Auxiliary Space: O(n*k) where k is sum of elements.
Please refer complete article on Subset Sum Problem | DP-25 for more details!
sagartomar9927
chandramauliguptach
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.Example:"
},
{
"code": null,
"e": 269,
"s": 168,
"text": "Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9\nOutput: True //There is a subset (4, 5) with sum 9.\n"
},
{
"code": null,
"e": 374,
"s": 269,
"text": "Following is naive recursive implementation that simply follows the recursive structure mentioned above."
},
{
"code": null,
"e": 379,
"s": 374,
"text": "Java"
},
{
"code": "// A recursive solution for subset sum// problemclass GFG { // Returns true if there is a subset // of set[] with sum equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than // sum, then ignore it if (set[n - 1] > sum) return isSubsetSum(set, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(set, n - 1, sum) || isSubsetSum(set, n - 1, sum - set[n - 1]); } /* Driver program to test above function */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println(\"Found a subset\" + \" with given sum\"); else System.out.println(\"No subset with\" + \" given sum\"); }} /* This code is contributed by Rajat Mishra */",
"e": 1633,
"s": 379,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1633,
"text": "Found a subset with given sum\n"
},
{
"code": null,
"e": 1709,
"s": 1664,
"text": "Time Complexity: O(2^n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1787,
"s": 1709,
"text": "We can solve the problem in Pseudo-polynomial time using Dynamic programming."
},
{
"code": null,
"e": 1792,
"s": 1787,
"text": "Java"
},
{
"code": "// A Dynamic Programming solution for subset// sum problemclass GFG { // Returns true if there is a subset of // set[] with sun equal to given sum static boolean isSubsetSum(int set[], int n, int sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i boolean subset[][] = new boolean[sum + 1][n + 1]; // If sum is 0, then answer is true for (int i = 0; i <= n; i++) subset[0][i] = true; // If sum is not 0 and set is empty, // then answer is false for (int i = 1; i <= sum; i++) subset[i][0] = false; // Fill the subset table in bottom // up manner for (int i = 1; i <= sum; i++) { for (int j = 1; j <= n; j++) { subset[i][j] = subset[i][j - 1]; if (i >= set[j - 1]) subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } /* Driver program to test above function */ public static void main(String args[]) { int set[] = { 3, 34, 4, 12, 5, 2 }; int sum = 9; int n = set.length; if (isSubsetSum(set, n, sum) == true) System.out.println(\"Found a subset\" + \" with given sum\"); else System.out.println(\"No subset with\" + \" given sum\"); }} /* This code is contributed by Rajat Mishra */",
"e": 3525,
"s": 1792,
"text": null
},
{
"code": null,
"e": 3556,
"s": 3525,
"text": "Found a subset with given sum\n"
},
{
"code": null,
"e": 3659,
"s": 3556,
"text": "Time Complexity: O(n*k) where k is sum of elements.Auxiliary Space: O(n*k) where k is sum of elements."
},
{
"code": null,
"e": 3737,
"s": 3659,
"text": "Please refer complete article on Subset Sum Problem | DP-25 for more details!"
},
{
"code": null,
"e": 3752,
"s": 3737,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3772,
"s": 3752,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 3786,
"s": 3772,
"text": "Java Programs"
}
] |
Samsung Software – Competency Test (Samsung R&D Bangalore) Experience > 1 yrs | 13 Feb, 2020
Round 1: If your body Temperature is above 36 degree, You have to go back .(I don’t know why?)
Round 2: we have to complete One Question within 4 hrs. There were 50 test cases, 5 test cases are visible and other 45 are in backend.
Yor are not allowed to use any library functions such as Array List, Stack, Queue.....
c/c++ java -allowed language, c# python and others –not allowed
In between they will provide Orio, juice coffee water ....(enjoy)
Question :(It was story based ...so actually I am not that brainy to write whole story...so some glimpse)
It was midnight, Robert joy was travelling in a ship, suddenly traveller got the distinct impression that the ship was swerving. Suddenly, however, the ship shook with a strange back-and-forth movement and began to wallow, it was typhoon ... So he decided to jump off the ship . Somehow he manages to take Lifeboat and while deboard, he puts some 3D block along with him . when he wake up, he found himself in Island, surrounded by light blue color ....
he get down from the lifeboat and tried to send a signal to Rescue team. But he didnt make it ...
So he decided to make height so that he can easily send the signal .. So whatever he kept the 3D blocks in lifeboat along with him, He started keeping one above another.
But the robert joy was very week in Mathematics and programmings, Imagine You were there and asking for help, to find the maximum Height by creating stack of 3D boxes, so that he can easily send the signal to rescue team .
But condition is there :
— you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box
|__________|
|________| Not possible here (consider 3D box) They will provide you proper image .
— multiple Instances of same block can be used so that block can be rotated to use any side as its base.
let say N is the Number Of block he has ...2<=N <=20;
Test cases: 1<=T<= 1000;
Input – T : No of Test cases
N : no of block
l, w, h : Lenght, width and height of each block .
Eg.
2
27 31 24
76 33 3
Ans : 76
3
9 9 9
1 1 1
435 345 567
Ansc : 577
I solved using DP but didn’t able to pass most of the hidden test cases, (So golden words came to me ” you may leave for the day “.)
Note : If You are really ready then go for this test, because They will provide you only 3 attempts for entire life. so never miss a chance, (I missed one) and if you are thinking you ll use another email and phone, u ll get blocked ..so be careful . This Is R&D.
Marketing
Samsung
Interview Experiences
Samsung
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "Round 1: If your body Temperature is above 36 degree, You have to go back .(I don’t know why?)"
},
{
"code": null,
"e": 264,
"s": 127,
"text": "Round 2: we have to complete One Question within 4 hrs. There were 50 test cases, 5 test cases are visible and other 45 are in backend."
},
{
"code": null,
"e": 351,
"s": 264,
"text": "Yor are not allowed to use any library functions such as Array List, Stack, Queue....."
},
{
"code": null,
"e": 416,
"s": 351,
"text": "c/c++ java -allowed language, c# python and others –not allowed"
},
{
"code": null,
"e": 484,
"s": 418,
"text": "In between they will provide Orio, juice coffee water ....(enjoy)"
},
{
"code": null,
"e": 591,
"s": 484,
"text": "Question :(It was story based ...so actually I am not that brainy to write whole story...so some glimpse)"
},
{
"code": null,
"e": 1045,
"s": 591,
"text": "It was midnight, Robert joy was travelling in a ship, suddenly traveller got the distinct impression that the ship was swerving. Suddenly, however, the ship shook with a strange back-and-forth movement and began to wallow, it was typhoon ... So he decided to jump off the ship . Somehow he manages to take Lifeboat and while deboard, he puts some 3D block along with him . when he wake up, he found himself in Island, surrounded by light blue color ...."
},
{
"code": null,
"e": 1143,
"s": 1045,
"text": "he get down from the lifeboat and tried to send a signal to Rescue team. But he didnt make it ..."
},
{
"code": null,
"e": 1314,
"s": 1143,
"text": "So he decided to make height so that he can easily send the signal .. So whatever he kept the 3D blocks in lifeboat along with him, He started keeping one above another."
},
{
"code": null,
"e": 1537,
"s": 1314,
"text": "But the robert joy was very week in Mathematics and programmings, Imagine You were there and asking for help, to find the maximum Height by creating stack of 3D boxes, so that he can easily send the signal to rescue team ."
},
{
"code": null,
"e": 1562,
"s": 1537,
"text": "But condition is there :"
},
{
"code": null,
"e": 1732,
"s": 1562,
"text": "— you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box"
},
{
"code": null,
"e": 1745,
"s": 1732,
"text": "|__________|"
},
{
"code": null,
"e": 1844,
"s": 1745,
"text": "|________| Not possible here (consider 3D box) They will provide you proper image ."
},
{
"code": null,
"e": 1951,
"s": 1846,
"text": "— multiple Instances of same block can be used so that block can be rotated to use any side as its base."
},
{
"code": null,
"e": 2007,
"s": 1953,
"text": "let say N is the Number Of block he has ...2<=N <=20;"
},
{
"code": null,
"e": 2032,
"s": 2007,
"text": "Test cases: 1<=T<= 1000;"
},
{
"code": null,
"e": 2062,
"s": 2032,
"text": "Input – T : No of Test cases"
},
{
"code": null,
"e": 2079,
"s": 2062,
"text": "N : no of block"
},
{
"code": null,
"e": 2137,
"s": 2079,
"text": "l, w, h : Lenght, width and height of each block ."
},
{
"code": null,
"e": 2141,
"s": 2137,
"text": "Eg."
},
{
"code": null,
"e": 2143,
"s": 2141,
"text": "2"
},
{
"code": null,
"e": 2153,
"s": 2143,
"text": "27 31 24"
},
{
"code": null,
"e": 2164,
"s": 2153,
"text": "76 33 3"
},
{
"code": null,
"e": 2173,
"s": 2164,
"text": "Ans : 76"
},
{
"code": null,
"e": 2175,
"s": 2173,
"text": "3"
},
{
"code": null,
"e": 2181,
"s": 2175,
"text": "9 9 9"
},
{
"code": null,
"e": 2187,
"s": 2181,
"text": "1 1 1"
},
{
"code": null,
"e": 2199,
"s": 2187,
"text": "435 345 567"
},
{
"code": null,
"e": 2210,
"s": 2199,
"text": "Ansc : 577"
},
{
"code": null,
"e": 2346,
"s": 2210,
"text": "I solved using DP but didn’t able to pass most of the hidden test cases, (So golden words came to me ” you may leave for the day “.)"
},
{
"code": null,
"e": 2610,
"s": 2346,
"text": "Note : If You are really ready then go for this test, because They will provide you only 3 attempts for entire life. so never miss a chance, (I missed one) and if you are thinking you ll use another email and phone, u ll get blocked ..so be careful . This Is R&D."
},
{
"code": null,
"e": 2622,
"s": 2612,
"text": "Marketing"
},
{
"code": null,
"e": 2630,
"s": 2622,
"text": "Samsung"
},
{
"code": null,
"e": 2652,
"s": 2630,
"text": "Interview Experiences"
},
{
"code": null,
"e": 2660,
"s": 2652,
"text": "Samsung"
}
] |
wcslen() function in C++ with Examples | 03 Oct, 2018
The wcslen() function is defined in cwchar.h header file. The function wcslen() function returns the length of the given wide string.
Syntax:
size_t wcslen(const wchar_t* str);
Parameter: This method takes a single parameter str which represents the pointer to the wide string whose length is to be calculated.
Return Value: This function returns the length of wide string.
Below programs illustrate the above function:-
Example 1:-
// c++ program to demonstrate// example of wcslen() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string to be used wchar_t str[] = L"geeks"; // Get the length of the string using wcslen() wcout << L"The length of '" << str << L"' is =" << wcslen(str) << endl; return 0;}
The length of 'geeks' is =5
Example 2:-
// c++ program to demonstrate// example of wcslen() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string to be used wchar_t str[] = L"A computer science portal for geeks"; // Get the length of the string using wcslen() wcout << L"The length of '" << str << L"' is =" << wcslen(str) << endl; return 0;}
The length of 'A computer science portal for geeks' is =35
=
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2018"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "The wcslen() function is defined in cwchar.h header file. The function wcslen() function returns the length of the given wide string."
},
{
"code": null,
"e": 170,
"s": 162,
"text": "Syntax:"
},
{
"code": null,
"e": 205,
"s": 170,
"text": "size_t wcslen(const wchar_t* str);"
},
{
"code": null,
"e": 339,
"s": 205,
"text": "Parameter: This method takes a single parameter str which represents the pointer to the wide string whose length is to be calculated."
},
{
"code": null,
"e": 402,
"s": 339,
"text": "Return Value: This function returns the length of wide string."
},
{
"code": null,
"e": 449,
"s": 402,
"text": "Below programs illustrate the above function:-"
},
{
"code": null,
"e": 461,
"s": 449,
"text": "Example 1:-"
},
{
"code": "// c++ program to demonstrate// example of wcslen() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string to be used wchar_t str[] = L\"geeks\"; // Get the length of the string using wcslen() wcout << L\"The length of '\" << str << L\"' is =\" << wcslen(str) << endl; return 0;}",
"e": 797,
"s": 461,
"text": null
},
{
"code": null,
"e": 826,
"s": 797,
"text": "The length of 'geeks' is =5\n"
},
{
"code": null,
"e": 838,
"s": 826,
"text": "Example 2:-"
},
{
"code": "// c++ program to demonstrate// example of wcslen() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string to be used wchar_t str[] = L\"A computer science portal for geeks\"; // Get the length of the string using wcslen() wcout << L\"The length of '\" << str << L\"' is =\" << wcslen(str) << endl; return 0;}",
"e": 1204,
"s": 838,
"text": null
},
{
"code": null,
"e": 1264,
"s": 1204,
"text": "The length of 'A computer science portal for geeks' is =35\n"
},
{
"code": null,
"e": 1266,
"s": 1264,
"text": "="
},
{
"code": null,
"e": 1270,
"s": 1266,
"text": "C++"
},
{
"code": null,
"e": 1274,
"s": 1270,
"text": "CPP"
}
] |
Count Palindromic Subsequences | Practice | GeeksforGeeks | Given a string str of length N, you have to find number of palindromic subsequence (need not necessarily be distinct) which could be formed from the string str.
Note: You have to return the answer module 109+7;
Example 1:
Input:
Str = "abcd"
Output:
4
Explanation:
palindromic subsequence are : "a" ,"b", "c" ,"d"
Example 2:
Input:
Str = "aab"
Output:
4
Explanation:
palindromic subsequence are :"a", "a", "b", "aa"
Your Task:
You don't need to read input or print anything. Your task is to complete the function countPs() which takes a string str as input parameter and returns the number of palindromic subsequence.
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N*N)
Constraints:
1<=length of string str <=1000
0
abhishekwasu20014 days ago
this code is running for 102 test cases but not for rest of three
can anyone tell me what is going wrong and how can get rid of this plz plz
long long int countPS(string str) { long long int dp[str.length()+1][str.length()+1]; for(int i=0;i<str.length();i++) for(int j=0;j<str.length();j++) dp[i][j]=0; for(int i=0;i<str.length();i++) dp[i][i]=1; long long int j=1,k=0,i=0; while(j<str.length()) { k=j; i=0; while(k<str.length()) { // cout<<"value of i is "<<i<<" value of j is "<<k<<endl; if(str[i]==str[k]) dp[i][k]=1+dp[i+1][k]+dp[i][k-1]; else dp[i][k]=dp[i+1][k]+dp[i][k-1]-dp[i+1][k-1]; i++; k++; } j++; } return dp[0][str.length()-1]; }
+1
milindprajapatmst196 days ago
# define ll long long
const int N = 1e3, MOD = 1e9 + 7;
ll dp[N][N];
ll _add(ll x, ll y) {
return (x + y) % MOD;
}
ll _sub(ll x, ll y) {
return (x - y) + (x >= y ? 0 : MOD);
}
ll _mul(ll x, ll y) {
return (x * y) % MOD;
}
class Solution {
public:
ll help(int k1, int k2, string& str) {
if (k1 > k2)
return 0;
if (k1 == k2)
return 1;
if (dp[k1][k2] == -1) {
ll result = _sub(_add(help(k1 + 1, k2, str), help(k1, k2 - 1, str)), help(k1 + 1, k2 - 1, str));
if (str[k1] == str[k2])
result = _add(result, _add(1, help(k1 + 1, k2 - 1, str)));
dp[k1][k2] = result;
}
return dp[k1][k2];
}
ll countPS(string& str) {
memset(dp, -1, sizeof(dp));
return help(0, str.size() - 1, str);
}
};
-1
anuragshubham341 week ago
class Solution{ static long[][] dp=new long[1001][1001]; static long m=1000000007; static long solve (String str,int i,int j){ if(i>j) return 0; if(i==j) return 1; if(dp[i][j]!=-1) return dp[i][j]; if(str.charAt((int)i)==str.charAt((int)j)) return dp[i][j]=(solve(str,i+1,j)+solve(str,i,j-1)+1)%m; else return dp[i][j]=(m+solve(str,i+1,j)%m+solve(str,i,j-1)%m-solve(str,i+1,j-1)%m)%m; } static long countPS(String str) { for(long[] a:dp) Arrays.fill(a,-1); return solve(str,0,str.length()-1); }}
+1
sparshtanejaa1 week ago
all thos getting tle use this
long long m = 1e9 + 7; int dp[1001][1001]; long long int cps(string &s,int i,int j) { if(i > j) return 0; if(i == j) return 1; if(dp[i][j] != -1) return dp[i][j]; if(s[i] == s[j]) { return dp[i][j] = ( 1 + cps(s,i+1,j) + cps(s,i,j-1))%m; } else { return dp[i][j] = (m+ cps(s,i+1,j) + cps(s,i,j-1) - cps(s,i+1,j-1))%m; } // return dp[i][j]%m; } long long int countPS(string s) { //Your code here memset(dp,-1,sizeof(dp)); return cps(s,0,s.size() -1); }
0
shilsoumyadip2 weeks ago
int dp[1001][1001]; long long int m = 1e9 + 7; long long int solve(string &s , int i , int j) { if(i>j) return 0; if(i==j) return 1; if(dp[i][j] != -1) return dp[i][j]; if(s[i] == s[j]) { return dp[i][j] = (solve(s,i+1,j) + solve(s,i,j-1) + 1)%m; } else { return dp[i][j] = (m + solve(s,i+1,j) + solve(s,i,j-1) - solve(s,i+1,j-1))%m; } } long long int countPS(string str) { //Your code here //int dp[str.length()][str.length()]; memset(dp,-1,sizeof(dp)); return solve(str,0,str.size()-1);
0
ishrivastava253 weeks ago
To avoid TLE, just pass the string by reference and take a mod when returning dp , see soln below , P.S :: We are adding mod to avoid negative solution, as we are subtarcting the recursive func also.
int dp[1001][1001]; long long int m = 1e9 + 7; long long int helper(string &str,int i,int j) { if(i>j) return 0; if(i==j) return 1; if(dp[i][j]!=-1) return (dp[i][j]); if(str[i]==str[j]) return dp[i][j]= (1+ helper(str,i+1,j) + helper(str,i,j-1))%m; else return dp[i][j]= ( m + helper(str,i+1,j) + helper(str,i,j-1) - helper(str,i+1,j-1))%m; } long long int countPS(string str) { memset(dp,-1,sizeof(dp)); int n=str.size(); return helper(str,0,n-1); }
+1
sandeepbhutia20111 month ago
Can anyone please explain why my code giving negative value even if i have used mod
/*You are required to complete below method */ long long int val=1000000007; long long int countPS(string str) { //Your code here int N=str.size();
vector<vector<long long int>> cnt(N+1,vector<long long int>(N+1,0)); for(int i=0;i<=N;i++){ cnt[i][i]=1; } for(int i=1;i<=N;i++){ for(int j=0;j<=N-i;j++){ if(str[j]==str[j+i]){ cnt[j][j+i]=(cnt[j][j+i-1] % val+cnt[j+1][j+i] % val+1)% val; } else{ cnt[j][j+i]=(cnt[j][j+i-1] % val + cnt[j+1][j+i] % val -cnt[j+1][j+i-1] % val )% val; } } } return cnt[0][N-1] % val;}
+2
deskhell2 months ago
To come up with a intuition for this problem is pretty tough I suggest.
class Solution{
public:
/*You are required to complete below method */
long long int countPS(string s)
{
int n = s.size();
const int mod = 1e9+7;
long long dp[n][n];
for(int g = 0; g < n; g++){
for(int i = 0, j = g; j < n; i++, j++){
if(g == 0)dp[i][j] = 1;
else if(g == 1)dp[i][j] = s[i] == s[j] ? 3 : 2;
else{
if(s[i] == s[j])
dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod + 1) % mod;
else
dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod - dp[i+1][j-1] + mod) % mod;
}
}
}
return dp[0][n-1];
}
};
-1
itsmanan132 months ago
Can someone please help my code is giving TLE I don't know why...
class Solution{
public:
/*You are required to complete below method */
long long int m = 1e9 + 7;
long long int dp[1005][1005];
long long int helper(int i,int j,string str)
{
if(i>j)
return 0;
if(i==j)
return 1;
if(dp[i][j]!=-1)
return dp[i][j];
if(str[i]==str[j])
return dp[i][j] = (1%m + helper(i+1,j,str)%m + helper(i,j-1,str)%m)%m;
else
return dp[i][j] = (helper(i+1,j,str)%m + helper(i,j-1,str)%m -
helper(i+1,j-1,str)%m)%m;
}
long long int countPS(string str)
{
//Your code here
memset(dp,-1,sizeof(dp));
int n = str.length();
return helper(0,n-1,str)%m;
}
};
+2
ruchitchudasama1232 months ago
simple and easy to understand code, if you hve any query regarding this approach or not able to understand code let me know.
https://auth.geeksforgeeks.org/user/ruchitchudasama123/practice/
public:
/*You are required to complete below method */
long long int M=1e9+7;
long long int go(int i,int j,string &str,vector<vector<long long int>> &dp){
if(i>j)return 0;
if(i==j)return 1;
if(dp[i][j]!=-1)return dp[i][j];
long long int ans=0;
if(str[i]==str[j]){
ans=1+go(i+1,j,str,dp)+go(i,j-1,str,dp)%M;
}
else{
ans=go(i+1,j,str,dp)+go(i,j-1,str,dp)-go(i+1,j-1,str,dp);
}
return dp[i][j]=ans;
}
long long int countPS(string str)
{
int n=str.size();
vector<vector<long long int>> dp(n+1,vector<long long int>(n+1,-1));
return go(0,n-1,str,dp)%M;
}
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": 451,
"s": 238,
"text": "Given a string str of length N, you have to find number of palindromic subsequence (need not necessarily be distinct) which could be formed from the string str.\nNote: You have to return the answer module 109+7;\n "
},
{
"code": null,
"e": 462,
"s": 451,
"text": "Example 1:"
},
{
"code": null,
"e": 556,
"s": 462,
"text": "Input: \nStr = \"abcd\"\nOutput: \n4\nExplanation:\npalindromic subsequence are : \"a\" ,\"b\", \"c\" ,\"d\""
},
{
"code": null,
"e": 569,
"s": 558,
"text": "Example 2:"
},
{
"code": null,
"e": 662,
"s": 569,
"text": "Input: \nStr = \"aab\"\nOutput: \n4\nExplanation:\npalindromic subsequence are :\"a\", \"a\", \"b\", \"aa\""
},
{
"code": null,
"e": 868,
"s": 664,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function countPs() which takes a string str as input parameter and returns the number of palindromic subsequence.\n "
},
{
"code": null,
"e": 934,
"s": 868,
"text": "Expected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(N*N)"
},
{
"code": null,
"e": 979,
"s": 934,
"text": "\nConstraints:\n1<=length of string str <=1000"
},
{
"code": null,
"e": 981,
"s": 979,
"text": "0"
},
{
"code": null,
"e": 1008,
"s": 981,
"text": "abhishekwasu20014 days ago"
},
{
"code": null,
"e": 1075,
"s": 1008,
"text": "this code is running for 102 test cases but not for rest of three "
},
{
"code": null,
"e": 1151,
"s": 1075,
"text": "can anyone tell me what is going wrong and how can get rid of this plz plz"
},
{
"code": null,
"e": 1925,
"s": 1157,
"text": "long long int countPS(string str) { long long int dp[str.length()+1][str.length()+1]; for(int i=0;i<str.length();i++) for(int j=0;j<str.length();j++) dp[i][j]=0; for(int i=0;i<str.length();i++) dp[i][i]=1; long long int j=1,k=0,i=0; while(j<str.length()) { k=j; i=0; while(k<str.length()) { // cout<<\"value of i is \"<<i<<\" value of j is \"<<k<<endl; if(str[i]==str[k]) dp[i][k]=1+dp[i+1][k]+dp[i][k-1]; else dp[i][k]=dp[i+1][k]+dp[i][k-1]-dp[i+1][k-1]; i++; k++; } j++; } return dp[0][str.length()-1]; }"
},
{
"code": null,
"e": 1928,
"s": 1925,
"text": "+1"
},
{
"code": null,
"e": 1958,
"s": 1928,
"text": "milindprajapatmst196 days ago"
},
{
"code": null,
"e": 2805,
"s": 1958,
"text": "# define ll long long\nconst int N = 1e3, MOD = 1e9 + 7;\nll dp[N][N];\nll _add(ll x, ll y) {\n return (x + y) % MOD;\n}\nll _sub(ll x, ll y) {\n return (x - y) + (x >= y ? 0 : MOD);\n}\nll _mul(ll x, ll y) {\n return (x * y) % MOD;\n}\nclass Solution {\n public:\n ll help(int k1, int k2, string& str) {\n if (k1 > k2)\n return 0;\n if (k1 == k2)\n return 1;\n if (dp[k1][k2] == -1) {\n ll result = _sub(_add(help(k1 + 1, k2, str), help(k1, k2 - 1, str)), help(k1 + 1, k2 - 1, str));\n if (str[k1] == str[k2])\n result = _add(result, _add(1, help(k1 + 1, k2 - 1, str)));\n dp[k1][k2] = result;\n }\n return dp[k1][k2];\n }\n ll countPS(string& str) {\n memset(dp, -1, sizeof(dp));\n return help(0, str.size() - 1, str);\n }\n \n};"
},
{
"code": null,
"e": 2808,
"s": 2805,
"text": "-1"
},
{
"code": null,
"e": 2834,
"s": 2808,
"text": "anuragshubham341 week ago"
},
{
"code": null,
"e": 3427,
"s": 2834,
"text": "class Solution{ static long[][] dp=new long[1001][1001]; static long m=1000000007; static long solve (String str,int i,int j){ if(i>j) return 0; if(i==j) return 1; if(dp[i][j]!=-1) return dp[i][j]; if(str.charAt((int)i)==str.charAt((int)j)) return dp[i][j]=(solve(str,i+1,j)+solve(str,i,j-1)+1)%m; else return dp[i][j]=(m+solve(str,i+1,j)%m+solve(str,i,j-1)%m-solve(str,i+1,j-1)%m)%m; } static long countPS(String str) { for(long[] a:dp) Arrays.fill(a,-1); return solve(str,0,str.length()-1); }}"
},
{
"code": null,
"e": 3430,
"s": 3427,
"text": "+1"
},
{
"code": null,
"e": 3454,
"s": 3430,
"text": "sparshtanejaa1 week ago"
},
{
"code": null,
"e": 3485,
"s": 3454,
"text": "all thos getting tle use this "
},
{
"code": null,
"e": 4057,
"s": 3487,
"text": "long long m = 1e9 + 7; int dp[1001][1001]; long long int cps(string &s,int i,int j) { if(i > j) return 0; if(i == j) return 1; if(dp[i][j] != -1) return dp[i][j]; if(s[i] == s[j]) { return dp[i][j] = ( 1 + cps(s,i+1,j) + cps(s,i,j-1))%m; } else { return dp[i][j] = (m+ cps(s,i+1,j) + cps(s,i,j-1) - cps(s,i+1,j-1))%m; } // return dp[i][j]%m; } long long int countPS(string s) { //Your code here memset(dp,-1,sizeof(dp)); return cps(s,0,s.size() -1); } "
},
{
"code": null,
"e": 4059,
"s": 4057,
"text": "0"
},
{
"code": null,
"e": 4084,
"s": 4059,
"text": "shilsoumyadip2 weeks ago"
},
{
"code": null,
"e": 4728,
"s": 4084,
"text": "int dp[1001][1001]; long long int m = 1e9 + 7; long long int solve(string &s , int i , int j) { if(i>j) return 0; if(i==j) return 1; if(dp[i][j] != -1) return dp[i][j]; if(s[i] == s[j]) { return dp[i][j] = (solve(s,i+1,j) + solve(s,i,j-1) + 1)%m; } else { return dp[i][j] = (m + solve(s,i+1,j) + solve(s,i,j-1) - solve(s,i+1,j-1))%m; } } long long int countPS(string str) { //Your code here //int dp[str.length()][str.length()]; memset(dp,-1,sizeof(dp)); return solve(str,0,str.size()-1); "
},
{
"code": null,
"e": 4730,
"s": 4728,
"text": "0"
},
{
"code": null,
"e": 4756,
"s": 4730,
"text": "ishrivastava253 weeks ago"
},
{
"code": null,
"e": 4957,
"s": 4756,
"text": "To avoid TLE, just pass the string by reference and take a mod when returning dp , see soln below , P.S :: We are adding mod to avoid negative solution, as we are subtarcting the recursive func also. "
},
{
"code": null,
"e": 5475,
"s": 4959,
"text": "int dp[1001][1001]; long long int m = 1e9 + 7; long long int helper(string &str,int i,int j) { if(i>j) return 0; if(i==j) return 1; if(dp[i][j]!=-1) return (dp[i][j]); if(str[i]==str[j]) return dp[i][j]= (1+ helper(str,i+1,j) + helper(str,i,j-1))%m; else return dp[i][j]= ( m + helper(str,i+1,j) + helper(str,i,j-1) - helper(str,i+1,j-1))%m; } long long int countPS(string str) { memset(dp,-1,sizeof(dp)); int n=str.size(); return helper(str,0,n-1); }"
},
{
"code": null,
"e": 5480,
"s": 5477,
"text": "+1"
},
{
"code": null,
"e": 5509,
"s": 5480,
"text": "sandeepbhutia20111 month ago"
},
{
"code": null,
"e": 5593,
"s": 5509,
"text": "Can anyone please explain why my code giving negative value even if i have used mod"
},
{
"code": null,
"e": 5765,
"s": 5595,
"text": " /*You are required to complete below method */ long long int val=1000000007; long long int countPS(string str) { //Your code here int N=str.size();"
},
{
"code": null,
"e": 6247,
"s": 5765,
"text": " vector<vector<long long int>> cnt(N+1,vector<long long int>(N+1,0)); for(int i=0;i<=N;i++){ cnt[i][i]=1; } for(int i=1;i<=N;i++){ for(int j=0;j<=N-i;j++){ if(str[j]==str[j+i]){ cnt[j][j+i]=(cnt[j][j+i-1] % val+cnt[j+1][j+i] % val+1)% val; } else{ cnt[j][j+i]=(cnt[j][j+i-1] % val + cnt[j+1][j+i] % val -cnt[j+1][j+i-1] % val )% val; } } } return cnt[0][N-1] % val;}"
},
{
"code": null,
"e": 6252,
"s": 6249,
"text": "+2"
},
{
"code": null,
"e": 6273,
"s": 6252,
"text": "deskhell2 months ago"
},
{
"code": null,
"e": 6345,
"s": 6273,
"text": "To come up with a intuition for this problem is pretty tough I suggest."
},
{
"code": null,
"e": 7107,
"s": 6345,
"text": "class Solution{\n public:\n /*You are required to complete below method */\n long long int countPS(string s)\n {\n int n = s.size();\n const int mod = 1e9+7;\n \n long long dp[n][n];\n for(int g = 0; g < n; g++){\n for(int i = 0, j = g; j < n; i++, j++){\n if(g == 0)dp[i][j] = 1;\n else if(g == 1)dp[i][j] = s[i] == s[j] ? 3 : 2;\n else{\n if(s[i] == s[j])\n dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod + 1) % mod;\n else \n dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod - dp[i+1][j-1] + mod) % mod;\n }\n }\n }\n return dp[0][n-1];\n }\n \n};"
},
{
"code": null,
"e": 7110,
"s": 7107,
"text": "-1"
},
{
"code": null,
"e": 7133,
"s": 7110,
"text": "itsmanan132 months ago"
},
{
"code": null,
"e": 7199,
"s": 7133,
"text": "Can someone please help my code is giving TLE I don't know why..."
},
{
"code": null,
"e": 8000,
"s": 7201,
"text": "class Solution{\npublic:\n /*You are required to complete below method */\n long long int m = 1e9 + 7;\n long long int dp[1005][1005];\n long long int helper(int i,int j,string str)\n {\n if(i>j)\n return 0;\n if(i==j)\n return 1;\n if(dp[i][j]!=-1) \n return dp[i][j];\n if(str[i]==str[j])\n return dp[i][j] = (1%m + helper(i+1,j,str)%m + helper(i,j-1,str)%m)%m;\n else\n return dp[i][j] = (helper(i+1,j,str)%m + helper(i,j-1,str)%m - \n helper(i+1,j-1,str)%m)%m;\n }\n long long int countPS(string str)\n {\n //Your code here\n memset(dp,-1,sizeof(dp));\n int n = str.length();\n return helper(0,n-1,str)%m;\n }\n \n};"
},
{
"code": null,
"e": 8003,
"s": 8000,
"text": "+2"
},
{
"code": null,
"e": 8034,
"s": 8003,
"text": "ruchitchudasama1232 months ago"
},
{
"code": null,
"e": 8159,
"s": 8034,
"text": "simple and easy to understand code, if you hve any query regarding this approach or not able to understand code let me know."
},
{
"code": null,
"e": 8224,
"s": 8159,
"text": "https://auth.geeksforgeeks.org/user/ruchitchudasama123/practice/"
},
{
"code": null,
"e": 8232,
"s": 8224,
"text": "public:"
},
{
"code": null,
"e": 8283,
"s": 8232,
"text": " /*You are required to complete below method */"
},
{
"code": null,
"e": 8310,
"s": 8283,
"text": " long long int M=1e9+7;"
},
{
"code": null,
"e": 8396,
"s": 8315,
"text": " long long int go(int i,int j,string &str,vector<vector<long long int>> &dp){"
},
{
"code": null,
"e": 8421,
"s": 8396,
"text": " if(i>j)return 0;"
},
{
"code": null,
"e": 8456,
"s": 8430,
"text": " if(i==j)return 1;"
},
{
"code": null,
"e": 8506,
"s": 8465,
"text": " if(dp[i][j]!=-1)return dp[i][j];"
},
{
"code": null,
"e": 8544,
"s": 8515,
"text": " long long int ans=0;"
},
{
"code": null,
"e": 8581,
"s": 8553,
"text": " if(str[i]==str[j]){"
},
{
"code": null,
"e": 8636,
"s": 8581,
"text": " ans=1+go(i+1,j,str,dp)+go(i,j-1,str,dp)%M;"
},
{
"code": null,
"e": 8646,
"s": 8636,
"text": " }"
},
{
"code": null,
"e": 8660,
"s": 8646,
"text": " else{"
},
{
"code": null,
"e": 8730,
"s": 8660,
"text": " ans=go(i+1,j,str,dp)+go(i,j-1,str,dp)-go(i+1,j-1,str,dp);"
},
{
"code": null,
"e": 8740,
"s": 8730,
"text": " }"
},
{
"code": null,
"e": 8769,
"s": 8740,
"text": " return dp[i][j]=ans;"
},
{
"code": null,
"e": 8775,
"s": 8769,
"text": " }"
},
{
"code": null,
"e": 8818,
"s": 8780,
"text": " long long int countPS(string str)"
},
{
"code": null,
"e": 8824,
"s": 8818,
"text": " {"
},
{
"code": null,
"e": 8850,
"s": 8824,
"text": " int n=str.size();"
},
{
"code": null,
"e": 8927,
"s": 8850,
"text": " vector<vector<long long int>> dp(n+1,vector<long long int>(n+1,-1));"
},
{
"code": null,
"e": 8962,
"s": 8927,
"text": " return go(0,n-1,str,dp)%M;"
},
{
"code": null,
"e": 8964,
"s": 8962,
"text": "}"
},
{
"code": null,
"e": 9110,
"s": 8964,
"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": 9146,
"s": 9110,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9156,
"s": 9146,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9166,
"s": 9156,
"text": "\nContest\n"
},
{
"code": null,
"e": 9229,
"s": 9166,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9377,
"s": 9229,
"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": 9585,
"s": 9377,
"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": 9691,
"s": 9585,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Can we insert values without mentioning the column name in MySQL? | Yes, we can insert values without mentioning the column name using the following syntax −
insert into yourTableName values(yourValue1,yourValue2,yourValue3,.....N);
Let us first create a table. Here, we have set Id as NOT NULL −
mysql> create table DemoTable862(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(100) ,
Age int
);
Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable862 values(NULL,'Chris',23);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable862 values(NULL,'Robert',21);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable862 values(NULL,'Mike',24);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable862 values(NULL,'Sam',25);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable862 values(NULL,'Bob',26);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable862;
This will produce the following output. Above, we have set NULL while inserting the values. Since we have set Id as NOT NULL, therefore those NULL values won’t work for Id column and the auto_increment will automatically add values for Id −
+----+-----------+------+
| Id | FirstName | Age |
+----+-----------+------+
| 1 | Chris | 23 |
| 2 | Robert | 21 |
| 3 | Mike | 24 |
| 4 | Sam | 25 |
| 5 | Bob | 26 |
+----+-----------+------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Yes, we can insert values without mentioning the column name using the following syntax −"
},
{
"code": null,
"e": 1227,
"s": 1152,
"text": "insert into yourTableName values(yourValue1,yourValue2,yourValue3,.....N);"
},
{
"code": null,
"e": 1291,
"s": 1227,
"text": "Let us first create a table. Here, we have set Id as NOT NULL −"
},
{
"code": null,
"e": 1451,
"s": 1291,
"text": "mysql> create table DemoTable862(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FirstName varchar(100) ,\n Age int\n);\nQuery OK, 0 rows affected (0.68 sec)"
},
{
"code": null,
"e": 1507,
"s": 1451,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1968,
"s": 1507,
"text": "mysql> insert into DemoTable862 values(NULL,'Chris',23);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable862 values(NULL,'Robert',21);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable862 values(NULL,'Mike',24);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable862 values(NULL,'Sam',25);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable862 values(NULL,'Bob',26);\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 2028,
"s": 1968,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2062,
"s": 2028,
"text": "mysql> select *from DemoTable862;"
},
{
"code": null,
"e": 2303,
"s": 2062,
"text": "This will produce the following output. Above, we have set NULL while inserting the values. Since we have set Id as NOT NULL, therefore those NULL values won’t work for Id column and the auto_increment will automatically add values for Id −"
},
{
"code": null,
"e": 2562,
"s": 2303,
"text": "+----+-----------+------+\n| Id | FirstName | Age |\n+----+-----------+------+\n| 1 | Chris | 23 |\n| 2 | Robert | 21 |\n| 3 | Mike | 24 |\n| 4 | Sam | 25 |\n| 5 | Bob | 26 |\n+----+-----------+------+\n5 rows in set (0.00 sec)"
}
] |
From Scikit-learn to TensorFlow: Part 2 | by Karthik M Swamy | Towards Data Science | Continuing from where we left, we delve deeper into how to develop machine learning (ML) algorithms using TensorFlow from a scikit-learn developer’s perspective. If you’d like to know the reasons to move to TensorFlow, motivations, do read my earlier post for Reasons to move to TensorFlow and a simple classification program that highlights similarities of developing for scikit-learn and TensorFlow.
In the earlier post, we compared the fit and predict paradigm similarities in scikit-learn and TensorFlow. In this post, I want to show we can develop a TensorFlow classification framework with Scikit-learn’s data processing and reporting tools. This will give a good method to interweave both the frameworks to come up with a neat and concise framework.
Machine learning (ML) problems are pervasive. However, the catch here is that once you start solving problems with ML, every new problem might seem like an ML problem, which is something like the old adage goes:
If all you have is a hammer, everything looks like a nail
There is an important distinction between a person who understands ML and a person who uses ML, which is, when not to use ML to solve a problem. You might not need to use ML if you can easily arrive at the solution with simple rules. For example, you don’t need an ML algorithm to predict all bikes and cars are modes of transport or to replace commonly misspelt words with the right spelling.
We will require ML if the rules become unwieldy and if there are too many parameters to determine such rules. For example, we will require ML to predict tomorrow’s weather as it depends on a number of factors such as season, location, other factors such as El Niño which makes writing rules difficult and often inaccurate. Another instance when we might need ML is when the data becomes humanly impossible to peruse and find patterns, which is an area ML seems to do a good job. Take the email spam or ham example, where we classify email as spam or not, based on the text present in the email (body + subject). This task is easy if the patterns for spammy emails were finite and possibly limited. However, the “princes” who send such emails tend to find new methods to make us all “rich”, making it necessary for us to develop ML frameworks to help us fight spam.
Having said all this, let’s take a look at a problem which is inherently difficult to find rules and a tough problem to get high precision and recall.
We will be using the Wisconsin Diagnostic Data for Breast Cancer detecting presence of cancer. This dataset is a binary classification problem (malignant or benign) and has 569 instances (data points) that allow us to perform the classification task.
All the code described in this post is available in my GitHub repo here.
We leverage Scikit-learn’s efficient data loading tools to obtain our data. The breast cancer dataset is available here. A list of other datasets that Scikit-learn allows us to load can be found here. Let us load the dataset and view some attributes of the data.
from sklearn.datasets import load_breast_cancercancer_data = load_breast_cancer()print("Number of instances in the dataset: %d" % len(cancer_data.target))>> Number of instances in the dataset: 569
Let’s discuss the impact of using the data as-is versus scaling the features prior to training the data. Scaling the data allows the features to be normalised. What this means is that data is centred around zero and scaled to have a standard deviation of one. In other words, we restrict the data to fall between [0, 1] without changing the original distribution of the data. This ensures that the classifier is not going to wildly search a large dimensional space for the optimal weights and instead restricts the search space between [0, 1]. This scaling has a big impact on how well a classifier performs and this can be seen in the experiments section below. We try two experiments, one with feature scaling and another without feature scaling.
We use the data from SKLearn as-is, simply loading variables using the in-built train, test splitter
from sklearn.model_selection import train_test_splitin_train, in_test, out_train, out_test = train_test_split(cancer_data[‘data’], cancer_data[‘target’])
For the second experiment, we scale the data using pre-processing functions available in SKLearn.
from sklearn.preprocessing import StandardScalerdata_scaler = StandardScaler()# Fit train data data_scaler.fit(in_train)in_train = data_scaler.transform(in_train)in_test = data_scaler.transform(in_test)
We design a neural network similar to my earlier post to keep a simple approach to the network and instead understand the effects of data pre-processing and overfitting. We use TensorFlow’s DNNClassifier which is available in the contrib module of TensorFlow. We define a network with three layers where each layer has <units> number of hidden units. In our experiments, we first evaluate performance of the network below by changing how the inputs are pre-processed, with a units=50. The best performing input is then chosen to experiment further to understand overfitting where we keep the data constant (best among D1 vs. D2) and vary units. The network structure is described below:
feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(in_train)classifier_tf = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[units, units, units], n_classes=2)classifier_tf.fit(in_train, out_train, steps=1000)
What the network above does is define a fully-connect network also known as a multi-layer perceptron with the input from the data we just loaded. A multi-layer perceptron can be described as below:
The input in our case is the data we loaded from the cancer dataset while the output is a binary value indicating if the input is malignant or benign.
The aim of these two experiments is to understand the impact of the number of hidden units on each layer which will also provide insight into overfitting.
For this experiment, we first run to choose either D1 or D2 (described above) and then vary the number of hidden units on each layer of the network. The number of hidden units for this experiment is kept low at H1=10.
We perform our fourth experiment with a larger number of hidden units than H1. This would be able to accommodate more variations in the data but might end up memorising the data and hence unable to perform well on test data. We run the experiment similar to H1 above and then run the network with H2=50.
We use Scikit-learn’s reporting functionality to understand how our classifier performed. We use the classification report and the confusion matrix to understand how our classifier performed.
The classification report produces a matrix with key metrics calculated using the predicted output and the actual output values. The metrics reported are precision, recall and f1-scores for each class as well as the average across all classes.
report = metrics.classification_report(out_test, predictions, target_names=cancer_data.target_names)print(report)
While the classification report provides key metrics, the confusion matrix provides the class in which each test data point was classified under. The confusion matrix shows how strong the classifier is in making a prediction for a class while at the same time, shows the vulnerabilities of the classifier in classifying the data under other classes.
# Plotting the confusion matrix using matplotlib%matplotlib inlineconfusion = metrics.confusion_matrix(out_test, predictions)# Plot non-normalized confusion matrixplt.figure()plot_confusion_matrix(confusion, classes=cancer_data.target_names, title=’Confusion matrix, without normalization’)
The classification report describes a holistic performance while the confusion matrix provides an exact number of data points classified under each class.
We first perform the experiment to understand if data normalisation helps with better classification. Hence, we choose H1 and experiment with D1 and D2. The results are provided below:
Performance with H1+D1
precision recall f1-score support malignant 0.94 0.88 0.91 51 benign 0.94 0.97 0.95 92avg / total 0.94 0.94 0.94 143Prediction Accuracy: 0.937063
Performance with H1+D2
precision recall f1-score support malignant 0.96 0.93 0.95 46 benign 0.97 0.98 0.97 97avg / total 0.96 0.97 0.96 143Prediction Accuracy: 0.965035
From our experiments, it is evident that data scaling provides a ~3% improvement in classification accuracy. This lets us choose D2 (data with scaling) for our experiments with H2.
Performance with H2+D2
precision recall f1-score support malignant 0.96 0.92 0.94 53 benign 0.96 0.98 0.97 90avg / total 0.96 0.96 0.96 143Prediction Accuracy: 0.958042
The performance metrics of H1+D2 and H2+D2 does not provide much insight into how the classifier performed across other classes in terms of number of data points. This is where the confusion matrix provides a better picture for further analysis.
The above matrices provide a clearer picture of the differences in the performance of the classifiers H1 and H2. Although H2 has five times more hidden units than H1, it performed poorer than H1 on the test data. The confusion matrix provides an exact distribution of the number of points that were incorrectly classified under each category.
In this post, we saw how to use Scikit-learn with TensorFlow to perform different classification experiments and view the performances of each of the classifier. We also performed simple experiments with data pre-processing and the network parameters to understand different concepts.
All the code described in this post is available in my GitHub repo here.
Let me know what topics you’d like me to discuss in my next post, as comments below. I’m on Twitter, in case you’d like to connect with me there! | [
{
"code": null,
"e": 573,
"s": 171,
"text": "Continuing from where we left, we delve deeper into how to develop machine learning (ML) algorithms using TensorFlow from a scikit-learn developer’s perspective. If you’d like to know the reasons to move to TensorFlow, motivations, do read my earlier post for Reasons to move to TensorFlow and a simple classification program that highlights similarities of developing for scikit-learn and TensorFlow."
},
{
"code": null,
"e": 928,
"s": 573,
"text": "In the earlier post, we compared the fit and predict paradigm similarities in scikit-learn and TensorFlow. In this post, I want to show we can develop a TensorFlow classification framework with Scikit-learn’s data processing and reporting tools. This will give a good method to interweave both the frameworks to come up with a neat and concise framework."
},
{
"code": null,
"e": 1140,
"s": 928,
"text": "Machine learning (ML) problems are pervasive. However, the catch here is that once you start solving problems with ML, every new problem might seem like an ML problem, which is something like the old adage goes:"
},
{
"code": null,
"e": 1198,
"s": 1140,
"text": "If all you have is a hammer, everything looks like a nail"
},
{
"code": null,
"e": 1592,
"s": 1198,
"text": "There is an important distinction between a person who understands ML and a person who uses ML, which is, when not to use ML to solve a problem. You might not need to use ML if you can easily arrive at the solution with simple rules. For example, you don’t need an ML algorithm to predict all bikes and cars are modes of transport or to replace commonly misspelt words with the right spelling."
},
{
"code": null,
"e": 2458,
"s": 1592,
"text": "We will require ML if the rules become unwieldy and if there are too many parameters to determine such rules. For example, we will require ML to predict tomorrow’s weather as it depends on a number of factors such as season, location, other factors such as El Niño which makes writing rules difficult and often inaccurate. Another instance when we might need ML is when the data becomes humanly impossible to peruse and find patterns, which is an area ML seems to do a good job. Take the email spam or ham example, where we classify email as spam or not, based on the text present in the email (body + subject). This task is easy if the patterns for spammy emails were finite and possibly limited. However, the “princes” who send such emails tend to find new methods to make us all “rich”, making it necessary for us to develop ML frameworks to help us fight spam."
},
{
"code": null,
"e": 2609,
"s": 2458,
"text": "Having said all this, let’s take a look at a problem which is inherently difficult to find rules and a tough problem to get high precision and recall."
},
{
"code": null,
"e": 2860,
"s": 2609,
"text": "We will be using the Wisconsin Diagnostic Data for Breast Cancer detecting presence of cancer. This dataset is a binary classification problem (malignant or benign) and has 569 instances (data points) that allow us to perform the classification task."
},
{
"code": null,
"e": 2933,
"s": 2860,
"text": "All the code described in this post is available in my GitHub repo here."
},
{
"code": null,
"e": 3196,
"s": 2933,
"text": "We leverage Scikit-learn’s efficient data loading tools to obtain our data. The breast cancer dataset is available here. A list of other datasets that Scikit-learn allows us to load can be found here. Let us load the dataset and view some attributes of the data."
},
{
"code": null,
"e": 3393,
"s": 3196,
"text": "from sklearn.datasets import load_breast_cancercancer_data = load_breast_cancer()print(\"Number of instances in the dataset: %d\" % len(cancer_data.target))>> Number of instances in the dataset: 569"
},
{
"code": null,
"e": 4142,
"s": 3393,
"text": "Let’s discuss the impact of using the data as-is versus scaling the features prior to training the data. Scaling the data allows the features to be normalised. What this means is that data is centred around zero and scaled to have a standard deviation of one. In other words, we restrict the data to fall between [0, 1] without changing the original distribution of the data. This ensures that the classifier is not going to wildly search a large dimensional space for the optimal weights and instead restricts the search space between [0, 1]. This scaling has a big impact on how well a classifier performs and this can be seen in the experiments section below. We try two experiments, one with feature scaling and another without feature scaling."
},
{
"code": null,
"e": 4243,
"s": 4142,
"text": "We use the data from SKLearn as-is, simply loading variables using the in-built train, test splitter"
},
{
"code": null,
"e": 4398,
"s": 4243,
"text": "from sklearn.model_selection import train_test_splitin_train, in_test, out_train, out_test = train_test_split(cancer_data[‘data’], cancer_data[‘target’])"
},
{
"code": null,
"e": 4496,
"s": 4398,
"text": "For the second experiment, we scale the data using pre-processing functions available in SKLearn."
},
{
"code": null,
"e": 4699,
"s": 4496,
"text": "from sklearn.preprocessing import StandardScalerdata_scaler = StandardScaler()# Fit train data data_scaler.fit(in_train)in_train = data_scaler.transform(in_train)in_test = data_scaler.transform(in_test)"
},
{
"code": null,
"e": 5386,
"s": 4699,
"text": "We design a neural network similar to my earlier post to keep a simple approach to the network and instead understand the effects of data pre-processing and overfitting. We use TensorFlow’s DNNClassifier which is available in the contrib module of TensorFlow. We define a network with three layers where each layer has <units> number of hidden units. In our experiments, we first evaluate performance of the network below by changing how the inputs are pre-processed, with a units=50. The best performing input is then chosen to experiment further to understand overfitting where we keep the data constant (best among D1 vs. D2) and vary units. The network structure is described below:"
},
{
"code": null,
"e": 5648,
"s": 5386,
"text": "feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(in_train)classifier_tf = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[units, units, units], n_classes=2)classifier_tf.fit(in_train, out_train, steps=1000)"
},
{
"code": null,
"e": 5846,
"s": 5648,
"text": "What the network above does is define a fully-connect network also known as a multi-layer perceptron with the input from the data we just loaded. A multi-layer perceptron can be described as below:"
},
{
"code": null,
"e": 5997,
"s": 5846,
"text": "The input in our case is the data we loaded from the cancer dataset while the output is a binary value indicating if the input is malignant or benign."
},
{
"code": null,
"e": 6152,
"s": 5997,
"text": "The aim of these two experiments is to understand the impact of the number of hidden units on each layer which will also provide insight into overfitting."
},
{
"code": null,
"e": 6370,
"s": 6152,
"text": "For this experiment, we first run to choose either D1 or D2 (described above) and then vary the number of hidden units on each layer of the network. The number of hidden units for this experiment is kept low at H1=10."
},
{
"code": null,
"e": 6674,
"s": 6370,
"text": "We perform our fourth experiment with a larger number of hidden units than H1. This would be able to accommodate more variations in the data but might end up memorising the data and hence unable to perform well on test data. We run the experiment similar to H1 above and then run the network with H2=50."
},
{
"code": null,
"e": 6866,
"s": 6674,
"text": "We use Scikit-learn’s reporting functionality to understand how our classifier performed. We use the classification report and the confusion matrix to understand how our classifier performed."
},
{
"code": null,
"e": 7110,
"s": 6866,
"text": "The classification report produces a matrix with key metrics calculated using the predicted output and the actual output values. The metrics reported are precision, recall and f1-scores for each class as well as the average across all classes."
},
{
"code": null,
"e": 7225,
"s": 7110,
"text": "report = metrics.classification_report(out_test, predictions, target_names=cancer_data.target_names)print(report)"
},
{
"code": null,
"e": 7575,
"s": 7225,
"text": "While the classification report provides key metrics, the confusion matrix provides the class in which each test data point was classified under. The confusion matrix shows how strong the classifier is in making a prediction for a class while at the same time, shows the vulnerabilities of the classifier in classifying the data under other classes."
},
{
"code": null,
"e": 7866,
"s": 7575,
"text": "# Plotting the confusion matrix using matplotlib%matplotlib inlineconfusion = metrics.confusion_matrix(out_test, predictions)# Plot non-normalized confusion matrixplt.figure()plot_confusion_matrix(confusion, classes=cancer_data.target_names, title=’Confusion matrix, without normalization’)"
},
{
"code": null,
"e": 8021,
"s": 7866,
"text": "The classification report describes a holistic performance while the confusion matrix provides an exact number of data points classified under each class."
},
{
"code": null,
"e": 8206,
"s": 8021,
"text": "We first perform the experiment to understand if data normalisation helps with better classification. Hence, we choose H1 and experiment with D1 and D2. The results are provided below:"
},
{
"code": null,
"e": 8229,
"s": 8206,
"text": "Performance with H1+D1"
},
{
"code": null,
"e": 8468,
"s": 8229,
"text": " precision recall f1-score support malignant 0.94 0.88 0.91 51 benign 0.94 0.97 0.95 92avg / total 0.94 0.94 0.94 143Prediction Accuracy: 0.937063"
},
{
"code": null,
"e": 8491,
"s": 8468,
"text": "Performance with H1+D2"
},
{
"code": null,
"e": 8730,
"s": 8491,
"text": " precision recall f1-score support malignant 0.96 0.93 0.95 46 benign 0.97 0.98 0.97 97avg / total 0.96 0.97 0.96 143Prediction Accuracy: 0.965035"
},
{
"code": null,
"e": 8911,
"s": 8730,
"text": "From our experiments, it is evident that data scaling provides a ~3% improvement in classification accuracy. This lets us choose D2 (data with scaling) for our experiments with H2."
},
{
"code": null,
"e": 8934,
"s": 8911,
"text": "Performance with H2+D2"
},
{
"code": null,
"e": 9173,
"s": 8934,
"text": " precision recall f1-score support malignant 0.96 0.92 0.94 53 benign 0.96 0.98 0.97 90avg / total 0.96 0.96 0.96 143Prediction Accuracy: 0.958042"
},
{
"code": null,
"e": 9419,
"s": 9173,
"text": "The performance metrics of H1+D2 and H2+D2 does not provide much insight into how the classifier performed across other classes in terms of number of data points. This is where the confusion matrix provides a better picture for further analysis."
},
{
"code": null,
"e": 9762,
"s": 9419,
"text": "The above matrices provide a clearer picture of the differences in the performance of the classifiers H1 and H2. Although H2 has five times more hidden units than H1, it performed poorer than H1 on the test data. The confusion matrix provides an exact distribution of the number of points that were incorrectly classified under each category."
},
{
"code": null,
"e": 10047,
"s": 9762,
"text": "In this post, we saw how to use Scikit-learn with TensorFlow to perform different classification experiments and view the performances of each of the classifier. We also performed simple experiments with data pre-processing and the network parameters to understand different concepts."
},
{
"code": null,
"e": 10120,
"s": 10047,
"text": "All the code described in this post is available in my GitHub repo here."
}
] |
Minimize deviation of an array by given operations - GeeksforGeeks | 09 Jun, 2021
Given an array A[] consisting of positive integers, the task is to calculate the minimum possible deviation of the given arrayA[] after performing the following operations any number of times:
Operation 1: If the array element is even, divide it by 2.
Operation 2: If the array element is odd, multiply it by 2.
The deviation of the array A[] is the difference between the maximum and minimum element present in the array A[].
Examples:
Input: A[] = {4, 1, 5, 20, 3}Output: 3Explanation: Array modifies to {4, 2, 5, 5, 3} after performing given operations. Therefore, deviation = 5 – 2 = 3.
Input: A[] = {1, 2, 3, 4}Output: 1Explanation: Array modifies to after two operations to {2, 2, 3, 2}. Therefore, deviation = 3 – 2 = 1.
Approach: The problem can be solved based on the following observations:
Even numbers can be divided multiple times until it converts to an odd number.
Odd numbers can be doubled only once as it converts to an even number.
Therefore, even numbers can never be increased.
Follow the steps below to solve the problem:
Traverse the array and double all the odd array elements. This nullifies the requirement for the 2nd operation.
Now, decrease the largest array element while it’s even.
To store the array elements in sorted manner, insert all array elements into a Set.
Greedily reduce the maximum element present in the Set
If the maximum element present in the Set is odd, break the loop.
Print the minimum deviation obtained.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum// deviation of the array A[]void minimumDeviation(int A[], int N){ // Store all array elements // in sorted order set<int> s; for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.insert(A[i]); // Odd number are transformed // using 2nd operation else s.insert(2 * A[i]); } // (Maximum - Minimum) int diff = *s.rbegin() - *s.begin(); // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((int)s.size() && *s.rbegin() % 2 == 0) { // Maximum element of the set int maxEl = *s.rbegin(); // Erase the maximum element s.erase(maxEl); // Using operation 1 s.insert(maxEl / 2); // (Maximum - Minimum) diff = min(diff, *s.rbegin() - *s.begin()); } // Print the Minimum // Deviation Obtained cout << diff;} // Driver Codeint main(){ int A[] = { 4, 1, 5, 20, 3 }; int N = sizeof(A) / sizeof(A[0]); // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N); return 0;}
// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to find the minimum// deviation of the array A[]static void minimumDeviation(int A[], int N){ // Store all array elements // in sorted order TreeSet<Integer> s = new TreeSet<Integer>(); for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.add(A[i]); // Odd number are transformed // using 2nd operation else s.add(2 * A[i]); } // (Maximum - Minimum) int diff = s.last() - s.first() ; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((s.last() % 2 == 0)) { // Maximum element of the set int maxEl = s.last(); // Erase the maximum element s.remove(maxEl); // Using operation 1 s.add(maxEl / 2); // (Maximum - Minimum) diff = Math.min(diff, s.last() - s.first()); } // Print the Minimum // Deviation Obtained System.out.print(diff);} // Driver codepublic static void main(String[] args){ int A[] = { 4, 1, 5, 20, 3 }; int N = A.length; // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N);}} // This code is contributed by susmitakundugoaldanga.
# Python 3 implementation of the# above approach # Function to find the minimum# deviation of the array A[]def minimumDeviation(A, N): # Store all array elements # in sorted order s = set([]) for i in range(N): if (A[i] % 2 == 0): s.add(A[i]) # Odd number are transformed # using 2nd operation else: s.add(2 * A[i]) # (Maximum - Minimum) s = list(s) diff = s[-1] - s[0] # Check if the size of set is > 0 and # the maximum element is divisible by 2 while (len(s) and s[-1] % 2 == 0): # Maximum element of the set maxEl = s[-1] # Erase the maximum element s.remove(maxEl) # Using operation 1 s.append(maxEl // 2) # (Maximum - Minimum) diff = min(diff, s[-1] - s[0]) # Print the Minimum # Deviation Obtained print(diff) # Driver Codeif __name__ == "__main__": A = [4, 1, 5, 20, 3] N = len(A) # Function Call to find # Minimum Deviation of A[] minimumDeviation(A, N) # This code is contributed by chitranayal.
// C# implementation of the// above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the minimum // deviation of the array A[] static void minimumDeviation(int[] A, int N) { // Store all array elements // in sorted order HashSet<int> s = new HashSet<int>(); for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.Add(A[i]); // Odd number are transformed // using 2nd operation else s.Add(2 * A[i]); } List<int> S = s.ToList(); S.Sort(); // (Maximum - Minimum) int diff = S[S.Count - 1] - S[0]; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((int)S.Count != 0 && S[S.Count - 1] % 2 == 0) { // Maximum element of the set int maxEl = S[S.Count - 1]; // Erase the maximum element S.RemoveAt(S.Count - 1); // Using operation 1 S.Add(maxEl / 2); S.Sort(); // (Maximum - Minimum) diff = Math.Min(diff, S[S.Count - 1] - S[0]); } // Print the Minimum // Deviation Obtained Console.Write(diff); } // Driver code static void Main() { int[] A = { 4, 1, 5, 20, 3 }; int N = A.Length; // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N); }} // This code is contributed by divyeshrabadiya07.
<script> // JavaScript implementation of the// above approach // Function to find the minimum// deviation of the array A[]function minimumDeviation(A, N){ // Store all array elements // in sorted order var s = new Set(); for (var i = 0; i < N; i++) { if (A[i] % 2 == 0) s.add(A[i]); // Odd number are transformed // using 2nd operation else s.add(2 * A[i]); } var tmp = [...s].sort((a,b)=>a-b); // (Maximum - Minimum) var diff = tmp[tmp.length-1] - tmp[0]; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while (s.size && tmp[tmp.length-1] % 2 == 0) { // Maximum element of the set var maxEl = tmp[tmp.length-1]; // Erase the maximum element s.delete(maxEl); // Using operation 1 s.add(parseInt(maxEl / 2)); tmp = [...s].sort((a,b)=>a-b); // (Maximum - Minimum) diff = Math.min(diff, tmp[tmp.length-1] - tmp[0]); } // Print the Minimum // Deviation Obtained document.write( diff);} // Driver Code var A = [4, 1, 5, 20, 3];var N = A.length; // Function Call to find// Minimum Deviation of A[]minimumDeviation(A, N); </script>
3
Time Complexity : O(N * log(N))Auxiliary Space : O(N)
ukasp
susmitakundugoaldanga
divyeshrabadiya07
rrrtnx
cpp-set
loop
statistical-algorithms
Arrays
Greedy
Hash
Mathematical
Arrays
Hash
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 25687,
"s": 25659,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 25880,
"s": 25687,
"text": "Given an array A[] consisting of positive integers, the task is to calculate the minimum possible deviation of the given arrayA[] after performing the following operations any number of times:"
},
{
"code": null,
"e": 25939,
"s": 25880,
"text": "Operation 1: If the array element is even, divide it by 2."
},
{
"code": null,
"e": 25999,
"s": 25939,
"text": "Operation 2: If the array element is odd, multiply it by 2."
},
{
"code": null,
"e": 26114,
"s": 25999,
"text": "The deviation of the array A[] is the difference between the maximum and minimum element present in the array A[]."
},
{
"code": null,
"e": 26124,
"s": 26114,
"text": "Examples:"
},
{
"code": null,
"e": 26278,
"s": 26124,
"text": "Input: A[] = {4, 1, 5, 20, 3}Output: 3Explanation: Array modifies to {4, 2, 5, 5, 3} after performing given operations. Therefore, deviation = 5 – 2 = 3."
},
{
"code": null,
"e": 26415,
"s": 26278,
"text": "Input: A[] = {1, 2, 3, 4}Output: 1Explanation: Array modifies to after two operations to {2, 2, 3, 2}. Therefore, deviation = 3 – 2 = 1."
},
{
"code": null,
"e": 26488,
"s": 26415,
"text": "Approach: The problem can be solved based on the following observations:"
},
{
"code": null,
"e": 26567,
"s": 26488,
"text": "Even numbers can be divided multiple times until it converts to an odd number."
},
{
"code": null,
"e": 26638,
"s": 26567,
"text": "Odd numbers can be doubled only once as it converts to an even number."
},
{
"code": null,
"e": 26686,
"s": 26638,
"text": "Therefore, even numbers can never be increased."
},
{
"code": null,
"e": 26733,
"s": 26686,
"text": "Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 26845,
"s": 26733,
"text": "Traverse the array and double all the odd array elements. This nullifies the requirement for the 2nd operation."
},
{
"code": null,
"e": 26902,
"s": 26845,
"text": "Now, decrease the largest array element while it’s even."
},
{
"code": null,
"e": 26986,
"s": 26902,
"text": "To store the array elements in sorted manner, insert all array elements into a Set."
},
{
"code": null,
"e": 27041,
"s": 26986,
"text": "Greedily reduce the maximum element present in the Set"
},
{
"code": null,
"e": 27107,
"s": 27041,
"text": "If the maximum element present in the Set is odd, break the loop."
},
{
"code": null,
"e": 27145,
"s": 27107,
"text": "Print the minimum deviation obtained."
},
{
"code": null,
"e": 27192,
"s": 27145,
"text": "Below is the implementation of above approach:"
},
{
"code": null,
"e": 27196,
"s": 27192,
"text": "C++"
},
{
"code": null,
"e": 27201,
"s": 27196,
"text": "Java"
},
{
"code": null,
"e": 27209,
"s": 27201,
"text": "Python3"
},
{
"code": null,
"e": 27212,
"s": 27209,
"text": "C#"
},
{
"code": null,
"e": 27223,
"s": 27212,
"text": "Javascript"
},
{
"code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum// deviation of the array A[]void minimumDeviation(int A[], int N){ // Store all array elements // in sorted order set<int> s; for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.insert(A[i]); // Odd number are transformed // using 2nd operation else s.insert(2 * A[i]); } // (Maximum - Minimum) int diff = *s.rbegin() - *s.begin(); // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((int)s.size() && *s.rbegin() % 2 == 0) { // Maximum element of the set int maxEl = *s.rbegin(); // Erase the maximum element s.erase(maxEl); // Using operation 1 s.insert(maxEl / 2); // (Maximum - Minimum) diff = min(diff, *s.rbegin() - *s.begin()); } // Print the Minimum // Deviation Obtained cout << diff;} // Driver Codeint main(){ int A[] = { 4, 1, 5, 20, 3 }; int N = sizeof(A) / sizeof(A[0]); // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N); return 0;}",
"e": 28440,
"s": 27223,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to find the minimum// deviation of the array A[]static void minimumDeviation(int A[], int N){ // Store all array elements // in sorted order TreeSet<Integer> s = new TreeSet<Integer>(); for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.add(A[i]); // Odd number are transformed // using 2nd operation else s.add(2 * A[i]); } // (Maximum - Minimum) int diff = s.last() - s.first() ; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((s.last() % 2 == 0)) { // Maximum element of the set int maxEl = s.last(); // Erase the maximum element s.remove(maxEl); // Using operation 1 s.add(maxEl / 2); // (Maximum - Minimum) diff = Math.min(diff, s.last() - s.first()); } // Print the Minimum // Deviation Obtained System.out.print(diff);} // Driver codepublic static void main(String[] args){ int A[] = { 4, 1, 5, 20, 3 }; int N = A.length; // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N);}} // This code is contributed by susmitakundugoaldanga.",
"e": 29724,
"s": 28440,
"text": null
},
{
"code": "# Python 3 implementation of the# above approach # Function to find the minimum# deviation of the array A[]def minimumDeviation(A, N): # Store all array elements # in sorted order s = set([]) for i in range(N): if (A[i] % 2 == 0): s.add(A[i]) # Odd number are transformed # using 2nd operation else: s.add(2 * A[i]) # (Maximum - Minimum) s = list(s) diff = s[-1] - s[0] # Check if the size of set is > 0 and # the maximum element is divisible by 2 while (len(s) and s[-1] % 2 == 0): # Maximum element of the set maxEl = s[-1] # Erase the maximum element s.remove(maxEl) # Using operation 1 s.append(maxEl // 2) # (Maximum - Minimum) diff = min(diff, s[-1] - s[0]) # Print the Minimum # Deviation Obtained print(diff) # Driver Codeif __name__ == \"__main__\": A = [4, 1, 5, 20, 3] N = len(A) # Function Call to find # Minimum Deviation of A[] minimumDeviation(A, N) # This code is contributed by chitranayal.",
"e": 30806,
"s": 29724,
"text": null
},
{
"code": "// C# implementation of the// above approachusing System;using System.Collections.Generic;using System.Linq;class GFG{ // Function to find the minimum // deviation of the array A[] static void minimumDeviation(int[] A, int N) { // Store all array elements // in sorted order HashSet<int> s = new HashSet<int>(); for (int i = 0; i < N; i++) { if (A[i] % 2 == 0) s.Add(A[i]); // Odd number are transformed // using 2nd operation else s.Add(2 * A[i]); } List<int> S = s.ToList(); S.Sort(); // (Maximum - Minimum) int diff = S[S.Count - 1] - S[0]; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while ((int)S.Count != 0 && S[S.Count - 1] % 2 == 0) { // Maximum element of the set int maxEl = S[S.Count - 1]; // Erase the maximum element S.RemoveAt(S.Count - 1); // Using operation 1 S.Add(maxEl / 2); S.Sort(); // (Maximum - Minimum) diff = Math.Min(diff, S[S.Count - 1] - S[0]); } // Print the Minimum // Deviation Obtained Console.Write(diff); } // Driver code static void Main() { int[] A = { 4, 1, 5, 20, 3 }; int N = A.Length; // Function Call to find // Minimum Deviation of A[] minimumDeviation(A, N); }} // This code is contributed by divyeshrabadiya07.",
"e": 32399,
"s": 30806,
"text": null
},
{
"code": "<script> // JavaScript implementation of the// above approach // Function to find the minimum// deviation of the array A[]function minimumDeviation(A, N){ // Store all array elements // in sorted order var s = new Set(); for (var i = 0; i < N; i++) { if (A[i] % 2 == 0) s.add(A[i]); // Odd number are transformed // using 2nd operation else s.add(2 * A[i]); } var tmp = [...s].sort((a,b)=>a-b); // (Maximum - Minimum) var diff = tmp[tmp.length-1] - tmp[0]; // Check if the size of set is > 0 and // the maximum element is divisible by 2 while (s.size && tmp[tmp.length-1] % 2 == 0) { // Maximum element of the set var maxEl = tmp[tmp.length-1]; // Erase the maximum element s.delete(maxEl); // Using operation 1 s.add(parseInt(maxEl / 2)); tmp = [...s].sort((a,b)=>a-b); // (Maximum - Minimum) diff = Math.min(diff, tmp[tmp.length-1] - tmp[0]); } // Print the Minimum // Deviation Obtained document.write( diff);} // Driver Code var A = [4, 1, 5, 20, 3];var N = A.length; // Function Call to find// Minimum Deviation of A[]minimumDeviation(A, N); </script>",
"e": 33635,
"s": 32399,
"text": null
},
{
"code": null,
"e": 33640,
"s": 33638,
"text": "3"
},
{
"code": null,
"e": 33697,
"s": 33642,
"text": "Time Complexity : O(N * log(N))Auxiliary Space : O(N) "
},
{
"code": null,
"e": 33703,
"s": 33697,
"text": "ukasp"
},
{
"code": null,
"e": 33725,
"s": 33703,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 33743,
"s": 33725,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33750,
"s": 33743,
"text": "rrrtnx"
},
{
"code": null,
"e": 33758,
"s": 33750,
"text": "cpp-set"
},
{
"code": null,
"e": 33763,
"s": 33758,
"text": "loop"
},
{
"code": null,
"e": 33786,
"s": 33763,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 33793,
"s": 33786,
"text": "Arrays"
},
{
"code": null,
"e": 33800,
"s": 33793,
"text": "Greedy"
},
{
"code": null,
"e": 33805,
"s": 33800,
"text": "Hash"
},
{
"code": null,
"e": 33818,
"s": 33805,
"text": "Mathematical"
},
{
"code": null,
"e": 33825,
"s": 33818,
"text": "Arrays"
},
{
"code": null,
"e": 33830,
"s": 33825,
"text": "Hash"
},
{
"code": null,
"e": 33837,
"s": 33830,
"text": "Greedy"
},
{
"code": null,
"e": 33850,
"s": 33837,
"text": "Mathematical"
},
{
"code": null,
"e": 33948,
"s": 33850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33957,
"s": 33948,
"text": "Comments"
},
{
"code": null,
"e": 33970,
"s": 33957,
"text": "Old Comments"
},
{
"code": null,
"e": 34018,
"s": 33970,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34050,
"s": 34018,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34104,
"s": 34050,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 34118,
"s": 34104,
"text": "Linear Search"
},
{
"code": null,
"e": 34163,
"s": 34118,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 34214,
"s": 34163,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 34265,
"s": 34214,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 34323,
"s": 34265,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 34383,
"s": 34323,
"text": "Write a program to print all permutations of a given string"
}
] |
Cubic spline Interpolation - GeeksforGeeks | 18 Jul, 2021
We estimate f(x) for arbitrary x, by drawing a smooth curve through the xi. If the desired x is between the largest and smallest of the xi then it is called interpolation, otherwise, it is called Extrapolation.
Random points
Linear Interpolation is a way of curve fitting the points by using linear polynomial such as the equation of the line. This is just similar to joining points by drawing a line b/w the two points in the dataset.
Linear Interpolation
Polynomial Interpolation is the way of fitting the curve by creating a higher degree polynomial to join those points.
Spline interpolation similar to the Polynomial interpolation x’ uses low-degree polynomials in each of the intervals and chooses the polynomial pieces such that they fit smoothly together. The resulting function is called a spline.
Cubic spline interpolation is a way of finding a curve that connects data points with a degree of three or less. Splines are polynomial that are smooth and continuous across a given plot and also continuous first and second derivatives where they join.
We take a set of points [xi, yi] for i = 0, 1, ..., n for the function y = f(x). The cubic spline interpolation is a piecewise continuous curve, passing through each of the values in the table.
Following are the conditions for the spline of degree K=3:The domain of s is in intervals of [a, b].S, S’, S” are all continuous function on [a, b].
The domain of s is in intervals of [a, b].
S, S’, S” are all continuous function on [a, b].
Here Si(x) is the cubic polynomial that will be used on the subinterval [xi, xi+1].
The main factor about spline is that it combines different polynomials and not use a single polynomial of degree n to fit all the points at once, it avoids high degree polynomials and thereby the potential problem of overfitting. These low-degree polynomials need to be such that the spline they form is not only continuous but also smooth.
But for the spline to be smooth and continuous, the two consecutive polynomials and Si (x) and Si+1 (x) must join at xi.
Or, Si (x) must be passed through two end-points:
Assume, S” (x) = Mi (i= 0,1,2, ..., n). Since S(x) is cubic polynomial, so S” (x) is the linear polynomial in [xi, xi+1], then S”’ (x) will be:
By applying the Taylor series:
Let, x = xi+1:
Similarly, we apply above equation b/w range [xi-1, xi]:
Let hi =xi – xi-1
Now, we have n-1 equations, but have n+1 variables i.e M0, M1, M2,...Mn-1, Mn. Therefore, we need to get 2 more equation. For that, we will be using additional boundary conditions.
Let’s consider that we know S’ (x0) = f0‘ and S’ (xn) = fn‘, especially if S’ (x0) and S’ (xn) both are 0. This is called the clamped boundary condition.
Similarly, for Mn
or
Combining the above equation in to the matrix form, we get the following matrix:
We will be using the Scipy to perform the linear spline interpolation. We will be using Cubic Spline and interp1d function of scipy to perform interpolation of function f(x) =1/(1+x^2).
Python3
#importsimport matplotlib.pyplot as pltimport numpy as npfrom scipy.interpolate import CubicSpline, interp1dplt.rcParams['figure.figsize'] =(12,8) x = np.arange(-10,10)y = 1/(1+x**2)# apply cubic spline interpolationcs = CubicSpline(x, y)# Apply Linear interpolationlinear_int = interp1d(x,y) xs = np.arange(-10, 10)ys = linear_int(xs) # plot linear interpolationplt.plot(x, y, 'o', label='data')plt.plot(xs,ys, label="S", color='green')plt.legend(loc='upper right', ncol=2)plt.title('Linear Interpolation')plt.show() # plot cubic spline interpolationplt.plot(x, y, 'o', label='data')plt.plot(xs, 1/(1+(xs**2)), label='true')plt.plot(xs, cs(xs), label="S")plt.plot(xs, cs(xs, 1), label="S'")plt.plot(xs, cs(xs, 2), label="S''")plt.plot(xs, cs(xs, 3), label="S'''")plt.ylim(-1.5, 1.5)plt.legend(loc='upper right', ncol=2)plt.title('Cubic Spline Interpolation')plt.show()
Linear Interpolation
Cubic Spline interpolation
Wikidiversity Cubic Spline Interpolation
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
ML | Stochastic Gradient Descent (SGD)
Intuition of Adam Optimizer
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
CNN | Introduction to Pooling Layer | [
{
"code": null,
"e": 24264,
"s": 24236,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24475,
"s": 24264,
"text": "We estimate f(x) for arbitrary x, by drawing a smooth curve through the xi. If the desired x is between the largest and smallest of the xi then it is called interpolation, otherwise, it is called Extrapolation."
},
{
"code": null,
"e": 24489,
"s": 24475,
"text": "Random points"
},
{
"code": null,
"e": 24700,
"s": 24489,
"text": "Linear Interpolation is a way of curve fitting the points by using linear polynomial such as the equation of the line. This is just similar to joining points by drawing a line b/w the two points in the dataset."
},
{
"code": null,
"e": 24721,
"s": 24700,
"text": "Linear Interpolation"
},
{
"code": null,
"e": 24839,
"s": 24721,
"text": "Polynomial Interpolation is the way of fitting the curve by creating a higher degree polynomial to join those points."
},
{
"code": null,
"e": 25071,
"s": 24839,
"text": "Spline interpolation similar to the Polynomial interpolation x’ uses low-degree polynomials in each of the intervals and chooses the polynomial pieces such that they fit smoothly together. The resulting function is called a spline."
},
{
"code": null,
"e": 25324,
"s": 25071,
"text": "Cubic spline interpolation is a way of finding a curve that connects data points with a degree of three or less. Splines are polynomial that are smooth and continuous across a given plot and also continuous first and second derivatives where they join."
},
{
"code": null,
"e": 25519,
"s": 25324,
"text": "We take a set of points [xi, yi] for i = 0, 1, ..., n for the function y = f(x). The cubic spline interpolation is a piecewise continuous curve, passing through each of the values in the table. "
},
{
"code": null,
"e": 25668,
"s": 25519,
"text": "Following are the conditions for the spline of degree K=3:The domain of s is in intervals of [a, b].S, S’, S” are all continuous function on [a, b]."
},
{
"code": null,
"e": 25711,
"s": 25668,
"text": "The domain of s is in intervals of [a, b]."
},
{
"code": null,
"e": 25760,
"s": 25711,
"text": "S, S’, S” are all continuous function on [a, b]."
},
{
"code": null,
"e": 25845,
"s": 25760,
"text": "Here Si(x) is the cubic polynomial that will be used on the subinterval [xi, xi+1]. "
},
{
"code": null,
"e": 26186,
"s": 25845,
"text": "The main factor about spline is that it combines different polynomials and not use a single polynomial of degree n to fit all the points at once, it avoids high degree polynomials and thereby the potential problem of overfitting. These low-degree polynomials need to be such that the spline they form is not only continuous but also smooth."
},
{
"code": null,
"e": 26308,
"s": 26186,
"text": "But for the spline to be smooth and continuous, the two consecutive polynomials and Si (x) and Si+1 (x) must join at xi. "
},
{
"code": null,
"e": 26358,
"s": 26308,
"text": "Or, Si (x) must be passed through two end-points:"
},
{
"code": null,
"e": 26502,
"s": 26358,
"text": "Assume, S” (x) = Mi (i= 0,1,2, ..., n). Since S(x) is cubic polynomial, so S” (x) is the linear polynomial in [xi, xi+1], then S”’ (x) will be:"
},
{
"code": null,
"e": 26533,
"s": 26502,
"text": "By applying the Taylor series:"
},
{
"code": null,
"e": 26548,
"s": 26533,
"text": "Let, x = xi+1:"
},
{
"code": null,
"e": 26607,
"s": 26550,
"text": "Similarly, we apply above equation b/w range [xi-1, xi]:"
},
{
"code": null,
"e": 26625,
"s": 26607,
"text": "Let hi =xi – xi-1"
},
{
"code": null,
"e": 26806,
"s": 26625,
"text": "Now, we have n-1 equations, but have n+1 variables i.e M0, M1, M2,...Mn-1, Mn. Therefore, we need to get 2 more equation. For that, we will be using additional boundary conditions."
},
{
"code": null,
"e": 26960,
"s": 26806,
"text": "Let’s consider that we know S’ (x0) = f0‘ and S’ (xn) = fn‘, especially if S’ (x0) and S’ (xn) both are 0. This is called the clamped boundary condition."
},
{
"code": null,
"e": 26978,
"s": 26960,
"text": "Similarly, for Mn"
},
{
"code": null,
"e": 26981,
"s": 26978,
"text": "or"
},
{
"code": null,
"e": 27062,
"s": 26981,
"text": "Combining the above equation in to the matrix form, we get the following matrix:"
},
{
"code": null,
"e": 27248,
"s": 27062,
"text": "We will be using the Scipy to perform the linear spline interpolation. We will be using Cubic Spline and interp1d function of scipy to perform interpolation of function f(x) =1/(1+x^2)."
},
{
"code": null,
"e": 27256,
"s": 27248,
"text": "Python3"
},
{
"code": "#importsimport matplotlib.pyplot as pltimport numpy as npfrom scipy.interpolate import CubicSpline, interp1dplt.rcParams['figure.figsize'] =(12,8) x = np.arange(-10,10)y = 1/(1+x**2)# apply cubic spline interpolationcs = CubicSpline(x, y)# Apply Linear interpolationlinear_int = interp1d(x,y) xs = np.arange(-10, 10)ys = linear_int(xs) # plot linear interpolationplt.plot(x, y, 'o', label='data')plt.plot(xs,ys, label=\"S\", color='green')plt.legend(loc='upper right', ncol=2)plt.title('Linear Interpolation')plt.show() # plot cubic spline interpolationplt.plot(x, y, 'o', label='data')plt.plot(xs, 1/(1+(xs**2)), label='true')plt.plot(xs, cs(xs), label=\"S\")plt.plot(xs, cs(xs, 1), label=\"S'\")plt.plot(xs, cs(xs, 2), label=\"S''\")plt.plot(xs, cs(xs, 3), label=\"S'''\")plt.ylim(-1.5, 1.5)plt.legend(loc='upper right', ncol=2)plt.title('Cubic Spline Interpolation')plt.show()",
"e": 28131,
"s": 27256,
"text": null
},
{
"code": null,
"e": 28152,
"s": 28131,
"text": "Linear Interpolation"
},
{
"code": null,
"e": 28179,
"s": 28152,
"text": "Cubic Spline interpolation"
},
{
"code": null,
"e": 28220,
"s": 28179,
"text": "Wikidiversity Cubic Spline Interpolation"
},
{
"code": null,
"e": 28418,
"s": 28220,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready."
},
{
"code": null,
"e": 28435,
"s": 28418,
"text": "Machine Learning"
},
{
"code": null,
"e": 28452,
"s": 28435,
"text": "Machine Learning"
},
{
"code": null,
"e": 28550,
"s": 28452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28559,
"s": 28550,
"text": "Comments"
},
{
"code": null,
"e": 28572,
"s": 28559,
"text": "Old Comments"
},
{
"code": null,
"e": 28605,
"s": 28572,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 28644,
"s": 28605,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 28679,
"s": 28644,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 28720,
"s": 28679,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 28768,
"s": 28720,
"text": "Python | Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 28807,
"s": 28768,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 28835,
"s": 28807,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 28886,
"s": 28835,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 28919,
"s": 28886,
"text": "Normalization vs Standardization"
}
] |
ArrayDeque removeFirst() Method in Java - GeeksforGeeks | 10 Dec, 2018
The Java.util.ArrayDeque.removeFirst() method is used to remove the first element of the Deque.
Syntax:
Array_Deque.removeFirst()
Parameters: The method does not take any parameters.
Return Value: This method returns the first element of the Deque after removing it.
Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.
Below programs illustrate the Java.util.ArrayDeque.removeFirst() method:
Program 1:
// Java code to illustrate removeFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using removeFirst() method de_que.removeFirst(); de_que.removeFirst(); de_que.removeFirst(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [For, Geeks]
Program 2:
// Java code to illustrate removeFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using removeFirst() method de_que.removeFirst(); de_que.removeFirst(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [30, 20, 5]
Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
Arrays.sort() in Java with examples
How to iterate any Map in Java | [
{
"code": null,
"e": 23497,
"s": 23469,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 23593,
"s": 23497,
"text": "The Java.util.ArrayDeque.removeFirst() method is used to remove the first element of the Deque."
},
{
"code": null,
"e": 23601,
"s": 23593,
"text": "Syntax:"
},
{
"code": null,
"e": 23627,
"s": 23601,
"text": "Array_Deque.removeFirst()"
},
{
"code": null,
"e": 23680,
"s": 23627,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 23764,
"s": 23680,
"text": "Return Value: This method returns the first element of the Deque after removing it."
},
{
"code": null,
"e": 23850,
"s": 23764,
"text": "Exceptions: The method throws NoSuchElementException is thrown if the deque is empty."
},
{
"code": null,
"e": 23923,
"s": 23850,
"text": "Below programs illustrate the Java.util.ArrayDeque.removeFirst() method:"
},
{
"code": null,
"e": 23934,
"s": 23923,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate removeFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using removeFirst() method de_que.removeFirst(); de_que.removeFirst(); de_que.removeFirst(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 24771,
"s": 23934,
"text": null
},
{
"code": null,
"e": 24874,
"s": 24771,
"text": "Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [For, Geeks]\n"
},
{
"code": null,
"e": 24885,
"s": 24874,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate removeFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using removeFirst() method de_que.removeFirst(); de_que.removeFirst(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 25672,
"s": 24885,
"text": null
},
{
"code": null,
"e": 25761,
"s": 25672,
"text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [30, 20, 5]\n"
},
{
"code": null,
"e": 25781,
"s": 25761,
"text": "Java - util package"
},
{
"code": null,
"e": 25797,
"s": 25781,
"text": "Java-ArrayDeque"
},
{
"code": null,
"e": 25814,
"s": 25797,
"text": "Java-Collections"
},
{
"code": null,
"e": 25829,
"s": 25814,
"text": "Java-Functions"
},
{
"code": null,
"e": 25834,
"s": 25829,
"text": "Java"
},
{
"code": null,
"e": 25839,
"s": 25834,
"text": "Java"
},
{
"code": null,
"e": 25856,
"s": 25839,
"text": "Java-Collections"
},
{
"code": null,
"e": 25954,
"s": 25856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25963,
"s": 25954,
"text": "Comments"
},
{
"code": null,
"e": 25976,
"s": 25963,
"text": "Old Comments"
},
{
"code": null,
"e": 25991,
"s": 25976,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26035,
"s": 25991,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26057,
"s": 26035,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26082,
"s": 26057,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26112,
"s": 26082,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26131,
"s": 26112,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26182,
"s": 26131,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26200,
"s": 26182,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26236,
"s": 26200,
"text": "Arrays.sort() in Java with examples"
}
] |
Where do we use $.extend() method in jQuery? | The jQuery.extend() method is used to merge contents of two or more objects together. The object is merged into the first object.
You can try to run the following code to learn how to use extend() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button1").click(function() {
var obj1 = {
maths: 60,
history: {pages: 150,price: 400,lessons: 30},
science: 120
};
var obj2 = {
history: { price: 150, lessons: 24 },
economics: 250
};
$.extend(true, obj1, obj2);
$("#demo").append(JSON.stringify(obj1));
});
});
</script>
</head>
<body>
<button id="button1">Result</button>
<div id="demo"></div>
</body>
</html> | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "The jQuery.extend() method is used to merge contents of two or more objects together. The object is merged into the first object. "
},
{
"code": null,
"e": 1269,
"s": 1193,
"text": "You can try to run the following code to learn how to use extend() method −"
},
{
"code": null,
"e": 1279,
"s": 1269,
"text": "Live Demo"
},
{
"code": null,
"e": 1869,
"s": 1279,
"text": "<!DOCTYPE html>\n<html>\n\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function() {\n $(\"#button1\").click(function() {\n var obj1 = {\n maths: 60,\n history: {pages: 150,price: 400,lessons: 30},\n science: 120\n };\n var obj2 = {\n history: { price: 150, lessons: 24 },\n economics: 250\n };\n $.extend(true, obj1, obj2);\n $(\"#demo\").append(JSON.stringify(obj1));\n });\n});\n</script>\n</head>\n<body>\n <button id=\"button1\">Result</button>\n <div id=\"demo\"></div>\n</body>\n</html>"
}
] |
Find median in row wise sorted matrix - GeeksforGeeks | 21 Feb, 2022
We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples:
Input : 1 3 5
2 6 9
3 6 9
Output : Median is 5
If we put all the values in a sorted
array A[] = 1 2 3 3 5 6 6 9 9)
Input: 1 3 4
2 5 6
7 8 9
Output: Median is 5
Simple Method: The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers that are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach: Algorithm:
First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than or equal to our mid. And accordingly change the min or max.For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number.
First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.
Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than or equal to our mid. And accordingly change the min or max.
For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find median of a matrix// sorted row wise#include<bits/stdc++.h>using namespace std; const int MAX = 100; // function to find median in the matrixint binaryMedian(int m[][MAX], int r ,int c){ int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min;} // driver program to check above functionsint main(){ int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << "Median is " << binaryMedian(m, r, c) << endl; return 0;}
// Java program to find median of a matrix// sorted row wiseimport java.util.Arrays; public class MedianInRowSorted{ // function to find median in the matrix static int binaryMedian(int m[][],int r, int c) { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i=0; i<r ; i++) { // Finding the minimum element if(m[i][0] < min) min = m[i][0]; // Finding the maximum element if(m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while(min < max) { int mid = min + (max - min) / 2; int place = 0; int get = 0; // Find count of elements smaller than mid for(int i = 0; i < r; ++i) { get = Arrays.binarySearch(m[i],mid); // If element is not found in the array the // binarySearch() method returns // (-(insertion_point) - 1). So once we know // the insertion point we can find elements // Smaller than the searched element by the // following calculation if(get < 0) get = Math.abs(get) - 1; // If element is found in the array it returns // the index(any index in case of duplicate). So we go to last // index of element which will give the number of // elements smaller than the number including // the searched element. else { while(get < m[i].length && m[i][get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min; } // Driver Program to test above method. public static void main(String[] args) { int r = 3, c = 3; int m[][]= { {1,3,5}, {2,6,9}, {3,6,9} }; System.out.println("Median is " + binaryMedian(m, r, c)); }} // This code is contributed by Sumit Ghosh
# Python program to find median of matrix# sorted row wise from bisect import bisect_right as upper_bound MAX = 100; # Function to find median in the matrixdef binaryMedian(m, r, d): mi = m[0][0] mx = 0 for i in range(r): if m[i][0] < mi: mi = m[i][0] if m[i][d-1] > mx : mx = m[i][d-1] desired = (r * d + 1) // 2 while (mi < mx): mid = mi + (mx - mi) // 2 place = [0]; # Find count of elements smaller than mid for i in range(r): j = upper_bound(m[i], mid) place[0] = place[0] + j if place[0] < desired: mi = mid + 1 else: mx = mid print ("Median is", mi) return # Driver coder, d = 3, 3 m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]binaryMedian(m, r, d) # This code is contributed by Sachin BIsht
// C# program to find median// of a matrix sorted row wiseusing System;class MedianInRowSorted{ // Function to find median// in the matrixstatic int binaryMedian(int [,]m, int r, int c){ int max = int.MinValue; int min = int.MaxValue; for(int i = 0; i < r; i++) { // Finding the minimum // element if(m[i, 0] < min) min = m[i, 0]; // Finding the maximum // element if(m[i, c - 1] > max) max = m[i, c - 1]; } int desired = (r * c + 1) / 2; while(min < max) { int mid = min + (max - min) / 2; int place = 0; int get = 0; // Find count of elements // smaller than mid for(int i = 0; i < r; ++i) { get = Array.BinarySearch( GetRow(m, i), mid); // If element is not found // in the array the binarySearch() // method returns (-(insertion_ // point) - 1). So once we know // the insertion point we can // find elements Smaller than // the searched element by the // following calculation if(get < 0) get = Math.Abs(get) - 1; // If element is found in the // array it returns the index(any // index in case of duplicate). So // we go to last index of element // which will give the number of // elements smaller than the number // including the searched element. else { while(get < GetRow(m, i).GetLength(0) && m[i, get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min;} public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} // Driver codepublic static void Main(String[] args){ int r = 3, c = 3; int [,]m = {{1,3,5}, {2,6,9}, {3,6,9} }; Console.WriteLine("Median is " + binaryMedian(m, r, c));}} // This code is contributed by Princi Singh
<script> // Javascript program to find median// of a matrix sorted row wise // Function to find median// in the matrixfunction binaryMedian(m, r, c){ var max = -1000000000; var min = 1000000000; for(var i = 0; i < r; i++) { // Finding the minimum // element if(m[i][0] < min) min = m[i][0]; // Finding the maximum // element if(m[i] > max) max = m[i]; } var desired = parseInt((r * c + 1) / 2); while(min < max) { var mid = min + parseInt((max - min) / 2); var place = 0; var get = 0; // Find count of elements // smaller than mid for(var i = 0; i < r; ++i) { var tmp = GetRow(m, i); for(var j = tmp.length; j>=0; j--) { if(tmp[j] <= mid) { get = j+1; break; } } // If element is not found // in the array the binarySearch() // method returns (-(insertion_ // point) - 1). So once we know // the insertion point we can // find elements Smaller than // the searched element by the // following calculation if(get < 0) get = Math.abs(get) - 1; // If element is found in the // array it returns the index(any // index in case of duplicate). So // we go to last index of element // which will give the number of // elements smaller than the number // including the searched element. else { while(get < GetRow(m, i).length && m[i][get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min;} function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = Array(rowLength).fill(0); for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} // Driver codevar r = 3, c = 3;var m = [[1,3,5], [2,6,9], [3,6,9]];document.write("Median is " + binaryMedian(m, r, c)); // This code is contributed by rutvik_56.</script>
Median is 5
Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations. Auxiliary Space: O(1)
YouTubeGeeksforGeeks500K subscribersFind median of a row-wise sorted Matrix | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_4rxBuhyLXw" 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 Akshit 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.
laveena14
sajal10798
princi singh
rutvik_56
2019285
walterwhitejunior
Binary Search
median-finding
Order-Statistics
statistical-algorithms
Matrix
Matrix
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Find the number of islands | Set 1 (Using DFS)
The Celebrity Problem
Min Cost Path | DP-6 | [
{
"code": null,
"e": 37678,
"s": 37650,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 37825,
"s": 37678,
"text": "We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: "
},
{
"code": null,
"e": 38017,
"s": 37825,
"text": "Input : 1 3 5\n 2 6 9\n 3 6 9\nOutput : Median is 5\nIf we put all the values in a sorted \narray A[] = 1 2 3 3 5 6 6 9 9)\n\nInput: 1 3 4\n 2 5 6\n 7 8 9\nOutput: Median is 5"
},
{
"code": null,
"e": 38678,
"s": 38017,
"text": "Simple Method: The simplest method to solve this problem is to store all the elements of the given matrix in an array of size r*c. Then we can either sort the array and find the median element in O(r*clog(r*c)) or we can use the approach discussed here to find the median in O(r*c). Auxiliary space required will be O(r*c) in both cases.An efficient approach for this problem is to use a binary search algorithm. The idea is that for a number to be median there should be exactly (n/2) numbers that are less than this number. So, we try to find the count of numbers less than all the numbers. Below is the step by step algorithm for this approach: Algorithm: "
},
{
"code": null,
"e": 39479,
"s": 38678,
"text": "First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row.Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than or equal to our mid. And accordingly change the min or max.For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number."
},
{
"code": null,
"e": 39717,
"s": 39479,
"text": "First, we find the minimum and maximum elements in the matrix. The minimum element can be easily found by comparing the first element of each row, and similarly, the maximum element can be found by comparing the last element of each row."
},
{
"code": null,
"e": 39924,
"s": 39717,
"text": "Then we use binary search on our range of numbers from minimum to maximum, we find the mid of the min and max and get a count of numbers less than or equal to our mid. And accordingly change the min or max."
},
{
"code": null,
"e": 40282,
"s": 39924,
"text": "For a number to be median, there should be (r*c)/2 numbers smaller than that number. So for every number, we get the count of numbers less than that by using upper_bound() in each row of the matrix, if it is less than the required count, the median must be greater than the selected number, else the median must be less than or equal to the selected number."
},
{
"code": null,
"e": 40334,
"s": 40282,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 40338,
"s": 40334,
"text": "C++"
},
{
"code": null,
"e": 40343,
"s": 40338,
"text": "Java"
},
{
"code": null,
"e": 40351,
"s": 40343,
"text": "Python3"
},
{
"code": null,
"e": 40354,
"s": 40351,
"text": "C#"
},
{
"code": null,
"e": 40365,
"s": 40354,
"text": "Javascript"
},
{
"code": "// C++ program to find median of a matrix// sorted row wise#include<bits/stdc++.h>using namespace std; const int MAX = 100; // function to find median in the matrixint binaryMedian(int m[][MAX], int r ,int c){ int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min;} // driver program to check above functionsint main(){ int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << \"Median is \" << binaryMedian(m, r, c) << endl; return 0;}",
"e": 41406,
"s": 40365,
"text": null
},
{
"code": "// Java program to find median of a matrix// sorted row wiseimport java.util.Arrays; public class MedianInRowSorted{ // function to find median in the matrix static int binaryMedian(int m[][],int r, int c) { int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i=0; i<r ; i++) { // Finding the minimum element if(m[i][0] < min) min = m[i][0]; // Finding the maximum element if(m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while(min < max) { int mid = min + (max - min) / 2; int place = 0; int get = 0; // Find count of elements smaller than mid for(int i = 0; i < r; ++i) { get = Arrays.binarySearch(m[i],mid); // If element is not found in the array the // binarySearch() method returns // (-(insertion_point) - 1). So once we know // the insertion point we can find elements // Smaller than the searched element by the // following calculation if(get < 0) get = Math.abs(get) - 1; // If element is found in the array it returns // the index(any index in case of duplicate). So we go to last // index of element which will give the number of // elements smaller than the number including // the searched element. else { while(get < m[i].length && m[i][get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min; } // Driver Program to test above method. public static void main(String[] args) { int r = 3, c = 3; int m[][]= { {1,3,5}, {2,6,9}, {3,6,9} }; System.out.println(\"Median is \" + binaryMedian(m, r, c)); }} // This code is contributed by Sumit Ghosh",
"e": 43742,
"s": 41406,
"text": null
},
{
"code": "# Python program to find median of matrix# sorted row wise from bisect import bisect_right as upper_bound MAX = 100; # Function to find median in the matrixdef binaryMedian(m, r, d): mi = m[0][0] mx = 0 for i in range(r): if m[i][0] < mi: mi = m[i][0] if m[i][d-1] > mx : mx = m[i][d-1] desired = (r * d + 1) // 2 while (mi < mx): mid = mi + (mx - mi) // 2 place = [0]; # Find count of elements smaller than mid for i in range(r): j = upper_bound(m[i], mid) place[0] = place[0] + j if place[0] < desired: mi = mid + 1 else: mx = mid print (\"Median is\", mi) return # Driver coder, d = 3, 3 m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]binaryMedian(m, r, d) # This code is contributed by Sachin BIsht",
"e": 44606,
"s": 43742,
"text": null
},
{
"code": "// C# program to find median// of a matrix sorted row wiseusing System;class MedianInRowSorted{ // Function to find median// in the matrixstatic int binaryMedian(int [,]m, int r, int c){ int max = int.MinValue; int min = int.MaxValue; for(int i = 0; i < r; i++) { // Finding the minimum // element if(m[i, 0] < min) min = m[i, 0]; // Finding the maximum // element if(m[i, c - 1] > max) max = m[i, c - 1]; } int desired = (r * c + 1) / 2; while(min < max) { int mid = min + (max - min) / 2; int place = 0; int get = 0; // Find count of elements // smaller than mid for(int i = 0; i < r; ++i) { get = Array.BinarySearch( GetRow(m, i), mid); // If element is not found // in the array the binarySearch() // method returns (-(insertion_ // point) - 1). So once we know // the insertion point we can // find elements Smaller than // the searched element by the // following calculation if(get < 0) get = Math.Abs(get) - 1; // If element is found in the // array it returns the index(any // index in case of duplicate). So // we go to last index of element // which will give the number of // elements smaller than the number // including the searched element. else { while(get < GetRow(m, i).GetLength(0) && m[i, get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min;} public static int[] GetRow(int[,] matrix, int row){ var rowLength = matrix.GetLength(1); var rowVector = new int[rowLength]; for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row, i]; return rowVector;} // Driver codepublic static void Main(String[] args){ int r = 3, c = 3; int [,]m = {{1,3,5}, {2,6,9}, {3,6,9} }; Console.WriteLine(\"Median is \" + binaryMedian(m, r, c));}} // This code is contributed by Princi Singh",
"e": 46706,
"s": 44606,
"text": null
},
{
"code": "<script> // Javascript program to find median// of a matrix sorted row wise // Function to find median// in the matrixfunction binaryMedian(m, r, c){ var max = -1000000000; var min = 1000000000; for(var i = 0; i < r; i++) { // Finding the minimum // element if(m[i][0] < min) min = m[i][0]; // Finding the maximum // element if(m[i] > max) max = m[i]; } var desired = parseInt((r * c + 1) / 2); while(min < max) { var mid = min + parseInt((max - min) / 2); var place = 0; var get = 0; // Find count of elements // smaller than mid for(var i = 0; i < r; ++i) { var tmp = GetRow(m, i); for(var j = tmp.length; j>=0; j--) { if(tmp[j] <= mid) { get = j+1; break; } } // If element is not found // in the array the binarySearch() // method returns (-(insertion_ // point) - 1). So once we know // the insertion point we can // find elements Smaller than // the searched element by the // following calculation if(get < 0) get = Math.abs(get) - 1; // If element is found in the // array it returns the index(any // index in case of duplicate). So // we go to last index of element // which will give the number of // elements smaller than the number // including the searched element. else { while(get < GetRow(m, i).length && m[i][get] == mid) get += 1; } place = place + get; } if (place < desired) min = mid + 1; else max = mid; } return min;} function GetRow(matrix, row){ var rowLength = matrix[0].length; var rowVector = Array(rowLength).fill(0); for (var i = 0; i < rowLength; i++) rowVector[i] = matrix[row][i]; return rowVector;} // Driver codevar r = 3, c = 3;var m = [[1,3,5], [2,6,9], [3,6,9]];document.write(\"Median is \" + binaryMedian(m, r, c)); // This code is contributed by rutvik_56.</script>",
"e": 48779,
"s": 46706,
"text": null
},
{
"code": null,
"e": 48791,
"s": 48779,
"text": "Median is 5"
},
{
"code": null,
"e": 49083,
"s": 48791,
"text": "Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time and is performed for each row. And since the numbers will be max of 32 bit, so binary search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 ) operations. Auxiliary Space: O(1) "
},
{
"code": null,
"e": 49922,
"s": 49083,
"text": "YouTubeGeeksforGeeks500K subscribersFind median of a row-wise sorted Matrix | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_4rxBuhyLXw\" 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": 50345,
"s": 49922,
"text": "This article is contributed by Akshit 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": 50355,
"s": 50345,
"text": "laveena14"
},
{
"code": null,
"e": 50366,
"s": 50355,
"text": "sajal10798"
},
{
"code": null,
"e": 50379,
"s": 50366,
"text": "princi singh"
},
{
"code": null,
"e": 50389,
"s": 50379,
"text": "rutvik_56"
},
{
"code": null,
"e": 50397,
"s": 50389,
"text": "2019285"
},
{
"code": null,
"e": 50415,
"s": 50397,
"text": "walterwhitejunior"
},
{
"code": null,
"e": 50429,
"s": 50415,
"text": "Binary Search"
},
{
"code": null,
"e": 50444,
"s": 50429,
"text": "median-finding"
},
{
"code": null,
"e": 50461,
"s": 50444,
"text": "Order-Statistics"
},
{
"code": null,
"e": 50484,
"s": 50461,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 50491,
"s": 50484,
"text": "Matrix"
},
{
"code": null,
"e": 50498,
"s": 50491,
"text": "Matrix"
},
{
"code": null,
"e": 50512,
"s": 50498,
"text": "Binary Search"
},
{
"code": null,
"e": 50610,
"s": 50512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50619,
"s": 50610,
"text": "Comments"
},
{
"code": null,
"e": 50632,
"s": 50619,
"text": "Old Comments"
},
{
"code": null,
"e": 50667,
"s": 50632,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 50711,
"s": 50667,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 50747,
"s": 50711,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 50771,
"s": 50747,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 50802,
"s": 50771,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 50864,
"s": 50802,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 50897,
"s": 50864,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 50944,
"s": 50897,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 50966,
"s": 50944,
"text": "The Celebrity Problem"
}
] |
C# | How to change BufferHeight of the Console - GeeksforGeeks | 28 Jan, 2019
Given the normal Console in C#, the task is to find the default value of Buffer Height and change it to something else.
Buffer Height refers to the current height of the buffer area of the console in rows.
Approach: This can be done using the BufferHeight property in the Console class of the System package in C#.
Program 1: Finding the default Buffer Height
// C# program to illustrate the// BufferHeight Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Height Console.WriteLine("Default Buffer Height: {0}", Console.BufferHeight); }}}
Output:
Program 2: Changing the Buffer Height to 100
// C# program to illustrate the// BufferHeight Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Height Console.WriteLine("Default Buffer Height: {0}", Console.BufferHeight); // Set the Buffer Height to 100 Console.BufferHeight = 100; // Display current Buffer Height Console.WriteLine("Changed Buffer Height: {0}", Console.BufferHeight); }}}
Output:
Note: See how the vertical scrolling bar on the right has changed in both the images.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 24031,
"s": 23911,
"text": "Given the normal Console in C#, the task is to find the default value of Buffer Height and change it to something else."
},
{
"code": null,
"e": 24117,
"s": 24031,
"text": "Buffer Height refers to the current height of the buffer area of the console in rows."
},
{
"code": null,
"e": 24226,
"s": 24117,
"text": "Approach: This can be done using the BufferHeight property in the Console class of the System package in C#."
},
{
"code": null,
"e": 24271,
"s": 24226,
"text": "Program 1: Finding the default Buffer Height"
},
{
"code": "// C# program to illustrate the// BufferHeight Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Height Console.WriteLine(\"Default Buffer Height: {0}\", Console.BufferHeight); }}}",
"e": 24672,
"s": 24271,
"text": null
},
{
"code": null,
"e": 24680,
"s": 24672,
"text": "Output:"
},
{
"code": null,
"e": 24725,
"s": 24680,
"text": "Program 2: Changing the Buffer Height to 100"
},
{
"code": "// C# program to illustrate the// BufferHeight Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Buffer Height Console.WriteLine(\"Default Buffer Height: {0}\", Console.BufferHeight); // Set the Buffer Height to 100 Console.BufferHeight = 100; // Display current Buffer Height Console.WriteLine(\"Changed Buffer Height: {0}\", Console.BufferHeight); }}}",
"e": 25355,
"s": 24725,
"text": null
},
{
"code": null,
"e": 25363,
"s": 25355,
"text": "Output:"
},
{
"code": null,
"e": 25449,
"s": 25363,
"text": "Note: See how the vertical scrolling bar on the right has changed in both the images."
},
{
"code": null,
"e": 25470,
"s": 25449,
"text": "CSharp-Console-Class"
},
{
"code": null,
"e": 25473,
"s": 25470,
"text": "C#"
},
{
"code": null,
"e": 25571,
"s": 25473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25580,
"s": 25571,
"text": "Comments"
},
{
"code": null,
"e": 25593,
"s": 25580,
"text": "Old Comments"
},
{
"code": null,
"e": 25633,
"s": 25593,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25656,
"s": 25633,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25684,
"s": 25656,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25706,
"s": 25684,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25723,
"s": 25706,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25763,
"s": 25723,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 25796,
"s": 25763,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 25839,
"s": 25796,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25855,
"s": 25839,
"text": "C# | List Class"
}
] |
Create a web server and run PHP script on it using Raspberry Pi - GeeksforGeeks | 23 Jul, 2018
In this post, creating a web server and running PHP script on it using Raspberry Pi will be discussed.
Web Servers are basically simple computer programs that dispense the web page when they are requested using the web client. The machines on which this program run are usually called as a server, with both the names web server and server almost used interchangeably.
Steps to create a web server and run PHP script on it using Raspberry Pi:
Change to root directory and run a update :sudo -i
apt-get update
Now install each of the packages which will be necessary for the following process,apt-get install nginx php5-fpm php5-cgi php5-cli php5-common
Then start the serverservice nginx start
Now run the following command:ifconfig // it tells the ip address
Change to root directory and run a update :sudo -i
apt-get update
sudo -i
apt-get update
Now install each of the packages which will be necessary for the following process,apt-get install nginx php5-fpm php5-cgi php5-cli php5-common
apt-get install nginx php5-fpm php5-cgi php5-cli php5-common
Then start the serverservice nginx start
service nginx start
Now run the following command:ifconfig // it tells the ip address
ifconfig // it tells the ip address
Now paste this ip address to computer’s browser. If everything above went well, then it will show the following text/window on the browser window.
Welcome to nginx!
To run PHP script on this web server:
Enter the config directory:cd /etc/nginx
Now navigate to sites-available directory.cd sites-availableThere will be a single file present having name default, open it and edit it by typingnano defaultNow find below lines and uncomment them.location=\.php5 {
fastcgi_split_path_info "(.*\.php)(/.*)5;
fastcgi.pass unix:/var/run/php5-fpm.
fastcgi_index index.php;
include fastcgi_params;
}
location=/\.bt{
}
Also, change below line,index index.html index.htm;toindex index.php index.html index.htm;
//to use PHP we added index.phpNow to save and exit, press Ctrl+x then press Y.Now lets restart the server, to collect the changes that have been done:service nginx restartNow we have to create a index.php file in our www directorycd/user/share/nginx/www
nano index.php
Write this script here:<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint("Hello from GeeksforGeeks");?></BODY></HTML>Now save it and then test everything in the browser using that IP address or type youripaddress/index.php e.g 192.168.182.1/index.php
Enter the config directory:cd /etc/nginx
cd /etc/nginx
Now navigate to sites-available directory.cd sites-available
cd sites-available
There will be a single file present having name default, open it and edit it by typingnano default
nano default
Now find below lines and uncomment them.location=\.php5 {
fastcgi_split_path_info "(.*\.php)(/.*)5;
fastcgi.pass unix:/var/run/php5-fpm.
fastcgi_index index.php;
include fastcgi_params;
}
location=/\.bt{
}
location=\.php5 {
fastcgi_split_path_info "(.*\.php)(/.*)5;
fastcgi.pass unix:/var/run/php5-fpm.
fastcgi_index index.php;
include fastcgi_params;
}
location=/\.bt{
}
Also, change below line,index index.html index.htm;toindex index.php index.html index.htm;
//to use PHP we added index.phpNow to save and exit, press Ctrl+x then press Y.
index index.html index.htm;
to
index index.php index.html index.htm;
//to use PHP we added index.php
Now to save and exit, press Ctrl+x then press Y.
Now lets restart the server, to collect the changes that have been done:service nginx restart
service nginx restart
Now we have to create a index.php file in our www directorycd/user/share/nginx/www
nano index.php
cd/user/share/nginx/www
nano index.php
Write this script here:<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint("Hello from GeeksforGeeks");?></BODY></HTML>
<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint("Hello from GeeksforGeeks");?></BODY></HTML>
Now save it and then test everything in the browser using that IP address or type youripaddress/index.php e.g 192.168.182.1/index.php
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
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": 24677,
"s": 24649,
"text": "\n23 Jul, 2018"
},
{
"code": null,
"e": 24780,
"s": 24677,
"text": "In this post, creating a web server and running PHP script on it using Raspberry Pi will be discussed."
},
{
"code": null,
"e": 25046,
"s": 24780,
"text": "Web Servers are basically simple computer programs that dispense the web page when they are requested using the web client. The machines on which this program run are usually called as a server, with both the names web server and server almost used interchangeably."
},
{
"code": null,
"e": 25120,
"s": 25046,
"text": "Steps to create a web server and run PHP script on it using Raspberry Pi:"
},
{
"code": null,
"e": 25442,
"s": 25120,
"text": "Change to root directory and run a update :sudo -i \napt-get update\nNow install each of the packages which will be necessary for the following process,apt-get install nginx php5-fpm php5-cgi php5-cli php5-common \nThen start the serverservice nginx start\nNow run the following command:ifconfig // it tells the ip address\n"
},
{
"code": null,
"e": 25510,
"s": 25442,
"text": "Change to root directory and run a update :sudo -i \napt-get update\n"
},
{
"code": null,
"e": 25535,
"s": 25510,
"text": "sudo -i \napt-get update\n"
},
{
"code": null,
"e": 25681,
"s": 25535,
"text": "Now install each of the packages which will be necessary for the following process,apt-get install nginx php5-fpm php5-cgi php5-cli php5-common \n"
},
{
"code": null,
"e": 25744,
"s": 25681,
"text": "apt-get install nginx php5-fpm php5-cgi php5-cli php5-common \n"
},
{
"code": null,
"e": 25786,
"s": 25744,
"text": "Then start the serverservice nginx start\n"
},
{
"code": null,
"e": 25807,
"s": 25786,
"text": "service nginx start\n"
},
{
"code": null,
"e": 25876,
"s": 25807,
"text": "Now run the following command:ifconfig // it tells the ip address\n"
},
{
"code": null,
"e": 25915,
"s": 25876,
"text": "ifconfig // it tells the ip address\n"
},
{
"code": null,
"e": 26062,
"s": 25915,
"text": "Now paste this ip address to computer’s browser. If everything above went well, then it will show the following text/window on the browser window."
},
{
"code": null,
"e": 26080,
"s": 26062,
"text": "Welcome to nginx!"
},
{
"code": null,
"e": 26118,
"s": 26080,
"text": "To run PHP script on this web server:"
},
{
"code": null,
"e": 27152,
"s": 26118,
"text": "Enter the config directory:cd /etc/nginx\nNow navigate to sites-available directory.cd sites-availableThere will be a single file present having name default, open it and edit it by typingnano defaultNow find below lines and uncomment them.location=\\.php5 {\nfastcgi_split_path_info \"(.*\\.php)(/.*)5;\n\n\nfastcgi.pass unix:/var/run/php5-fpm.\nfastcgi_index index.php;\ninclude fastcgi_params;\n}\n\nlocation=/\\.bt{\n\n }\nAlso, change below line,index index.html index.htm;toindex index.php index.html index.htm;\n//to use PHP we added index.phpNow to save and exit, press Ctrl+x then press Y.Now lets restart the server, to collect the changes that have been done:service nginx restartNow we have to create a index.php file in our www directorycd/user/share/nginx/www\nnano index.php\nWrite this script here:<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint(\"Hello from GeeksforGeeks\");?></BODY></HTML>Now save it and then test everything in the browser using that IP address or type youripaddress/index.php e.g 192.168.182.1/index.php"
},
{
"code": null,
"e": 27194,
"s": 27152,
"text": "Enter the config directory:cd /etc/nginx\n"
},
{
"code": null,
"e": 27209,
"s": 27194,
"text": "cd /etc/nginx\n"
},
{
"code": null,
"e": 27270,
"s": 27209,
"text": "Now navigate to sites-available directory.cd sites-available"
},
{
"code": null,
"e": 27289,
"s": 27270,
"text": "cd sites-available"
},
{
"code": null,
"e": 27388,
"s": 27289,
"text": "There will be a single file present having name default, open it and edit it by typingnano default"
},
{
"code": null,
"e": 27401,
"s": 27388,
"text": "nano default"
},
{
"code": null,
"e": 27613,
"s": 27401,
"text": "Now find below lines and uncomment them.location=\\.php5 {\nfastcgi_split_path_info \"(.*\\.php)(/.*)5;\n\n\nfastcgi.pass unix:/var/run/php5-fpm.\nfastcgi_index index.php;\ninclude fastcgi_params;\n}\n\nlocation=/\\.bt{\n\n }\n"
},
{
"code": null,
"e": 27785,
"s": 27613,
"text": "location=\\.php5 {\nfastcgi_split_path_info \"(.*\\.php)(/.*)5;\n\n\nfastcgi.pass unix:/var/run/php5-fpm.\nfastcgi_index index.php;\ninclude fastcgi_params;\n}\n\nlocation=/\\.bt{\n\n }\n"
},
{
"code": null,
"e": 27956,
"s": 27785,
"text": "Also, change below line,index index.html index.htm;toindex index.php index.html index.htm;\n//to use PHP we added index.phpNow to save and exit, press Ctrl+x then press Y."
},
{
"code": null,
"e": 27984,
"s": 27956,
"text": "index index.html index.htm;"
},
{
"code": null,
"e": 27987,
"s": 27984,
"text": "to"
},
{
"code": null,
"e": 28057,
"s": 27987,
"text": "index index.php index.html index.htm;\n//to use PHP we added index.php"
},
{
"code": null,
"e": 28106,
"s": 28057,
"text": "Now to save and exit, press Ctrl+x then press Y."
},
{
"code": null,
"e": 28200,
"s": 28106,
"text": "Now lets restart the server, to collect the changes that have been done:service nginx restart"
},
{
"code": null,
"e": 28222,
"s": 28200,
"text": "service nginx restart"
},
{
"code": null,
"e": 28321,
"s": 28222,
"text": "Now we have to create a index.php file in our www directorycd/user/share/nginx/www\nnano index.php\n"
},
{
"code": null,
"e": 28361,
"s": 28321,
"text": "cd/user/share/nginx/www\nnano index.php\n"
},
{
"code": null,
"e": 28491,
"s": 28361,
"text": "Write this script here:<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint(\"Hello from GeeksforGeeks\");?></BODY></HTML>"
},
{
"code": "<HTML><HEAD><TITLE> hello world<TITLE></HEAD><BODY><?phpprint(\"Hello from GeeksforGeeks\");?></BODY></HTML>",
"e": 28598,
"s": 28491,
"text": null
},
{
"code": null,
"e": 28732,
"s": 28598,
"text": "Now save it and then test everything in the browser using that IP address or type youripaddress/index.php e.g 192.168.182.1/index.php"
},
{
"code": null,
"e": 28736,
"s": 28732,
"text": "PHP"
},
{
"code": null,
"e": 28753,
"s": 28736,
"text": "Web Technologies"
},
{
"code": null,
"e": 28757,
"s": 28753,
"text": "PHP"
},
{
"code": null,
"e": 28855,
"s": 28757,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28864,
"s": 28855,
"text": "Comments"
},
{
"code": null,
"e": 28877,
"s": 28864,
"text": "Old Comments"
},
{
"code": null,
"e": 28927,
"s": 28877,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28967,
"s": 28927,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29028,
"s": 28967,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29078,
"s": 29028,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29105,
"s": 29078,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29147,
"s": 29105,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29180,
"s": 29147,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29242,
"s": 29180,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29285,
"s": 29242,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How can I get last 4 characters of a string in Python? | The slice operator in Python takes two operands. First operand is the beginning of slice. The index is counted from left by default. A negative operand starts counting from end. Second operand is the index of last character in slice. If omitted, slice goes upto end.
We want last four characters. Hence we count beginning of position from end by -4 and if we omit second operand, it will go to end.
>>> string = "Thanks. I am fine"
>>> string[-4:]
'fine' | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "The slice operator in Python takes two operands. First operand is the beginning of slice. The index is counted from left by default. A negative operand starts counting from end. Second operand is the index of last character in slice. If omitted, slice goes upto end."
},
{
"code": null,
"e": 1461,
"s": 1329,
"text": "We want last four characters. Hence we count beginning of position from end by -4 and if we omit second operand, it will go to end."
},
{
"code": null,
"e": 1517,
"s": 1461,
"text": ">>> string = \"Thanks. I am fine\"\n>>> string[-4:]\n'fine'"
}
] |
Concatenate 2 strings in ABAP without using CONCATENATE function | In ABAP you can use && sign to concatenate variables as below
hello TYPE string,
world TYPE string,
helloworld TYPE string.
hello = 'hello'.
world = 'world'.
helloworld = hello && world.
If you want to concatenate strings directly, you can use
helloworld = 'hello' && 'world'.
If you want to keep space in between, you would require ` symbol as below
helloworld = hello && ` and ` && world | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "In ABAP you can use && sign to concatenate variables as below"
},
{
"code": null,
"e": 1249,
"s": 1124,
"text": "hello TYPE string,\nworld TYPE string,\nhelloworld TYPE string.\nhello = 'hello'.\nworld = 'world'.\nhelloworld = hello && world."
},
{
"code": null,
"e": 1306,
"s": 1249,
"text": "If you want to concatenate strings directly, you can use"
},
{
"code": null,
"e": 1339,
"s": 1306,
"text": "helloworld = 'hello' && 'world'."
},
{
"code": null,
"e": 1413,
"s": 1339,
"text": "If you want to keep space in between, you would require ` symbol as below"
},
{
"code": null,
"e": 1452,
"s": 1413,
"text": "helloworld = hello && ` and ` && world"
}
] |
Lodash _.forOwn() Method - GeeksforGeeks | 14 Sep, 2020
The Lodash _.forOwn() Method Iterates over the own keys of the given object and invoke iteratee for each property. The iteratee function is invoked with three arguments: (value, key, object). Iteratee function may exit iteration early by explicitly returning false.
Syntax:
_.forOwn( object, iteratee_function)
Parameters: This method accepts two parameters as mentioned above and described below:
object: This is the object to find in.
iteratee_function: the function that is invoked per iteration.
Return Value: This method returns an object.
Example 1:
// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forOwn(users, function(value, key) { console.log(key, '=', value);});
Output:
a = 1
b = 2
c = 3
Example 2:
// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forOwn(users, function(value, key) { if(value > 2) { console.log(key, value); }});
Output:
c 3
Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:
npm install lodash
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
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": 25220,
"s": 25192,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25486,
"s": 25220,
"text": "The Lodash _.forOwn() Method Iterates over the own keys of the given object and invoke iteratee for each property. The iteratee function is invoked with three arguments: (value, key, object). Iteratee function may exit iteration early by explicitly returning false."
},
{
"code": null,
"e": 25494,
"s": 25486,
"text": "Syntax:"
},
{
"code": null,
"e": 25532,
"s": 25494,
"text": "_.forOwn( object, iteratee_function)\n"
},
{
"code": null,
"e": 25619,
"s": 25532,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25658,
"s": 25619,
"text": "object: This is the object to find in."
},
{
"code": null,
"e": 25721,
"s": 25658,
"text": "iteratee_function: the function that is invoked per iteration."
},
{
"code": null,
"e": 25766,
"s": 25721,
"text": "Return Value: This method returns an object."
},
{
"code": null,
"e": 25777,
"s": 25766,
"text": "Example 1:"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forOwn(users, function(value, key) { console.log(key, '=', value);});",
"e": 25956,
"s": 25777,
"text": null
},
{
"code": null,
"e": 25964,
"s": 25956,
"text": "Output:"
},
{
"code": null,
"e": 25983,
"s": 25964,
"text": "a = 1\nb = 2\nc = 3\n"
},
{
"code": null,
"e": 25994,
"s": 25983,
"text": "Example 2:"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forOwn(users, function(value, key) { if(value > 2) { console.log(key, value); }});",
"e": 26198,
"s": 25994,
"text": null
},
{
"code": null,
"e": 26206,
"s": 26198,
"text": "Output:"
},
{
"code": null,
"e": 26211,
"s": 26206,
"text": "c 3\n"
},
{
"code": null,
"e": 26362,
"s": 26211,
"text": "Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:"
},
{
"code": null,
"e": 26381,
"s": 26362,
"text": "npm install lodash"
},
{
"code": null,
"e": 26399,
"s": 26381,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 26410,
"s": 26399,
"text": "JavaScript"
},
{
"code": null,
"e": 26427,
"s": 26410,
"text": "Web Technologies"
},
{
"code": null,
"e": 26525,
"s": 26427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26534,
"s": 26525,
"text": "Comments"
},
{
"code": null,
"e": 26547,
"s": 26534,
"text": "Old Comments"
},
{
"code": null,
"e": 26608,
"s": 26547,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26649,
"s": 26608,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26702,
"s": 26649,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 26756,
"s": 26702,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26804,
"s": 26756,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 26846,
"s": 26804,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26879,
"s": 26846,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26941,
"s": 26879,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26984,
"s": 26941,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Subset with sum divisible by m - GeeksforGeeks | 22 Apr, 2022
Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Input Constraints Size of set i.e., n <= 1000000, m <= 1000Examples:
Input : arr[] = {3, 1, 7, 5};
m = 6;
Output : YES
Input : arr[] = {1, 6};
m = 5;
Output : NO
This problem is a variant of subset sum problem. In subset sum problem we check if given sum subset exists or not, here we need to find if there exists some subset with sum divisible by m or not.
Naive Approach( Using Recurison) :
C++
Python3
Javascript
// C++ program to check if there is a subset// with sum divisible by m.#include <bits/stdc++.h>using namespace std; // Returns true if there is a subset// of arr[] with sum divisible by mbool helper(int N, int nums[], int sum, int idx, int m){ // if we reach last index if(idx == N){ // and if the sum mod m is zero if(sum && sum%m == 0){ // return return true ; } return false ; } // 2 choices - to pick or to not pick bool picked = helper(N, nums, sum+nums[idx], idx+1,m) ; bool notPicked = helper(N, nums, sum, idx+1, m) ; return picked || notPicked ;} bool modularSum(int arr[], int n, int m){ return helper(n, arr, 0, 0, m) ;} // Driver codeint main(){ int arr[] = {1, 7}; int n = sizeof(arr)/sizeof(arr[0]); int m = 5; modularSum(arr, n, m) ? cout << "YES\n" : cout << "NO\n"; return 0;}
# Python3 program to check if there is a subset# with sum divisible by m. # Returns true if there is a subset# of arr[] with sum divisible by mdef helper(N, nums, sum, idx, m): # if we reach last index if(idx == N): # and if the sum mod m is zero if(sum and sum%m == 0): # return return True return False # 2 choices - to pick or to not pick picked = helper(N, nums, sum+nums[idx], idx+1,m) notPicked = helper(N, nums, sum, idx+1, m) return picked or notPicked def modularSum(arr, n, m): return helper(n, arr, 0, 0, m) # Driver codearr = [1, 7]n = len(arr)m = 5 print("YES") if modularSum(arr, n, m) else print("NO") # This code is contributed by shinjanpatra.
<script> // JavaScript program to check if there is a subset// with sum divisible by m. // Returns true if there is a subset// of arr[] with sum divisible by mfunction helper(N, nums, sum, idx, m){ // if we reach last index if(idx == N) { // and if the sum mod m is zero if(sum && sum%m == 0) { // return return true ; } return false ; } // 2 choices - to pick or to not pick let picked = helper(N, nums, sum+nums[idx], idx+1,m) ; let notPicked = helper(N, nums, sum, idx+1, m) ; return picked || notPicked ;} function modularSum(arr, n, m){ return helper(n, arr, 0, 0, m) ;} // Driver code let arr = [1, 7];let n = arr.length;let m = 5; modularSum(arr, n, m) ? document.write("YES","</br>") : document.write("NO","</br>"); // This code is contributed by shinjanpatra.</script>
NO
Time Complexity: O(2N)
Efficient Approach:
Seeing input constraint, it looks like typical DP solution will work in O(nm) time. But in tight time limits in competitive programming, the solution may work. Also auxiliary space is high for DP table, but here is catch.If n > m there will always be a subset with sum divisible by m (which is easy to prove with pigeonhole principle). So we need to handle only cases of n <= m .For n <= m we create a boolean DP table which will store the status of each value from 0 to m-1 which are possible subset sum (modulo m) which have been encountered so far.Now we loop through each element of given array arr[], and we add (modulo m) j which have DP[j] = true, and store all the such (j+arr[i])%m possible subset-sum in a boolean array temp, and at the end of iteration over j, we update DP table with temp. Also we add arr[i] to DP ie.. DP[arr[i]%m] = true. In the end if DP[0] is true then it means YES there exists a subset with sum which is divisible by m, else NO.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if there is a subset// with sum divisible by m.#include <bits/stdc++.h>using namespace std; // Returns true if there is a subset// of arr[] with sum divisible by mbool modularSum(int arr[], int n, int m){ if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false bool DP[m]; memset(DP, false, m); // we'll loop through all the elements of arr[] for (int i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. bool temp[m]; memset(temp,false,m); // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (int j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0];} // Driver codeint main(){ int arr[] = {1, 7}; int n = sizeof(arr)/sizeof(arr[0]); int m = 5; modularSum(arr, n, m) ? cout << "YES\n" : cout << "NO\n"; return 0;}
// Java program to check if there is a subset// with sum divisible by m.import java.util.Arrays; class GFG { // Returns true if there is a subset // of arr[] with sum divisible by m static boolean modularSum(int arr[], int n, int m) { if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false boolean DP[]=new boolean[m]; Arrays.fill(DP, false); // we'll loop through all the elements // of arr[] for (int i = 0; i < n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum // (after modulo). It is used to make // sure that arr[i] is added only to // those entries for which DP[j] // was true before current iteration. boolean temp[] = new boolean[m]; Arrays.fill(temp, false); // For each element of arr[], we loop // through all elements of DP table // from 1 to m and we add current // element i. e., arr[i] to all those // elements which are true in DP table for (int j = 0; j < m; j++) { // if an element is true in // DP table if (DP[j] == true) { if (DP[(j + arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j + arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j = 0; j < m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single // element subset, arr[i]%m is one // of the possible sum DP[arr[i] % m] = true; } return DP[0]; } //driver code public static void main(String arg[]) { int arr[] = {1, 7}; int n = arr.length; int m = 5; if(modularSum(arr, n, m)) System.out.print("YES\n"); else System.out.print("NO\n"); }} //This code is contributed by Anant Agarwal.
# Python3 program to check if there is# a subset with sum divisible by m. # Returns true if there is a subset# of arr[] with sum divisible by mdef modularSum(arr, n, m): if (n > m): return True # This array will keep track of all # the possible sum (after modulo m) # which can be made using subsets of arr[] # initialising boolean array with all false DP = [False for i in range(m)] # we'll loop through all the elements of arr[] for i in range(n): # anytime we encounter a sum divisible # by m, we are done if (DP[0]): return True # To store all the new encountered sum (after # modulo). It is used to make sure that arr[i] # is added only to those entries for which DP[j] # was true before current iteration. temp = [False for i in range(m)] # For each element of arr[], we loop through # all elements of DP table from 1 to m and # we add current element i. e., arr[i] to # all those elements which are true in DP # table for j in range(m): # if an element is true in DP table if (DP[j] == True): if (DP[(j + arr[i]) % m] == False): # We update it in temp and update # to DP once loop of j is over temp[(j + arr[i]) % m] = True # Updating all the elements of temp # to DP table since iteration over # j is over for j in range(m): if (temp[j]): DP[j] = True # Also since arr[i] is a single element # subset, arr[i]%m is one of the possible # sum DP[arr[i] % m] = True return DP[0] # Driver codearr = [1, 7]n = len(arr)m = 5print("YES") if(modularSum(arr, n, m)) else print("NO") # This code is contributed by Anant Agarwal.
// C# program to check if there is// a subset with sum divisible by m.using System; class GFG { // Returns true if there is a subset// of arr[] with sum divisible by mstatic bool modularSum(int []arr, int n, int m){ if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false bool []DP=new bool[m]; for (int l=0;l<DP.Length;l++) DP[l]=false; // we'll loop through all the elements of arr[] for (int i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. bool []temp=new bool[m]; for (int l=0;l<temp.Length;l++) temp[l]=false; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (int j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0];} //driver codepublic static void Main(){ int []arr = {1, 7}; int n = arr.Length; int m = 5; if(modularSum(arr, n, m)) Console.Write("YES\n"); else Console.Write("NO\n");}} //This code is contributed by Anant Agarwal.
<?php// Php program to check if there is a// subset with sum divisible by m. // Returns true if there is a subset// of arr[] with sum divisible by mfunction modularSum($arr, $n, $m){ if ($n > $m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false $DP = Array_fill(0, $m, false); // we'll loop through all the elements of arr[] for ($i = 0; $i < $n; $i++) { // anytime we encounter a sum divisible // by m, we are done if ($DP[0]) return true; // To store all the new encountered sum // (after modulo). It is used to make // sure that arr[i] is added only to those // entries for which DP[j] was true before // current iteration. $temp = array_fill(0, $m, false) ; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for ($j = 0; $j < $m; $j++) { // if an element is true in DP table if ($DP[$j] == true) { if ($DP[($j + $arr[$i]) % $m] == false) // We update it in temp and update // to DP once loop of j is over $temp[($j + $arr[$i]) % $m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for ($j = 0; $j < $m; $j++) if ($temp[$j]) $DP[$j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum $DP[$arr[$i] % $m] = true; } return $DP[0];} // Driver Code$arr = array(1, 7);$n = sizeof($arr);$m = 5; if (modularSum($arr, $n, $m) == true ) echo "YES\n";else echo "NO\n"; // This code is contributed by Ryuga?>
<script> // JavaScript program to check if there is // a subset with sum divisible by m. // Returns true if there is a subset // of arr[] with sum divisible by m function modularSum(arr, n, m) { if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false let DP = new Array(m); for (let l=0;l<m;l++) DP[l]=false; // we'll loop through all the elements of arr[] for (let i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. let temp=new Array(m); for (let l=0;l<m;l++) temp[l]=false; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (let j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (let j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0]; } let arr = [1, 7]; let n = arr.length; let m = 5; if(modularSum(arr, n, m)) document.write("YES" + "</br>"); else document.write("NO" + "</br>"); </script>
NO
Time Complexity : O(m^2) Auxiliary Space : O(m)This article is contributed by Pratik Chhajer. 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.
ankthon
divyeshrabadiya07
prasanna1995
shinjanpatra
surinderdawra388
divisibility
subset
Dynamic Programming
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Coin Change | DP-7
Sieve of Eratosthenes
Edit Distance | DP-5
Efficient program to print all prime factors of a given number
Overlapping Subproblems Property in Dynamic Programming | DP-1 | [
{
"code": null,
"e": 24852,
"s": 24824,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 25058,
"s": 24852,
"text": "Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m. Input Constraints Size of set i.e., n <= 1000000, m <= 1000Examples: "
},
{
"code": null,
"e": 25168,
"s": 25058,
"text": "Input : arr[] = {3, 1, 7, 5};\n m = 6;\nOutput : YES\n\nInput : arr[] = {1, 6};\n m = 5;\nOutput : NO"
},
{
"code": null,
"e": 25366,
"s": 25170,
"text": "This problem is a variant of subset sum problem. In subset sum problem we check if given sum subset exists or not, here we need to find if there exists some subset with sum divisible by m or not."
},
{
"code": null,
"e": 25401,
"s": 25366,
"text": "Naive Approach( Using Recurison) :"
},
{
"code": null,
"e": 25405,
"s": 25401,
"text": "C++"
},
{
"code": null,
"e": 25413,
"s": 25405,
"text": "Python3"
},
{
"code": null,
"e": 25424,
"s": 25413,
"text": "Javascript"
},
{
"code": "// C++ program to check if there is a subset// with sum divisible by m.#include <bits/stdc++.h>using namespace std; // Returns true if there is a subset// of arr[] with sum divisible by mbool helper(int N, int nums[], int sum, int idx, int m){ // if we reach last index if(idx == N){ // and if the sum mod m is zero if(sum && sum%m == 0){ // return return true ; } return false ; } // 2 choices - to pick or to not pick bool picked = helper(N, nums, sum+nums[idx], idx+1,m) ; bool notPicked = helper(N, nums, sum, idx+1, m) ; return picked || notPicked ;} bool modularSum(int arr[], int n, int m){ return helper(n, arr, 0, 0, m) ;} // Driver codeint main(){ int arr[] = {1, 7}; int n = sizeof(arr)/sizeof(arr[0]); int m = 5; modularSum(arr, n, m) ? cout << \"YES\\n\" : cout << \"NO\\n\"; return 0;}",
"e": 26354,
"s": 25424,
"text": null
},
{
"code": "# Python3 program to check if there is a subset# with sum divisible by m. # Returns true if there is a subset# of arr[] with sum divisible by mdef helper(N, nums, sum, idx, m): # if we reach last index if(idx == N): # and if the sum mod m is zero if(sum and sum%m == 0): # return return True return False # 2 choices - to pick or to not pick picked = helper(N, nums, sum+nums[idx], idx+1,m) notPicked = helper(N, nums, sum, idx+1, m) return picked or notPicked def modularSum(arr, n, m): return helper(n, arr, 0, 0, m) # Driver codearr = [1, 7]n = len(arr)m = 5 print(\"YES\") if modularSum(arr, n, m) else print(\"NO\") # This code is contributed by shinjanpatra.",
"e": 27105,
"s": 26354,
"text": null
},
{
"code": "<script> // JavaScript program to check if there is a subset// with sum divisible by m. // Returns true if there is a subset// of arr[] with sum divisible by mfunction helper(N, nums, sum, idx, m){ // if we reach last index if(idx == N) { // and if the sum mod m is zero if(sum && sum%m == 0) { // return return true ; } return false ; } // 2 choices - to pick or to not pick let picked = helper(N, nums, sum+nums[idx], idx+1,m) ; let notPicked = helper(N, nums, sum, idx+1, m) ; return picked || notPicked ;} function modularSum(arr, n, m){ return helper(n, arr, 0, 0, m) ;} // Driver code let arr = [1, 7];let n = arr.length;let m = 5; modularSum(arr, n, m) ? document.write(\"YES\",\"</br>\") : document.write(\"NO\",\"</br>\"); // This code is contributed by shinjanpatra.</script>",
"e": 27999,
"s": 27105,
"text": null
},
{
"code": null,
"e": 28002,
"s": 27999,
"text": "NO"
},
{
"code": null,
"e": 28025,
"s": 28002,
"text": "Time Complexity: O(2N)"
},
{
"code": null,
"e": 28045,
"s": 28025,
"text": "Efficient Approach:"
},
{
"code": null,
"e": 29011,
"s": 28045,
"text": " Seeing input constraint, it looks like typical DP solution will work in O(nm) time. But in tight time limits in competitive programming, the solution may work. Also auxiliary space is high for DP table, but here is catch.If n > m there will always be a subset with sum divisible by m (which is easy to prove with pigeonhole principle). So we need to handle only cases of n <= m .For n <= m we create a boolean DP table which will store the status of each value from 0 to m-1 which are possible subset sum (modulo m) which have been encountered so far.Now we loop through each element of given array arr[], and we add (modulo m) j which have DP[j] = true, and store all the such (j+arr[i])%m possible subset-sum in a boolean array temp, and at the end of iteration over j, we update DP table with temp. Also we add arr[i] to DP ie.. DP[arr[i]%m] = true. In the end if DP[0] is true then it means YES there exists a subset with sum which is divisible by m, else NO. "
},
{
"code": null,
"e": 29015,
"s": 29011,
"text": "C++"
},
{
"code": null,
"e": 29020,
"s": 29015,
"text": "Java"
},
{
"code": null,
"e": 29028,
"s": 29020,
"text": "Python3"
},
{
"code": null,
"e": 29031,
"s": 29028,
"text": "C#"
},
{
"code": null,
"e": 29035,
"s": 29031,
"text": "PHP"
},
{
"code": null,
"e": 29046,
"s": 29035,
"text": "Javascript"
},
{
"code": "// C++ program to check if there is a subset// with sum divisible by m.#include <bits/stdc++.h>using namespace std; // Returns true if there is a subset// of arr[] with sum divisible by mbool modularSum(int arr[], int n, int m){ if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false bool DP[m]; memset(DP, false, m); // we'll loop through all the elements of arr[] for (int i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. bool temp[m]; memset(temp,false,m); // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (int j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0];} // Driver codeint main(){ int arr[] = {1, 7}; int n = sizeof(arr)/sizeof(arr[0]); int m = 5; modularSum(arr, n, m) ? cout << \"YES\\n\" : cout << \"NO\\n\"; return 0;}",
"e": 31131,
"s": 29046,
"text": null
},
{
"code": "// Java program to check if there is a subset// with sum divisible by m.import java.util.Arrays; class GFG { // Returns true if there is a subset // of arr[] with sum divisible by m static boolean modularSum(int arr[], int n, int m) { if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false boolean DP[]=new boolean[m]; Arrays.fill(DP, false); // we'll loop through all the elements // of arr[] for (int i = 0; i < n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum // (after modulo). It is used to make // sure that arr[i] is added only to // those entries for which DP[j] // was true before current iteration. boolean temp[] = new boolean[m]; Arrays.fill(temp, false); // For each element of arr[], we loop // through all elements of DP table // from 1 to m and we add current // element i. e., arr[i] to all those // elements which are true in DP table for (int j = 0; j < m; j++) { // if an element is true in // DP table if (DP[j] == true) { if (DP[(j + arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j + arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j = 0; j < m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single // element subset, arr[i]%m is one // of the possible sum DP[arr[i] % m] = true; } return DP[0]; } //driver code public static void main(String arg[]) { int arr[] = {1, 7}; int n = arr.length; int m = 5; if(modularSum(arr, n, m)) System.out.print(\"YES\\n\"); else System.out.print(\"NO\\n\"); }} //This code is contributed by Anant Agarwal.",
"e": 33754,
"s": 31131,
"text": null
},
{
"code": "# Python3 program to check if there is# a subset with sum divisible by m. # Returns true if there is a subset# of arr[] with sum divisible by mdef modularSum(arr, n, m): if (n > m): return True # This array will keep track of all # the possible sum (after modulo m) # which can be made using subsets of arr[] # initialising boolean array with all false DP = [False for i in range(m)] # we'll loop through all the elements of arr[] for i in range(n): # anytime we encounter a sum divisible # by m, we are done if (DP[0]): return True # To store all the new encountered sum (after # modulo). It is used to make sure that arr[i] # is added only to those entries for which DP[j] # was true before current iteration. temp = [False for i in range(m)] # For each element of arr[], we loop through # all elements of DP table from 1 to m and # we add current element i. e., arr[i] to # all those elements which are true in DP # table for j in range(m): # if an element is true in DP table if (DP[j] == True): if (DP[(j + arr[i]) % m] == False): # We update it in temp and update # to DP once loop of j is over temp[(j + arr[i]) % m] = True # Updating all the elements of temp # to DP table since iteration over # j is over for j in range(m): if (temp[j]): DP[j] = True # Also since arr[i] is a single element # subset, arr[i]%m is one of the possible # sum DP[arr[i] % m] = True return DP[0] # Driver codearr = [1, 7]n = len(arr)m = 5print(\"YES\") if(modularSum(arr, n, m)) else print(\"NO\") # This code is contributed by Anant Agarwal.",
"e": 35651,
"s": 33754,
"text": null
},
{
"code": "// C# program to check if there is// a subset with sum divisible by m.using System; class GFG { // Returns true if there is a subset// of arr[] with sum divisible by mstatic bool modularSum(int []arr, int n, int m){ if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false bool []DP=new bool[m]; for (int l=0;l<DP.Length;l++) DP[l]=false; // we'll loop through all the elements of arr[] for (int i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. bool []temp=new bool[m]; for (int l=0;l<temp.Length;l++) temp[l]=false; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (int j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (int j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0];} //driver codepublic static void Main(){ int []arr = {1, 7}; int n = arr.Length; int m = 5; if(modularSum(arr, n, m)) Console.Write(\"YES\\n\"); else Console.Write(\"NO\\n\");}} //This code is contributed by Anant Agarwal.",
"e": 37882,
"s": 35651,
"text": null
},
{
"code": "<?php// Php program to check if there is a// subset with sum divisible by m. // Returns true if there is a subset// of arr[] with sum divisible by mfunction modularSum($arr, $n, $m){ if ($n > $m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false $DP = Array_fill(0, $m, false); // we'll loop through all the elements of arr[] for ($i = 0; $i < $n; $i++) { // anytime we encounter a sum divisible // by m, we are done if ($DP[0]) return true; // To store all the new encountered sum // (after modulo). It is used to make // sure that arr[i] is added only to those // entries for which DP[j] was true before // current iteration. $temp = array_fill(0, $m, false) ; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for ($j = 0; $j < $m; $j++) { // if an element is true in DP table if ($DP[$j] == true) { if ($DP[($j + $arr[$i]) % $m] == false) // We update it in temp and update // to DP once loop of j is over $temp[($j + $arr[$i]) % $m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for ($j = 0; $j < $m; $j++) if ($temp[$j]) $DP[$j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum $DP[$arr[$i] % $m] = true; } return $DP[0];} // Driver Code$arr = array(1, 7);$n = sizeof($arr);$m = 5; if (modularSum($arr, $n, $m) == true ) echo \"YES\\n\";else echo \"NO\\n\"; // This code is contributed by Ryuga?>",
"e": 39925,
"s": 37882,
"text": null
},
{
"code": "<script> // JavaScript program to check if there is // a subset with sum divisible by m. // Returns true if there is a subset // of arr[] with sum divisible by m function modularSum(arr, n, m) { if (n > m) return true; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false let DP = new Array(m); for (let l=0;l<m;l++) DP[l]=false; // we'll loop through all the elements of arr[] for (let i=0; i<n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[0]) return true; // To store all the new encountered sum (after // modulo). It is used to make sure that arr[i] // is added only to those entries for which DP[j] // was true before current iteration. let temp=new Array(m); for (let l=0;l<m;l++) temp[l]=false; // For each element of arr[], we loop through // all elements of DP table from 1 to m and // we add current element i. e., arr[i] to // all those elements which are true in DP // table for (let j=0; j<m; j++) { // if an element is true in DP table if (DP[j] == true) { if (DP[(j+arr[i]) % m] == false) // We update it in temp and update // to DP once loop of j is over temp[(j+arr[i]) % m] = true; } } // Updating all the elements of temp // to DP table since iteration over // j is over for (let j=0; j<m; j++) if (temp[j]) DP[j] = true; // Also since arr[i] is a single element // subset, arr[i]%m is one of the possible // sum DP[arr[i]%m] = true; } return DP[0]; } let arr = [1, 7]; let n = arr.length; let m = 5; if(modularSum(arr, n, m)) document.write(\"YES\" + \"</br>\"); else document.write(\"NO\" + \"</br>\"); </script>",
"e": 42262,
"s": 39925,
"text": null
},
{
"code": null,
"e": 42265,
"s": 42262,
"text": "NO"
},
{
"code": null,
"e": 42734,
"s": 42265,
"text": "Time Complexity : O(m^2) Auxiliary Space : O(m)This article is contributed by Pratik Chhajer. 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": 42742,
"s": 42734,
"text": "ankthon"
},
{
"code": null,
"e": 42760,
"s": 42742,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 42773,
"s": 42760,
"text": "prasanna1995"
},
{
"code": null,
"e": 42786,
"s": 42773,
"text": "shinjanpatra"
},
{
"code": null,
"e": 42803,
"s": 42786,
"text": "surinderdawra388"
},
{
"code": null,
"e": 42816,
"s": 42803,
"text": "divisibility"
},
{
"code": null,
"e": 42823,
"s": 42816,
"text": "subset"
},
{
"code": null,
"e": 42843,
"s": 42823,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42863,
"s": 42843,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42870,
"s": 42863,
"text": "subset"
},
{
"code": null,
"e": 42968,
"s": 42870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42977,
"s": 42968,
"text": "Comments"
},
{
"code": null,
"e": 42990,
"s": 42977,
"text": "Old Comments"
},
{
"code": null,
"e": 43021,
"s": 42990,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 43054,
"s": 43021,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 43092,
"s": 43054,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 43127,
"s": 43092,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 43195,
"s": 43127,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43214,
"s": 43195,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 43236,
"s": 43214,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 43257,
"s": 43236,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 43320,
"s": 43257,
"text": "Efficient program to print all prime factors of a given number"
}
] |
How to move the x-axis to top in a JavaFX line chart? | Inline chart, the data values have represented a series of points connected by a line. In JavaFX, you can create a line chart by instantiating the javafx.scene.chart.LineChart class.
By default,
A JavaFX Line chart contains symbols pointing out the values in the series
along the x-axis. Typically, these are small circles.
A JavaFX Line chart contains symbols pointing out the values in the series
along the x-axis. Typically, these are small circles.
The X-Axis on the bottom in the plot.
The X-Axis on the bottom in the plot.
Y-Axis on the left.
Y-Axis on the left.
The Axis class (superclass of all axes) has a property named side, this specifies the side of the plot at which you need to have the current axis (left, right, top-bottom). You can set the value to this property using the setSide() method. This method accepts one of the following values as a parameter −
Side.BOTTOM
Side.BOTTOM
Side.TOP
Side.TOP
Side.LEFT
Side.LEFT
Side.RIGHT
Side.RIGHT
To move the X-Axis to top, invoke the setSide() method on the object of the XAxis of your plot by passing the value Side.TOP as a parameter.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class LineChartAxisShift extends Application {
public void start(Stage stage) {
//Defining the x an y axes
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
//Setting labels for the axes
xAxis.setLabel("Months");
yAxis.setLabel("Rainfall (mm)");
//Creating a line chart
LineChart linechart = new LineChart(xAxis, yAxis);
//Preparing the data points for the line1
XYChart.Series series = new XYChart.Series();
series.getData().add(new XYChart.Data("Jul", 169.9));
series.getData().add(new XYChart.Data("Aug", 178.7));
series.getData().add(new XYChart.Data("Sep", 158.3));
series.getData().add(new XYChart.Data("Oct", 97.2));
series.getData().add(new XYChart.Data("Nov", 22.4));
series.getData().add(new XYChart.Data("Dec", 5.9));
//Setting the name to the line (series)
series.setName("Rainfall In Hyderabad");
//Setting the data to Line chart
linechart.getData().add(series);
//Shifting the X-axis
xAxis.setSide(Side.TOP);
//Creating a stack pane to hold the chart
StackPane pane = new StackPane(linechart);
pane.setPadding(new Insets(15, 15, 15, 15));
pane.setStyle("-fx-background-color: BEIGE");
//Setting the Scene
Scene scene = new Scene(pane, 595, 350);
stage.setTitle("Line Chart");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Inline chart, the data values have represented a series of points connected by a line. In JavaFX, you can create a line chart by instantiating the javafx.scene.chart.LineChart class."
},
{
"code": null,
"e": 1257,
"s": 1245,
"text": "By default,"
},
{
"code": null,
"e": 1386,
"s": 1257,
"text": "A JavaFX Line chart contains symbols pointing out the values in the series\nalong the x-axis. Typically, these are small circles."
},
{
"code": null,
"e": 1515,
"s": 1386,
"text": "A JavaFX Line chart contains symbols pointing out the values in the series\nalong the x-axis. Typically, these are small circles."
},
{
"code": null,
"e": 1553,
"s": 1515,
"text": "The X-Axis on the bottom in the plot."
},
{
"code": null,
"e": 1591,
"s": 1553,
"text": "The X-Axis on the bottom in the plot."
},
{
"code": null,
"e": 1611,
"s": 1591,
"text": "Y-Axis on the left."
},
{
"code": null,
"e": 1631,
"s": 1611,
"text": "Y-Axis on the left."
},
{
"code": null,
"e": 1936,
"s": 1631,
"text": "The Axis class (superclass of all axes) has a property named side, this specifies the side of the plot at which you need to have the current axis (left, right, top-bottom). You can set the value to this property using the setSide() method. This method accepts one of the following values as a parameter −"
},
{
"code": null,
"e": 1948,
"s": 1936,
"text": "Side.BOTTOM"
},
{
"code": null,
"e": 1960,
"s": 1948,
"text": "Side.BOTTOM"
},
{
"code": null,
"e": 1969,
"s": 1960,
"text": "Side.TOP"
},
{
"code": null,
"e": 1978,
"s": 1969,
"text": "Side.TOP"
},
{
"code": null,
"e": 1988,
"s": 1978,
"text": "Side.LEFT"
},
{
"code": null,
"e": 1998,
"s": 1988,
"text": "Side.LEFT"
},
{
"code": null,
"e": 2009,
"s": 1998,
"text": "Side.RIGHT"
},
{
"code": null,
"e": 2020,
"s": 2009,
"text": "Side.RIGHT"
},
{
"code": null,
"e": 2161,
"s": 2020,
"text": "To move the X-Axis to top, invoke the setSide() method on the object of the XAxis of your plot by passing the value Side.TOP as a parameter."
},
{
"code": null,
"e": 4028,
"s": 2161,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.geometry.Side;\nimport javafx.scene.Scene;\nimport javafx.stage.Stage;\nimport javafx.scene.chart.CategoryAxis;\nimport javafx.scene.chart.LineChart;\nimport javafx.scene.chart.NumberAxis;\nimport javafx.scene.chart.XYChart;\nimport javafx.scene.layout.StackPane;\npublic class LineChartAxisShift extends Application {\n public void start(Stage stage) {\n //Defining the x an y axes\n CategoryAxis xAxis = new CategoryAxis();\n NumberAxis yAxis = new NumberAxis();\n //Setting labels for the axes\n xAxis.setLabel(\"Months\");\n yAxis.setLabel(\"Rainfall (mm)\");\n //Creating a line chart\n LineChart linechart = new LineChart(xAxis, yAxis);\n //Preparing the data points for the line1\n XYChart.Series series = new XYChart.Series();\n series.getData().add(new XYChart.Data(\"Jul\", 169.9));\n series.getData().add(new XYChart.Data(\"Aug\", 178.7));\n series.getData().add(new XYChart.Data(\"Sep\", 158.3));\n series.getData().add(new XYChart.Data(\"Oct\", 97.2));\n series.getData().add(new XYChart.Data(\"Nov\", 22.4));\n series.getData().add(new XYChart.Data(\"Dec\", 5.9));\n //Setting the name to the line (series)\n series.setName(\"Rainfall In Hyderabad\");\n //Setting the data to Line chart\n linechart.getData().add(series);\n //Shifting the X-axis\n xAxis.setSide(Side.TOP);\n //Creating a stack pane to hold the chart\n StackPane pane = new StackPane(linechart);\n pane.setPadding(new Insets(15, 15, 15, 15));\n pane.setStyle(\"-fx-background-color: BEIGE\");\n //Setting the Scene\n Scene scene = new Scene(pane, 595, 350);\n stage.setTitle(\"Line Chart\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Implementation Differences in LSTM Layers: TensorFlow vs PyTorch | by Madhushan Buwaneswaran | Towards Data Science | Tensorflow and Pytorch are the two most widely used libraries in deep learning. Both these libraries have different approaches when it comes to implementing neural networks. Both these libraries started with major differences. Usually, TF was more preferred for developing production-ready models due to its better optimizations, and Pytorch was preferred for research works due to its more “pythonic” syntax and eager execution. But with Torchscript and TF 2.0, the gap between the two libraries has shrunk.
Both of these libraries have good community support and active contributions. So we can easily implement different types of neural networks without any major issues in both these libraries. But these two libraries have architectural differences. Hence, there are certain differences we need to focus on when implementing a neural network.
One such difference is in the layers API. A neural network (NN) can be designed using either the sub-classing approach or sequential model API approach in both these libraries. The sub-classing approach is more preferred out of the two since it is object-oriented and extensible. When implementing a NN in either of these libraries, we can use already designed layers — linear (fully connected) layers, convolution layers, recurrent layers, etc. and extend them into our model. In TF, we use tensorflow.keras.layers, and in Pytorch, we use torch.nn to access these layers. As I mentioned earlier, there are subtle differences in the implementation of these layers. Most of the time, they are minor and intuitive. But in LSTM (Long Short-Term Memory) layers, these differences are somewhat major and significant. The way the layer is parameterized, the default values for the parameters, and the default output of the layer mostly differ between Pytorch and TF in LSTM layers.
In this post, I will try to explain the differences between LSTM layers in these two libraries. I hope it will be of help if someone refers to a NN (with LSTM layers) implemented in one library and tries to reproduce it in the other.
I have added this section only for the sake of completion and as a refresher (in case one needs it). But if you are trying to understand the implementation differences when using LSTM layers, then I hope you already have a background in deep learning and know the fundamentals of LSTMs. So you can skip this part.
A recurrent neural network (RNN) is a special type of NN which is designed to learn from sequential data. A conventional NN would take an input and give a prediction based on that input only. It doesn’t look into previous inputs/outputs and make a decision. But when predicting the next value in sequential data (eg. — sentences, the daily average temperature in a city), we cannot do it by looking at the current data point only. We have to look at the behavior of the series (up to the current point) as a whole and get the ‘context of the series’ to make a meaningful prediction. This is what RNNs are specialized for. RNNs are used for tasks like language modeling, machine translation, sequence prediction, etc.
Fig. 1 shows how an RNN takes the current value and previous lateral output as input. The lateral output of the previous timestep is passed by the recurrent mechanism (as at). It is expected (and proven) that the RNN layer will learn to capture the ‘context’ of the sequence in the lateral output. Please note that the unrolled version of the RNN shown in fig. 1 (b) depicts the same layer as copies for better understanding and doesn’t represent multiple layers.
xt - Primary input at timestep t. Shape - (nx,1)
at - Lateral output at timestep t (also the lateral input with a unit time delay). Shape - (na,1)
ht - Primary output at timestep t. Shape - (nh,1)
Waa - Weight matrix that is multiplied with lateral input. Shape - (na,na)
Wax - Weight matrix that is multiplied with primary input. Shape - (na,nx)
ba - Bias term added when generating at. Shape - (na,1)
Wha - Weight matrix that is multiplied with at when generating ht. Shape - (nh,na)
bh - Bias term added when generating ht. Shape - (nh,1)
g() - non linear activation function (eg.- σ(), tanh() )
The design principle of RNN expects that the ‘context’ derived from earlier values in the series persists along the sequence for a long range. But it was observed in practical scenarios, the RNN’s ability to learn the ‘context’ of a sequence deteriorates with distance. That is, RNNs are not good enough to capture long-term dependencies in sequences. Long Short-Term Memory (LSTM) networks are a specialized version of RNN that was introduced with the intention of preserving long-term ‘context’ information in sequences. The inherent design of LSTMs enables them to capture the long-term context through what is known as cell state (denoted by ct). The diagram below (Fig. 2) shows a typical LSTM layer. The diagram I used is based on the diagrams used in a blog post on understanding LSTMs by Chris Olah. (It is a wonderful blog post. Do check it out.)
xt - Primary input at timestep t. Shape - (nx,1)
ct - Cell state at timestep t. Shape - (nh,1)
ht - Primary output at timestep t. Shape - (nh,1)
c~t - Candidate vector to update ct. Shape - (nh,1)
Γf - Forget gate mask. Shape - (nh,1)
Γu - Update gate mask. Shape - (nh,1)
Γo - Output gate mask. Shape - (nh,1)
Wc - Weight matrix used to generate candidate vector. Shape - (nh,nh+nx)
bc - Bias term used to generate candidate vector. Shape (nh,1)
Wf - Weight matrix in forget gate. Shape - (nh,nh+nx)
bf - Bias term in forget gate. Shape - (nh,1)
Wu - Weight matrix in update gate. Shape - (nh,nh+nx)
bu - Bias term in update gate. Shape - (nh,1)
Wo - Weight matrix in output gate. Shape - (nh,nh+nx)
bo - Bias term in output gate. Shape - (nh,1)
As Chris explains in his blog, the cell state can be thought of as a conveyor belt, which carries the long-term ‘context’ from start to end of the sequence. At each timestep based on the current input (xt) and the previous output (ht−1), the LSTM layer decides what information to forget from the ‘context’ and what information to add to the ‘context’. The forgetting is handled by the forget gate (Γf). Γf can be thought of as a mask that is applied to ct−1. If a value in a certain position in Γf is 0 (or closer), when multiplied with ct−1, it removes the information in that position from the context. If the value of the mask is 1 (or closer) in some other position, after multiplication with ct−1, it allows the information in that position to persist in the context. The operation Γf.*ct−1 (.* — element-wise multiplication) makes sure that the unwanted part of the context is forgotten. The addition of new information to the cell state is handled in two steps. First, a candidate vector (c̃t) is created through the sub-layer with tanh activation, based on xt and ht−1. Then the update gate (Γu) generates a mask (just like in forget gate) which decides what part of the candidate vector is added to the cell state. ThenΓu.*c̃t is added to ct−1 to generate ct. Finally, to generate the output, we pass ct through a tanh non-linearity and use it. But to decide what part of it to give out, we make use of the update gate (Γo). Γo.*tanh(ct) is given out as the output of the LSTM layer at timestep t.
Please note that both ct−1 and ht−1 are given as lateral inputs in an LSTM layer, compared to the vanilla RNN layer where only at−1 is given.
If you need additional information on the principles of RNN and LSTM, I would recommend going through the first week of the Sequence Models course by Andrew Ng (it is free to audit) and reading this wonderful blog post by Chris Olah.
At the time of writing Tensorflow version was 2.4.1
In TF, we can use tf.keras.layers.LSTM and create an LSTM layer. When initializing an LSTM layer, the only required parameter is units. The parameter units corresponds to the number of output features of that layer. That is units = nh in our terminology. nx will be inferred from the output of the previous layer. Hence the library can initialize all the weight and bias terms in the LSTM layer.
TF LSTM layer expects a 3 dimensional tensor as input during forward propagation. This input should be of the shape (batch, timesteps, input_features). This is shown in the code snippet below. Suppose we are using this LSTM layer to train a language model. Our input will be sentences. The first dimension corresponds to how many sentences we use as one batch to train the model. The second dimension corresponds to how many words are present in one such sentence. In practical setting, the number of words in each sentence varies from sentence to sentence. So, in order to batch these sentences, we can select the length of the longest sentence in the training corpus as this dimension and pad the other sentences with trailing zeros. The last dimension corresponds to the number of features used to represent each word. For simplicity, if we say, we are using one-hot encoding and there are 10000 words in our vocabulary, then this dimension will be 10000.
import tensorflow as tf
batch_size = 32
timesteps = 10
input_features = 8
output_features = 4
inputs = tf.random.normal([batch_size, timesteps, input_features])
lstm = tf.keras.layers.LSTM(units=output_features)
output = lstm(inputs)
print("Output shape of the LSTM layer's default output : ", output.shape)
Output shape of the LSTM layer's default output : (32, 4)
The output is of the shape : (batch_size, output_features) - (nbatch,nh)
This output corresponds to hT where T is the last timestep in the sequence.
But when initializing the layer, if we set time_major = True, then the input will be expected in the shape - (timesteps, batch, feature).
As seen from the above code snippet, the output of the LSTM (with default parameters) is of shape (32,4), which corresponds to (batch, output_features). So if we go back to the example of the language model, the output has one vector per sentence, with nh number of features per sentence (nh = units = no. of output features). This one vector (per sentence) is the output of the LSTM layer corresponding to the last timestep T (last word of the sentence). This output is hT in our notation. This is depicted in fig. 3.
However, if we want to stack multiple LSTM layers, the next layer also expects a time series as input. In such situations, we can set return_sequences=True when initiating the layer. Then the output will be of shape (32,10,4), which corresponds to (batch, timesteps, output_features). If return_sequence is set to True, then ht : ∀t = 1,2...T will be returned as output. This is shown in the code snippet below and the first LSTM layer in fig. 4.
If we want to get the cell state (ct) as an output, we need to set return_state=True when initiating the layer. Then We get a list of 3 tensors as output. According to documentation, if we set both return_sequences=True and return_state=True, these three tensors will be — whole_seq_output, final_memory_state,and final_carry_state. This is shown in the code snippet below.
In our notation,
whole_seq_output — output corresponding to all timesteps. ht : ∀t = 1,2...T ; Shape — (batch, timesteps, output_features)
final_memory_state — Output corresponding to the last timestep.hT; Shape — (batch, output_features)
final_carry_state — Last cell state.cT; Shape — (batch, output_features)
If we set return_sequences=False and return_state=True, then these three tensors will be — final_memory_state, final_memory_state, and final_carry_state.
A single LSTM layer has five places where activation functions are used. But if we look at the parameters, we see only two parameters to set activation functions — activation and recurrent_activation. If we set a value to the activation parameter, it changes the activation applied to the candidate vector and the activation applied to the cell state just before element-wise multiplication with the output gate. Setting a value to recurrent_activation will change the activation functions of forget gate, update gate, and output gate.
Other parameters are quite self-explanatory or seldom used. One other thing to note is, we can set unroll=True, and the network will be unrolled. It will speed up the training process but will be memory intensive (since the same layer is copied multiple times).
The following code snippet implements the model shown in fig. 4 using TF. Note the output shape of each layer and the number of trainable parameters in each layer.
At the time of writing, Pytorch version was 1.8.1
In Pytorch, an LSTM layer can be created using torch.nn.LSTM. It requires two parameters at initiation input_size and hidden_size.input_size and hidden_size correspond to the number of input features to the layer and the number of output features of that layer, respectively. In our terminology, hidden_size = nh and input_size = nx.
During forward propagation, the Pytorch LSTM layer expects a 3 dimensional tensor as input (similar to TF). But the default ordering of the dimensions changes. The input tensor should be of shape (timesteps, batch, input_features). If we want to get the same order of dimensions as TF, we should set batch_first=True at layer initiation.
Another major difference that can be seen in Pytorch LSTM API is that, at initiation, we can set num_layers=k and initiate a block of k LSTM layers stacked as a single object. However, I personally do not prefer this approach since it makes the overall implementation less readable and less maintainable.
The next big difference is the output of the Pytorch LSTM layer. The output of the Pytorch LSTM layer is a tuple with two elements. The first element of the tuple is LSTM’s output corresponding to all timesteps (ht : ∀t = 1,2...T) with shape (timesteps, batch, output_features). The second element of the tuple is another tuple with two elements. The first element of this second tuple is the output corresponding to the last timestep (hT). It has the shape (1, batch, output_features). The second element of this second tuple is the cell state corresponding to the last timestep (cT). It also has the shape (1, batch, output_features). If we had initiated the LSTM as a block of stacked layers by setting num_layers=k, then hT and cT would have the shape (k, batch, output_features). Here, both hT and cT would have the last states of all the k layers in the stack. Further at initiation, had we set batch_first=True, then the timesteps and batch dimensions would swap in the output (similar to the input).
As far as I know, changing the activation functions inside the LSTM layer is not possible in Pytorch. Also, it is not possible to limit the LSTM layer to give only one output (as in TF). However, we can assign the outputs to variables, use the required output, and ignore the others, as shown in the code segment below. Apart from that, other parameters should be self-explanatory.
Note that if you set the LSTM layer to be bidirectional (which I didn’t talk about in this article), then the output shape will be different from what I have mentioned above. Please refer to the documentation for such a scenario.
The following code snippet implements the model shown in fig. 4 using Pytorch. Note the output shape of each layer and the number of trainable parameters in each layer.
If we look at the number of parameters in the two implementations of the model in fig. 4., it can be observed that there is a difference in the number of parameters in LSTM layers. This is again a design choice. Pytorch does a minor change when implementing the LSTM equations (1), (2), (3), and (4). TF adds a single bias vector (as in our equations) in each of these equations. But Pytorch (as shown here) adds two bias vectors per equation. Since the shape of each bias vector is (nh,1) and four such additional vectors are there per layer, there will be 4*nh more parameters in the Pytorch LSTM layers. In LSTM1 layer nh=8, so there are 32 additional parameters. In LSTM2 layer nh=4, so there are 16 more parameters. | [
{
"code": null,
"e": 681,
"s": 172,
"text": "Tensorflow and Pytorch are the two most widely used libraries in deep learning. Both these libraries have different approaches when it comes to implementing neural networks. Both these libraries started with major differences. Usually, TF was more preferred for developing production-ready models due to its better optimizations, and Pytorch was preferred for research works due to its more “pythonic” syntax and eager execution. But with Torchscript and TF 2.0, the gap between the two libraries has shrunk."
},
{
"code": null,
"e": 1020,
"s": 681,
"text": "Both of these libraries have good community support and active contributions. So we can easily implement different types of neural networks without any major issues in both these libraries. But these two libraries have architectural differences. Hence, there are certain differences we need to focus on when implementing a neural network."
},
{
"code": null,
"e": 1996,
"s": 1020,
"text": "One such difference is in the layers API. A neural network (NN) can be designed using either the sub-classing approach or sequential model API approach in both these libraries. The sub-classing approach is more preferred out of the two since it is object-oriented and extensible. When implementing a NN in either of these libraries, we can use already designed layers — linear (fully connected) layers, convolution layers, recurrent layers, etc. and extend them into our model. In TF, we use tensorflow.keras.layers, and in Pytorch, we use torch.nn to access these layers. As I mentioned earlier, there are subtle differences in the implementation of these layers. Most of the time, they are minor and intuitive. But in LSTM (Long Short-Term Memory) layers, these differences are somewhat major and significant. The way the layer is parameterized, the default values for the parameters, and the default output of the layer mostly differ between Pytorch and TF in LSTM layers."
},
{
"code": null,
"e": 2230,
"s": 1996,
"text": "In this post, I will try to explain the differences between LSTM layers in these two libraries. I hope it will be of help if someone refers to a NN (with LSTM layers) implemented in one library and tries to reproduce it in the other."
},
{
"code": null,
"e": 2544,
"s": 2230,
"text": "I have added this section only for the sake of completion and as a refresher (in case one needs it). But if you are trying to understand the implementation differences when using LSTM layers, then I hope you already have a background in deep learning and know the fundamentals of LSTMs. So you can skip this part."
},
{
"code": null,
"e": 3261,
"s": 2544,
"text": "A recurrent neural network (RNN) is a special type of NN which is designed to learn from sequential data. A conventional NN would take an input and give a prediction based on that input only. It doesn’t look into previous inputs/outputs and make a decision. But when predicting the next value in sequential data (eg. — sentences, the daily average temperature in a city), we cannot do it by looking at the current data point only. We have to look at the behavior of the series (up to the current point) as a whole and get the ‘context of the series’ to make a meaningful prediction. This is what RNNs are specialized for. RNNs are used for tasks like language modeling, machine translation, sequence prediction, etc."
},
{
"code": null,
"e": 3725,
"s": 3261,
"text": "Fig. 1 shows how an RNN takes the current value and previous lateral output as input. The lateral output of the previous timestep is passed by the recurrent mechanism (as at). It is expected (and proven) that the RNN layer will learn to capture the ‘context’ of the sequence in the lateral output. Please note that the unrolled version of the RNN shown in fig. 1 (b) depicts the same layer as copies for better understanding and doesn’t represent multiple layers."
},
{
"code": null,
"e": 4326,
"s": 3725,
"text": "xt - Primary input at timestep t. Shape - (nx,1)\nat - Lateral output at timestep t (also the lateral input with a unit time delay). Shape - (na,1)\nht - Primary output at timestep t. Shape - (nh,1)\nWaa - Weight matrix that is multiplied with lateral input. Shape - (na,na)\nWax - Weight matrix that is multiplied with primary input. Shape - (na,nx)\nba - Bias term added when generating at. Shape - (na,1)\nWha - Weight matrix that is multiplied with at when generating ht. Shape - (nh,na)\nbh - Bias term added when generating ht. Shape - (nh,1)\ng() - non linear activation function (eg.- σ(), tanh() )"
},
{
"code": null,
"e": 5182,
"s": 4326,
"text": "The design principle of RNN expects that the ‘context’ derived from earlier values in the series persists along the sequence for a long range. But it was observed in practical scenarios, the RNN’s ability to learn the ‘context’ of a sequence deteriorates with distance. That is, RNNs are not good enough to capture long-term dependencies in sequences. Long Short-Term Memory (LSTM) networks are a specialized version of RNN that was introduced with the intention of preserving long-term ‘context’ information in sequences. The inherent design of LSTMs enables them to capture the long-term context through what is known as cell state (denoted by ct). The diagram below (Fig. 2) shows a typical LSTM layer. The diagram I used is based on the diagrams used in a blog post on understanding LSTMs by Chris Olah. (It is a wonderful blog post. Do check it out.)"
},
{
"code": null,
"e": 5379,
"s": 5182,
"text": "xt - Primary input at timestep t. Shape - (nx,1)\nct - Cell state at timestep t. Shape - (nh,1)\nht - Primary output at timestep t. Shape - (nh,1)\nc~t - Candidate vector to update ct. Shape - (nh,1)"
},
{
"code": null,
"e": 5493,
"s": 5379,
"text": "Γf - Forget gate mask. Shape - (nh,1)\nΓu - Update gate mask. Shape - (nh,1)\nΓo - Output gate mask. Shape - (nh,1)"
},
{
"code": null,
"e": 5929,
"s": 5493,
"text": "Wc - Weight matrix used to generate candidate vector. Shape - (nh,nh+nx)\nbc - Bias term used to generate candidate vector. Shape (nh,1)\nWf - Weight matrix in forget gate. Shape - (nh,nh+nx)\nbf - Bias term in forget gate. Shape - (nh,1)\nWu - Weight matrix in update gate. Shape - (nh,nh+nx)\nbu - Bias term in update gate. Shape - (nh,1)\nWo - Weight matrix in output gate. Shape - (nh,nh+nx)\nbo - Bias term in output gate. Shape - (nh,1)"
},
{
"code": null,
"e": 7437,
"s": 5929,
"text": "As Chris explains in his blog, the cell state can be thought of as a conveyor belt, which carries the long-term ‘context’ from start to end of the sequence. At each timestep based on the current input (xt) and the previous output (ht−1), the LSTM layer decides what information to forget from the ‘context’ and what information to add to the ‘context’. The forgetting is handled by the forget gate (Γf). Γf can be thought of as a mask that is applied to ct−1. If a value in a certain position in Γf is 0 (or closer), when multiplied with ct−1, it removes the information in that position from the context. If the value of the mask is 1 (or closer) in some other position, after multiplication with ct−1, it allows the information in that position to persist in the context. The operation Γf.*ct−1 (.* — element-wise multiplication) makes sure that the unwanted part of the context is forgotten. The addition of new information to the cell state is handled in two steps. First, a candidate vector (c̃t) is created through the sub-layer with tanh activation, based on xt and ht−1. Then the update gate (Γu) generates a mask (just like in forget gate) which decides what part of the candidate vector is added to the cell state. ThenΓu.*c̃t is added to ct−1 to generate ct. Finally, to generate the output, we pass ct through a tanh non-linearity and use it. But to decide what part of it to give out, we make use of the update gate (Γo). Γo.*tanh(ct) is given out as the output of the LSTM layer at timestep t."
},
{
"code": null,
"e": 7579,
"s": 7437,
"text": "Please note that both ct−1 and ht−1 are given as lateral inputs in an LSTM layer, compared to the vanilla RNN layer where only at−1 is given."
},
{
"code": null,
"e": 7813,
"s": 7579,
"text": "If you need additional information on the principles of RNN and LSTM, I would recommend going through the first week of the Sequence Models course by Andrew Ng (it is free to audit) and reading this wonderful blog post by Chris Olah."
},
{
"code": null,
"e": 7865,
"s": 7813,
"text": "At the time of writing Tensorflow version was 2.4.1"
},
{
"code": null,
"e": 8261,
"s": 7865,
"text": "In TF, we can use tf.keras.layers.LSTM and create an LSTM layer. When initializing an LSTM layer, the only required parameter is units. The parameter units corresponds to the number of output features of that layer. That is units = nh in our terminology. nx will be inferred from the output of the previous layer. Hence the library can initialize all the weight and bias terms in the LSTM layer."
},
{
"code": null,
"e": 9220,
"s": 8261,
"text": "TF LSTM layer expects a 3 dimensional tensor as input during forward propagation. This input should be of the shape (batch, timesteps, input_features). This is shown in the code snippet below. Suppose we are using this LSTM layer to train a language model. Our input will be sentences. The first dimension corresponds to how many sentences we use as one batch to train the model. The second dimension corresponds to how many words are present in one such sentence. In practical setting, the number of words in each sentence varies from sentence to sentence. So, in order to batch these sentences, we can select the length of the longest sentence in the training corpus as this dimension and pad the other sentences with trailing zeros. The last dimension corresponds to the number of features used to represent each word. For simplicity, if we say, we are using one-hot encoding and there are 10000 words in our vocabulary, then this dimension will be 10000."
},
{
"code": null,
"e": 9245,
"s": 9220,
"text": "import tensorflow as tf\n"
},
{
"code": null,
"e": 9532,
"s": 9245,
"text": "batch_size = 32\ntimesteps = 10\ninput_features = 8\noutput_features = 4\n\ninputs = tf.random.normal([batch_size, timesteps, input_features])\nlstm = tf.keras.layers.LSTM(units=output_features)\noutput = lstm(inputs)\n\nprint(\"Output shape of the LSTM layer's default output : \", output.shape)\n"
},
{
"code": null,
"e": 9592,
"s": 9532,
"text": "Output shape of the LSTM layer's default output : (32, 4)\n"
},
{
"code": null,
"e": 9744,
"s": 9592,
"text": "The output is of the shape : (batch_size, output_features) - (nbatch,nh)\nThis output corresponds to hT where T is the last timestep in the sequence."
},
{
"code": null,
"e": 9882,
"s": 9744,
"text": "But when initializing the layer, if we set time_major = True, then the input will be expected in the shape - (timesteps, batch, feature)."
},
{
"code": null,
"e": 10401,
"s": 9882,
"text": "As seen from the above code snippet, the output of the LSTM (with default parameters) is of shape (32,4), which corresponds to (batch, output_features). So if we go back to the example of the language model, the output has one vector per sentence, with nh number of features per sentence (nh = units = no. of output features). This one vector (per sentence) is the output of the LSTM layer corresponding to the last timestep T (last word of the sentence). This output is hT in our notation. This is depicted in fig. 3."
},
{
"code": null,
"e": 10848,
"s": 10401,
"text": "However, if we want to stack multiple LSTM layers, the next layer also expects a time series as input. In such situations, we can set return_sequences=True when initiating the layer. Then the output will be of shape (32,10,4), which corresponds to (batch, timesteps, output_features). If return_sequence is set to True, then ht : ∀t = 1,2...T will be returned as output. This is shown in the code snippet below and the first LSTM layer in fig. 4."
},
{
"code": null,
"e": 11222,
"s": 10848,
"text": "If we want to get the cell state (ct) as an output, we need to set return_state=True when initiating the layer. Then We get a list of 3 tensors as output. According to documentation, if we set both return_sequences=True and return_state=True, these three tensors will be — whole_seq_output, final_memory_state,and final_carry_state. This is shown in the code snippet below."
},
{
"code": null,
"e": 11239,
"s": 11222,
"text": "In our notation,"
},
{
"code": null,
"e": 11361,
"s": 11239,
"text": "whole_seq_output — output corresponding to all timesteps. ht : ∀t = 1,2...T ; Shape — (batch, timesteps, output_features)"
},
{
"code": null,
"e": 11461,
"s": 11361,
"text": "final_memory_state — Output corresponding to the last timestep.hT; Shape — (batch, output_features)"
},
{
"code": null,
"e": 11534,
"s": 11461,
"text": "final_carry_state — Last cell state.cT; Shape — (batch, output_features)"
},
{
"code": null,
"e": 11688,
"s": 11534,
"text": "If we set return_sequences=False and return_state=True, then these three tensors will be — final_memory_state, final_memory_state, and final_carry_state."
},
{
"code": null,
"e": 12224,
"s": 11688,
"text": "A single LSTM layer has five places where activation functions are used. But if we look at the parameters, we see only two parameters to set activation functions — activation and recurrent_activation. If we set a value to the activation parameter, it changes the activation applied to the candidate vector and the activation applied to the cell state just before element-wise multiplication with the output gate. Setting a value to recurrent_activation will change the activation functions of forget gate, update gate, and output gate."
},
{
"code": null,
"e": 12486,
"s": 12224,
"text": "Other parameters are quite self-explanatory or seldom used. One other thing to note is, we can set unroll=True, and the network will be unrolled. It will speed up the training process but will be memory intensive (since the same layer is copied multiple times)."
},
{
"code": null,
"e": 12650,
"s": 12486,
"text": "The following code snippet implements the model shown in fig. 4 using TF. Note the output shape of each layer and the number of trainable parameters in each layer."
},
{
"code": null,
"e": 12700,
"s": 12650,
"text": "At the time of writing, Pytorch version was 1.8.1"
},
{
"code": null,
"e": 13034,
"s": 12700,
"text": "In Pytorch, an LSTM layer can be created using torch.nn.LSTM. It requires two parameters at initiation input_size and hidden_size.input_size and hidden_size correspond to the number of input features to the layer and the number of output features of that layer, respectively. In our terminology, hidden_size = nh and input_size = nx."
},
{
"code": null,
"e": 13372,
"s": 13034,
"text": "During forward propagation, the Pytorch LSTM layer expects a 3 dimensional tensor as input (similar to TF). But the default ordering of the dimensions changes. The input tensor should be of shape (timesteps, batch, input_features). If we want to get the same order of dimensions as TF, we should set batch_first=True at layer initiation."
},
{
"code": null,
"e": 13677,
"s": 13372,
"text": "Another major difference that can be seen in Pytorch LSTM API is that, at initiation, we can set num_layers=k and initiate a block of k LSTM layers stacked as a single object. However, I personally do not prefer this approach since it makes the overall implementation less readable and less maintainable."
},
{
"code": null,
"e": 14685,
"s": 13677,
"text": "The next big difference is the output of the Pytorch LSTM layer. The output of the Pytorch LSTM layer is a tuple with two elements. The first element of the tuple is LSTM’s output corresponding to all timesteps (ht : ∀t = 1,2...T) with shape (timesteps, batch, output_features). The second element of the tuple is another tuple with two elements. The first element of this second tuple is the output corresponding to the last timestep (hT). It has the shape (1, batch, output_features). The second element of this second tuple is the cell state corresponding to the last timestep (cT). It also has the shape (1, batch, output_features). If we had initiated the LSTM as a block of stacked layers by setting num_layers=k, then hT and cT would have the shape (k, batch, output_features). Here, both hT and cT would have the last states of all the k layers in the stack. Further at initiation, had we set batch_first=True, then the timesteps and batch dimensions would swap in the output (similar to the input)."
},
{
"code": null,
"e": 15067,
"s": 14685,
"text": "As far as I know, changing the activation functions inside the LSTM layer is not possible in Pytorch. Also, it is not possible to limit the LSTM layer to give only one output (as in TF). However, we can assign the outputs to variables, use the required output, and ignore the others, as shown in the code segment below. Apart from that, other parameters should be self-explanatory."
},
{
"code": null,
"e": 15297,
"s": 15067,
"text": "Note that if you set the LSTM layer to be bidirectional (which I didn’t talk about in this article), then the output shape will be different from what I have mentioned above. Please refer to the documentation for such a scenario."
},
{
"code": null,
"e": 15466,
"s": 15297,
"text": "The following code snippet implements the model shown in fig. 4 using Pytorch. Note the output shape of each layer and the number of trainable parameters in each layer."
}
] |
Python | Counting sign change in list containing Positive and Negative Integers - GeeksforGeeks | 21 Jun, 2019
Given a list containing Positive and Negative integers, We have to find number of times the sign(Positive or Negative) changes in the list.
Input: [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12]
Output:9
Explanation :
Sign change from -1 to 2, ans = 1
Sign change from 3 to -4, ans = 2
Sign change from -4 to 5, ans = 3
Sign change from 5 to -6, ans = 4
Sign change from -6 to 7, ans = 5
Sign change from 8 to -9, ans = 6
Sign change from -9 to 10, ans = 7
Sign change from 10 to -11 ans = 8
Sign change from -11 to 12, ans = 9
Input: [-1, 2, 3, -4, 5, -11, 12]
Output:5
Explanation :
Sign change from -1 to 2, ans = 1
Sign change from 3 to -4, ans = 2
Sign change from -4 to 5, ans = 3
Sign change from 5 to -11, ans = 4
Sign change from -11 to 12, ans = 5
Let’s discuss certain ways in which this task is performed.
Method #1: Using IterationUsing Iteration to find number of time sign changes in the list.
# Python Code to find number of # time sign changes in the list. # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] # Variable Initializationprev = Input[0]ans = 0 # Using Iterationfor elem in Input: if elem == 0: sign = -1 else: sign = elem / abs(elem) if sign == -prev: ans = ans + 1 prev = sign # Printing answerprint(ans)
Output :
9
Method #2: Using Itertools and groupbyThis is yet another way to perform this particular task using itertools.
# Python Code to find number of # time sign changes in the list. # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] # Importingimport itertools # Using groupbyOutput = len(list(itertools.groupby(Input, lambda Input: Input > 0))) Output = Output -1 # Printing outputprint(Output)
Output :
9
Method #3: Using ZipThe most concise and readable way to find number of time sign changes in the list is using zip.
# Python Code to find number of # time sign changes in the list. # Using zip to checkdef check(Input): Input = [-1 if not x else x for x in Input] # zip with leading 1, so that opening negative value is # treated as sign change return sum((x ^ y)<0 for x, y in zip([1]+Input, Input)) # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] Output = check(Input) Output = Output -1 # Printing outputprint(Output)
Output :
9
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 24352,
"s": 24212,
"text": "Given a list containing Positive and Negative integers, We have to find number of times the sign(Positive or Negative) changes in the list."
},
{
"code": null,
"e": 24974,
"s": 24352,
"text": "Input: [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] \nOutput:9\nExplanation : \nSign change from -1 to 2, ans = 1\nSign change from 3 to -4, ans = 2\nSign change from -4 to 5, ans = 3\nSign change from 5 to -6, ans = 4\nSign change from -6 to 7, ans = 5\nSign change from 8 to -9, ans = 6\nSign change from -9 to 10, ans = 7\nSign change from 10 to -11 ans = 8\nSign change from -11 to 12, ans = 9\n\nInput: [-1, 2, 3, -4, 5, -11, 12] \nOutput:5\nExplanation :\nSign change from -1 to 2, ans = 1\nSign change from 3 to -4, ans = 2\nSign change from -4 to 5, ans = 3\nSign change from 5 to -11, ans = 4\nSign change from -11 to 12, ans = 5\n\n"
},
{
"code": null,
"e": 25034,
"s": 24974,
"text": "Let’s discuss certain ways in which this task is performed."
},
{
"code": null,
"e": 25125,
"s": 25034,
"text": "Method #1: Using IterationUsing Iteration to find number of time sign changes in the list."
},
{
"code": "# Python Code to find number of # time sign changes in the list. # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] # Variable Initializationprev = Input[0]ans = 0 # Using Iterationfor elem in Input: if elem == 0: sign = -1 else: sign = elem / abs(elem) if sign == -prev: ans = ans + 1 prev = sign # Printing answerprint(ans)",
"e": 25524,
"s": 25125,
"text": null
},
{
"code": null,
"e": 25533,
"s": 25524,
"text": "Output :"
},
{
"code": null,
"e": 25535,
"s": 25533,
"text": "9"
},
{
"code": null,
"e": 25646,
"s": 25535,
"text": "Method #2: Using Itertools and groupbyThis is yet another way to perform this particular task using itertools."
},
{
"code": "# Python Code to find number of # time sign changes in the list. # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] # Importingimport itertools # Using groupbyOutput = len(list(itertools.groupby(Input, lambda Input: Input > 0))) Output = Output -1 # Printing outputprint(Output)",
"e": 25960,
"s": 25646,
"text": null
},
{
"code": null,
"e": 25969,
"s": 25960,
"text": "Output :"
},
{
"code": null,
"e": 25971,
"s": 25969,
"text": "9"
},
{
"code": null,
"e": 26087,
"s": 25971,
"text": "Method #3: Using ZipThe most concise and readable way to find number of time sign changes in the list is using zip."
},
{
"code": "# Python Code to find number of # time sign changes in the list. # Using zip to checkdef check(Input): Input = [-1 if not x else x for x in Input] # zip with leading 1, so that opening negative value is # treated as sign change return sum((x ^ y)<0 for x, y in zip([1]+Input, Input)) # Input list InitializationInput = [-1, 2, 3, -4, 5, -6, 7, 8, -9, 10, -11, 12] Output = check(Input) Output = Output -1 # Printing outputprint(Output)",
"e": 26540,
"s": 26087,
"text": null
},
{
"code": null,
"e": 26549,
"s": 26540,
"text": "Output :"
},
{
"code": null,
"e": 26551,
"s": 26549,
"text": "9"
},
{
"code": null,
"e": 26558,
"s": 26551,
"text": "Python"
},
{
"code": null,
"e": 26656,
"s": 26558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26665,
"s": 26656,
"text": "Comments"
},
{
"code": null,
"e": 26678,
"s": 26665,
"text": "Old Comments"
},
{
"code": null,
"e": 26710,
"s": 26678,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26766,
"s": 26710,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26787,
"s": 26766,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26826,
"s": 26787,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26868,
"s": 26826,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26895,
"s": 26868,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26926,
"s": 26895,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26968,
"s": 26926,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27004,
"s": 26968,
"text": "Python | Pandas dataframe.groupby()"
}
] |
How to set text direction in HTML? | To set text direction in HTML, use the style attribute. The style attribute specifies an inline style for an element. The style attribute is used with the CSS property direction to set direction. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can use the following property values to set direction −
You can try to run the following code to set text direction in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Text Direction</title>
</head>
<body>
<p style = "direction: rtl;">
This text will get displayed from right to left
</p>
<p>This is normal text.</p>
</body>
</html> | [
{
"code": null,
"e": 1420,
"s": 1062,
"text": "To set text direction in HTML, use the style attribute. The style attribute specifies an inline style for an element. The style attribute is used with the CSS property direction to set direction. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet."
},
{
"code": null,
"e": 1481,
"s": 1420,
"text": "You can use the following property values to set direction −"
},
{
"code": null,
"e": 1551,
"s": 1483,
"text": "You can try to run the following code to set text direction in HTML"
},
{
"code": null,
"e": 1561,
"s": 1551,
"text": "Live Demo"
},
{
"code": null,
"e": 1783,
"s": 1561,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>HTML Text Direction</title>\n</head>\n<body>\n <p style = \"direction: rtl;\">\n This text will get displayed from right to left\n </p>\n <p>This is normal text.</p>\n</body>\n</html>"
}
] |
Converting days into years months and weeks - JavaScript | We are required to write a JavaScript function that takes in a number (representing the number of days) and returns an object with three properties, namely −
weeks, months, years, days
And the properties should have proper values of these four properties that can be made from the number of days. We should not consider leap years here and consider all years to have 365 days.
For example −
If the input is 738, then the output should be −
const output = {
years: 2,
months: 0,
weeks: 1,
days: 1
}
Let’s write the code for this function −
const days = 738;
const calculateTimimg = d => {
let months = 0, years = 0, days = 0, weeks = 0;
while(d){
if(d >= 365){
years++;
d -= 365;
}else if(d >= 30){
months++;
d -= 30;
}else if(d >= 7){
weeks++;
d -= 7;
}else{
days++;
d--;
}
};
return {
years, months, weeks, days
};
};
console.log(calculateTimimg(days));
The output in the console: −
{ years: 2, months: 0, weeks: 1, days: 1 } | [
{
"code": null,
"e": 1220,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number (representing the number of days) and returns an object with three properties, namely −"
},
{
"code": null,
"e": 1247,
"s": 1220,
"text": "weeks, months, years, days"
},
{
"code": null,
"e": 1439,
"s": 1247,
"text": "And the properties should have proper values of these four properties that can be made from the number of days. We should not consider leap years here and consider all years to have 365 days."
},
{
"code": null,
"e": 1453,
"s": 1439,
"text": "For example −"
},
{
"code": null,
"e": 1502,
"s": 1453,
"text": "If the input is 738, then the output should be −"
},
{
"code": null,
"e": 1572,
"s": 1502,
"text": "const output = {\n years: 2,\n months: 0,\n weeks: 1,\n days: 1\n}"
},
{
"code": null,
"e": 1613,
"s": 1572,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 2052,
"s": 1613,
"text": "const days = 738;\nconst calculateTimimg = d => {\n let months = 0, years = 0, days = 0, weeks = 0;\n while(d){\n if(d >= 365){\n years++;\n d -= 365;\n }else if(d >= 30){\n months++;\n d -= 30;\n }else if(d >= 7){\n weeks++;\n d -= 7;\n }else{\n days++;\n d--;\n }\n };\n return {\n years, months, weeks, days\n };\n};\nconsole.log(calculateTimimg(days));"
},
{
"code": null,
"e": 2081,
"s": 2052,
"text": "The output in the console: −"
},
{
"code": null,
"e": 2124,
"s": 2081,
"text": "{ years: 2, months: 0, weeks: 1, days: 1 }"
}
] |
Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively | When it is required to check the number of times a given letter occurs in a string using recursion, a method can be defined, and an ‘if’ condition can be used.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
Live Demo
def check_frequency(my_str,my_ch):
if not my_str:
return 0
elif my_str[0]==my_ch:
return 1+check_frequency(my_str[1:],my_ch)
else:
return check_frequency(my_str[1:],my_ch)
my_string = input("Enter the string :")
my_char = input("Enter the character that needs to be checked :")
print("The frequency of " + str(my_char) + " is :")
print(check_frequency(my_string,my_char))
Enter the string :jaanea
Enter the character that needs to be checked :a
The frequency of a is :
3
A method named ‘check_frequency’ is defined that takes a string and a character as parameters.
It checks to see if the characters in a string match the character passed to the method.
If they do, it is returned.
Else the method is called recursively on all characters of the string.
The string and the character are taken as user inputs.
The method is called by passing these values as parameters.
The output is dislayed on the console. | [
{
"code": null,
"e": 1222,
"s": 1062,
"text": "When it is required to check the number of times a given letter occurs in a string using recursion, a method can be defined, and an ‘if’ condition can be used."
},
{
"code": null,
"e": 1357,
"s": 1222,
"text": "The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem."
},
{
"code": null,
"e": 1397,
"s": 1357,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1408,
"s": 1397,
"text": " Live Demo"
},
{
"code": null,
"e": 1807,
"s": 1408,
"text": "def check_frequency(my_str,my_ch):\n if not my_str:\n return 0\n elif my_str[0]==my_ch:\n return 1+check_frequency(my_str[1:],my_ch)\n else:\n return check_frequency(my_str[1:],my_ch)\nmy_string = input(\"Enter the string :\")\nmy_char = input(\"Enter the character that needs to be checked :\")\nprint(\"The frequency of \" + str(my_char) + \" is :\")\nprint(check_frequency(my_string,my_char))"
},
{
"code": null,
"e": 1906,
"s": 1807,
"text": "Enter the string :jaanea\nEnter the character that needs to be checked :a\nThe frequency of a is :\n3"
},
{
"code": null,
"e": 2001,
"s": 1906,
"text": "A method named ‘check_frequency’ is defined that takes a string and a character as parameters."
},
{
"code": null,
"e": 2090,
"s": 2001,
"text": "It checks to see if the characters in a string match the character passed to the method."
},
{
"code": null,
"e": 2118,
"s": 2090,
"text": "If they do, it is returned."
},
{
"code": null,
"e": 2189,
"s": 2118,
"text": "Else the method is called recursively on all characters of the string."
},
{
"code": null,
"e": 2244,
"s": 2189,
"text": "The string and the character are taken as user inputs."
},
{
"code": null,
"e": 2304,
"s": 2244,
"text": "The method is called by passing these values as parameters."
},
{
"code": null,
"e": 2343,
"s": 2304,
"text": "The output is dislayed on the console."
}
] |
Channel Allocation Problem in Computer Network - GeeksforGeeks | 26 Jul, 2021
Channel allocation is a process in which a single channel is divided and allotted to multiple users in order to carry user specific tasks. There are user’s quantity may vary every time the process takes place. If there are N number of users and channel is divided into N equal-sized sub channels, Each user is assigned one portion. If the number of users are small and don’t vary at times, than Frequency Division Multiplexing can be used as it is a simple and efficient channel bandwidth allocating technique.
Channel allocation problem can be solved by two schemes: Static Channel Allocation in LANs and MANs, and Dynamic Channel Allocation.
These are explained as following below.
1. Static Channel Allocation in LANs and MANs: It is the classical or traditional approach of allocating a single channel among multiple competing users Frequency Division Multiplexing (FDM). if there are N users, the bandwidth is divided into N equal sized portions each user being assigned one portion. since each user has a private frequency band, there is no interface between users.
It is not efficient to divide into fixed number of chunks.
T = 1/(U*C-L)
T(FDM) = N*T(1/U(C/N)-L/N)
Where,
T = mean time delay,
C = capacity of channel,
L = arrival rate of frames,
1/U = bits/frame,
N = number of sub channels,
T(FDM) = Frequency Division Multiplexing Time
2. Dynamic Channel Allocation: Possible assumptions include:
Station Model: Assumes that each of N stations independently produce frames. The probability of producing a packet in the interval IDt where I is the constant arrival rate of new frames. Single Channel Assumption: In this allocation all stations are equivalent and can send and receive on that channel. Collision Assumption: If two frames overlap in time-wise, then that’s collision. Any collision is an error, and both frames must re transmitted. Collisions are only possible error. Time can be divided into Slotted or Continuous. Stations can sense a channel is busy before they try it.
Station Model: Assumes that each of N stations independently produce frames. The probability of producing a packet in the interval IDt where I is the constant arrival rate of new frames.
Single Channel Assumption: In this allocation all stations are equivalent and can send and receive on that channel.
Collision Assumption: If two frames overlap in time-wise, then that’s collision. Any collision is an error, and both frames must re transmitted. Collisions are only possible error.
Time can be divided into Slotted or Continuous.
Stations can sense a channel is busy before they try it.
Protocol Assumption:
N independent stations.
A station is blocked until its generated frame is transmitted.
probability of a frame being generated in a period of length Dt is IDt where I is the arrival rate of frames.
Only a single Channel available.
Time can be either: Continuous or slotted.
Carrier Sense: A station can sense if a channel is already busy before transmission.
No Carrier Sense: Time out used to sense loss data.
anikaseth98
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP
Socket Programming in Python
Data encryption standard (DES) | Set 1
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Normal Forms in DBMS
Differences between TCP and UDP | [
{
"code": null,
"e": 24500,
"s": 24472,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 25012,
"s": 24500,
"text": "Channel allocation is a process in which a single channel is divided and allotted to multiple users in order to carry user specific tasks. There are user’s quantity may vary every time the process takes place. If there are N number of users and channel is divided into N equal-sized sub channels, Each user is assigned one portion. If the number of users are small and don’t vary at times, than Frequency Division Multiplexing can be used as it is a simple and efficient channel bandwidth allocating technique. "
},
{
"code": null,
"e": 25146,
"s": 25012,
"text": "Channel allocation problem can be solved by two schemes: Static Channel Allocation in LANs and MANs, and Dynamic Channel Allocation. "
},
{
"code": null,
"e": 25189,
"s": 25148,
"text": "These are explained as following below. "
},
{
"code": null,
"e": 25578,
"s": 25189,
"text": "1. Static Channel Allocation in LANs and MANs: It is the classical or traditional approach of allocating a single channel among multiple competing users Frequency Division Multiplexing (FDM). if there are N users, the bandwidth is divided into N equal sized portions each user being assigned one portion. since each user has a private frequency band, there is no interface between users. "
},
{
"code": null,
"e": 25638,
"s": 25578,
"text": "It is not efficient to divide into fixed number of chunks. "
},
{
"code": null,
"e": 25683,
"s": 25640,
"text": "T = 1/(U*C-L)\n\nT(FDM) = N*T(1/U(C/N)-L/N) "
},
{
"code": null,
"e": 25692,
"s": 25683,
"text": "Where, "
},
{
"code": null,
"e": 25859,
"s": 25692,
"text": "T = mean time delay,\nC = capacity of channel,\nL = arrival rate of frames,\n1/U = bits/frame,\nN = number of sub channels,\nT(FDM) = Frequency Division Multiplexing Time "
},
{
"code": null,
"e": 25922,
"s": 25859,
"text": "2. Dynamic Channel Allocation: Possible assumptions include: "
},
{
"code": null,
"e": 26517,
"s": 25922,
"text": "Station Model: Assumes that each of N stations independently produce frames. The probability of producing a packet in the interval IDt where I is the constant arrival rate of new frames. Single Channel Assumption: In this allocation all stations are equivalent and can send and receive on that channel. Collision Assumption: If two frames overlap in time-wise, then that’s collision. Any collision is an error, and both frames must re transmitted. Collisions are only possible error. Time can be divided into Slotted or Continuous. Stations can sense a channel is busy before they try it. "
},
{
"code": null,
"e": 26706,
"s": 26517,
"text": "Station Model: Assumes that each of N stations independently produce frames. The probability of producing a packet in the interval IDt where I is the constant arrival rate of new frames. "
},
{
"code": null,
"e": 26824,
"s": 26706,
"text": "Single Channel Assumption: In this allocation all stations are equivalent and can send and receive on that channel. "
},
{
"code": null,
"e": 27007,
"s": 26824,
"text": "Collision Assumption: If two frames overlap in time-wise, then that’s collision. Any collision is an error, and both frames must re transmitted. Collisions are only possible error. "
},
{
"code": null,
"e": 27057,
"s": 27007,
"text": "Time can be divided into Slotted or Continuous. "
},
{
"code": null,
"e": 27116,
"s": 27057,
"text": "Stations can sense a channel is busy before they try it. "
},
{
"code": null,
"e": 27139,
"s": 27116,
"text": "Protocol Assumption: "
},
{
"code": null,
"e": 27163,
"s": 27139,
"text": "N independent stations."
},
{
"code": null,
"e": 27226,
"s": 27163,
"text": "A station is blocked until its generated frame is transmitted."
},
{
"code": null,
"e": 27336,
"s": 27226,
"text": "probability of a frame being generated in a period of length Dt is IDt where I is the arrival rate of frames."
},
{
"code": null,
"e": 27369,
"s": 27336,
"text": "Only a single Channel available."
},
{
"code": null,
"e": 27412,
"s": 27369,
"text": "Time can be either: Continuous or slotted."
},
{
"code": null,
"e": 27497,
"s": 27412,
"text": "Carrier Sense: A station can sense if a channel is already busy before transmission."
},
{
"code": null,
"e": 27549,
"s": 27497,
"text": "No Carrier Sense: Time out used to sense loss data."
},
{
"code": null,
"e": 27563,
"s": 27551,
"text": "anikaseth98"
},
{
"code": null,
"e": 27581,
"s": 27563,
"text": "Computer Networks"
},
{
"code": null,
"e": 27589,
"s": 27581,
"text": "GATE CS"
},
{
"code": null,
"e": 27607,
"s": 27589,
"text": "Computer Networks"
},
{
"code": null,
"e": 27705,
"s": 27607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27735,
"s": 27705,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 27773,
"s": 27735,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27805,
"s": 27773,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27834,
"s": 27805,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 27873,
"s": 27834,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 27897,
"s": 27873,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 27946,
"s": 27897,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 27973,
"s": 27946,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 27994,
"s": 27973,
"text": "Normal Forms in DBMS"
}
] |
Algorithms | Analysis of Algorithms | Question 2 - GeeksforGeeks | 16 May, 2019
What is the time complexity of fun()?
int fun(int n){ int count = 0; for (int i = 0; i < n; i++) for (int j = i; j > 0; j--) count = count + 1; return count;}
(A) Theta (n)(B) Theta (n^2)(C) Theta (n*Logn)(D) Theta (nLognLogn)Answer: (B)Explanation: The time complexity can be calculated by counting number of times the expression “count = count + 1;” is executed. The expression is executed 0 + 1 + 2 + 3 + 4 + .... + (n-1) times.
Time complexity = Theta(0 + 1 + 2 + 3 + .. + n-1) = Theta (n*(n-1)/2) = Theta(n2)Quiz of this Question
Algorithms-Analysis of Algorithms
Analysis of Algorithms
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Greedy Algorithms | Question 1
Algorithms | Recursion | Question 9
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
Algorithms | Sorting | Question 23
Algorithms | Sorting | Question 5 | [
{
"code": null,
"e": 25036,
"s": 25008,
"text": "\n16 May, 2019"
},
{
"code": null,
"e": 25074,
"s": 25036,
"text": "What is the time complexity of fun()?"
},
{
"code": "int fun(int n){ int count = 0; for (int i = 0; i < n; i++) for (int j = i; j > 0; j--) count = count + 1; return count;} ",
"e": 25210,
"s": 25074,
"text": null
},
{
"code": null,
"e": 25483,
"s": 25210,
"text": "(A) Theta (n)(B) Theta (n^2)(C) Theta (n*Logn)(D) Theta (nLognLogn)Answer: (B)Explanation: The time complexity can be calculated by counting number of times the expression “count = count + 1;” is executed. The expression is executed 0 + 1 + 2 + 3 + 4 + .... + (n-1) times."
},
{
"code": null,
"e": 25586,
"s": 25483,
"text": "Time complexity = Theta(0 + 1 + 2 + 3 + .. + n-1) = Theta (n*(n-1)/2) = Theta(n2)Quiz of this Question"
},
{
"code": null,
"e": 25620,
"s": 25586,
"text": "Algorithms-Analysis of Algorithms"
},
{
"code": null,
"e": 25643,
"s": 25620,
"text": "Analysis of Algorithms"
},
{
"code": null,
"e": 25659,
"s": 25643,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 25757,
"s": 25659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25803,
"s": 25757,
"text": "Algorithms | Dynamic Programming | Question 2"
},
{
"code": null,
"e": 25849,
"s": 25803,
"text": "Algorithms | Dynamic Programming | Question 3"
},
{
"code": null,
"e": 25899,
"s": 25849,
"text": "Algorithms | Analysis of Algorithms | Question 17"
},
{
"code": null,
"e": 25943,
"s": 25899,
"text": "Algorithms | Greedy Algorithms | Question 1"
},
{
"code": null,
"e": 25979,
"s": 25943,
"text": "Algorithms | Recursion | Question 9"
},
{
"code": null,
"e": 26030,
"s": 25979,
"text": "Algorithms Quiz | Dynamic Programming | Question 8"
},
{
"code": null,
"e": 26075,
"s": 26030,
"text": "Algorithms | Divide and Conquer | Question 6"
},
{
"code": null,
"e": 26119,
"s": 26075,
"text": "Algorithms | Graph Traversals | Question 12"
},
{
"code": null,
"e": 26154,
"s": 26119,
"text": "Algorithms | Sorting | Question 23"
}
] |
PHP Variable functions | If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.
Variable functions can not be built eith language constructs such as include, require, echo etc. One can find a workaround though, using function wrappers.
In following example, value of a variable matches with function of name. The function is thus called by putting parentheses in front of variable
Live Demo
<?php
function hello(){
echo "Hello World";
}
$var="Hello";
$var();
?>
This will produce following result. −
Hello World
Here is another example of variable function with arguments
Live Demo
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>
This will produce following result. −
30
In following example, name of function to called is input by user
<?php
function add($x, $y){
echo $x+$y;
}
function sub($x, $y){
echo $x-$y;
}
$var=readline("enter name of function: ");
$var(10,20);
?>
This will produce following result. −
enter name of function: add
30
Concept of variable function can be extended to method in a class
<?php
class myclass{
function welcome($name){
echo "Welcome $name";
}
}
$obj=new myclass();
$f="welcome";
$obj->$f("Amar");
?>
This will produce following result. −
Welcome Amar
A static method can be also called by variable method technique
Live Demo
<?php
class myclass{
static function welcome($name){
echo "Welcome $name";
}
}
$f="welcome";
myclass::$f("Amar");
?>
This will now throw exception as follows −
Welcome Amar | [
{
"code": null,
"e": 1368,
"s": 1062,
"text": "If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc."
},
{
"code": null,
"e": 1524,
"s": 1368,
"text": "Variable functions can not be built eith language constructs such as include, require, echo etc. One can find a workaround though, using function wrappers."
},
{
"code": null,
"e": 1669,
"s": 1524,
"text": "In following example, value of a variable matches with function of name. The function is thus called by putting parentheses in front of variable"
},
{
"code": null,
"e": 1680,
"s": 1669,
"text": " Live Demo"
},
{
"code": null,
"e": 1754,
"s": 1680,
"text": "<?php\nfunction hello(){\n echo \"Hello World\";\n}\n$var=\"Hello\";\n$var();\n?>"
},
{
"code": null,
"e": 1792,
"s": 1754,
"text": "This will produce following result. −"
},
{
"code": null,
"e": 1804,
"s": 1792,
"text": "Hello World"
},
{
"code": null,
"e": 1864,
"s": 1804,
"text": "Here is another example of variable function with arguments"
},
{
"code": null,
"e": 1875,
"s": 1864,
"text": " Live Demo"
},
{
"code": null,
"e": 1948,
"s": 1875,
"text": "<?php\nfunction add($x, $y){\n echo $x+$y;\n}\n$var=\"add\";\n$var(10,20);\n?>"
},
{
"code": null,
"e": 1986,
"s": 1948,
"text": "This will produce following result. −"
},
{
"code": null,
"e": 1989,
"s": 1986,
"text": "30"
},
{
"code": null,
"e": 2055,
"s": 1989,
"text": "In following example, name of function to called is input by user"
},
{
"code": null,
"e": 2198,
"s": 2055,
"text": "<?php\nfunction add($x, $y){\n echo $x+$y;\n}\nfunction sub($x, $y){\n echo $x-$y;\n}\n$var=readline(\"enter name of function: \");\n$var(10,20);\n?>"
},
{
"code": null,
"e": 2236,
"s": 2198,
"text": "This will produce following result. −"
},
{
"code": null,
"e": 2267,
"s": 2236,
"text": "enter name of function: add\n30"
},
{
"code": null,
"e": 2333,
"s": 2267,
"text": "Concept of variable function can be extended to method in a class"
},
{
"code": null,
"e": 2472,
"s": 2333,
"text": "<?php\nclass myclass{\n function welcome($name){\n echo \"Welcome $name\";\n }\n}\n$obj=new myclass();\n$f=\"welcome\";\n$obj->$f(\"Amar\");\n?>"
},
{
"code": null,
"e": 2510,
"s": 2472,
"text": "This will produce following result. −"
},
{
"code": null,
"e": 2523,
"s": 2510,
"text": "Welcome Amar"
},
{
"code": null,
"e": 2587,
"s": 2523,
"text": "A static method can be also called by variable method technique"
},
{
"code": null,
"e": 2598,
"s": 2587,
"text": " Live Demo"
},
{
"code": null,
"e": 2727,
"s": 2598,
"text": "<?php\nclass myclass{\n static function welcome($name){\n echo \"Welcome $name\";\n }\n}\n$f=\"welcome\";\nmyclass::$f(\"Amar\");\n?>"
},
{
"code": null,
"e": 2770,
"s": 2727,
"text": "This will now throw exception as follows −"
},
{
"code": null,
"e": 2783,
"s": 2770,
"text": "Welcome Amar"
}
] |
Tableau your Time Series Forecast with TabPy! | by Jerry Paul | Towards Data Science | Welcome to a quick and short (hopefully) illustration of how one can integrate data science models with Tableau using TabPy. We will specifically look at time series forecasting in this story.
We will use three time series models which are built in python using the superstore dataset ( retail industry data ). We will use Jupyter notebook to build our python codes and then move on to Tableau.
This article is aimed at demonstrating how a model can be integrated with Tableau’s analytics extensions and make it seamless for consumption.
Why Tableau? Well, I love it and I can’t stress enough on how easy it is to explore your data.
Let’s start by looking at the data :
We simply keep our date and sales columns for building a time series object. The below code sorts the sales figures in ascending order and aggregates the data at a month level.
#fetching required columnsdata = superstore[[‘Order Date’,’Sales’]] data = data.sort_values(by = 'Order Date')#creating a ts objectdata['Order Date'] = pd.to_datetime(data['Order Date'])data.index = data['Order Date']data = data.resample('M').sum()
We are ready to visualize the time series:
import matplotlib.pyplot as pltimport seaborn as snsplt.subplots(figsize = (17,7))sns.lineplot(x = “Order Date”, y = “Sales”, data = data)plt.show()
The above is our time series plot. There are three important components to time series : Trend, Seasonality and Error. We can look at the series as an ‘additive model’ or a ‘multiplicative model’ depending on the nature of the series and the hypothesis we postulate. I will be parking the model building and forecasting methods in the next article as a continuation of this one where we will cover different techniques, decomposition, stationarity testing, auto-correlation and partial auto-correlation factors and model summary.
For now, I will share the code I had written to finalize the model before I switch gears to Tableau.
As mentioned in the beginning of the article, we will use three models. These are Holt’s Linear Model, Holt-Winter’s Model and ARIMA. The first two are exponential smoothing methods and ARIMA stands for Auto Regressive Integrated Moving Average which is a regression method.
Below is the python code for Holt’s Linear Method :
The model is trained on 42 months and the last 6 months are used for predictions. Model parameters can be tuned for accuracy.The model appends both and gives the entire series back to us.
Tableau has inbuilt analytics extensions that allow integration with other platforms.
In our case we choose TabPy.
Make sure to install TabPy and start the same in your terminal as laid out in the below resource :
tableau.github.io
You can test the connection in Tableau in the pop-up described above.
We also import TabPyClient in our python environment to create a connection object.
We will be using this connection object to deploy our models on the TabPy Server that we initiated.
Let’s look at the modified code for Holt’s Linear method that can be deployed on TabPy.
Holt’s Linear Method
We have created a function that returns the model output. Since we will be reading data from Tableau, we have used parameters that take in values we shall pass from Tableau. You will note that we have used the connection object to deploy the model in TabPy. Similarly, you can create functions for other models.
Holt-Winter’s Method
ARIMA
Now that we have deployed these models in TabPy, let’s consume it in Tableau. We will create a calculated field that looks like below :
Tableau uses four functions, namely SCRIPT_REAL, SCRIPT_STR, SCRIPT_BOOL and SCRIPT_INT for return types real, string, boolean and integer respectively. The above code tells Tableau to run the ‘Seasonal ARIMA Method’ which is deployed on TabPy with 3 parameters (Date, Sales and Months to Forecast) and return the ‘response’ to Tableau’s calculated field.
Similarly, we define calculated fields for the other 2 models. If we want to see all at a glance in Tableau, it will look like this :
Note that you can dynamically change the forecast period as you want and see the predictions. You want to choose the model that gives you the best accuracy. You can optionally create a parameter in Tableau to toggle among models.
A key point to note is that we need to accommodate the forecast period (in months in our case) in Tableau so that we make space for the returned values from TabPy.This is because the original dataset does not have these null records for the future dates when we pass values from Tableau. I have tweaked the data to extend the date range as shown below :
The above code essentially extends the date range after adding the required months to forecast and passes it to TabPy. Also, we choose ‘Show Missing Values’ for this calculated date field.
There is a small trade off here.Since we extend the date range, the last date and sales figures get pushed to the new forecast end date. However, we are only interested in the forecast; we can exclude this datapoint or use LAST()=FALSE in the filter box. Feel free to come up with ideas for the same.
Let’s finally plug this into our dashboard :
There you go! We have a well integrated forecasting model sitting inside Tableau’s visual discovery. You can definitely bring in accuracy scores and model parameters to Tableau and make this jazzier!
As mentioned, more to come in my next story. | [
{
"code": null,
"e": 365,
"s": 172,
"text": "Welcome to a quick and short (hopefully) illustration of how one can integrate data science models with Tableau using TabPy. We will specifically look at time series forecasting in this story."
},
{
"code": null,
"e": 567,
"s": 365,
"text": "We will use three time series models which are built in python using the superstore dataset ( retail industry data ). We will use Jupyter notebook to build our python codes and then move on to Tableau."
},
{
"code": null,
"e": 710,
"s": 567,
"text": "This article is aimed at demonstrating how a model can be integrated with Tableau’s analytics extensions and make it seamless for consumption."
},
{
"code": null,
"e": 805,
"s": 710,
"text": "Why Tableau? Well, I love it and I can’t stress enough on how easy it is to explore your data."
},
{
"code": null,
"e": 842,
"s": 805,
"text": "Let’s start by looking at the data :"
},
{
"code": null,
"e": 1019,
"s": 842,
"text": "We simply keep our date and sales columns for building a time series object. The below code sorts the sales figures in ascending order and aggregates the data at a month level."
},
{
"code": null,
"e": 1268,
"s": 1019,
"text": "#fetching required columnsdata = superstore[[‘Order Date’,’Sales’]] data = data.sort_values(by = 'Order Date')#creating a ts objectdata['Order Date'] = pd.to_datetime(data['Order Date'])data.index = data['Order Date']data = data.resample('M').sum()"
},
{
"code": null,
"e": 1311,
"s": 1268,
"text": "We are ready to visualize the time series:"
},
{
"code": null,
"e": 1460,
"s": 1311,
"text": "import matplotlib.pyplot as pltimport seaborn as snsplt.subplots(figsize = (17,7))sns.lineplot(x = “Order Date”, y = “Sales”, data = data)plt.show()"
},
{
"code": null,
"e": 1990,
"s": 1460,
"text": "The above is our time series plot. There are three important components to time series : Trend, Seasonality and Error. We can look at the series as an ‘additive model’ or a ‘multiplicative model’ depending on the nature of the series and the hypothesis we postulate. I will be parking the model building and forecasting methods in the next article as a continuation of this one where we will cover different techniques, decomposition, stationarity testing, auto-correlation and partial auto-correlation factors and model summary."
},
{
"code": null,
"e": 2091,
"s": 1990,
"text": "For now, I will share the code I had written to finalize the model before I switch gears to Tableau."
},
{
"code": null,
"e": 2366,
"s": 2091,
"text": "As mentioned in the beginning of the article, we will use three models. These are Holt’s Linear Model, Holt-Winter’s Model and ARIMA. The first two are exponential smoothing methods and ARIMA stands for Auto Regressive Integrated Moving Average which is a regression method."
},
{
"code": null,
"e": 2418,
"s": 2366,
"text": "Below is the python code for Holt’s Linear Method :"
},
{
"code": null,
"e": 2606,
"s": 2418,
"text": "The model is trained on 42 months and the last 6 months are used for predictions. Model parameters can be tuned for accuracy.The model appends both and gives the entire series back to us."
},
{
"code": null,
"e": 2692,
"s": 2606,
"text": "Tableau has inbuilt analytics extensions that allow integration with other platforms."
},
{
"code": null,
"e": 2721,
"s": 2692,
"text": "In our case we choose TabPy."
},
{
"code": null,
"e": 2820,
"s": 2721,
"text": "Make sure to install TabPy and start the same in your terminal as laid out in the below resource :"
},
{
"code": null,
"e": 2838,
"s": 2820,
"text": "tableau.github.io"
},
{
"code": null,
"e": 2908,
"s": 2838,
"text": "You can test the connection in Tableau in the pop-up described above."
},
{
"code": null,
"e": 2992,
"s": 2908,
"text": "We also import TabPyClient in our python environment to create a connection object."
},
{
"code": null,
"e": 3092,
"s": 2992,
"text": "We will be using this connection object to deploy our models on the TabPy Server that we initiated."
},
{
"code": null,
"e": 3180,
"s": 3092,
"text": "Let’s look at the modified code for Holt’s Linear method that can be deployed on TabPy."
},
{
"code": null,
"e": 3201,
"s": 3180,
"text": "Holt’s Linear Method"
},
{
"code": null,
"e": 3513,
"s": 3201,
"text": "We have created a function that returns the model output. Since we will be reading data from Tableau, we have used parameters that take in values we shall pass from Tableau. You will note that we have used the connection object to deploy the model in TabPy. Similarly, you can create functions for other models."
},
{
"code": null,
"e": 3534,
"s": 3513,
"text": "Holt-Winter’s Method"
},
{
"code": null,
"e": 3540,
"s": 3534,
"text": "ARIMA"
},
{
"code": null,
"e": 3676,
"s": 3540,
"text": "Now that we have deployed these models in TabPy, let’s consume it in Tableau. We will create a calculated field that looks like below :"
},
{
"code": null,
"e": 4032,
"s": 3676,
"text": "Tableau uses four functions, namely SCRIPT_REAL, SCRIPT_STR, SCRIPT_BOOL and SCRIPT_INT for return types real, string, boolean and integer respectively. The above code tells Tableau to run the ‘Seasonal ARIMA Method’ which is deployed on TabPy with 3 parameters (Date, Sales and Months to Forecast) and return the ‘response’ to Tableau’s calculated field."
},
{
"code": null,
"e": 4166,
"s": 4032,
"text": "Similarly, we define calculated fields for the other 2 models. If we want to see all at a glance in Tableau, it will look like this :"
},
{
"code": null,
"e": 4396,
"s": 4166,
"text": "Note that you can dynamically change the forecast period as you want and see the predictions. You want to choose the model that gives you the best accuracy. You can optionally create a parameter in Tableau to toggle among models."
},
{
"code": null,
"e": 4750,
"s": 4396,
"text": "A key point to note is that we need to accommodate the forecast period (in months in our case) in Tableau so that we make space for the returned values from TabPy.This is because the original dataset does not have these null records for the future dates when we pass values from Tableau. I have tweaked the data to extend the date range as shown below :"
},
{
"code": null,
"e": 4939,
"s": 4750,
"text": "The above code essentially extends the date range after adding the required months to forecast and passes it to TabPy. Also, we choose ‘Show Missing Values’ for this calculated date field."
},
{
"code": null,
"e": 5240,
"s": 4939,
"text": "There is a small trade off here.Since we extend the date range, the last date and sales figures get pushed to the new forecast end date. However, we are only interested in the forecast; we can exclude this datapoint or use LAST()=FALSE in the filter box. Feel free to come up with ideas for the same."
},
{
"code": null,
"e": 5285,
"s": 5240,
"text": "Let’s finally plug this into our dashboard :"
},
{
"code": null,
"e": 5485,
"s": 5285,
"text": "There you go! We have a well integrated forecasting model sitting inside Tableau’s visual discovery. You can definitely bring in accuracy scores and model parameters to Tableau and make this jazzier!"
}
] |
shmctl() - Unix, Linux System Call | Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
The
buf argument is a pointer to a shmid_ds structure,
defined in <sys/shm.h> as follows:
struct shmid_ds {
struct ipc_perm shm_perm; /* Ownership and permissions */
size_t shm_segsz; /* Size of segment (bytes) */
time_t shm_atime; /* Last attach time */
time_t shm_dtime; /* Last detach time */
time_t shm_ctime; /* Last change time */
pid_t shm_cpid; /* PID of creator */
pid_t shm_lpid; /* PID of last shmat()/shmdt() */
shmatt_t shm_nattch; /* No. of current attaches */
...
};
The
ipc_perm structure is defined in <sys/ipc.h> as follows
(the highlighted fields are settable using
IPC_SET):
struct ipc_perm {
key_t key; /* Key supplied to shmget() */
uid_t uid; /* Effective UID of owner */
gid_t gid; /* Effective GID of owner */
uid_t cuid; /* Effective UID of creator */
gid_t cgid; /* Effective GID of creator */
unsigned short mode; /* Permissions + SHM_DEST and
SHM_LOCKED flags */
unsigned short seq; /* Sequence number */
};
Valid values for
cmd are:
struct shminfo {
unsigned long shmmax; /* Max. segment size */
unsigned long shmmin; /* Min. segment size; always 1 */
unsigned long shmmni; /* Max. # of segments */
unsigned long shmseg; /* Max. # of segments that a
process can attach; unused */
unsigned long shmall; /* Max. # of pages of shared
memory, system-wide */
};
struct shminfo {
unsigned long shmmax; /* Max. segment size */
unsigned long shmmin; /* Min. segment size; always 1 */
unsigned long shmmni; /* Max. # of segments */
unsigned long shmseg; /* Max. # of segments that a
process can attach; unused */
unsigned long shmall; /* Max. # of pages of shared
memory, system-wide */
};
struct shm_info {
int used_ids; /* # of currently existing
segments */
unsigned long shm_tot; /* Total number of shared
memory pages */
unsigned long shm_rss; /* # of resident shared
memory pages */
unsigned long shm_swp; /* # of swapped shared
memory pages */
unsigned long swap_attempts; /* Unused since Linux 2.4 */
unsigned long swap_successes; /* Unused since Linux 2.4 */
};
struct shm_info {
int used_ids; /* # of currently existing
segments */
unsigned long shm_tot; /* Total number of shared
memory pages */
unsigned long shm_rss; /* # of resident shared
memory pages */
unsigned long shm_swp; /* # of swapped shared
memory pages */
unsigned long swap_attempts; /* Unused since Linux 2.4 */
unsigned long swap_successes; /* Unused since Linux 2.4 */
};
On error, -1 is returned, and
errno is set appropriately.
Or (in kernels before 2.6.9),
SHM_LOCK or
SHM_UNLOCK was specified, but the process was not privileged
(Linux: did not have the
CAP_IPC_LOCK capability).
(Since Linux 2.6.9, this error can also occur if the
RLIMIT_MEMLOCK is 0 and the caller is not privileged.)
Linux permits a process to attach
(shmat()) a shared memory segment that has already been marked for deletion
using
shmctl(IPC_RMID). This feature is not available on other Unix implementations;
portable applications should avoid relying on it.
Various fields in a struct shmid_ds were shorts under Linux 2.2
and have become longs under Linux 2.4. To take advantage of this,
a recompilation under glibc-2.1.91 or later should suffice.
(The kernel distinguishes old and new calls by an IPC_64 flag in
cmd.)
mlock (2)
mlock (2)
setrlimit (2)
setrlimit (2)
shmget (2)
shmget (2)
shmop (2)
shmop (2)
Advertisements
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": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2376,
"s": 2319,
"text": "\nint shmctl(int shmid, int cmd, struct shmid_ds *buf); \n"
},
{
"code": null,
"e": 2468,
"s": 2376,
"text": "\nThe\nbuf argument is a pointer to a shmid_ds structure,\ndefined in <sys/shm.h> as follows:\n"
},
{
"code": null,
"e": 2981,
"s": 2471,
"text": "struct shmid_ds {\n struct ipc_perm shm_perm; /* Ownership and permissions */\n size_t shm_segsz; /* Size of segment (bytes) */\n time_t shm_atime; /* Last attach time */\n time_t shm_dtime; /* Last detach time */\n time_t shm_ctime; /* Last change time */\n pid_t shm_cpid; /* PID of creator */\n pid_t shm_lpid; /* PID of last shmat()/shmdt() */\n shmatt_t shm_nattch; /* No. of current attaches */\n ...\n};\n"
},
{
"code": null,
"e": 3096,
"s": 2981,
"text": "\nThe\nipc_perm structure is defined in <sys/ipc.h> as follows\n(the highlighted fields are settable using\nIPC_SET): "
},
{
"code": null,
"e": 3555,
"s": 3099,
"text": "struct ipc_perm {\n key_t key; /* Key supplied to shmget() */\n uid_t uid; /* Effective UID of owner */\n gid_t gid; /* Effective GID of owner */\n uid_t cuid; /* Effective UID of creator */\n gid_t cgid; /* Effective GID of creator */\n unsigned short mode; /* Permissions + SHM_DEST and\n SHM_LOCKED flags */\n unsigned short seq; /* Sequence number */\n};\n"
},
{
"code": null,
"e": 3583,
"s": 3555,
"text": "\nValid values for\ncmd are:\n"
},
{
"code": null,
"e": 3991,
"s": 3583,
"text": "\n\nstruct shminfo {\n unsigned long shmmax; /* Max. segment size */\n unsigned long shmmin; /* Min. segment size; always 1 */\n unsigned long shmmni; /* Max. # of segments */\n unsigned long shmseg; /* Max. # of segments that a\n process can attach; unused */\n unsigned long shmall; /* Max. # of pages of shared\n memory, system-wide */\n};\n\n\n"
},
{
"code": null,
"e": 4396,
"s": 3991,
"text": "\nstruct shminfo {\n unsigned long shmmax; /* Max. segment size */\n unsigned long shmmin; /* Min. segment size; always 1 */\n unsigned long shmmni; /* Max. # of segments */\n unsigned long shmseg; /* Max. # of segments that a\n process can attach; unused */\n unsigned long shmall; /* Max. # of pages of shared\n memory, system-wide */\n};\n"
},
{
"code": null,
"e": 4947,
"s": 4399,
"text": "\n\nstruct shm_info {\n int used_ids; /* # of currently existing\n segments */\n unsigned long shm_tot; /* Total number of shared\n memory pages */\n unsigned long shm_rss; /* # of resident shared\n memory pages */\n unsigned long shm_swp; /* # of swapped shared\n memory pages */\n unsigned long swap_attempts; /* Unused since Linux 2.4 */\n unsigned long swap_successes; /* Unused since Linux 2.4 */\n};\n\n\n"
},
{
"code": null,
"e": 5492,
"s": 4947,
"text": "\nstruct shm_info {\n int used_ids; /* # of currently existing\n segments */\n unsigned long shm_tot; /* Total number of shared\n memory pages */\n unsigned long shm_rss; /* # of resident shared\n memory pages */\n unsigned long shm_swp; /* # of swapped shared\n memory pages */\n unsigned long swap_attempts; /* Unused since Linux 2.4 */\n unsigned long swap_successes; /* Unused since Linux 2.4 */\n};\n"
},
{
"code": null,
"e": 5555,
"s": 5495,
"text": "\nOn error, -1 is returned, and\nerrno is set appropriately.\n"
},
{
"code": null,
"e": 5819,
"s": 5555,
"text": "\nOr (in kernels before 2.6.9),\nSHM_LOCK or\nSHM_UNLOCK was specified, but the process was not privileged\n(Linux: did not have the\nCAP_IPC_LOCK capability).\n(Since Linux 2.6.9, this error can also occur if the\nRLIMIT_MEMLOCK is 0 and the caller is not privileged.)\n"
},
{
"code": null,
"e": 6066,
"s": 5819,
"text": "\nLinux permits a process to attach\n(shmat()) a shared memory segment that has already been marked for deletion\nusing\nshmctl(IPC_RMID). This feature is not available on other Unix implementations;\nportable applications should avoid relying on it.\n"
},
{
"code": null,
"e": 6329,
"s": 6066,
"text": "\nVarious fields in a struct shmid_ds were shorts under Linux 2.2\nand have become longs under Linux 2.4. To take advantage of this,\na recompilation under glibc-2.1.91 or later should suffice.\n(The kernel distinguishes old and new calls by an IPC_64 flag in\ncmd.) "
},
{
"code": null,
"e": 6339,
"s": 6329,
"text": "mlock (2)"
},
{
"code": null,
"e": 6349,
"s": 6339,
"text": "mlock (2)"
},
{
"code": null,
"e": 6363,
"s": 6349,
"text": "setrlimit (2)"
},
{
"code": null,
"e": 6377,
"s": 6363,
"text": "setrlimit (2)"
},
{
"code": null,
"e": 6388,
"s": 6377,
"text": "shmget (2)"
},
{
"code": null,
"e": 6399,
"s": 6388,
"text": "shmget (2)"
},
{
"code": null,
"e": 6409,
"s": 6399,
"text": "shmop (2)"
},
{
"code": null,
"e": 6419,
"s": 6409,
"text": "shmop (2)"
},
{
"code": null,
"e": 6436,
"s": 6419,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 6471,
"s": 6436,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 6499,
"s": 6471,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6533,
"s": 6499,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6550,
"s": 6533,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6583,
"s": 6550,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6594,
"s": 6583,
"text": " Pradeep D"
},
{
"code": null,
"e": 6629,
"s": 6594,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6645,
"s": 6629,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 6678,
"s": 6645,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6690,
"s": 6678,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6722,
"s": 6690,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6730,
"s": 6722,
"text": " Uplatz"
},
{
"code": null,
"e": 6737,
"s": 6730,
"text": " Print"
},
{
"code": null,
"e": 6748,
"s": 6737,
"text": " Add Notes"
}
] |
mysql_fetch_array vs mysql_fetch_assoc vs mysql_fetch_object? | These mysql_* functions are deprecated and other functions are available that gives better security and functionality.
Note: As an alternative, use either _assoc or _row though.
The function returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The associativity array tells us about the key value pair, whereas the key tells about any column name and the value tells about the row value.
Here we can map the column name as key and value as row. For example.
Key is ID and value is corresponding name.
This function name suggests that it returns an array. It fetches a result row as an associative array, a numeric array, or both. It has both numeric values as well as string values for a key.
This function returns row as an object and does not return an array. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "These mysql_* functions are deprecated and other functions are available that gives better security and functionality."
},
{
"code": null,
"e": 1240,
"s": 1181,
"text": "Note: As an alternative, use either _assoc or _row though."
},
{
"code": null,
"e": 1510,
"s": 1240,
"text": "The function returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The associativity array tells us about the key value pair, whereas the key tells about any column name and the value tells about the row value."
},
{
"code": null,
"e": 1580,
"s": 1510,
"text": "Here we can map the column name as key and value as row. For example."
},
{
"code": null,
"e": 1624,
"s": 1580,
"text": "Key is ID and value is corresponding name.\n"
},
{
"code": null,
"e": 1816,
"s": 1624,
"text": "This function name suggests that it returns an array. It fetches a result row as an associative array, a numeric array, or both. It has both numeric values as well as string values for a key."
},
{
"code": null,
"e": 1885,
"s": 1816,
"text": "This function returns row as an object and does not return an array."
}
] |
Batch Script - LABEL | This batch command adds, sets or removes a disk label.
Label
@echo off
label
The above command will prompt the user to enter a new label for the current drive.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2224,
"s": 2169,
"text": "This batch command adds, sets or removes a disk label."
},
{
"code": null,
"e": 2231,
"s": 2224,
"text": "Label\n"
},
{
"code": null,
"e": 2249,
"s": 2231,
"text": "@echo off \nlabel\n"
},
{
"code": null,
"e": 2332,
"s": 2249,
"text": "The above command will prompt the user to enter a new label for the current drive."
},
{
"code": null,
"e": 2339,
"s": 2332,
"text": " Print"
},
{
"code": null,
"e": 2350,
"s": 2339,
"text": " Add Notes"
}
] |
A shorthand array notation in C for repeated values - GeeksforGeeks | 18 Sep, 2017
In C, when there are many repeated values, we can use a shorthand array notation to define array. Below program demonstrates same.
// C program to demonstrate working of shorthand// array rotation.#include <stdio.h> int main(){ // This line is same as // int array[10] = {1, 1, 1, 1, 0, 0, 2, 2, 2, 2}; int array[10] = {[0 ... 3]1, [6 ... 9]2}; for (int i = 0; i < 10; i++) printf("%d ", array[i]); return 0;}
Output:
1 1 1 1 0 0 2 2 2 2
Note that middle gap of 2 is automatically filled with 0.
This article is contributed by Kaushik Annangi. 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.
c-array
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Exception Handling in C++
Function Pointer in C
Structures in C | [
{
"code": null,
"e": 23975,
"s": 23947,
"text": "\n18 Sep, 2017"
},
{
"code": null,
"e": 24106,
"s": 23975,
"text": "In C, when there are many repeated values, we can use a shorthand array notation to define array. Below program demonstrates same."
},
{
"code": "// C program to demonstrate working of shorthand// array rotation.#include <stdio.h> int main(){ // This line is same as // int array[10] = {1, 1, 1, 1, 0, 0, 2, 2, 2, 2}; int array[10] = {[0 ... 3]1, [6 ... 9]2}; for (int i = 0; i < 10; i++) printf(\"%d \", array[i]); return 0;}",
"e": 24410,
"s": 24106,
"text": null
},
{
"code": null,
"e": 24418,
"s": 24410,
"text": "Output:"
},
{
"code": null,
"e": 24440,
"s": 24418,
"text": "1 1 1 1 0 0 2 2 2 2 \n"
},
{
"code": null,
"e": 24498,
"s": 24440,
"text": "Note that middle gap of 2 is automatically filled with 0."
},
{
"code": null,
"e": 24801,
"s": 24498,
"text": "This article is contributed by Kaushik Annangi. 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": 24926,
"s": 24801,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 24934,
"s": 24926,
"text": "c-array"
},
{
"code": null,
"e": 24945,
"s": 24934,
"text": "C Language"
},
{
"code": null,
"e": 25043,
"s": 24945,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25052,
"s": 25043,
"text": "Comments"
},
{
"code": null,
"e": 25065,
"s": 25052,
"text": "Old Comments"
},
{
"code": null,
"e": 25097,
"s": 25065,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25137,
"s": 25097,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25165,
"s": 25137,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25177,
"s": 25165,
"text": "fork() in C"
},
{
"code": null,
"e": 25223,
"s": 25177,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25270,
"s": 25223,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 25308,
"s": 25270,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25334,
"s": 25308,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25356,
"s": 25334,
"text": "Function Pointer in C"
}
] |
9 Magic Command to Enhance Your Jupyter Notebook Experience | by Cornellius Yudha Wijaya | Towards Data Science | Do you believe in magic? If you are not, then you should definitely believe in the Jupyter Notebook magic command. The name sounds absurd, but Jupyter Notebook contains a special command we called Magic Command.
True to its name, Magic Command or Line Magic is a special command we execute to achieve some result within the Jupyter Notebook. The magic command works by using the % symbol with the command you want to run.
There are many kinds of Magic Command, but I would only show my top 9 Magic Command in this article.
Let’s get into it.
Who? what is who? This command is a Magic command that would show all the available variables you had in your Jupyter Notebook Environment. Let me show you an example below.
import seaborn as snsdf = sns.load_dataset('mpg')a = 'simple'b = 2
Above, we create 3 different variables; df, a, and b. If you type %who in your Jupyter Notebook cell, it would show all existing variables.
In the above image, we can see that we have all the variables, including the environment's pre-existing variables.
What if you want to see specific variables, say only the str variable? It is easy. You need to type the object type after the magic command. In this case, it was %who str .
This magic command is an interesting one. This magic command was used to evaluate the code execution speed by running it multiple times and produce the average + standard deviation of the execution time. Let’s try it with an example.
import numpy as np%timeit np.random.normal(size=1000)
Using %timeit magic command, we know that the execution time only deviates around 341ns per execution time.
This command is useful when you want to pinpoint the stability of your code execution and looping process.
What if you work on a project in one notebook and want to pass around the variables you had into another notebook. You do not need to pickle it or save it in some object file. What you need is to use the %store magic command.
This is our previous Jupyter Notebook with the ‘df’ variable containing the mpg data frame. Next, I want to move this ‘df’ variable into another Notebook. I only need to type %store df .
The ‘df’ variable is now stored within the Jupyter Notebook and ready to use in a different Jupyter Notebook. Let’s try to create a new notebook and type %store -r df .
Just like that, our ‘df’ variable has moved into another Notebook and ready to use for another analysis. What is unique about the %store magic command is that you could delete the variable in the notebook, and you would still have the variable you store within the %store magic command.
Another magic command that has something to do with time. %prun is a specific magic command to evaluate how much time your function or program to execute each function.
What is amazing about %prun is that shows the table where you could see the number of times each internal function was called within the statement, the time each call took, and the cumulative time of all runs of the function.
Let’s try to run the %prunmagic command with an example.
%prun sns.load_dataset('mpg')
As you can see in the image above, we can see each function's execution time within the statement and their time plus the cumulative time.
Have you been working so much on your analysis and wondering what kind of thing you have done and your current status. You might also confuse than ever when you have to jump around between the cells to run your function.
For this case, we could use the %history magic command to see the log of your activity and trace back what you already did.
Try to run the %history in your Jupyter Notebook cell and see what’s the output. Here is mine below.
Sometimes when you are working with a new object or packages, you want to get all the detailed information. If you are the lazy type like me, we can use the magic command %pinfo2 to get all the detailed information in our Jupyter Notebook cell.
Let’s try to run the magic command using our previous DataFrame object.
%pinfo df
Using this magic command, we can see all the information regarding the object and all the parameter available that we can use.
We know that Jupyter Notebook is not the best IDE for the development and production environment, but it doesn’t mean that we cannot do it in the Jupyter Cell.
What if you already have all that amazing function you code and want to save it in the python file. Sure, you can open another IDE and copy+paste the file, but there is an easier way to do it. We can use the magic command %%writefile to achieve the same result.
Let’s try running the following code.
%%writefile test.pydef number_awesome(x): return 9
Check your current directory; you should have a new Python file right now.
What if you want to do it the other way, like reading the Python file into your Jupyter Notebook? You could do it as well using the %pycat magic command.
Let’s try to read our previous Python file.
%pycat test.py
A new pop up would show up with all the code within the Python file into the Jupyter Notebook.
This magic command is useful when you have many production and development codes you want to experiment with within the Jupyter Notebook.
The last magic command you should know is %quickref . Why is this the should know magic command? Because this magic command explains all the magic command that exists in the Jupyter Notebook with detail.
Let’s try to run it in your notebook.
%quickref
Just like that, you now are presented with all the explanations of every single magic command you could use. How useful is that!
Magic command is a special command within the Jupyter Notebook to improve our everyday activities as a Data Scientist. There are 9 magic commands that I feel necessary to know for people to use; they are:
%who%timeit%store%prun%history or %hist%pinfo%%writefile%pycat%quickref
%who
%timeit
%store
%prun
%history or %hist
%pinfo
%%writefile
%pycat
%quickref
I hope it helps!
If you are not subscribed as a Medium Member, please consider subscribing through my referral. | [
{
"code": null,
"e": 383,
"s": 171,
"text": "Do you believe in magic? If you are not, then you should definitely believe in the Jupyter Notebook magic command. The name sounds absurd, but Jupyter Notebook contains a special command we called Magic Command."
},
{
"code": null,
"e": 593,
"s": 383,
"text": "True to its name, Magic Command or Line Magic is a special command we execute to achieve some result within the Jupyter Notebook. The magic command works by using the % symbol with the command you want to run."
},
{
"code": null,
"e": 694,
"s": 593,
"text": "There are many kinds of Magic Command, but I would only show my top 9 Magic Command in this article."
},
{
"code": null,
"e": 713,
"s": 694,
"text": "Let’s get into it."
},
{
"code": null,
"e": 887,
"s": 713,
"text": "Who? what is who? This command is a Magic command that would show all the available variables you had in your Jupyter Notebook Environment. Let me show you an example below."
},
{
"code": null,
"e": 954,
"s": 887,
"text": "import seaborn as snsdf = sns.load_dataset('mpg')a = 'simple'b = 2"
},
{
"code": null,
"e": 1094,
"s": 954,
"text": "Above, we create 3 different variables; df, a, and b. If you type %who in your Jupyter Notebook cell, it would show all existing variables."
},
{
"code": null,
"e": 1209,
"s": 1094,
"text": "In the above image, we can see that we have all the variables, including the environment's pre-existing variables."
},
{
"code": null,
"e": 1382,
"s": 1209,
"text": "What if you want to see specific variables, say only the str variable? It is easy. You need to type the object type after the magic command. In this case, it was %who str ."
},
{
"code": null,
"e": 1616,
"s": 1382,
"text": "This magic command is an interesting one. This magic command was used to evaluate the code execution speed by running it multiple times and produce the average + standard deviation of the execution time. Let’s try it with an example."
},
{
"code": null,
"e": 1670,
"s": 1616,
"text": "import numpy as np%timeit np.random.normal(size=1000)"
},
{
"code": null,
"e": 1778,
"s": 1670,
"text": "Using %timeit magic command, we know that the execution time only deviates around 341ns per execution time."
},
{
"code": null,
"e": 1885,
"s": 1778,
"text": "This command is useful when you want to pinpoint the stability of your code execution and looping process."
},
{
"code": null,
"e": 2111,
"s": 1885,
"text": "What if you work on a project in one notebook and want to pass around the variables you had into another notebook. You do not need to pickle it or save it in some object file. What you need is to use the %store magic command."
},
{
"code": null,
"e": 2298,
"s": 2111,
"text": "This is our previous Jupyter Notebook with the ‘df’ variable containing the mpg data frame. Next, I want to move this ‘df’ variable into another Notebook. I only need to type %store df ."
},
{
"code": null,
"e": 2467,
"s": 2298,
"text": "The ‘df’ variable is now stored within the Jupyter Notebook and ready to use in a different Jupyter Notebook. Let’s try to create a new notebook and type %store -r df ."
},
{
"code": null,
"e": 2754,
"s": 2467,
"text": "Just like that, our ‘df’ variable has moved into another Notebook and ready to use for another analysis. What is unique about the %store magic command is that you could delete the variable in the notebook, and you would still have the variable you store within the %store magic command."
},
{
"code": null,
"e": 2923,
"s": 2754,
"text": "Another magic command that has something to do with time. %prun is a specific magic command to evaluate how much time your function or program to execute each function."
},
{
"code": null,
"e": 3149,
"s": 2923,
"text": "What is amazing about %prun is that shows the table where you could see the number of times each internal function was called within the statement, the time each call took, and the cumulative time of all runs of the function."
},
{
"code": null,
"e": 3206,
"s": 3149,
"text": "Let’s try to run the %prunmagic command with an example."
},
{
"code": null,
"e": 3236,
"s": 3206,
"text": "%prun sns.load_dataset('mpg')"
},
{
"code": null,
"e": 3375,
"s": 3236,
"text": "As you can see in the image above, we can see each function's execution time within the statement and their time plus the cumulative time."
},
{
"code": null,
"e": 3596,
"s": 3375,
"text": "Have you been working so much on your analysis and wondering what kind of thing you have done and your current status. You might also confuse than ever when you have to jump around between the cells to run your function."
},
{
"code": null,
"e": 3720,
"s": 3596,
"text": "For this case, we could use the %history magic command to see the log of your activity and trace back what you already did."
},
{
"code": null,
"e": 3821,
"s": 3720,
"text": "Try to run the %history in your Jupyter Notebook cell and see what’s the output. Here is mine below."
},
{
"code": null,
"e": 4066,
"s": 3821,
"text": "Sometimes when you are working with a new object or packages, you want to get all the detailed information. If you are the lazy type like me, we can use the magic command %pinfo2 to get all the detailed information in our Jupyter Notebook cell."
},
{
"code": null,
"e": 4138,
"s": 4066,
"text": "Let’s try to run the magic command using our previous DataFrame object."
},
{
"code": null,
"e": 4148,
"s": 4138,
"text": "%pinfo df"
},
{
"code": null,
"e": 4275,
"s": 4148,
"text": "Using this magic command, we can see all the information regarding the object and all the parameter available that we can use."
},
{
"code": null,
"e": 4435,
"s": 4275,
"text": "We know that Jupyter Notebook is not the best IDE for the development and production environment, but it doesn’t mean that we cannot do it in the Jupyter Cell."
},
{
"code": null,
"e": 4697,
"s": 4435,
"text": "What if you already have all that amazing function you code and want to save it in the python file. Sure, you can open another IDE and copy+paste the file, but there is an easier way to do it. We can use the magic command %%writefile to achieve the same result."
},
{
"code": null,
"e": 4735,
"s": 4697,
"text": "Let’s try running the following code."
},
{
"code": null,
"e": 4789,
"s": 4735,
"text": "%%writefile test.pydef number_awesome(x): return 9"
},
{
"code": null,
"e": 4864,
"s": 4789,
"text": "Check your current directory; you should have a new Python file right now."
},
{
"code": null,
"e": 5018,
"s": 4864,
"text": "What if you want to do it the other way, like reading the Python file into your Jupyter Notebook? You could do it as well using the %pycat magic command."
},
{
"code": null,
"e": 5062,
"s": 5018,
"text": "Let’s try to read our previous Python file."
},
{
"code": null,
"e": 5077,
"s": 5062,
"text": "%pycat test.py"
},
{
"code": null,
"e": 5172,
"s": 5077,
"text": "A new pop up would show up with all the code within the Python file into the Jupyter Notebook."
},
{
"code": null,
"e": 5310,
"s": 5172,
"text": "This magic command is useful when you have many production and development codes you want to experiment with within the Jupyter Notebook."
},
{
"code": null,
"e": 5514,
"s": 5310,
"text": "The last magic command you should know is %quickref . Why is this the should know magic command? Because this magic command explains all the magic command that exists in the Jupyter Notebook with detail."
},
{
"code": null,
"e": 5552,
"s": 5514,
"text": "Let’s try to run it in your notebook."
},
{
"code": null,
"e": 5562,
"s": 5552,
"text": "%quickref"
},
{
"code": null,
"e": 5691,
"s": 5562,
"text": "Just like that, you now are presented with all the explanations of every single magic command you could use. How useful is that!"
},
{
"code": null,
"e": 5896,
"s": 5691,
"text": "Magic command is a special command within the Jupyter Notebook to improve our everyday activities as a Data Scientist. There are 9 magic commands that I feel necessary to know for people to use; they are:"
},
{
"code": null,
"e": 5968,
"s": 5896,
"text": "%who%timeit%store%prun%history or %hist%pinfo%%writefile%pycat%quickref"
},
{
"code": null,
"e": 5973,
"s": 5968,
"text": "%who"
},
{
"code": null,
"e": 5981,
"s": 5973,
"text": "%timeit"
},
{
"code": null,
"e": 5988,
"s": 5981,
"text": "%store"
},
{
"code": null,
"e": 5994,
"s": 5988,
"text": "%prun"
},
{
"code": null,
"e": 6012,
"s": 5994,
"text": "%history or %hist"
},
{
"code": null,
"e": 6019,
"s": 6012,
"text": "%pinfo"
},
{
"code": null,
"e": 6031,
"s": 6019,
"text": "%%writefile"
},
{
"code": null,
"e": 6038,
"s": 6031,
"text": "%pycat"
},
{
"code": null,
"e": 6048,
"s": 6038,
"text": "%quickref"
},
{
"code": null,
"e": 6065,
"s": 6048,
"text": "I hope it helps!"
}
] |
Conditional Probability with a Python Example | by GreekDataGuy | Towards Data Science | This article has 2 parts:1. Theory behind conditional probability2. Example with python
For once, wikipedia has an approachable definition,
In probability theory, conditional probability is a measure of the probability of an event occurring given that another event has (by assumption, presumption, assertion or evidence) occurred.
Translation: given B is true, what is the probability that A is also true.
It’s easier to understand something with concrete examples. Below are a few random examples of conditional probabilities we could calculate.
What’s the probability of someone sleeping less than 8 hours if they’re a college student.What’s the probability of a dog living longer than 15 years if they’re a border collie.What’s the probability of using all your vacation days if you work for the government.
What’s the probability of someone sleeping less than 8 hours if they’re a college student.
What’s the probability of a dog living longer than 15 years if they’re a border collie.
What’s the probability of using all your vacation days if you work for the government.
The formula for conditional probability is P(A|B) = P(A ∩ B) / P(B).
The parts:P(A|B) = probability of A occurring, given B occurs P(A ∩ B) = probability of both A and B occurringP(B) = probability of B occurring
| means “given”. Meaning “in cases where something else occurs”.
∩ means intersection which you can think of as and, or the overlap in the context of a Venn diagram.
But why do we divide P(A ∩ B) by P(B)in the formula?
Because we want to exclude the probability of non-B cases. We’re scoping our probability to that falling within B.
Dividing byP(B) removes the probability of anything not B . C — B above.
We’re going to calculate the probability a student gets an A (80%+) in math, given they miss 10 or more classes.
Download the dataset from kaggle and inspect the data.
import pandas as pddf = pd.read_csv('student-alcohol-consumption/student-mat.csv')df.head(3)
And check the number of records.
len(df)#=> 395
We’re only concerned with the columns, absences (number of absences), and G3 (final grade from 0 to 20).
Let’s create a couple new boolean columns based on these columns to make our lives easier.
Add a boolean column called grade_A noting if a student achieved 80% or higher as a final score. Original values are on a 0–20 scale so we multiply by 5.
df['grade_A'] = np.where(df['G3']*5 >= 80, 1, 0)
Make another boolean column called high_absenses with a value of 1 if a student missed 10 or more classes.
df['high_absenses'] = np.where(df['absences'] >= 10, 1, 0)
Add one more column to make building a pivot table easier.
df['count'] = 1
And drop all columns we don’t care about.
df = df[['grade_A','high_absenses','count']]df.head()
Nice. Now we’ll create a pivot table from this.
pd.pivot_table( df, values='count', index=['grade_A'], columns=['high_absenses'], aggfunc=np.size, fill_value=0)
We now have all the data we need to do our calculation. Let’s start by calculating each individual part in the formula.
In our case:P(A) is the probability of a grade of 80% or greater. P(B) is the probability of missing 10 or more classes.P(A|B) is the probability of a 80%+ grade, given missing 10 or more classes.
Calculations of parts:P(A) = (35 + 5) / (35 + 5 + 277 + 78) = 0.10126582278481013P(B) = (78 + 5) / (35 + 5 + 277 + 78) = 0.21012658227848102P(A ∩ B) = 5 / (35 + 5 + 277 + 78) = 0.012658227848101266
And per the formula, P(A|B) = P(A ∩ B) / P(B), put it together.
P(A|B) = 0.012658227848101266/ 0.21012658227848102= 0.06
There we have it. The probability of getting at least an 80% final grade, given missing 10 or more classes is 6%.
While the learning from our specific example is clear - go to class if you want good grades, conditional probability can be applied to more serious circumstances.
For example, the probability a person has a particular disease, given test results.
An understanding is also essential before diving into more complicated probability estimations using Bayes’ theorem. | [
{
"code": null,
"e": 259,
"s": 171,
"text": "This article has 2 parts:1. Theory behind conditional probability2. Example with python"
},
{
"code": null,
"e": 311,
"s": 259,
"text": "For once, wikipedia has an approachable definition,"
},
{
"code": null,
"e": 503,
"s": 311,
"text": "In probability theory, conditional probability is a measure of the probability of an event occurring given that another event has (by assumption, presumption, assertion or evidence) occurred."
},
{
"code": null,
"e": 578,
"s": 503,
"text": "Translation: given B is true, what is the probability that A is also true."
},
{
"code": null,
"e": 719,
"s": 578,
"text": "It’s easier to understand something with concrete examples. Below are a few random examples of conditional probabilities we could calculate."
},
{
"code": null,
"e": 983,
"s": 719,
"text": "What’s the probability of someone sleeping less than 8 hours if they’re a college student.What’s the probability of a dog living longer than 15 years if they’re a border collie.What’s the probability of using all your vacation days if you work for the government."
},
{
"code": null,
"e": 1074,
"s": 983,
"text": "What’s the probability of someone sleeping less than 8 hours if they’re a college student."
},
{
"code": null,
"e": 1162,
"s": 1074,
"text": "What’s the probability of a dog living longer than 15 years if they’re a border collie."
},
{
"code": null,
"e": 1249,
"s": 1162,
"text": "What’s the probability of using all your vacation days if you work for the government."
},
{
"code": null,
"e": 1318,
"s": 1249,
"text": "The formula for conditional probability is P(A|B) = P(A ∩ B) / P(B)."
},
{
"code": null,
"e": 1462,
"s": 1318,
"text": "The parts:P(A|B) = probability of A occurring, given B occurs P(A ∩ B) = probability of both A and B occurringP(B) = probability of B occurring"
},
{
"code": null,
"e": 1527,
"s": 1462,
"text": "| means “given”. Meaning “in cases where something else occurs”."
},
{
"code": null,
"e": 1628,
"s": 1527,
"text": "∩ means intersection which you can think of as and, or the overlap in the context of a Venn diagram."
},
{
"code": null,
"e": 1681,
"s": 1628,
"text": "But why do we divide P(A ∩ B) by P(B)in the formula?"
},
{
"code": null,
"e": 1796,
"s": 1681,
"text": "Because we want to exclude the probability of non-B cases. We’re scoping our probability to that falling within B."
},
{
"code": null,
"e": 1869,
"s": 1796,
"text": "Dividing byP(B) removes the probability of anything not B . C — B above."
},
{
"code": null,
"e": 1982,
"s": 1869,
"text": "We’re going to calculate the probability a student gets an A (80%+) in math, given they miss 10 or more classes."
},
{
"code": null,
"e": 2037,
"s": 1982,
"text": "Download the dataset from kaggle and inspect the data."
},
{
"code": null,
"e": 2130,
"s": 2037,
"text": "import pandas as pddf = pd.read_csv('student-alcohol-consumption/student-mat.csv')df.head(3)"
},
{
"code": null,
"e": 2163,
"s": 2130,
"text": "And check the number of records."
},
{
"code": null,
"e": 2178,
"s": 2163,
"text": "len(df)#=> 395"
},
{
"code": null,
"e": 2283,
"s": 2178,
"text": "We’re only concerned with the columns, absences (number of absences), and G3 (final grade from 0 to 20)."
},
{
"code": null,
"e": 2374,
"s": 2283,
"text": "Let’s create a couple new boolean columns based on these columns to make our lives easier."
},
{
"code": null,
"e": 2528,
"s": 2374,
"text": "Add a boolean column called grade_A noting if a student achieved 80% or higher as a final score. Original values are on a 0–20 scale so we multiply by 5."
},
{
"code": null,
"e": 2577,
"s": 2528,
"text": "df['grade_A'] = np.where(df['G3']*5 >= 80, 1, 0)"
},
{
"code": null,
"e": 2684,
"s": 2577,
"text": "Make another boolean column called high_absenses with a value of 1 if a student missed 10 or more classes."
},
{
"code": null,
"e": 2743,
"s": 2684,
"text": "df['high_absenses'] = np.where(df['absences'] >= 10, 1, 0)"
},
{
"code": null,
"e": 2802,
"s": 2743,
"text": "Add one more column to make building a pivot table easier."
},
{
"code": null,
"e": 2818,
"s": 2802,
"text": "df['count'] = 1"
},
{
"code": null,
"e": 2860,
"s": 2818,
"text": "And drop all columns we don’t care about."
},
{
"code": null,
"e": 2914,
"s": 2860,
"text": "df = df[['grade_A','high_absenses','count']]df.head()"
},
{
"code": null,
"e": 2962,
"s": 2914,
"text": "Nice. Now we’ll create a pivot table from this."
},
{
"code": null,
"e": 3098,
"s": 2962,
"text": "pd.pivot_table( df, values='count', index=['grade_A'], columns=['high_absenses'], aggfunc=np.size, fill_value=0)"
},
{
"code": null,
"e": 3218,
"s": 3098,
"text": "We now have all the data we need to do our calculation. Let’s start by calculating each individual part in the formula."
},
{
"code": null,
"e": 3415,
"s": 3218,
"text": "In our case:P(A) is the probability of a grade of 80% or greater. P(B) is the probability of missing 10 or more classes.P(A|B) is the probability of a 80%+ grade, given missing 10 or more classes."
},
{
"code": null,
"e": 3613,
"s": 3415,
"text": "Calculations of parts:P(A) = (35 + 5) / (35 + 5 + 277 + 78) = 0.10126582278481013P(B) = (78 + 5) / (35 + 5 + 277 + 78) = 0.21012658227848102P(A ∩ B) = 5 / (35 + 5 + 277 + 78) = 0.012658227848101266"
},
{
"code": null,
"e": 3677,
"s": 3613,
"text": "And per the formula, P(A|B) = P(A ∩ B) / P(B), put it together."
},
{
"code": null,
"e": 3734,
"s": 3677,
"text": "P(A|B) = 0.012658227848101266/ 0.21012658227848102= 0.06"
},
{
"code": null,
"e": 3848,
"s": 3734,
"text": "There we have it. The probability of getting at least an 80% final grade, given missing 10 or more classes is 6%."
},
{
"code": null,
"e": 4011,
"s": 3848,
"text": "While the learning from our specific example is clear - go to class if you want good grades, conditional probability can be applied to more serious circumstances."
},
{
"code": null,
"e": 4095,
"s": 4011,
"text": "For example, the probability a person has a particular disease, given test results."
}
] |
Tryit Editor v3.7 | Tryit: HTML form element | [] |
Jupyter Notebook to PDF in a few lines | by Cornellius Yudha Wijaya | Towards Data Science | If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here.
While working on our Jupyter Notebook, sometimes we want to share our processed dataset complete with the created plot and the markdown explanation we already created in a readable form. There is an easy way to turn our Jupyer Notebooks into PDF files. Just with a simple setup, you can access your notebook as a PDF.
For example, I would use the notebook I provide in my article here to convert to the PDF form. Below is my Jupyter Notebook.
And below is the notebook in the PDF form.
As you can see, it shows all the codes and your explanation just like that. How fancy is it?
Now let me show you how to do it.
The first thing we need to do is to install the necessary package. Here we would use the package called notebook-as-pdf to help us convert Jupyter Notebook as PDF file. You need to run the following code in your command prompt.
pip install -U notebook-as-pdf
We also need an additional setup for Chromium. It is used to perform the HTML to PDF conversion. Just run the following code in your code prompt.
pyppeteer-install
Just like that, we have already finished our preparation. Now, let’s open the notebook you intend to convert into the PDF. In your notebook, click the file menu bar then select Download as then select the PDF via HTML to transform the notebook.
Just like that, you already have your notebook as a PDF file. If you prefer to use command prompt to convert the notebook, you could do it with the following code.
jupyter-nbconvert --to PDFviaHTML example.ipynb
The result would be called example.pdf as our Jupyter Notebook is called example.ipynb.
Here I showed you a trick to convert your Jupyter Notebook into a PDF file. It might be simple but will prove useful in the long run.
If you want to read more about the package, you can visit the website here.
Visit me on my LinkedIn or Twitter
If you are not subscribed as a Medium Member, please consider subscribing through my referral. | [
{
"code": null,
"e": 342,
"s": 172,
"text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here."
},
{
"code": null,
"e": 660,
"s": 342,
"text": "While working on our Jupyter Notebook, sometimes we want to share our processed dataset complete with the created plot and the markdown explanation we already created in a readable form. There is an easy way to turn our Jupyer Notebooks into PDF files. Just with a simple setup, you can access your notebook as a PDF."
},
{
"code": null,
"e": 785,
"s": 660,
"text": "For example, I would use the notebook I provide in my article here to convert to the PDF form. Below is my Jupyter Notebook."
},
{
"code": null,
"e": 828,
"s": 785,
"text": "And below is the notebook in the PDF form."
},
{
"code": null,
"e": 921,
"s": 828,
"text": "As you can see, it shows all the codes and your explanation just like that. How fancy is it?"
},
{
"code": null,
"e": 955,
"s": 921,
"text": "Now let me show you how to do it."
},
{
"code": null,
"e": 1183,
"s": 955,
"text": "The first thing we need to do is to install the necessary package. Here we would use the package called notebook-as-pdf to help us convert Jupyter Notebook as PDF file. You need to run the following code in your command prompt."
},
{
"code": null,
"e": 1214,
"s": 1183,
"text": "pip install -U notebook-as-pdf"
},
{
"code": null,
"e": 1360,
"s": 1214,
"text": "We also need an additional setup for Chromium. It is used to perform the HTML to PDF conversion. Just run the following code in your code prompt."
},
{
"code": null,
"e": 1378,
"s": 1360,
"text": "pyppeteer-install"
},
{
"code": null,
"e": 1623,
"s": 1378,
"text": "Just like that, we have already finished our preparation. Now, let’s open the notebook you intend to convert into the PDF. In your notebook, click the file menu bar then select Download as then select the PDF via HTML to transform the notebook."
},
{
"code": null,
"e": 1787,
"s": 1623,
"text": "Just like that, you already have your notebook as a PDF file. If you prefer to use command prompt to convert the notebook, you could do it with the following code."
},
{
"code": null,
"e": 1835,
"s": 1787,
"text": "jupyter-nbconvert --to PDFviaHTML example.ipynb"
},
{
"code": null,
"e": 1923,
"s": 1835,
"text": "The result would be called example.pdf as our Jupyter Notebook is called example.ipynb."
},
{
"code": null,
"e": 2057,
"s": 1923,
"text": "Here I showed you a trick to convert your Jupyter Notebook into a PDF file. It might be simple but will prove useful in the long run."
},
{
"code": null,
"e": 2133,
"s": 2057,
"text": "If you want to read more about the package, you can visit the website here."
},
{
"code": null,
"e": 2168,
"s": 2133,
"text": "Visit me on my LinkedIn or Twitter"
}
] |
Build a GUI Application to ping the host using Python - GeeksforGeeks | 04 Dec, 2021
Prerequisite: Python GUI – Tkinter
In this article, we are going to see how to ping the host with a URL or IP using the python ping module in Python. This module provides a simple way to ping in python. And It checks the host is available or not and measures how long the response takes.
“Before” starting we need to install this module into your system.
pip install pythonping
The GUI would look like below:
Syntax: ping(‘URL or IP’)
Parameter:
verbose : enables the verbose mode, printing output to a stream
timeout : is the number of seconds you wish to wait for a response, before assuming the target is unreachable
payload : allows you to use a specific payload (bytes)
size : is an integer that allows you to specify the size of the ICMP payload you desire
Code:
Python3
# import modulefrom pythonping import ping # pinging the hostping('www.google.com', verbose=True)
Output:
Reply from 142.250.71.4, 9 bytes in 61.09ms
Reply from 142.250.71.4, 9 bytes in 60.24ms
Reply from 142.250.71.4, 9 bytes in 60.22ms
Reply from 142.250.71.4, 9 bytes in 60.04ms
Reply from 142.250.71.4, 9 bytes in 61.09ms
Reply from 142.250.71.4, 9 bytes in 60.24ms
Reply from 142.250.71.4, 9 bytes in 60.22ms
Reply from 142.250.71.4, 9 bytes in 60.04ms
Round Trip Times min/avg/max is 60.04/60.4/61.09 ms
Implementation for GUI:
Pinging GUI Application with Tkinter
Python3
# import modulesfrom tkinter import *from pythonping import ping def get_ping(): result = ping(e.get(), verbose=True) res.set(result) # object of tkinter# and background set for light greymaster = Tk()master.configure(bg='light grey') # Variable Classes in tkinterres = StringVar() # Creating label for each information# name using widget LabelLabel(master, text="Enter URL or IP :", bg="light grey").grid(row=0, sticky=W)Label(master, text="Result :", bg="light grey").grid(row=1, sticky=W) # Creating label for class variable# name using widget EntryLabel(master, text="", textvariable=res, bg="light grey").grid( row=1, column=1, sticky=W) e = Entry(master)e.grid(row=0, column=1) # creating a button using the widget# Button that will call the submit functionb = Button(master, text="Show", command=get_ping)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()
Output:
abhigoya
avtarkumar719
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n04 Dec, 2021"
},
{
"code": null,
"e": 23936,
"s": 23901,
"text": "Prerequisite: Python GUI – Tkinter"
},
{
"code": null,
"e": 24189,
"s": 23936,
"text": "In this article, we are going to see how to ping the host with a URL or IP using the python ping module in Python. This module provides a simple way to ping in python. And It checks the host is available or not and measures how long the response takes."
},
{
"code": null,
"e": 24256,
"s": 24189,
"text": "“Before” starting we need to install this module into your system."
},
{
"code": null,
"e": 24279,
"s": 24256,
"text": "pip install pythonping"
},
{
"code": null,
"e": 24310,
"s": 24279,
"text": "The GUI would look like below:"
},
{
"code": null,
"e": 24336,
"s": 24310,
"text": "Syntax: ping(‘URL or IP’)"
},
{
"code": null,
"e": 24347,
"s": 24336,
"text": "Parameter:"
},
{
"code": null,
"e": 24411,
"s": 24347,
"text": "verbose : enables the verbose mode, printing output to a stream"
},
{
"code": null,
"e": 24521,
"s": 24411,
"text": "timeout : is the number of seconds you wish to wait for a response, before assuming the target is unreachable"
},
{
"code": null,
"e": 24576,
"s": 24521,
"text": "payload : allows you to use a specific payload (bytes)"
},
{
"code": null,
"e": 24664,
"s": 24576,
"text": "size : is an integer that allows you to specify the size of the ICMP payload you desire"
},
{
"code": null,
"e": 24670,
"s": 24664,
"text": "Code:"
},
{
"code": null,
"e": 24678,
"s": 24670,
"text": "Python3"
},
{
"code": "# import modulefrom pythonping import ping # pinging the hostping('www.google.com', verbose=True)",
"e": 24776,
"s": 24678,
"text": null
},
{
"code": null,
"e": 24785,
"s": 24776,
"text": " Output:"
},
{
"code": null,
"e": 25190,
"s": 24785,
"text": "Reply from 142.250.71.4, 9 bytes in 61.09ms\nReply from 142.250.71.4, 9 bytes in 60.24ms\nReply from 142.250.71.4, 9 bytes in 60.22ms\nReply from 142.250.71.4, 9 bytes in 60.04ms\nReply from 142.250.71.4, 9 bytes in 61.09ms\nReply from 142.250.71.4, 9 bytes in 60.24ms\nReply from 142.250.71.4, 9 bytes in 60.22ms\nReply from 142.250.71.4, 9 bytes in 60.04ms\n\nRound Trip Times min/avg/max is 60.04/60.4/61.09 ms"
},
{
"code": null,
"e": 25214,
"s": 25190,
"text": "Implementation for GUI:"
},
{
"code": null,
"e": 25251,
"s": 25214,
"text": "Pinging GUI Application with Tkinter"
},
{
"code": null,
"e": 25259,
"s": 25251,
"text": "Python3"
},
{
"code": "# import modulesfrom tkinter import *from pythonping import ping def get_ping(): result = ping(e.get(), verbose=True) res.set(result) # object of tkinter# and background set for light greymaster = Tk()master.configure(bg='light grey') # Variable Classes in tkinterres = StringVar() # Creating label for each information# name using widget LabelLabel(master, text=\"Enter URL or IP :\", bg=\"light grey\").grid(row=0, sticky=W)Label(master, text=\"Result :\", bg=\"light grey\").grid(row=1, sticky=W) # Creating label for class variable# name using widget EntryLabel(master, text=\"\", textvariable=res, bg=\"light grey\").grid( row=1, column=1, sticky=W) e = Entry(master)e.grid(row=0, column=1) # creating a button using the widget# Button that will call the submit functionb = Button(master, text=\"Show\", command=get_ping)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()",
"e": 26161,
"s": 25259,
"text": null
},
{
"code": null,
"e": 26170,
"s": 26161,
"text": " Output:"
},
{
"code": null,
"e": 26179,
"s": 26170,
"text": "abhigoya"
},
{
"code": null,
"e": 26193,
"s": 26179,
"text": "avtarkumar719"
},
{
"code": null,
"e": 26218,
"s": 26193,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 26233,
"s": 26218,
"text": "Python-tkinter"
},
{
"code": null,
"e": 26248,
"s": 26233,
"text": "python-utility"
},
{
"code": null,
"e": 26255,
"s": 26248,
"text": "Python"
},
{
"code": null,
"e": 26353,
"s": 26255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26362,
"s": 26353,
"text": "Comments"
},
{
"code": null,
"e": 26375,
"s": 26362,
"text": "Old Comments"
},
{
"code": null,
"e": 26396,
"s": 26375,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26428,
"s": 26396,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26451,
"s": 26428,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26473,
"s": 26451,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26500,
"s": 26473,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26516,
"s": 26500,
"text": "Deque in Python"
},
{
"code": null,
"e": 26558,
"s": 26516,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26614,
"s": 26558,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26659,
"s": 26614,
"text": "Python - Ways to remove duplicates from list"
}
] |
How to verify action bar tittle is truncating or not in android? | This example demonstrates How to verify action bar tittle is truncating or not in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to action bar tittle status.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@SuppressLint("RestrictedApi")
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Home");
getSupportActionBar().setSubtitle("sairam");
textView.setText(" "+getSupportActionBar().isTitleTruncated());
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() = = android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(menuItem);
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1153,
"s": 1062,
"text": "This example demonstrates How to verify action bar tittle is truncating or not in android."
},
{
"code": null,
"e": 1282,
"s": 1153,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1347,
"s": 1282,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1907,
"s": 1347,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1979,
"s": 1907,
"text": "In the above code, we have taken text view to action bar tittle status."
},
{
"code": null,
"e": 2036,
"s": 1979,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3403,
"s": 2036,
"text": "package com.example.myapplication;\nimport android.annotation.SuppressLint;\nimport android.app.ActivityManager;\nimport android.app.admin.DevicePolicyManager;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @SuppressLint(\"RestrictedApi\")\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n getSupportActionBar().setDisplayHomeAsUpEnabled(true);\n getSupportActionBar().setTitle(\"Home\");\n getSupportActionBar().setSubtitle(\"sairam\");\n textView.setText(\" \"+getSupportActionBar().isTitleTruncated());\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem menuItem) {\n if (menuItem.getItemId() = = android.R.id.home) {\n finish();\n }\n return super.onOptionsItemSelected(menuItem);\n }\n}"
},
{
"code": null,
"e": 3750,
"s": 3403,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3790,
"s": 3750,
"text": "Click here to download the project code"
}
] |
Solve System of Equations in R | 23 Aug, 2021
In this article, we will discuss how to solve a system of equations in R Programming Language.
solve() function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated.
Syntax: solve(a, b)
Parameters:
a: coefficients of the equation
b: vector or matrix of the equation
Given Equations:
x + 2y + 3z = 20
2x + 2y + 3z = 100
3x + 2y + 8z = 200
Matrix A and B for solution using coefficient of equations:
A->
1 2 3
2 2 3
3 2 8
B->
20
100
200
To solve this using two matrices in R we use the following code:
R
# create matrix A and B using given equationsA <- rbind(c(1, 2, 3), c(2, 2, 3), c(3, 2, 8))B <- c(20, 100, 200) # Solve them using solve function in Rsolve(A, B)
Output:
80 -36 3.99999999999999
which means x=80, y=-36 and z=4 is the solution for linear equations.
To get solutions in form of fractions, we use library MASS in R Language and wrap solve function in fractions.
Given Equations:
19x + 32y + 31z = 1110
22x + 28y + 13z = 1406
31x + 12y + 81z = 3040
Matrix A and B for solution using coefficient of equations:
A->
19 32 31
22 28 13
31 12 81
B->
1110
1406
3040
To solve this using two matrices in R we use the following code:
R
# Load package MASSlibrary(MASS) # create matrix A and B using given equationsA <- rbind(c(19, 32, 31), c(22, 28, 31), c(31, 12, 81))B <- c(1110, 1406, 3040) # Solve them using solve# function wrapped in fractionsfractions(solve(A, B))
Output:
[1] 159950/2243 -92039/4486 29784/2243
which means x=159950/2243 , y=-92039/4486 and z=29784/2243 is the solution for the above given linear equation.
R
# create matrix A and B using given equationsA <- matrix(c(4, 7, 3, 6), ncol = 2)print(A) print("Inverse matrix") # Solve them using solve function in Rprint(solve(A))
Output:
[,1] [,2]
[1,] 4 3
[2,] 7 6
[1] "Inverse matrix"
[,1] [,2]
[1,] 2.000000 -1.000000
[2,] -2.333333 1.333333
Picked
R Math-Function
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "In this article, we will discuss how to solve a system of equations in R Programming Language. "
},
{
"code": null,
"e": 306,
"s": 124,
"text": "solve() function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated."
},
{
"code": null,
"e": 326,
"s": 306,
"text": "Syntax: solve(a, b)"
},
{
"code": null,
"e": 338,
"s": 326,
"text": "Parameters:"
},
{
"code": null,
"e": 370,
"s": 338,
"text": "a: coefficients of the equation"
},
{
"code": null,
"e": 406,
"s": 370,
"text": "b: vector or matrix of the equation"
},
{
"code": null,
"e": 592,
"s": 406,
"text": "Given Equations:\nx + 2y + 3z = 20 \n2x + 2y + 3z = 100 \n3x + 2y + 8z = 200\n\nMatrix A and B for solution using coefficient of equations:\nA->\n1 2 3\n2 2 3\n3 2 8\nB->\n20\n100\n200"
},
{
"code": null,
"e": 657,
"s": 592,
"text": "To solve this using two matrices in R we use the following code:"
},
{
"code": null,
"e": 659,
"s": 657,
"text": "R"
},
{
"code": "# create matrix A and B using given equationsA <- rbind(c(1, 2, 3), c(2, 2, 3), c(3, 2, 8))B <- c(20, 100, 200) # Solve them using solve function in Rsolve(A, B)",
"e": 844,
"s": 659,
"text": null
},
{
"code": null,
"e": 852,
"s": 844,
"text": "Output:"
},
{
"code": null,
"e": 876,
"s": 852,
"text": "80 -36 3.99999999999999"
},
{
"code": null,
"e": 946,
"s": 876,
"text": "which means x=80, y=-36 and z=4 is the solution for linear equations."
},
{
"code": null,
"e": 1057,
"s": 946,
"text": "To get solutions in form of fractions, we use library MASS in R Language and wrap solve function in fractions."
},
{
"code": null,
"e": 1269,
"s": 1057,
"text": "Given Equations:\n19x + 32y + 31z = 1110 \n22x + 28y + 13z = 1406 \n31x + 12y + 81z = 3040\nMatrix A and B for solution using coefficient of equations:\nA->\n19 32 31\n22 28 13\n31 12 81\nB->\n1110\n1406\n3040"
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "To solve this using two matrices in R we use the following code:"
},
{
"code": null,
"e": 1336,
"s": 1334,
"text": "R"
},
{
"code": "# Load package MASSlibrary(MASS) # create matrix A and B using given equationsA <- rbind(c(19, 32, 31), c(22, 28, 31), c(31, 12, 81))B <- c(1110, 1406, 3040) # Solve them using solve# function wrapped in fractionsfractions(solve(A, B))",
"e": 1596,
"s": 1336,
"text": null
},
{
"code": null,
"e": 1604,
"s": 1596,
"text": "Output:"
},
{
"code": null,
"e": 1644,
"s": 1604,
"text": "[1] 159950/2243 -92039/4486 29784/2243"
},
{
"code": null,
"e": 1756,
"s": 1644,
"text": "which means x=159950/2243 , y=-92039/4486 and z=29784/2243 is the solution for the above given linear equation."
},
{
"code": null,
"e": 1758,
"s": 1756,
"text": "R"
},
{
"code": "# create matrix A and B using given equationsA <- matrix(c(4, 7, 3, 6), ncol = 2)print(A) print(\"Inverse matrix\") # Solve them using solve function in Rprint(solve(A))",
"e": 1928,
"s": 1758,
"text": null
},
{
"code": null,
"e": 1936,
"s": 1928,
"text": "Output:"
},
{
"code": null,
"e": 2077,
"s": 1936,
"text": " [,1] [,2]\n[1,] 4 3\n[2,] 7 6\n[1] \"Inverse matrix\"\n [,1] [,2]\n[1,] 2.000000 -1.000000\n[2,] -2.333333 1.333333"
},
{
"code": null,
"e": 2084,
"s": 2077,
"text": "Picked"
},
{
"code": null,
"e": 2100,
"s": 2084,
"text": "R Math-Function"
},
{
"code": null,
"e": 2111,
"s": 2100,
"text": "R Language"
},
{
"code": null,
"e": 2122,
"s": 2111,
"text": "R Programs"
},
{
"code": null,
"e": 2220,
"s": 2122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2272,
"s": 2220,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2330,
"s": 2272,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2365,
"s": 2330,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2403,
"s": 2365,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2452,
"s": 2403,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2510,
"s": 2452,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2559,
"s": 2510,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2602,
"s": 2559,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2640,
"s": 2602,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to use GIT in Ubuntu ? (Part -2) | 15 Nov, 2021
In the previous article, we learnt how to use basic GIT. In this article we would try to learn some more basic concepts like branching and merging.
SOME MORE BASIC COMMANDS:
Some of the very helpful commands while using git are:
git
Type this in the terminal and you’ll see a bunch of commonly used GIT commands with their usage. To know about a command in detail, you can type in ‘git help <command>’ .
git status
This is one of the most useful commands of GIT. If, at any point of time, you wish to know your current branch or changes in the files which aren’t staged for commit or untracked files, type in this command.
Here, the branch is master and everything is up-to-data. Let’s make some changes in the file and then use this command again.
There are changes which are not staged for commit in the file helloworld.c and we have the option of adding these changes in the final commit or discarding the changes in the final commit. We can add them with the git add . command (as discussed previously) and discard the changes in the file by the command git checkout — helloworld.c (NOTE: There is a space in between ‘–‘ and ‘helloworld.c’)
git log
With this command one can see the commit logs with the Date, Time, Name of the Author and commit notes. This command is very useful in a group of developers working on the same project.
git add
As discussed previously, we must add the file(s) to the list while we would commit later. We can add the files with the help of git add . or git add helloworld.c But, let’s say we want to add only a specific group of files with similar extensions. Let’s say all the files ending with .txt . Then we can do it by git add *.txt command. This would add only the files which ends with .txt .
Now, if we want to ignore a specific group of files with similar extensions ( .txt, .cpp, etc) then we can also do it with git. For example, Let us consider we want to ignore the .c~ files that we can see (helloworld.c~). I have made another file named newfile.c so that there is another .c~ file which would be ignored. We need to follow two simple steps:
We need to make a .gitignore file where we would store all the extensions to be ignored. We can make a such a file by typing touch .gitignore in the terminal and then open it with a text editor.Type in all the extensions of files which you want to ignore. Here, I want to ignore all the .c~ files and the.gitignore~ file.
We need to make a .gitignore file where we would store all the extensions to be ignored. We can make a such a file by typing touch .gitignore in the terminal and then open it with a text editor.
Type in all the extensions of files which you want to ignore. Here, I want to ignore all the .c~ files and the.gitignore~ file.
We can see the file newfile.c~ by typing the command ls but when we check the status ( git status), we can see just two untracked files (.gitignore and newfile.c) . Note that there is no newfile.c~ file which means that it has been ignored successfully. We can now add the untracked files and then commit as we have been doing earlier.
BRANCHING & MERGING
Branching allows you to work on a copy of code in the mainline without actually effecting the main line directory. For example, Let’s say if you want to work on a new module of the project, then you can choose a new branch on which you’ll work. Everyone else can work on the same project by working on their branches without being affected by your work. When you’re done, then you can merge all your work back into the main branch. A few important commands used for branching and merging are :
git branch
This lists all the local branches of your account. If you have not created a branch, then it’s by default the master branch.
git branch NewBranchName This creates a new branch starting at the some point in history as the current branch. Note that it doesn’t make it the current working branch so we need to change it manually with the command git checkout NewBranchName
Now if we execute the command git status then it would also show the current branch to be newmodule.
If on this branch we made some changes to the file aboutme.txt and then we want to merge the two files aboutme.txt (on branch: newmodule) and aboutme.txt (on branch: master). For merging, you must ensure that the current branch is your destination branch. Here, the destination branch would be the master branch. So, we would switch our current branch from newmodule to master by git checkout master and then merge them.
git merge SourceBranchName
This would Merge the specified branch ( SourceBranchName) into the current branch and auto-commit the results.
Here, we made some changes in the aboutme.txt file in the branch: newmodule
Now, after staging and committing the changes in the newmodule branch, we changed out current branch to master by git checkout master and open aboutme.txt.
Note that this aboutme.txt file is not updated with the second line as in branch: newmodule
Now , we would use the command git merge newmodule to merge both the branches. Now, opening aboutme.txt , we see that the file is updated with the second line as well.
This would run pretty smooth but mostly we’re going to run into Merge Conflicts even in the simplest cases. You can imagine how complex this can get while working in real-life projects. But whenever we run into a merge conflict, we can launch a mergetool which can help fixing a conflict in a far more easier way. Meld is a mergetool available on the Ubuntu software center. You can also install it using command line on Ubuntu, Windows and Mac.
Article By Harshit Gupta:
Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks. You can reach him at https://in.linkedin.com/pub/harshit-gupta/102/b71/605
If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.
surindertarika1234
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Git - Difference Between Git Fetch and Git Pull
How to Set Upstream Branch on Git?
How to Push Git Branch to Remote?
How to Export Eclipse projects to GitHub?
Merge Conflicts and How to handle them
How to Add Git Credentials in Eclipse?
What is README.md File?
How to Add Videos on README .md File in a GitHub Repository?
Git - Origin Master
How to Add GIFs on README .md File in a GitHub Repository? | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 203,
"s": 54,
"text": "In the previous article, we learnt how to use basic GIT. In this article we would try to learn some more basic concepts like branching and merging. "
},
{
"code": null,
"e": 231,
"s": 203,
"text": " SOME MORE BASIC COMMANDS: "
},
{
"code": null,
"e": 288,
"s": 231,
"text": "Some of the very helpful commands while using git are: "
},
{
"code": null,
"e": 292,
"s": 288,
"text": "git"
},
{
"code": null,
"e": 463,
"s": 292,
"text": "Type this in the terminal and you’ll see a bunch of commonly used GIT commands with their usage. To know about a command in detail, you can type in ‘git help <command>’ ."
},
{
"code": null,
"e": 477,
"s": 466,
"text": "git status"
},
{
"code": null,
"e": 686,
"s": 477,
"text": "This is one of the most useful commands of GIT. If, at any point of time, you wish to know your current branch or changes in the files which aren’t staged for commit or untracked files, type in this command. "
},
{
"code": null,
"e": 814,
"s": 688,
"text": "Here, the branch is master and everything is up-to-data. Let’s make some changes in the file and then use this command again."
},
{
"code": null,
"e": 1214,
"s": 816,
"text": "There are changes which are not staged for commit in the file helloworld.c and we have the option of adding these changes in the final commit or discarding the changes in the final commit. We can add them with the git add . command (as discussed previously) and discard the changes in the file by the command git checkout — helloworld.c (NOTE: There is a space in between ‘–‘ and ‘helloworld.c’) "
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "git log"
},
{
"code": null,
"e": 1408,
"s": 1222,
"text": "With this command one can see the commit logs with the Date, Time, Name of the Author and commit notes. This command is very useful in a group of developers working on the same project."
},
{
"code": null,
"e": 1419,
"s": 1411,
"text": "git add"
},
{
"code": null,
"e": 1808,
"s": 1419,
"text": "As discussed previously, we must add the file(s) to the list while we would commit later. We can add the files with the help of git add . or git add helloworld.c But, let’s say we want to add only a specific group of files with similar extensions. Let’s say all the files ending with .txt . Then we can do it by git add *.txt command. This would add only the files which ends with .txt . "
},
{
"code": null,
"e": 2167,
"s": 1808,
"text": "Now, if we want to ignore a specific group of files with similar extensions ( .txt, .cpp, etc) then we can also do it with git. For example, Let us consider we want to ignore the .c~ files that we can see (helloworld.c~). I have made another file named newfile.c so that there is another .c~ file which would be ignored. We need to follow two simple steps: "
},
{
"code": null,
"e": 2489,
"s": 2167,
"text": "We need to make a .gitignore file where we would store all the extensions to be ignored. We can make a such a file by typing touch .gitignore in the terminal and then open it with a text editor.Type in all the extensions of files which you want to ignore. Here, I want to ignore all the .c~ files and the.gitignore~ file."
},
{
"code": null,
"e": 2684,
"s": 2489,
"text": "We need to make a .gitignore file where we would store all the extensions to be ignored. We can make a such a file by typing touch .gitignore in the terminal and then open it with a text editor."
},
{
"code": null,
"e": 2812,
"s": 2684,
"text": "Type in all the extensions of files which you want to ignore. Here, I want to ignore all the .c~ files and the.gitignore~ file."
},
{
"code": null,
"e": 3151,
"s": 2814,
"text": "We can see the file newfile.c~ by typing the command ls but when we check the status ( git status), we can see just two untracked files (.gitignore and newfile.c) . Note that there is no newfile.c~ file which means that it has been ignored successfully. We can now add the untracked files and then commit as we have been doing earlier. "
},
{
"code": null,
"e": 3177,
"s": 3157,
"text": "BRANCHING & MERGING"
},
{
"code": null,
"e": 3673,
"s": 3177,
"text": "Branching allows you to work on a copy of code in the mainline without actually effecting the main line directory. For example, Let’s say if you want to work on a new module of the project, then you can choose a new branch on which you’ll work. Everyone else can work on the same project by working on their branches without being affected by your work. When you’re done, then you can merge all your work back into the main branch. A few important commands used for branching and merging are : "
},
{
"code": null,
"e": 3684,
"s": 3673,
"text": "git branch"
},
{
"code": null,
"e": 3810,
"s": 3684,
"text": "This lists all the local branches of your account. If you have not created a branch, then it’s by default the master branch. "
},
{
"code": null,
"e": 4059,
"s": 3814,
"text": "git branch NewBranchName This creates a new branch starting at the some point in history as the current branch. Note that it doesn’t make it the current working branch so we need to change it manually with the command git checkout NewBranchName"
},
{
"code": null,
"e": 4167,
"s": 4064,
"text": "Now if we execute the command git status then it would also show the current branch to be newmodule. "
},
{
"code": null,
"e": 4590,
"s": 4167,
"text": "If on this branch we made some changes to the file aboutme.txt and then we want to merge the two files aboutme.txt (on branch: newmodule) and aboutme.txt (on branch: master). For merging, you must ensure that the current branch is your destination branch. Here, the destination branch would be the master branch. So, we would switch our current branch from newmodule to master by git checkout master and then merge them. "
},
{
"code": null,
"e": 4618,
"s": 4590,
"text": " git merge SourceBranchName"
},
{
"code": null,
"e": 4730,
"s": 4618,
"text": "This would Merge the specified branch ( SourceBranchName) into the current branch and auto-commit the results. "
},
{
"code": null,
"e": 4807,
"s": 4730,
"text": "Here, we made some changes in the aboutme.txt file in the branch: newmodule "
},
{
"code": null,
"e": 4972,
"s": 4815,
"text": "Now, after staging and committing the changes in the newmodule branch, we changed out current branch to master by git checkout master and open aboutme.txt. "
},
{
"code": null,
"e": 5067,
"s": 4974,
"text": "Note that this aboutme.txt file is not updated with the second line as in branch: newmodule "
},
{
"code": null,
"e": 5236,
"s": 5067,
"text": "Now , we would use the command git merge newmodule to merge both the branches. Now, opening aboutme.txt , we see that the file is updated with the second line as well. "
},
{
"code": null,
"e": 5685,
"s": 5238,
"text": "This would run pretty smooth but mostly we’re going to run into Merge Conflicts even in the simplest cases. You can imagine how complex this can get while working in real-life projects. But whenever we run into a merge conflict, we can launch a mergetool which can help fixing a conflict in a far more easier way. Meld is a mergetool available on the Ubuntu software center. You can also install it using command line on Ubuntu, Windows and Mac. "
},
{
"code": null,
"e": 5712,
"s": 5685,
"text": "Article By Harshit Gupta: "
},
{
"code": null,
"e": 6097,
"s": 5712,
"text": "Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks. You can reach him at https://in.linkedin.com/pub/harshit-gupta/102/b71/605 "
},
{
"code": null,
"e": 6200,
"s": 6097,
"text": "If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks. "
},
{
"code": null,
"e": 6222,
"s": 6203,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6226,
"s": 6222,
"text": "Git"
},
{
"code": null,
"e": 6324,
"s": 6226,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6372,
"s": 6324,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 6407,
"s": 6372,
"text": "How to Set Upstream Branch on Git?"
},
{
"code": null,
"e": 6441,
"s": 6407,
"text": "How to Push Git Branch to Remote?"
},
{
"code": null,
"e": 6483,
"s": 6441,
"text": "How to Export Eclipse projects to GitHub?"
},
{
"code": null,
"e": 6522,
"s": 6483,
"text": "Merge Conflicts and How to handle them"
},
{
"code": null,
"e": 6561,
"s": 6522,
"text": "How to Add Git Credentials in Eclipse?"
},
{
"code": null,
"e": 6585,
"s": 6561,
"text": "What is README.md File?"
},
{
"code": null,
"e": 6646,
"s": 6585,
"text": "How to Add Videos on README .md File in a GitHub Repository?"
},
{
"code": null,
"e": 6666,
"s": 6646,
"text": "Git - Origin Master"
}
] |
Copy the entire contents of a directory to another directory in PHP | 09 May, 2019
Given a directory and the task is to copy the content of the directory to another directory using PHP functions. There are many functions used to copy the content of one directory to another.
Used Functions:
copy() Function: The copy() function is used to make a copy of a specified file. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure.Syntax:bool copy($source, $dest)
Syntax:
bool copy($source, $dest)
opendir() Function: The opendir() function is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.Syntax:opendir($path, $context)
Syntax:
opendir($path, $context)
is_dir() Function: The is_dir() function is used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else returns False.Syntax:is_dir($file)
Syntax:
is_dir($file)
scandir( ) Function: The scandir() function is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path. The directory, stream behavior and sorting_order of the files and directories are passed as a parameter to the scandir() function and it returns an array of filenames on success, or False on failure.Syntax:scandir(directory, sorting_order, context)
Syntax:
scandir(directory, sorting_order, context)
readdir() Function: The readdir() function is used to return the name of the next entry in a directory. This method returns the filenames in the order as they are stored in the filenamesystem. The directory handle is sent as a parameter to the readdir() function and it returns the entry name/filename on success or False on failure.Syntax:readdir(dir_handle)
Syntax:
readdir(dir_handle)
Example 1: This example uses readdir() function to read files from the source directory.
<?php function custom_copy($src, $dst) { // open the source directory $dir = opendir($src); // Make the destination directory if not exist @mkdir($dst); // Loop through the files in source directory while( $file = readdir($dir) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { // Recursively calling custom copy function // for sub directory custom_copy($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir);} $src = "C:/xampp/htdocs/geeks"; $dst = "C:/xampp/htdocs/gfg"; custom_copy($src, $dst); ?>
Output:
Before Run the program on localhost:
After Run the program on localhost:
Example 2: This example uses scandir() function to read files from the source directory.
<?php function custom_copy($src, $dst) { // open the source directory $dir = opendir($src); // Make the destination directory if not exist @mkdir($dst); // Loop through the files in source directory foreach (scandir($src) as $file) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { // Recursively calling custom copy function // for sub directory custom_copy($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir);} $src = "C:/xampp/htdocs/geeks"; $dst = "C:/xampp/htdocs/gfg"; custom_copy($src, $dst); ?>
Output:
Before Run the program on localhost:
After Run the program on localhost:
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": "\n09 May, 2019"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "Given a directory and the task is to copy the content of the directory to another directory using PHP functions. There are many functions used to copy the content of one directory to another."
},
{
"code": null,
"e": 236,
"s": 220,
"text": "Used Functions:"
},
{
"code": null,
"e": 539,
"s": 236,
"text": "copy() Function: The copy() function is used to make a copy of a specified file. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure.Syntax:bool copy($source, $dest)"
},
{
"code": null,
"e": 547,
"s": 539,
"text": "Syntax:"
},
{
"code": null,
"e": 573,
"s": 547,
"text": "bool copy($source, $dest)"
},
{
"code": null,
"e": 847,
"s": 573,
"text": "opendir() Function: The opendir() function is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.Syntax:opendir($path, $context)"
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Syntax:"
},
{
"code": null,
"e": 880,
"s": 855,
"text": "opendir($path, $context)"
},
{
"code": null,
"e": 1144,
"s": 880,
"text": "is_dir() Function: The is_dir() function is used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else returns False.Syntax:is_dir($file)"
},
{
"code": null,
"e": 1152,
"s": 1144,
"text": "Syntax:"
},
{
"code": null,
"e": 1166,
"s": 1152,
"text": "is_dir($file)"
},
{
"code": null,
"e": 1637,
"s": 1166,
"text": "scandir( ) Function: The scandir() function is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path. The directory, stream behavior and sorting_order of the files and directories are passed as a parameter to the scandir() function and it returns an array of filenames on success, or False on failure.Syntax:scandir(directory, sorting_order, context)"
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Syntax:"
},
{
"code": null,
"e": 1688,
"s": 1645,
"text": "scandir(directory, sorting_order, context)"
},
{
"code": null,
"e": 2048,
"s": 1688,
"text": "readdir() Function: The readdir() function is used to return the name of the next entry in a directory. This method returns the filenames in the order as they are stored in the filenamesystem. The directory handle is sent as a parameter to the readdir() function and it returns the entry name/filename on success or False on failure.Syntax:readdir(dir_handle)"
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Syntax:"
},
{
"code": null,
"e": 2076,
"s": 2056,
"text": "readdir(dir_handle)"
},
{
"code": null,
"e": 2165,
"s": 2076,
"text": "Example 1: This example uses readdir() function to read files from the source directory."
},
{
"code": "<?php function custom_copy($src, $dst) { // open the source directory $dir = opendir($src); // Make the destination directory if not exist @mkdir($dst); // Loop through the files in source directory while( $file = readdir($dir) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { // Recursively calling custom copy function // for sub directory custom_copy($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir);} $src = \"C:/xampp/htdocs/geeks\"; $dst = \"C:/xampp/htdocs/gfg\"; custom_copy($src, $dst); ?>",
"e": 2952,
"s": 2165,
"text": null
},
{
"code": null,
"e": 2960,
"s": 2952,
"text": "Output:"
},
{
"code": null,
"e": 2997,
"s": 2960,
"text": "Before Run the program on localhost:"
},
{
"code": null,
"e": 3033,
"s": 2997,
"text": "After Run the program on localhost:"
},
{
"code": null,
"e": 3122,
"s": 3033,
"text": "Example 2: This example uses scandir() function to read files from the source directory."
},
{
"code": "<?php function custom_copy($src, $dst) { // open the source directory $dir = opendir($src); // Make the destination directory if not exist @mkdir($dst); // Loop through the files in source directory foreach (scandir($src) as $file) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { // Recursively calling custom copy function // for sub directory custom_copy($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir);} $src = \"C:/xampp/htdocs/geeks\"; $dst = \"C:/xampp/htdocs/gfg\"; custom_copy($src, $dst); ?>",
"e": 3921,
"s": 3122,
"text": null
},
{
"code": null,
"e": 3929,
"s": 3921,
"text": "Output:"
},
{
"code": null,
"e": 3966,
"s": 3929,
"text": "Before Run the program on localhost:"
},
{
"code": null,
"e": 4002,
"s": 3966,
"text": "After Run the program on localhost:"
},
{
"code": null,
"e": 4009,
"s": 4002,
"text": "Picked"
},
{
"code": null,
"e": 4013,
"s": 4009,
"text": "PHP"
},
{
"code": null,
"e": 4026,
"s": 4013,
"text": "PHP Programs"
},
{
"code": null,
"e": 4043,
"s": 4026,
"text": "Web Technologies"
},
{
"code": null,
"e": 4070,
"s": 4043,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4074,
"s": 4070,
"text": "PHP"
}
] |
HTML | DOM Input Checkbox defaultChecked Property | 30 May, 2022
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
Syntax:
checkboxObject.defaultChecked
Return Values: It returns a Boolean value that returns true if the checkbox is checked by default otherwise returns false.
Example: This example illustrates the Input Checkbox defaultChecked property.
HTML
<!DOCTYPE html><html> <head> <title> DOM Input Checkbox defaultChecked Property </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>DOM Input Checkbox defaultChecked Property</h2> <form id="myGeeks"> <!-- Below input elements have attribute checked --> <input type="checkbox" name="check" id="GFG" value="1" Checked>Checked by default<br> <input type="checkbox" name="check" value="2"> Not checked by default<br> </form><br> <button onclick="myGeeks()"> Submit </button> <p id="sudo" style="color:green;font-size:25px;"></p> <!-- Script to return the Input Checkbox defaultChecked Property --> <script> function myGeeks() { var g = document.getElementById("GFG").defaultChecked; document.getElementById("sudo").innerHTML = g; } </script> </body></html>
Output: Before clicking on the Button:
After clicking on the Button:
Supported Browsers: The browser supported by DOM input Checkbox defaultchecked property are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
arorakashish0911
hritikbhatnagar2182
vinayedula
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 268,
"s": 53,
"text": "The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false."
},
{
"code": null,
"e": 277,
"s": 268,
"text": "Syntax: "
},
{
"code": null,
"e": 307,
"s": 277,
"text": "checkboxObject.defaultChecked"
},
{
"code": null,
"e": 430,
"s": 307,
"text": "Return Values: It returns a Boolean value that returns true if the checkbox is checked by default otherwise returns false."
},
{
"code": null,
"e": 509,
"s": 430,
"text": "Example: This example illustrates the Input Checkbox defaultChecked property. "
},
{
"code": null,
"e": 514,
"s": 509,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM Input Checkbox defaultChecked Property </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>DOM Input Checkbox defaultChecked Property</h2> <form id=\"myGeeks\"> <!-- Below input elements have attribute checked --> <input type=\"checkbox\" name=\"check\" id=\"GFG\" value=\"1\" Checked>Checked by default<br> <input type=\"checkbox\" name=\"check\" value=\"2\"> Not checked by default<br> </form><br> <button onclick=\"myGeeks()\"> Submit </button> <p id=\"sudo\" style=\"color:green;font-size:25px;\"></p> <!-- Script to return the Input Checkbox defaultChecked Property --> <script> function myGeeks() { var g = document.getElementById(\"GFG\").defaultChecked; document.getElementById(\"sudo\").innerHTML = g; } </script> </body></html> ",
"e": 1717,
"s": 514,
"text": null
},
{
"code": null,
"e": 1758,
"s": 1717,
"text": "Output: Before clicking on the Button: "
},
{
"code": null,
"e": 1790,
"s": 1758,
"text": "After clicking on the Button: "
},
{
"code": null,
"e": 1897,
"s": 1790,
"text": "Supported Browsers: The browser supported by DOM input Checkbox defaultchecked property are listed below: "
},
{
"code": null,
"e": 1911,
"s": 1897,
"text": "Google Chrome"
},
{
"code": null,
"e": 1929,
"s": 1911,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1937,
"s": 1929,
"text": "Firefox"
},
{
"code": null,
"e": 1943,
"s": 1937,
"text": "Opera"
},
{
"code": null,
"e": 1950,
"s": 1943,
"text": "Safari"
},
{
"code": null,
"e": 1969,
"s": 1952,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1989,
"s": 1969,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 2000,
"s": 1989,
"text": "vinayedula"
},
{
"code": null,
"e": 2009,
"s": 2000,
"text": "HTML-DOM"
},
{
"code": null,
"e": 2014,
"s": 2009,
"text": "HTML"
},
{
"code": null,
"e": 2031,
"s": 2014,
"text": "Web Technologies"
},
{
"code": null,
"e": 2036,
"s": 2031,
"text": "HTML"
},
{
"code": null,
"e": 2134,
"s": 2036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2182,
"s": 2134,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2206,
"s": 2182,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2256,
"s": 2206,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2295,
"s": 2256,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2332,
"s": 2295,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2365,
"s": 2332,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2426,
"s": 2365,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2469,
"s": 2426,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2541,
"s": 2469,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Draw a moving cycle using computer graphics programming in C/C++ | 04 Aug, 2021
In C graphics, the graphics.h functions are used to draw different shapes like circles, rectangles, etc, display text(any message) in a different format (different fonts and colors). By using the functions in the header graphics.h, programs, animations, and different games can also be made. In this article, let’s discuss how to draw a moving cycle in C using graphics.
Functions used:
line(x1, y1, x2, y2): It is a function provided by graphics.h header file to draw a line. Here x1, y1 is the first coordinates of the line, and x2, y2 are the second coordinates of the line respectively.
circle(x, y, r): It is a function provided by graphics.h header file to draw a circle. The x, y are the center points of the circle and r is the radius of the circle.
rectangle(X1, Y1, X2, Y2): It is employed in the creation of a rectangle. The rectangle must be drawn using the coordinates of the left top and right bottom corners. The X-coordinate and Y-coordinate of the top left corner are X1 and Y1 and the X-coordinate and Y-coordinate of the bottom right corner are X2 and Y2 respectively.
delay(n): It is used to hold the program for a specific time period. Here n is the number of seconds you want to hold the program.
cleardevice(): It is used to clear the screen in graphic mode. It sets the position of the cursor to its initial position, that is, (0, 0) coordinates.
closegraph(): It is used to close the graph.
Approach: Following are the steps below to generate a moving cycle:
Pass the three arguments to the initgraph() function to initialize the graphics driver and graphics mode.
Create the upper body of the cycle by drawing lines.
Create the wheels of the cycle by drawing circles and choose the coordinates so that the wheels aligned just below the upper body of the cycle.
The next step is to create the road by drawing lines and stone by drawing rectangles.
Choose the coordinates so that the cycle is just above the road.
Change the cycle’s position using a loop continuously so that it appears to be moving on the road.
Below is the implementation of the above approach:
C++
// C++ program to draw the moving// cycle using computer graphics #include <conio.h>#include <dos.h>#include <graphics.h>#include <iostream.h> // Driver codeint main(){ int gd = DETECT, gm, i, a; // Path of the program initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Move the cycle for (i = 0; i < 600; i++) { // Upper body of cycle line(50 + i, 405, 100 + i, 405); line(75 + i, 375, 125 + i, 375); line(50 + i, 405, 75 + i, 375); line(100 + i, 405, 100 + i, 345); line(150 + i, 405, 100 + i, 345); line(75 + i, 345, 75 + i, 370); line(70 + i, 370, 80 + i, 370); line(80 + i, 345, 100 + i, 345); // Wheel circle(150 + i, 405, 30); circle(50 + i, 405, 30); // Road line(0, 436, getmaxx(), 436); // Stone rectangle(getmaxx() - i, 436, 650 - i, 431); // Stop the screen for 10 secs delay(10); // Clear the screen cleardevice(); } getch(); // Close the graph closegraph();}
Output:
c-graphics
computer-graphics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 399,
"s": 28,
"text": "In C graphics, the graphics.h functions are used to draw different shapes like circles, rectangles, etc, display text(any message) in a different format (different fonts and colors). By using the functions in the header graphics.h, programs, animations, and different games can also be made. In this article, let’s discuss how to draw a moving cycle in C using graphics."
},
{
"code": null,
"e": 415,
"s": 399,
"text": "Functions used:"
},
{
"code": null,
"e": 619,
"s": 415,
"text": "line(x1, y1, x2, y2): It is a function provided by graphics.h header file to draw a line. Here x1, y1 is the first coordinates of the line, and x2, y2 are the second coordinates of the line respectively."
},
{
"code": null,
"e": 786,
"s": 619,
"text": "circle(x, y, r): It is a function provided by graphics.h header file to draw a circle. The x, y are the center points of the circle and r is the radius of the circle."
},
{
"code": null,
"e": 1116,
"s": 786,
"text": "rectangle(X1, Y1, X2, Y2): It is employed in the creation of a rectangle. The rectangle must be drawn using the coordinates of the left top and right bottom corners. The X-coordinate and Y-coordinate of the top left corner are X1 and Y1 and the X-coordinate and Y-coordinate of the bottom right corner are X2 and Y2 respectively."
},
{
"code": null,
"e": 1247,
"s": 1116,
"text": "delay(n): It is used to hold the program for a specific time period. Here n is the number of seconds you want to hold the program."
},
{
"code": null,
"e": 1399,
"s": 1247,
"text": "cleardevice(): It is used to clear the screen in graphic mode. It sets the position of the cursor to its initial position, that is, (0, 0) coordinates."
},
{
"code": null,
"e": 1444,
"s": 1399,
"text": "closegraph(): It is used to close the graph."
},
{
"code": null,
"e": 1512,
"s": 1444,
"text": "Approach: Following are the steps below to generate a moving cycle:"
},
{
"code": null,
"e": 1618,
"s": 1512,
"text": "Pass the three arguments to the initgraph() function to initialize the graphics driver and graphics mode."
},
{
"code": null,
"e": 1671,
"s": 1618,
"text": "Create the upper body of the cycle by drawing lines."
},
{
"code": null,
"e": 1815,
"s": 1671,
"text": "Create the wheels of the cycle by drawing circles and choose the coordinates so that the wheels aligned just below the upper body of the cycle."
},
{
"code": null,
"e": 1901,
"s": 1815,
"text": "The next step is to create the road by drawing lines and stone by drawing rectangles."
},
{
"code": null,
"e": 1966,
"s": 1901,
"text": "Choose the coordinates so that the cycle is just above the road."
},
{
"code": null,
"e": 2065,
"s": 1966,
"text": "Change the cycle’s position using a loop continuously so that it appears to be moving on the road."
},
{
"code": null,
"e": 2116,
"s": 2065,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2120,
"s": 2116,
"text": "C++"
},
{
"code": "// C++ program to draw the moving// cycle using computer graphics #include <conio.h>#include <dos.h>#include <graphics.h>#include <iostream.h> // Driver codeint main(){ int gd = DETECT, gm, i, a; // Path of the program initgraph(&gd, &gm, \"C:\\\\TURBOC3\\\\BGI\"); // Move the cycle for (i = 0; i < 600; i++) { // Upper body of cycle line(50 + i, 405, 100 + i, 405); line(75 + i, 375, 125 + i, 375); line(50 + i, 405, 75 + i, 375); line(100 + i, 405, 100 + i, 345); line(150 + i, 405, 100 + i, 345); line(75 + i, 345, 75 + i, 370); line(70 + i, 370, 80 + i, 370); line(80 + i, 345, 100 + i, 345); // Wheel circle(150 + i, 405, 30); circle(50 + i, 405, 30); // Road line(0, 436, getmaxx(), 436); // Stone rectangle(getmaxx() - i, 436, 650 - i, 431); // Stop the screen for 10 secs delay(10); // Clear the screen cleardevice(); } getch(); // Close the graph closegraph();}",
"e": 3190,
"s": 2120,
"text": null
},
{
"code": null,
"e": 3198,
"s": 3190,
"text": "Output:"
},
{
"code": null,
"e": 3209,
"s": 3198,
"text": "c-graphics"
},
{
"code": null,
"e": 3227,
"s": 3209,
"text": "computer-graphics"
},
{
"code": null,
"e": 3231,
"s": 3227,
"text": "C++"
},
{
"code": null,
"e": 3244,
"s": 3231,
"text": "C++ Programs"
},
{
"code": null,
"e": 3248,
"s": 3244,
"text": "CPP"
},
{
"code": null,
"e": 3346,
"s": 3248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3373,
"s": 3346,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 3416,
"s": 3373,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3470,
"s": 3416,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3504,
"s": 3470,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3521,
"s": 3504,
"text": "Substring in C++"
},
{
"code": null,
"e": 3556,
"s": 3521,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 3590,
"s": 3556,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 3634,
"s": 3590,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 3693,
"s": 3634,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Creating a simple machine learning model | 13 Jun, 2018
Create a Linear Regression Model in Python using a randomly created data set.
Linear Regression ModelLinear regression geeks for geeks
Generating the Training Set
# python library to generate random numbersfrom random import randint # the limit within which random numbers are generatedTRAIN_SET_LIMIT = 1000 # to create exactly 100 data itemsTRAIN_SET_COUNT = 100 # list that contains input and corresponding outputTRAIN_INPUT = list()TRAIN_OUTPUT = list() # loop to create 100 data items with three columns eachfor i in range(TRAIN_SET_COUNT): a = randint(0, TRAIN_SET_LIMIT) b = randint(0, TRAIN_SET_LIMIT) c = randint(0, TRAIN_SET_LIMIT) # creating the output for each data item op = a + (2 * b) + (3 * c) TRAIN_INPUT.append([a, b, c]) # adding each output to output list TRAIN_OUTPUT.append(op)
Machine Learning Model – Linear Regression
The Model can be created in two steps:-1. Training the model with Training Data2. Testing the model with Test Data
Training the ModelThe data that was created using the above code is used to train the model
# Sk-Learn contains the linear regression modelfrom sklearn.linear_model import LinearRegression # Initialize the linear regression modelpredictor = LinearRegression(n_jobs =-1) # Fill the Model with the Datapredictor.fit(X = TRAIN_INPUT, y = TRAIN_OUTPUT)
Testing the DataThe testing is done Manually. Testing can be done using some random data and testing if the model gives the correct result for the input data.
# Random Test dataX_TEST = [[ 10, 20, 30 ]] # Predict the result of X_TEST which holds testing dataoutcome = predictor.predict(X = X_TEST) # Predict the coefficientscoefficients = predictor.coef_ # Print the result obtained for the test dataprint('Outcome : {}\nCoefficients : {}'.format(outcome, coefficients))
The Outcome of the above provided test-data should be, 10 + 20*2 + 30*3 = 140.Output
Outcome : [ 140.]
Coefficients : [ 1. 2. 3.]
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
How to Run a Python Script using Docker?
ML | Underfitting and Overfitting
Clustering in Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Underfitting and Overfitting | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2018"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "Create a Linear Regression Model in Python using a randomly created data set."
},
{
"code": null,
"e": 189,
"s": 132,
"text": "Linear Regression ModelLinear regression geeks for geeks"
},
{
"code": null,
"e": 217,
"s": 189,
"text": "Generating the Training Set"
},
{
"code": "# python library to generate random numbersfrom random import randint # the limit within which random numbers are generatedTRAIN_SET_LIMIT = 1000 # to create exactly 100 data itemsTRAIN_SET_COUNT = 100 # list that contains input and corresponding outputTRAIN_INPUT = list()TRAIN_OUTPUT = list() # loop to create 100 data items with three columns eachfor i in range(TRAIN_SET_COUNT): a = randint(0, TRAIN_SET_LIMIT) b = randint(0, TRAIN_SET_LIMIT) c = randint(0, TRAIN_SET_LIMIT) # creating the output for each data item op = a + (2 * b) + (3 * c) TRAIN_INPUT.append([a, b, c]) # adding each output to output list TRAIN_OUTPUT.append(op)",
"e": 879,
"s": 217,
"text": null
},
{
"code": null,
"e": 922,
"s": 879,
"text": "Machine Learning Model – Linear Regression"
},
{
"code": null,
"e": 1037,
"s": 922,
"text": "The Model can be created in two steps:-1. Training the model with Training Data2. Testing the model with Test Data"
},
{
"code": null,
"e": 1129,
"s": 1037,
"text": "Training the ModelThe data that was created using the above code is used to train the model"
},
{
"code": "# Sk-Learn contains the linear regression modelfrom sklearn.linear_model import LinearRegression # Initialize the linear regression modelpredictor = LinearRegression(n_jobs =-1) # Fill the Model with the Datapredictor.fit(X = TRAIN_INPUT, y = TRAIN_OUTPUT)",
"e": 1388,
"s": 1129,
"text": null
},
{
"code": null,
"e": 1547,
"s": 1388,
"text": "Testing the DataThe testing is done Manually. Testing can be done using some random data and testing if the model gives the correct result for the input data."
},
{
"code": "# Random Test dataX_TEST = [[ 10, 20, 30 ]] # Predict the result of X_TEST which holds testing dataoutcome = predictor.predict(X = X_TEST) # Predict the coefficientscoefficients = predictor.coef_ # Print the result obtained for the test dataprint('Outcome : {}\\nCoefficients : {}'.format(outcome, coefficients))",
"e": 1862,
"s": 1547,
"text": null
},
{
"code": null,
"e": 1947,
"s": 1862,
"text": "The Outcome of the above provided test-data should be, 10 + 20*2 + 30*3 = 140.Output"
},
{
"code": null,
"e": 1993,
"s": 1947,
"text": "Outcome : [ 140.]\nCoefficients : [ 1. 2. 3.]\n"
},
{
"code": null,
"e": 2019,
"s": 1993,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2036,
"s": 2019,
"text": "Machine Learning"
},
{
"code": null,
"e": 2043,
"s": 2036,
"text": "Python"
},
{
"code": null,
"e": 2060,
"s": 2043,
"text": "Machine Learning"
},
{
"code": null,
"e": 2158,
"s": 2060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2181,
"s": 2158,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 2207,
"s": 2181,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2248,
"s": 2207,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 2282,
"s": 2248,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 2313,
"s": 2282,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 2347,
"s": 2313,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 2371,
"s": 2347,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 2404,
"s": 2371,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 2445,
"s": 2404,
"text": "Introduction to Recurrent Neural Network"
}
] |
Warnings in Python | 23 Jan, 2020
Warnings are provided to warn the developer of situations that aren’t necessarily exceptions. Usually, a warning occurs when there is some obsolete of certain programming elements, such as keyword, function or class, etc. A warning in a program is distinct from an error. Python program terminates immediately if an error occurs. Conversely, a warning is not critical. It shows some message, but the program runs. The warn() function defined in the ‘warning‘ module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python.
# program to display warning a message import warnings print('Geeks') # displaying the warning message warnings.warn('Warning Message: 4') print('Geeks !')
Output:
Geeks
main.py:8: UserWarning: Warning Message: 4
warnings.warn('Warning Message: 4')
Geeks!
In the above program, the warn() function of the warning module is used to display the message Warning: Message: 4, the UserWarning is the default category of warn() function.
In Python there are a variety of built-in exceptions which reflect categories of warning, some of them are:
Warning Class: It is the super class of all warning category classes and a subclass of the Exception class.
UserWarning Class: warn() function default category.
DeprecationWarning Class: Base category for alerts regarding obsolete features when those warnings are for other developers (triggered by code in __main__ unless ignored).
SyntaxWarning Class: Base class for warnings of suspicious syntactic attributes.
RuntimeWarning Class: Base class for warnings of suspicious run time attributes.
FutureWarning Class: Base class for warnings on obsolete features when certain warnings are meant for end-users of Python-written programs.
PendingDeprecationWarning Class: Base class for warnings of an outdated attribute.
ImportWarning Class: Base class for warnings caused during a module importation process.
UnicodeWarning Class: Base class for Unicode based warnings.
BytesWarning Class: Base class for bytes and bytearray based warnings.
ResourceWarning Class: Base class for resource-related warnings.
The warning filter in Python handles warnings (presented, disregarded or raised to exceptions). The warnings filter establishes an organized list of filter parameters, any particular warnings are matched on each filter requirement throughout the list till the match is made, the filter determines the match arrangement. Every entry is indeed a tuple (action, message, category, module, lineno) of the form in which:
The action can be any of the following strings:StringExplanation“default”Displays the first matching warnings for each position“error”Converts warnings to raise exceptions“ignore”Never display warnings which match“always”Always display the warnings which match“module”Displays the first matching warnings per module“once”Display just the first matching warnings, regardless of where they are located
The message is a string that has a regular expression that must match the beginning of the warning. (The expression compiled is always case-insensitive)
The category is a class (warning subclass) of which the warning class must be a subclass for matching.
The module is a string with a regular expression which must match the module name (The expression compiled is always case-insensitive).
The lineno is an integer to match the number of the line in which the warning appeared, or 0 to match any number of the line.
Some of the commonly used functions of the warning module are:
warn(message, category=None, stacklevel=1, source=None): This function displays a warning, or disregard it or converts is to an exception.# program to illustrate warn() # function in warning module # importing modulesimport warnings # displaying warningwarnings.warn('Geeks 4 Geeks')Output:main.py:2: UserWarning: Geeks 4 Geeks
warnings.warn('Geeks 4 Geeks')
In the above program warnings are displayed using the warn() function of warning module.
# program to illustrate warn() # function in warning module # importing modulesimport warnings # displaying warningwarnings.warn('Geeks 4 Geeks')
Output:
main.py:2: UserWarning: Geeks 4 Geeks
warnings.warn('Geeks 4 Geeks')
In the above program warnings are displayed using the warn() function of warning module.
warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None): This function is a low-level method with warn() features
filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False): This function adds an entry into the specifications of the warnings filter.# program to illustrate filterwarnings()# function in warning module # importing moduleimport warnings # adding entry into the specifications# of the warnings filter.warnings.filterwarnings('ignore', '.*do not.*', ) # displaying wariningswarnings.warn('Geeks 4 Geeks !') # this warning will not be displayedwarnings.warn('Do not show this message')Output:main.py:8: UserWarning: Geeks 4 Geeks!
warnings.warn('Geeks 4 Geeks!')
Here the second warning message is not displayed due to warnings.filterwarnings('ignore', '.*do not.*', ) in which action is "ignore" .
# program to illustrate filterwarnings()# function in warning module # importing moduleimport warnings # adding entry into the specifications# of the warnings filter.warnings.filterwarnings('ignore', '.*do not.*', ) # displaying wariningswarnings.warn('Geeks 4 Geeks !') # this warning will not be displayedwarnings.warn('Do not show this message')
Output:
main.py:8: UserWarning: Geeks 4 Geeks!
warnings.warn('Geeks 4 Geeks!')
Here the second warning message is not displayed due to warnings.filterwarnings('ignore', '.*do not.*', ) in which action is "ignore" .
showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file.
simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.# program to illustrate simplefilter() # function in warning module # importing moduleimport warnings # adding a single entry into warnings filterwarnings.simplefilter('error', UserWarning) # displaying the warningwarnings.warn('This is a warning message')Output:Traceback (most recent call last):
File "main.py", line 8, in
warnings.warn('This is a warning message')
UserWarning: This is a warning message
In the above program, a single entry is added to the warnings filter using warnings.simplefilter('error', UserWarning) in which the action is "error" and category is UserWrning and then the warning is displayed using the warn() method.
# program to illustrate simplefilter() # function in warning module # importing moduleimport warnings # adding a single entry into warnings filterwarnings.simplefilter('error', UserWarning) # displaying the warningwarnings.warn('This is a warning message')
Output:
Traceback (most recent call last):
File "main.py", line 8, in
warnings.warn('This is a warning message')
UserWarning: This is a warning message
In the above program, a single entry is added to the warnings filter using warnings.simplefilter('error', UserWarning) in which the action is "error" and category is UserWrning and then the warning is displayed using the warn() method.
Python-Miscellaneous
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": "\n23 Jan, 2020"
},
{
"code": null,
"e": 620,
"s": 28,
"text": "Warnings are provided to warn the developer of situations that aren’t necessarily exceptions. Usually, a warning occurs when there is some obsolete of certain programming elements, such as keyword, function or class, etc. A warning in a program is distinct from an error. Python program terminates immediately if an error occurs. Conversely, a warning is not critical. It shows some message, but the program runs. The warn() function defined in the ‘warning‘ module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python."
},
{
"code": "# program to display warning a message import warnings print('Geeks') # displaying the warning message warnings.warn('Warning Message: 4') print('Geeks !')",
"e": 783,
"s": 620,
"text": null
},
{
"code": null,
"e": 791,
"s": 783,
"text": "Output:"
},
{
"code": null,
"e": 888,
"s": 791,
"text": "Geeks\nmain.py:8: UserWarning: Warning Message: 4 \n warnings.warn('Warning Message: 4')\nGeeks!\n"
},
{
"code": null,
"e": 1064,
"s": 888,
"text": "In the above program, the warn() function of the warning module is used to display the message Warning: Message: 4, the UserWarning is the default category of warn() function."
},
{
"code": null,
"e": 1172,
"s": 1064,
"text": "In Python there are a variety of built-in exceptions which reflect categories of warning, some of them are:"
},
{
"code": null,
"e": 1280,
"s": 1172,
"text": "Warning Class: It is the super class of all warning category classes and a subclass of the Exception class."
},
{
"code": null,
"e": 1333,
"s": 1280,
"text": "UserWarning Class: warn() function default category."
},
{
"code": null,
"e": 1505,
"s": 1333,
"text": "DeprecationWarning Class: Base category for alerts regarding obsolete features when those warnings are for other developers (triggered by code in __main__ unless ignored)."
},
{
"code": null,
"e": 1586,
"s": 1505,
"text": "SyntaxWarning Class: Base class for warnings of suspicious syntactic attributes."
},
{
"code": null,
"e": 1667,
"s": 1586,
"text": "RuntimeWarning Class: Base class for warnings of suspicious run time attributes."
},
{
"code": null,
"e": 1807,
"s": 1667,
"text": "FutureWarning Class: Base class for warnings on obsolete features when certain warnings are meant for end-users of Python-written programs."
},
{
"code": null,
"e": 1890,
"s": 1807,
"text": "PendingDeprecationWarning Class: Base class for warnings of an outdated attribute."
},
{
"code": null,
"e": 1979,
"s": 1890,
"text": "ImportWarning Class: Base class for warnings caused during a module importation process."
},
{
"code": null,
"e": 2040,
"s": 1979,
"text": "UnicodeWarning Class: Base class for Unicode based warnings."
},
{
"code": null,
"e": 2111,
"s": 2040,
"text": "BytesWarning Class: Base class for bytes and bytearray based warnings."
},
{
"code": null,
"e": 2176,
"s": 2111,
"text": "ResourceWarning Class: Base class for resource-related warnings."
},
{
"code": null,
"e": 2592,
"s": 2176,
"text": "The warning filter in Python handles warnings (presented, disregarded or raised to exceptions). The warnings filter establishes an organized list of filter parameters, any particular warnings are matched on each filter requirement throughout the list till the match is made, the filter determines the match arrangement. Every entry is indeed a tuple (action, message, category, module, lineno) of the form in which:"
},
{
"code": null,
"e": 2992,
"s": 2592,
"text": "The action can be any of the following strings:StringExplanation“default”Displays the first matching warnings for each position“error”Converts warnings to raise exceptions“ignore”Never display warnings which match“always”Always display the warnings which match“module”Displays the first matching warnings per module“once”Display just the first matching warnings, regardless of where they are located"
},
{
"code": null,
"e": 3145,
"s": 2992,
"text": "The message is a string that has a regular expression that must match the beginning of the warning. (The expression compiled is always case-insensitive)"
},
{
"code": null,
"e": 3248,
"s": 3145,
"text": "The category is a class (warning subclass) of which the warning class must be a subclass for matching."
},
{
"code": null,
"e": 3384,
"s": 3248,
"text": "The module is a string with a regular expression which must match the module name (The expression compiled is always case-insensitive)."
},
{
"code": null,
"e": 3510,
"s": 3384,
"text": "The lineno is an integer to match the number of the line in which the warning appeared, or 0 to match any number of the line."
},
{
"code": null,
"e": 3573,
"s": 3510,
"text": "Some of the commonly used functions of the warning module are:"
},
{
"code": null,
"e": 4025,
"s": 3573,
"text": "warn(message, category=None, stacklevel=1, source=None): This function displays a warning, or disregard it or converts is to an exception.# program to illustrate warn() # function in warning module # importing modulesimport warnings # displaying warningwarnings.warn('Geeks 4 Geeks')Output:main.py:2: UserWarning: Geeks 4 Geeks\n warnings.warn('Geeks 4 Geeks')\nIn the above program warnings are displayed using the warn() function of warning module."
},
{
"code": "# program to illustrate warn() # function in warning module # importing modulesimport warnings # displaying warningwarnings.warn('Geeks 4 Geeks')",
"e": 4173,
"s": 4025,
"text": null
},
{
"code": null,
"e": 4181,
"s": 4173,
"text": "Output:"
},
{
"code": null,
"e": 4253,
"s": 4181,
"text": "main.py:2: UserWarning: Geeks 4 Geeks\n warnings.warn('Geeks 4 Geeks')\n"
},
{
"code": null,
"e": 4342,
"s": 4253,
"text": "In the above program warnings are displayed using the warn() function of warning module."
},
{
"code": null,
"e": 4513,
"s": 4342,
"text": "warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None): This function is a low-level method with warn() features"
},
{
"code": null,
"e": 5243,
"s": 4513,
"text": "filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False): This function adds an entry into the specifications of the warnings filter.# program to illustrate filterwarnings()# function in warning module # importing moduleimport warnings # adding entry into the specifications# of the warnings filter.warnings.filterwarnings('ignore', '.*do not.*', ) # displaying wariningswarnings.warn('Geeks 4 Geeks !') # this warning will not be displayedwarnings.warn('Do not show this message')Output:main.py:8: UserWarning: Geeks 4 Geeks!\n warnings.warn('Geeks 4 Geeks!')\nHere the second warning message is not displayed due to warnings.filterwarnings('ignore', '.*do not.*', ) in which action is \"ignore\" ."
},
{
"code": "# program to illustrate filterwarnings()# function in warning module # importing moduleimport warnings # adding entry into the specifications# of the warnings filter.warnings.filterwarnings('ignore', '.*do not.*', ) # displaying wariningswarnings.warn('Geeks 4 Geeks !') # this warning will not be displayedwarnings.warn('Do not show this message')",
"e": 5596,
"s": 5243,
"text": null
},
{
"code": null,
"e": 5604,
"s": 5596,
"text": "Output:"
},
{
"code": null,
"e": 5678,
"s": 5604,
"text": "main.py:8: UserWarning: Geeks 4 Geeks!\n warnings.warn('Geeks 4 Geeks!')\n"
},
{
"code": null,
"e": 5814,
"s": 5678,
"text": "Here the second warning message is not displayed due to warnings.filterwarnings('ignore', '.*do not.*', ) in which action is \"ignore\" ."
},
{
"code": null,
"e": 5928,
"s": 5814,
"text": "showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file."
},
{
"code": null,
"e": 6727,
"s": 5928,
"text": "simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.# program to illustrate simplefilter() # function in warning module # importing moduleimport warnings # adding a single entry into warnings filterwarnings.simplefilter('error', UserWarning) # displaying the warningwarnings.warn('This is a warning message')Output:Traceback (most recent call last):\n File \"main.py\", line 8, in \n warnings.warn('This is a warning message')\nUserWarning: This is a warning message\nIn the above program, a single entry is added to the warnings filter using warnings.simplefilter('error', UserWarning) in which the action is \"error\" and category is UserWrning and then the warning is displayed using the warn() method."
},
{
"code": "# program to illustrate simplefilter() # function in warning module # importing moduleimport warnings # adding a single entry into warnings filterwarnings.simplefilter('error', UserWarning) # displaying the warningwarnings.warn('This is a warning message')",
"e": 6987,
"s": 6727,
"text": null
},
{
"code": null,
"e": 6995,
"s": 6987,
"text": "Output:"
},
{
"code": null,
"e": 7152,
"s": 6995,
"text": "Traceback (most recent call last):\n File \"main.py\", line 8, in \n warnings.warn('This is a warning message')\nUserWarning: This is a warning message\n"
},
{
"code": null,
"e": 7388,
"s": 7152,
"text": "In the above program, a single entry is added to the warnings filter using warnings.simplefilter('error', UserWarning) in which the action is \"error\" and category is UserWrning and then the warning is displayed using the warn() method."
},
{
"code": null,
"e": 7409,
"s": 7388,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 7416,
"s": 7409,
"text": "Python"
},
{
"code": null,
"e": 7514,
"s": 7416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7532,
"s": 7514,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7574,
"s": 7532,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7596,
"s": 7574,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7631,
"s": 7596,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7657,
"s": 7631,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7689,
"s": 7657,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7718,
"s": 7689,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7745,
"s": 7718,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7775,
"s": 7745,
"text": "Iterate over a list in Python"
}
] |
type() function in Python | 13 Oct, 2020
type() method returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes.
Two different types of arguments can be passed to type() function, single and three argument. If single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.
Syntax :
type(object)
type(name, bases, dict)
Parameters :
name : name of class, which later corresponds to the __name__ attribute of the class.bases : tuple of classes from which the current class derives. Later corresponds to the __bases__ attribute.dict : a dictionary that holds the namespaces for the class. Later corresponds to the __dict__ attribute.
Returntype :
returns a new type class or essentially a metaclass.
Code #1 :
# Python3 simple code to explain# the type() functionprint(type([]) is list) print(type([]) is not list) print(type(()) is tuple) print(type({}) is dict) print(type({}) is not list)
Output :
True
False
True
True
True
Code #2 :
# Python3 code to explain# the type() function # Class of type dictclass DictType: DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'} # Will print the object type # of existing class print(type(DictNumber)) # Class of type list class ListType: ListNumber = [1, 2, 3, 4, 5] # Will print the object type # of existing class print(type(ListNumber)) # Class of type tuple class TupleType: TupleNumber = ('Geeks', 'for', 'geeks') # Will print the object type # of existing class print(type(TupleNumber)) # Creating object of each class d = DictType()l = ListType()t = TupleType()
Output :
<class 'dict'>
<class 'list'>
<class 'tuple'>
Code #3 :
# Python3 code to explain# the type() function # Class of type dictclass DictType: DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'} # Class of type list class ListType: ListNumber = [1, 2, 3, 4, 5] # Creating object of each class d = DictType()l = ListType() # Will print accordingly whether both# the objects are of same type or not if type(d) is not type(l): print("Both class have different object type.")else: print("Same Object type")
Output :
Both class have different object type.
Code #4 : Use of type(name, bases, dict)
# Python3 program to demonstrate# type(name, bases, dict) # New class(has no base) class with the# dynamic class initialization of type()new = type('New', (object, ), dict(var1 ='GeeksforGeeks', b = 2009)) # Print type() which returns class 'type'print(type(new))print(vars(new)) # Base class, incorporated# in our new classclass test: a = "Geeksforgeeks" b = 2009 # Dynamically initialize Newer class# It will derive from the base class testnewer = type('Newer', (test, ), dict(a ='Geeks', b = 2018)) print(type(newer))print(vars(newer))
Output :
{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': , 'b': 2009, '__dict__': , '__doc__': None}
{'b': 2018, '__doc__': None, '__module__': '__main__', 'a': 'Geeks'}
Applications :
type() function is basically used for debugging purposes. When used other string functions like .upper(), .lower(), .split() with text extracted from a web crawler, it might not work because they might be of different type which doesn’t support string functions. And as a result it will keep throwing errors, which are very difficult to debug [Consider the error as : GeneratorType has no attribute lower() ] . type() function can be used at that point to determine the type of text extracted and then change it to other forms of string before we use string functions or any other operations on it.
type() with three arguments can be used to dynamically initialize classes or existing classes with attributes. It is also used to register database tables with SQL.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Oct, 2020"
},
{
"code": null,
"e": 185,
"s": 52,
"text": "type() method returns class type of the argument(object) passed as parameter. type() function is mostly used for debugging purposes."
},
{
"code": null,
"e": 440,
"s": 185,
"text": "Two different types of arguments can be passed to type() function, single and three argument. If single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object."
},
{
"code": null,
"e": 449,
"s": 440,
"text": "Syntax :"
},
{
"code": null,
"e": 486,
"s": 449,
"text": "type(object)\ntype(name, bases, dict)"
},
{
"code": null,
"e": 499,
"s": 486,
"text": "Parameters :"
},
{
"code": null,
"e": 798,
"s": 499,
"text": "name : name of class, which later corresponds to the __name__ attribute of the class.bases : tuple of classes from which the current class derives. Later corresponds to the __bases__ attribute.dict : a dictionary that holds the namespaces for the class. Later corresponds to the __dict__ attribute."
},
{
"code": null,
"e": 811,
"s": 798,
"text": "Returntype :"
},
{
"code": null,
"e": 864,
"s": 811,
"text": "returns a new type class or essentially a metaclass."
},
{
"code": null,
"e": 876,
"s": 866,
"text": "Code #1 :"
},
{
"code": "# Python3 simple code to explain# the type() functionprint(type([]) is list) print(type([]) is not list) print(type(()) is tuple) print(type({}) is dict) print(type({}) is not list)",
"e": 1062,
"s": 876,
"text": null
},
{
"code": null,
"e": 1071,
"s": 1062,
"text": "Output :"
},
{
"code": null,
"e": 1097,
"s": 1071,
"text": "True\nFalse\nTrue\nTrue\nTrue"
},
{
"code": null,
"e": 1109,
"s": 1099,
"text": "Code #2 :"
},
{
"code": "# Python3 code to explain# the type() function # Class of type dictclass DictType: DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'} # Will print the object type # of existing class print(type(DictNumber)) # Class of type list class ListType: ListNumber = [1, 2, 3, 4, 5] # Will print the object type # of existing class print(type(ListNumber)) # Class of type tuple class TupleType: TupleNumber = ('Geeks', 'for', 'geeks') # Will print the object type # of existing class print(type(TupleNumber)) # Creating object of each class d = DictType()l = ListType()t = TupleType()",
"e": 1773,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1782,
"s": 1773,
"text": "Output :"
},
{
"code": null,
"e": 1828,
"s": 1782,
"text": "<class 'dict'>\n<class 'list'>\n<class 'tuple'>"
},
{
"code": null,
"e": 1840,
"s": 1830,
"text": "Code #3 :"
},
{
"code": "# Python3 code to explain# the type() function # Class of type dictclass DictType: DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'} # Class of type list class ListType: ListNumber = [1, 2, 3, 4, 5] # Creating object of each class d = DictType()l = ListType() # Will print accordingly whether both# the objects are of same type or not if type(d) is not type(l): print(\"Both class have different object type.\")else: print(\"Same Object type\")",
"e": 2313,
"s": 1840,
"text": null
},
{
"code": null,
"e": 2322,
"s": 2313,
"text": "Output :"
},
{
"code": null,
"e": 2361,
"s": 2322,
"text": "Both class have different object type."
},
{
"code": null,
"e": 2403,
"s": 2361,
"text": " Code #4 : Use of type(name, bases, dict)"
},
{
"code": "# Python3 program to demonstrate# type(name, bases, dict) # New class(has no base) class with the# dynamic class initialization of type()new = type('New', (object, ), dict(var1 ='GeeksforGeeks', b = 2009)) # Print type() which returns class 'type'print(type(new))print(vars(new)) # Base class, incorporated# in our new classclass test: a = \"Geeksforgeeks\" b = 2009 # Dynamically initialize Newer class# It will derive from the base class testnewer = type('Newer', (test, ), dict(a ='Geeks', b = 2018)) print(type(newer))print(vars(newer))",
"e": 2975,
"s": 2403,
"text": null
},
{
"code": null,
"e": 2984,
"s": 2975,
"text": "Output :"
},
{
"code": null,
"e": 3166,
"s": 2984,
"text": "{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': , 'b': 2009, '__dict__': , '__doc__': None}\n\n{'b': 2018, '__doc__': None, '__module__': '__main__', 'a': 'Geeks'}\n"
},
{
"code": null,
"e": 3182,
"s": 3166,
"text": " Applications :"
},
{
"code": null,
"e": 3781,
"s": 3182,
"text": "type() function is basically used for debugging purposes. When used other string functions like .upper(), .lower(), .split() with text extracted from a web crawler, it might not work because they might be of different type which doesn’t support string functions. And as a result it will keep throwing errors, which are very difficult to debug [Consider the error as : GeneratorType has no attribute lower() ] . type() function can be used at that point to determine the type of text extracted and then change it to other forms of string before we use string functions or any other operations on it."
},
{
"code": null,
"e": 3946,
"s": 3781,
"text": "type() with three arguments can be used to dynamically initialize classes or existing classes with attributes. It is also used to register database tables with SQL."
},
{
"code": null,
"e": 3972,
"s": 3946,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 3979,
"s": 3972,
"text": "Python"
},
{
"code": null,
"e": 4077,
"s": 3979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4095,
"s": 4077,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4137,
"s": 4095,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4159,
"s": 4137,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4185,
"s": 4159,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4217,
"s": 4185,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4246,
"s": 4217,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4273,
"s": 4246,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4294,
"s": 4273,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4317,
"s": 4294,
"text": "Introduction To PYTHON"
}
] |
Convert an Array into Collection in Java | 09 Jun, 2022
Java Collection provides an architecture to store and manipulate a group of objects. The datatype of data can be changed to a general data type like array into Collection. To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T... a) that converts the array into a Collection.
Steps:
Define a function to write logic
Take array input from the user
Convert array input into Collection with help of asList() function.
Methods used:
1. asList(): This method of java.util.Arrays class is used to return a fixed-size list backed by the specified array and acting as a bridge between array-based and collection-based APIs, in combination with Collection.toArray().
This runs in O(1) time.
Example 1:
Java
// Convert an Array into Collection in Java // import java util libraryimport java.util.*; // class for writing logic of the problempublic class ArrayToCollection { public static void main(String args[]) { // array input String playersArray[] = { "Virat", "Sachin", "Rohit", "Bumrah" }; // printing input elements for comparison System.out.println("Array input: " + Arrays.toString(playersArray)); // converting array into Collection // with asList() function List playersList = Arrays.asList(playersArray); // print converted elements System.out.println("Converted elements: " + playersList); }}
Output:
Array input: [Virat, Sachin, Rohit, Bumrah]
Converted elements: [Virat, Sachin, Rohit, Bumrah]
Example 2:
Java
// Convert an Array into Collection in Java // import java util libraryimport java.util.*; public class ArrayToCollection { public static void main(String args[]) { String countryArray[] = { "India", "Pakistan", "Afganistan", "Srilanka" }; System.out.println("Array input: " + Arrays.toString(countryArray)); List countryList = Arrays.asList(countryArray); System.out.println("Converted elements: " + countryList); }}
Output:
Array input: [India, Pakistan, Afganistan, Srilanka]
Converted elements: [India, Pakistan, Afganistan, Srilanka]
2. Collections.addAll() method :
This method is used in converting the given array to the List object. To use this method, we have to import the package java.util.Collections. You can simply specify this by putting import java.util.* for using the Collections method needed for implementing the program.
Step 1: Declare and initialize the array “countryArray”.
Step 2: Declare the list object “countryList”.
Step 3 : Now, use the method Collections.addAll(Collections,Array). Here, the items in the array will be added to the List.
Example
Java
import java.util.*; class GFG { public static void main(String[] args) { String countryArray[] = { "India", "Pakistan", "Afganistan", "Srilanka" }; List<String> countryList = new ArrayList<>(); Collections.addAll(countryList, countryArray); System.out.println("Converted ArrayList elements: " + countryList); }}
Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]
3.List.of() method:
To use this method, we have to import the package java.util. It is a static method. List.of() returns an immutable list but to make it mutable list we have to specify this inside the constructor of ArrayList.
Step 1: Declare and initialize the array “countryArray”.
Step 2: Declare the list object “countryList”.
Step 3: Inside the constructor of ArrayList(), specify the List.of(array_name) method. It will simply add the array of elements to the list.
Example
Java
import java.util.*; class GFG { public static void main(String[] args) { String countryArray[] = { "India", "Pakistan", "Afganistan", "Srilanka" }; List<String> countryList = new ArrayList<>(List.of(countryArray)); System.out.println("Converted ArrayList elements: " + countryList); }}
Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]
4.Arrays.stream() method:
To use this method, import the package static java.util.stream.Collectors.toList. Specify the array element in the Arrays.stream() method and convert it into the list using toList() method.
Step 1: Declare and initialize the array “countryArray”.
Step 2: Declare the list object “countryList”.
Step 3: Specify the array name inside the Arrays.stream() method as Arrays.stream(array_name) and collect(toList()) is used to collect all stream and make it into a List instance.
Example
Java
import static java.util.stream.Collectors.toList; import java.util.*;class GFG { public static void main(String[] args) { String countryArray[] = { "India", "Pakistan", "Afganistan", "Srilanka" }; List<String> countryList = Arrays.stream(countryArray).collect(toList()); System.out.println("Converted ArrayList elements: " + countryList); }}
Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]
avtarkumar719
keerthikarathan123
Java-Array-Programs
Java-Collections
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 381,
"s": 28,
"text": "Java Collection provides an architecture to store and manipulate a group of objects. The datatype of data can be changed to a general data type like array into Collection. To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T... a) that converts the array into a Collection."
},
{
"code": null,
"e": 388,
"s": 381,
"text": "Steps:"
},
{
"code": null,
"e": 421,
"s": 388,
"text": "Define a function to write logic"
},
{
"code": null,
"e": 452,
"s": 421,
"text": "Take array input from the user"
},
{
"code": null,
"e": 520,
"s": 452,
"text": "Convert array input into Collection with help of asList() function."
},
{
"code": null,
"e": 534,
"s": 520,
"text": "Methods used:"
},
{
"code": null,
"e": 763,
"s": 534,
"text": "1. asList(): This method of java.util.Arrays class is used to return a fixed-size list backed by the specified array and acting as a bridge between array-based and collection-based APIs, in combination with Collection.toArray()."
},
{
"code": null,
"e": 787,
"s": 763,
"text": "This runs in O(1) time."
},
{
"code": null,
"e": 798,
"s": 787,
"text": "Example 1:"
},
{
"code": null,
"e": 803,
"s": 798,
"text": "Java"
},
{
"code": "// Convert an Array into Collection in Java // import java util libraryimport java.util.*; // class for writing logic of the problempublic class ArrayToCollection { public static void main(String args[]) { // array input String playersArray[] = { \"Virat\", \"Sachin\", \"Rohit\", \"Bumrah\" }; // printing input elements for comparison System.out.println(\"Array input: \" + Arrays.toString(playersArray)); // converting array into Collection // with asList() function List playersList = Arrays.asList(playersArray); // print converted elements System.out.println(\"Converted elements: \" + playersList); }}",
"e": 1556,
"s": 803,
"text": null
},
{
"code": null,
"e": 1564,
"s": 1556,
"text": "Output:"
},
{
"code": null,
"e": 1659,
"s": 1564,
"text": "Array input: [Virat, Sachin, Rohit, Bumrah]\nConverted elements: [Virat, Sachin, Rohit, Bumrah]"
},
{
"code": null,
"e": 1670,
"s": 1659,
"text": "Example 2:"
},
{
"code": null,
"e": 1675,
"s": 1670,
"text": "Java"
},
{
"code": "// Convert an Array into Collection in Java // import java util libraryimport java.util.*; public class ArrayToCollection { public static void main(String args[]) { String countryArray[] = { \"India\", \"Pakistan\", \"Afganistan\", \"Srilanka\" }; System.out.println(\"Array input: \" + Arrays.toString(countryArray)); List countryList = Arrays.asList(countryArray); System.out.println(\"Converted elements: \" + countryList); }}",
"e": 2219,
"s": 1675,
"text": null
},
{
"code": null,
"e": 2227,
"s": 2219,
"text": "Output:"
},
{
"code": null,
"e": 2340,
"s": 2227,
"text": "Array input: [India, Pakistan, Afganistan, Srilanka]\nConverted elements: [India, Pakistan, Afganistan, Srilanka]"
},
{
"code": null,
"e": 2373,
"s": 2340,
"text": "2. Collections.addAll() method :"
},
{
"code": null,
"e": 2646,
"s": 2373,
"text": "This method is used in converting the given array to the List object. To use this method, we have to import the package java.util.Collections. You can simply specify this by putting import java.util.* for using the Collections method needed for implementing the program. "
},
{
"code": null,
"e": 2703,
"s": 2646,
"text": "Step 1: Declare and initialize the array “countryArray”."
},
{
"code": null,
"e": 2750,
"s": 2703,
"text": "Step 2: Declare the list object “countryList”."
},
{
"code": null,
"e": 2874,
"s": 2750,
"text": "Step 3 : Now, use the method Collections.addAll(Collections,Array). Here, the items in the array will be added to the List."
},
{
"code": null,
"e": 2882,
"s": 2874,
"text": "Example"
},
{
"code": null,
"e": 2887,
"s": 2882,
"text": "Java"
},
{
"code": "import java.util.*; class GFG { public static void main(String[] args) { String countryArray[] = { \"India\", \"Pakistan\", \"Afganistan\", \"Srilanka\" }; List<String> countryList = new ArrayList<>(); Collections.addAll(countryList, countryArray); System.out.println(\"Converted ArrayList elements: \" + countryList); }}",
"e": 3290,
"s": 2887,
"text": null
},
{
"code": null,
"e": 3361,
"s": 3290,
"text": "Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]\n"
},
{
"code": null,
"e": 3381,
"s": 3361,
"text": "3.List.of() method:"
},
{
"code": null,
"e": 3590,
"s": 3381,
"text": "To use this method, we have to import the package java.util. It is a static method. List.of() returns an immutable list but to make it mutable list we have to specify this inside the constructor of ArrayList."
},
{
"code": null,
"e": 3647,
"s": 3590,
"text": "Step 1: Declare and initialize the array “countryArray”."
},
{
"code": null,
"e": 3694,
"s": 3647,
"text": "Step 2: Declare the list object “countryList”."
},
{
"code": null,
"e": 3835,
"s": 3694,
"text": "Step 3: Inside the constructor of ArrayList(), specify the List.of(array_name) method. It will simply add the array of elements to the list."
},
{
"code": null,
"e": 3843,
"s": 3835,
"text": "Example"
},
{
"code": null,
"e": 3848,
"s": 3843,
"text": "Java"
},
{
"code": "import java.util.*; class GFG { public static void main(String[] args) { String countryArray[] = { \"India\", \"Pakistan\", \"Afganistan\", \"Srilanka\" }; List<String> countryList = new ArrayList<>(List.of(countryArray)); System.out.println(\"Converted ArrayList elements: \" + countryList); }}",
"e": 4229,
"s": 3848,
"text": null
},
{
"code": null,
"e": 4300,
"s": 4229,
"text": "Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]\n"
},
{
"code": null,
"e": 4326,
"s": 4300,
"text": "4.Arrays.stream() method:"
},
{
"code": null,
"e": 4516,
"s": 4326,
"text": "To use this method, import the package static java.util.stream.Collectors.toList. Specify the array element in the Arrays.stream() method and convert it into the list using toList() method."
},
{
"code": null,
"e": 4573,
"s": 4516,
"text": "Step 1: Declare and initialize the array “countryArray”."
},
{
"code": null,
"e": 4620,
"s": 4573,
"text": "Step 2: Declare the list object “countryList”."
},
{
"code": null,
"e": 4800,
"s": 4620,
"text": "Step 3: Specify the array name inside the Arrays.stream() method as Arrays.stream(array_name) and collect(toList()) is used to collect all stream and make it into a List instance."
},
{
"code": null,
"e": 4808,
"s": 4800,
"text": "Example"
},
{
"code": null,
"e": 4813,
"s": 4808,
"text": "Java"
},
{
"code": "import static java.util.stream.Collectors.toList; import java.util.*;class GFG { public static void main(String[] args) { String countryArray[] = { \"India\", \"Pakistan\", \"Afganistan\", \"Srilanka\" }; List<String> countryList = Arrays.stream(countryArray).collect(toList()); System.out.println(\"Converted ArrayList elements: \" + countryList); }}",
"e": 5250,
"s": 4813,
"text": null
},
{
"code": null,
"e": 5321,
"s": 5250,
"text": "Converted ArrayList elements: [India, Pakistan, Afganistan, Srilanka]\n"
},
{
"code": null,
"e": 5335,
"s": 5321,
"text": "avtarkumar719"
},
{
"code": null,
"e": 5354,
"s": 5335,
"text": "keerthikarathan123"
},
{
"code": null,
"e": 5374,
"s": 5354,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 5391,
"s": 5374,
"text": "Java-Collections"
},
{
"code": null,
"e": 5396,
"s": 5391,
"text": "Java"
},
{
"code": null,
"e": 5410,
"s": 5396,
"text": "Java Programs"
},
{
"code": null,
"e": 5415,
"s": 5410,
"text": "Java"
},
{
"code": null,
"e": 5432,
"s": 5415,
"text": "Java-Collections"
},
{
"code": null,
"e": 5530,
"s": 5432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5545,
"s": 5530,
"text": "Stream In Java"
},
{
"code": null,
"e": 5566,
"s": 5545,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5587,
"s": 5566,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5606,
"s": 5587,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5623,
"s": 5606,
"text": "Generics in Java"
},
{
"code": null,
"e": 5649,
"s": 5623,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5683,
"s": 5649,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 5730,
"s": 5683,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 5768,
"s": 5730,
"text": "Factory method design pattern in Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.