title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
C++ Program to compute division upto n decimal places
|
Given with the value of x and y as a positive integer with the value of n for number of decimal places and the task is to generate the division up to n decimal places.
Input-: x = 36, y = 7, n = 5
Output-: 5.14285
Input-: x = 22, y = 7, n = 10
Output-: 3.1428571428
Approach used in the below program is as follows −
Input the value of a, b and n
Check if b is 0 than division will go upto infinite and if a is 0 than result will be 0 as something divides to 0 is 0
If n is greater than 1 than store the value of remainder and subtract it from the dividend after that multiply the result by ten. Start the next iteration
Print the result
START
Step 1-> declare function to compute division upto n decimal places
void compute_division(int a, int b, int n)
check IF (b == 0)
print Infinite
End
check IF(a == 0)
print 0
End
check IF(n <= 0)
print a/b
End
check IF(((a > 0) && (b < 0)) || ((a < 0) && (b > 0)))
print “-”
set a = a > 0 ? a : -a
set b = b > 0 ? b : -b
End
Declare and set int dec = a / b
Loop For int i = 0 and i <= n and i++
print dec
Set a = a - (b * dec)
IF(a == 0)
break
End
Set a = a * 10
set dec = a / b
IF (i == 0)
print “.”
End
End
Step 2-> In main()
Declare and set int a = 36, b = 7, n = 5
Call compute_division(a, b, n)
STOP
#include <bits/stdc++.h>
using namespace std;
void compute_division(int a, int b, int n) {
if (b == 0) {
cout << "Infinite" << endl;
return;
}
if (a == 0) {
cout << 0 << endl;
return;
}
if (n <= 0) {
cout << a / b << endl;
return;
}
if (((a > 0) && (b < 0)) || ((a < 0) && (b > 0))) {
cout << "-";
a = a > 0 ? a : -a;
b = b > 0 ? b : -b;
}
int dec = a / b;
for (int i = 0; i <= n; i++) {
cout <<dec;
a = a - (b * dec);
if (a == 0)
break;
a = a * 10;
dec = a / b;
if (i == 0)
cout << ".";
}
}
int main() {
int a = 36, b = 7, n = 5;
compute_division(a, b, n);
return 0;
}
5.14285
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "Given with the value of x and y as a positive integer with the value of n for number of decimal places and the task is to generate the division up to n decimal places."
},
{
"code": null,
"e": 1328,
"s": 1230,
"text": "Input-: x = 36, y = 7, n = 5\nOutput-: 5.14285\nInput-: x = 22, y = 7, n = 10\nOutput-: 3.1428571428"
},
{
"code": null,
"e": 1379,
"s": 1328,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 1409,
"s": 1379,
"text": "Input the value of a, b and n"
},
{
"code": null,
"e": 1528,
"s": 1409,
"text": "Check if b is 0 than division will go upto infinite and if a is 0 than result will be 0 as something divides to 0 is 0"
},
{
"code": null,
"e": 1683,
"s": 1528,
"text": "If n is greater than 1 than store the value of remainder and subtract it from the dividend after that multiply the result by ten. Start the next iteration"
},
{
"code": null,
"e": 1700,
"s": 1683,
"text": "Print the result"
},
{
"code": null,
"e": 2453,
"s": 1700,
"text": "START\nStep 1-> declare function to compute division upto n decimal places\n void compute_division(int a, int b, int n)\n check IF (b == 0)\n print Infinite\n End\n check IF(a == 0)\n print 0\n End\n check IF(n <= 0)\n print a/b\n End\n check IF(((a > 0) && (b < 0)) || ((a < 0) && (b > 0)))\n print “-”\n set a = a > 0 ? a : -a\n set b = b > 0 ? b : -b\n End\n Declare and set int dec = a / b\n Loop For int i = 0 and i <= n and i++\n print dec\n Set a = a - (b * dec)\n IF(a == 0)\n break\n End\n Set a = a * 10\n set dec = a / b\n IF (i == 0)\n print “.”\n End\n End\nStep 2-> In main()\n Declare and set int a = 36, b = 7, n = 5\n Call compute_division(a, b, n)\nSTOP"
},
{
"code": null,
"e": 3223,
"s": 2453,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid compute_division(int a, int b, int n) {\n if (b == 0) {\n cout << \"Infinite\" << endl;\n return;\n }\n if (a == 0) {\n cout << 0 << endl;\n return;\n }\n if (n <= 0) {\n cout << a / b << endl;\n return;\n }\n if (((a > 0) && (b < 0)) || ((a < 0) && (b > 0))) {\n cout << \"-\";\n a = a > 0 ? a : -a;\n b = b > 0 ? b : -b;\n }\n int dec = a / b;\n for (int i = 0; i <= n; i++) {\n cout <<dec;\n a = a - (b * dec);\n if (a == 0)\n break;\n a = a * 10;\n dec = a / b;\n if (i == 0)\n cout << \".\";\n }\n}\nint main() {\n int a = 36, b = 7, n = 5;\n compute_division(a, b, n);\n return 0;\n}"
},
{
"code": null,
"e": 3231,
"s": 3223,
"text": "5.14285"
}
] |
Functional Programming - Recursion
|
A function that calls itself is known as a recursive function and this technique is known as recursion. A recursion instruction continues until another instruction prevents it.
The following example shows how recursion works in C++, which is an object-oriented programming language −
#include <stdio.h>
long int fact(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, fact(n));
return 0;
}
long int fact(int n) {
if (n >= 1)
return n*fact(n-1);
else
return 1;
}
It will produce the following output
Enter a positive integer: 5
Factorial of 5 = 120
The following example shows how recursion works in Python, which is a functional programming language −
def fact(n):
if n == 1:
return n
else:
return n* fact (n-1)
# accepts input from user
num = int(input("Enter a number: "))
# check whether number is positive or not
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
else:
print("The factorial of " + str(num) + " is " + str(fact(num)))
It will produce the following output −
Enter a number: 6
The factorial of 6 is 720
32 Lectures
3.5 hours
Pavan Lalwani
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
72 Lectures
10.5 hours
Arun Ammasai
51 Lectures
2 hours
Skillbakerystudios
43 Lectures
4 hours
Mohammad Nauman
8 Lectures
1 hours
Santharam Sivalenka
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1998,
"s": 1821,
"text": "A function that calls itself is known as a recursive function and this technique is known as recursion. A recursion instruction continues until another instruction prevents it."
},
{
"code": null,
"e": 2105,
"s": 1998,
"text": "The following example shows how recursion works in C++, which is an object-oriented programming language −"
},
{
"code": null,
"e": 2400,
"s": 2105,
"text": "#include <stdio.h> \nlong int fact(int n); \n\nint main() { \n int n; \n printf(\"Enter a positive integer: \"); \n scanf(\"%d\", &n); \n printf(\"Factorial of %d = %ld\", n, fact(n)); \n return 0; \n} \nlong int fact(int n) { \n if (n >= 1) \n return n*fact(n-1); \n else \n return 1; \n} "
},
{
"code": null,
"e": 2437,
"s": 2400,
"text": "It will produce the following output"
},
{
"code": null,
"e": 2489,
"s": 2437,
"text": "Enter a positive integer: 5 \nFactorial of 5 = 120 \n"
},
{
"code": null,
"e": 2593,
"s": 2489,
"text": "The following example shows how recursion works in Python, which is a functional programming language −"
},
{
"code": null,
"e": 2943,
"s": 2593,
"text": "def fact(n): \n if n == 1: \n return n \n else: \n return n* fact (n-1) \n\n# accepts input from user \nnum = int(input(\"Enter a number: \")) \n# check whether number is positive or not \n\nif num < 0: \n print(\"Sorry, factorial does not exist for negative numbers\") \nelse: \n print(\"The factorial of \" + str(num) + \" is \" + str(fact(num))) "
},
{
"code": null,
"e": 2982,
"s": 2943,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3030,
"s": 2982,
"text": "Enter a number: 6\nThe factorial of 6 is 720 \n"
},
{
"code": null,
"e": 3065,
"s": 3030,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3080,
"s": 3065,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3113,
"s": 3080,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3137,
"s": 3113,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3173,
"s": 3137,
"text": "\n 72 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3187,
"s": 3173,
"text": " Arun Ammasai"
},
{
"code": null,
"e": 3220,
"s": 3187,
"text": "\n 51 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3240,
"s": 3220,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3273,
"s": 3240,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3290,
"s": 3273,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3322,
"s": 3290,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3343,
"s": 3322,
"text": " Santharam Sivalenka"
},
{
"code": null,
"e": 3350,
"s": 3343,
"text": " Print"
},
{
"code": null,
"e": 3361,
"s": 3350,
"text": " Add Notes"
}
] |
AWT Event Classes
|
The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used.
It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon.This class is defined in java.util package.
Following is the declaration for java.util.EventObject class:
public class EventObject
extends Object
implements Serializable
Following are the fields for java.util.EventObject class:
protected Object source -- The object on which the Event initially occurred.
protected Object source -- The object on which the Event initially occurred.
EventObject(Object source)
Constructs a prototypical Event.
Object getSource()
The object on which the Event initially occurred.
String toString()
Returns a String representation of this EventObject.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Following is the list of commonly used event classes.
AWTEvent
It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class.
ActionEvent
The ActionEvent is generated when button is clicked or the item of a list is double clicked.
InputEvent
The InputEvent class is root event class for all component-level input events.
KeyEvent
On entering the character the Key event is generated.
MouseEvent
This event indicates a mouse action occurred in a component.
TextEvent
The object of this class represents the text events.
WindowEvent
The object of this class represents the change in state of a window.
AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
The object of this class represents the change in state of a window.
ContainerEvent
The object of this class represents the change in state of a window.
MouseMotionEvent
The object of this class represents the change in state of a window.
PaintEvent
The object of this class represents the change in state of a window.
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1883,
"s": 1747,
"text": "The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used."
},
{
"code": null,
"e": 2171,
"s": 1883,
"text": "It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon.This class is defined in java.util package."
},
{
"code": null,
"e": 2233,
"s": 2171,
"text": "Following is the declaration for java.util.EventObject class:"
},
{
"code": null,
"e": 2306,
"s": 2233,
"text": "public class EventObject\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 2364,
"s": 2306,
"text": "Following are the fields for java.util.EventObject class:"
},
{
"code": null,
"e": 2443,
"s": 2364,
"text": "protected Object source -- The object on which the Event initially occurred. \t"
},
{
"code": null,
"e": 2522,
"s": 2443,
"text": "protected Object source -- The object on which the Event initially occurred. \t"
},
{
"code": null,
"e": 2550,
"s": 2522,
"text": "EventObject(Object source) "
},
{
"code": null,
"e": 2583,
"s": 2550,
"text": "Constructs a prototypical Event."
},
{
"code": null,
"e": 2602,
"s": 2583,
"text": "Object getSource()"
},
{
"code": null,
"e": 2652,
"s": 2602,
"text": "The object on which the Event initially occurred."
},
{
"code": null,
"e": 2670,
"s": 2652,
"text": "String\ttoString()"
},
{
"code": null,
"e": 2723,
"s": 2670,
"text": "Returns a String representation of this EventObject."
},
{
"code": null,
"e": 2779,
"s": 2723,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 2796,
"s": 2779,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2813,
"s": 2796,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2867,
"s": 2813,
"text": "Following is the list of commonly used event classes."
},
{
"code": null,
"e": 2876,
"s": 2867,
"text": "AWTEvent"
},
{
"code": null,
"e": 2998,
"s": 2876,
"text": "It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class."
},
{
"code": null,
"e": 3010,
"s": 2998,
"text": "ActionEvent"
},
{
"code": null,
"e": 3103,
"s": 3010,
"text": "The ActionEvent is generated when button is clicked or the item of a list is double clicked."
},
{
"code": null,
"e": 3114,
"s": 3103,
"text": "InputEvent"
},
{
"code": null,
"e": 3193,
"s": 3114,
"text": "The InputEvent class is root event class for all component-level input events."
},
{
"code": null,
"e": 3202,
"s": 3193,
"text": "KeyEvent"
},
{
"code": null,
"e": 3256,
"s": 3202,
"text": "On entering the character the Key event is generated."
},
{
"code": null,
"e": 3267,
"s": 3256,
"text": "MouseEvent"
},
{
"code": null,
"e": 3328,
"s": 3267,
"text": "This event indicates a mouse action occurred in a component."
},
{
"code": null,
"e": 3338,
"s": 3328,
"text": "TextEvent"
},
{
"code": null,
"e": 3391,
"s": 3338,
"text": "The object of this class represents the text events."
},
{
"code": null,
"e": 3403,
"s": 3391,
"text": "WindowEvent"
},
{
"code": null,
"e": 3472,
"s": 3403,
"text": "The object of this class represents the change in state of a window."
},
{
"code": null,
"e": 3488,
"s": 3472,
"text": "AdjustmentEvent"
},
{
"code": null,
"e": 3576,
"s": 3488,
"text": "The object of this class represents the adjustment event emitted by Adjustable objects."
},
{
"code": null,
"e": 3591,
"s": 3576,
"text": "ComponentEvent"
},
{
"code": null,
"e": 3660,
"s": 3591,
"text": "The object of this class represents the change in state of a window."
},
{
"code": null,
"e": 3675,
"s": 3660,
"text": "ContainerEvent"
},
{
"code": null,
"e": 3744,
"s": 3675,
"text": "The object of this class represents the change in state of a window."
},
{
"code": null,
"e": 3761,
"s": 3744,
"text": "MouseMotionEvent"
},
{
"code": null,
"e": 3830,
"s": 3761,
"text": "The object of this class represents the change in state of a window."
},
{
"code": null,
"e": 3841,
"s": 3830,
"text": "PaintEvent"
},
{
"code": null,
"e": 3910,
"s": 3841,
"text": "The object of this class represents the change in state of a window."
},
{
"code": null,
"e": 3943,
"s": 3910,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3951,
"s": 3943,
"text": " EduOLC"
},
{
"code": null,
"e": 3958,
"s": 3951,
"text": " Print"
},
{
"code": null,
"e": 3969,
"s": 3958,
"text": " Add Notes"
}
] |
Finding Data Type of User Input using Regular Expression in Java - GeeksforGeeks
|
16 Oct, 2020
Given a string, the task is to find its corresponding datatype using regular expression in java.
We can broadly classify all data types into following types:
Integer: Numeric datatypes like byte, short, int, long take the form of an Integer object.Double: Decimal datatypes like float and double take the form of Double object.Date: Date in any format (like dd-mm-yyyy or dd/mm/yyyy) is a part of java.util.DateString: All remaining inputs come under the String type.
Integer: Numeric datatypes like byte, short, int, long take the form of an Integer object.
Double: Decimal datatypes like float and double take the form of Double object.
Date: Date in any format (like dd-mm-yyyy or dd/mm/yyyy) is a part of java.util.Date
String: All remaining inputs come under the String type.
Note: Character inputs and boolean values will also be considered as string.
Examples:
Input: “56.73”
Output: java.lang.Double
Explanation: 56.73 is of float data type which are part of java.lang.Double
Input: “true”
Output: java.lang.String
Explanation: Here true is considered as a regular string which is a part of java.lang.String
Approach:
Take input in the form of a string.
Now if the input contains only digits, it is an Integer object. If it contains numbers with a decimal point, it is a Double-object. If the input is in the form of a Date, we print it as java.util.Date object. Else, we say that the input is a String object which may contain alphanumeric and special characters.
Below is the implementation of the above approach:
Java
public class GFG { // method stub public static void main(String[] arg) { String input = "56.73"; String dataType = null; // checking for Integer if (input.matches("\\d+")) { dataType = "java.lang.Integer"; } // checking for floating point numbers else if (input.matches("\\d*[.]\\d+")) { dataType = "java.lang.Double"; } // checking for date format dd/mm/yyyy else if (input.matches( "\\d{2}[/]\\d{2}[/]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format mm/dd/yyyy else if (input.matches( "\\d{2}[/]\\d{2}[/]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format dd-mon-yy else if (input.matches( "\\d{2}[-]\\w{3}[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for date format dd-mon-yyyy else if (input.matches( "\\d{2}[-]\\w{3}[-]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format dd-month-yy else if (input.matches("\\d{2}[-]\\w+[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for date format dd-month-yyyy else if (input.matches("\\d{2}[-]\\w+[-]\\d{4}")) { dataType = "java.util.Date"; } // checking for date format yyyy-mm-dd else if (input.matches( "\\d{4}[-]\\d{2}[-]\\d{2}")) { dataType = "java.util.Date"; } // checking for String else { dataType = "java.lang.String"; } System.out.println("The datatype of " + input + " is: " + dataType); }}
The datatype of 56.73 is: java.lang.Double
vivek.singh0302
java-regular-expression
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n16 Oct, 2020"
},
{
"code": null,
"e": 24045,
"s": 23948,
"text": "Given a string, the task is to find its corresponding datatype using regular expression in java."
},
{
"code": null,
"e": 24106,
"s": 24045,
"text": "We can broadly classify all data types into following types:"
},
{
"code": null,
"e": 24416,
"s": 24106,
"text": "Integer: Numeric datatypes like byte, short, int, long take the form of an Integer object.Double: Decimal datatypes like float and double take the form of Double object.Date: Date in any format (like dd-mm-yyyy or dd/mm/yyyy) is a part of java.util.DateString: All remaining inputs come under the String type."
},
{
"code": null,
"e": 24507,
"s": 24416,
"text": "Integer: Numeric datatypes like byte, short, int, long take the form of an Integer object."
},
{
"code": null,
"e": 24587,
"s": 24507,
"text": "Double: Decimal datatypes like float and double take the form of Double object."
},
{
"code": null,
"e": 24672,
"s": 24587,
"text": "Date: Date in any format (like dd-mm-yyyy or dd/mm/yyyy) is a part of java.util.Date"
},
{
"code": null,
"e": 24729,
"s": 24672,
"text": "String: All remaining inputs come under the String type."
},
{
"code": null,
"e": 24806,
"s": 24729,
"text": "Note: Character inputs and boolean values will also be considered as string."
},
{
"code": null,
"e": 24816,
"s": 24806,
"text": "Examples:"
},
{
"code": null,
"e": 24831,
"s": 24816,
"text": "Input: “56.73”"
},
{
"code": null,
"e": 24856,
"s": 24831,
"text": "Output: java.lang.Double"
},
{
"code": null,
"e": 24932,
"s": 24856,
"text": "Explanation: 56.73 is of float data type which are part of java.lang.Double"
},
{
"code": null,
"e": 24946,
"s": 24932,
"text": "Input: “true”"
},
{
"code": null,
"e": 24971,
"s": 24946,
"text": "Output: java.lang.String"
},
{
"code": null,
"e": 25064,
"s": 24971,
"text": "Explanation: Here true is considered as a regular string which is a part of java.lang.String"
},
{
"code": null,
"e": 25074,
"s": 25064,
"text": "Approach:"
},
{
"code": null,
"e": 25110,
"s": 25074,
"text": "Take input in the form of a string."
},
{
"code": null,
"e": 25421,
"s": 25110,
"text": "Now if the input contains only digits, it is an Integer object. If it contains numbers with a decimal point, it is a Double-object. If the input is in the form of a Date, we print it as java.util.Date object. Else, we say that the input is a String object which may contain alphanumeric and special characters."
},
{
"code": null,
"e": 25472,
"s": 25421,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25477,
"s": 25472,
"text": "Java"
},
{
"code": "public class GFG { // method stub public static void main(String[] arg) { String input = \"56.73\"; String dataType = null; // checking for Integer if (input.matches(\"\\\\d+\")) { dataType = \"java.lang.Integer\"; } // checking for floating point numbers else if (input.matches(\"\\\\d*[.]\\\\d+\")) { dataType = \"java.lang.Double\"; } // checking for date format dd/mm/yyyy else if (input.matches( \"\\\\d{2}[/]\\\\d{2}[/]\\\\d{4}\")) { dataType = \"java.util.Date\"; } // checking for date format mm/dd/yyyy else if (input.matches( \"\\\\d{2}[/]\\\\d{2}[/]\\\\d{4}\")) { dataType = \"java.util.Date\"; } // checking for date format dd-mon-yy else if (input.matches( \"\\\\d{2}[-]\\\\w{3}[-]\\\\d{2}\")) { dataType = \"java.util.Date\"; } // checking for date format dd-mon-yyyy else if (input.matches( \"\\\\d{2}[-]\\\\w{3}[-]\\\\d{4}\")) { dataType = \"java.util.Date\"; } // checking for date format dd-month-yy else if (input.matches(\"\\\\d{2}[-]\\\\w+[-]\\\\d{2}\")) { dataType = \"java.util.Date\"; } // checking for date format dd-month-yyyy else if (input.matches(\"\\\\d{2}[-]\\\\w+[-]\\\\d{4}\")) { dataType = \"java.util.Date\"; } // checking for date format yyyy-mm-dd else if (input.matches( \"\\\\d{4}[-]\\\\d{2}[-]\\\\d{2}\")) { dataType = \"java.util.Date\"; } // checking for String else { dataType = \"java.lang.String\"; } System.out.println(\"The datatype of \" + input + \" is: \" + dataType); }}",
"e": 27299,
"s": 25477,
"text": null
},
{
"code": null,
"e": 27347,
"s": 27302,
"text": "The datatype of 56.73 is: java.lang.Double\n\n"
},
{
"code": null,
"e": 27365,
"s": 27349,
"text": "vivek.singh0302"
},
{
"code": null,
"e": 27389,
"s": 27365,
"text": "java-regular-expression"
},
{
"code": null,
"e": 27394,
"s": 27389,
"text": "Java"
},
{
"code": null,
"e": 27408,
"s": 27394,
"text": "Java Programs"
},
{
"code": null,
"e": 27413,
"s": 27408,
"text": "Java"
},
{
"code": null,
"e": 27511,
"s": 27413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27520,
"s": 27511,
"text": "Comments"
},
{
"code": null,
"e": 27533,
"s": 27520,
"text": "Old Comments"
},
{
"code": null,
"e": 27579,
"s": 27533,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27600,
"s": 27579,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27615,
"s": 27600,
"text": "Stream In Java"
},
{
"code": null,
"e": 27632,
"s": 27615,
"text": "Generics in Java"
},
{
"code": null,
"e": 27651,
"s": 27632,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27695,
"s": 27651,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27721,
"s": 27695,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27755,
"s": 27721,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27802,
"s": 27755,
"text": "Implementing a Linked List in Java using Class"
}
] |
XML - Databases
|
XML Database is used to store huge amount of information in the XML format. As the use of XML is increasing in every field, it is required to have a secured place to store the XML documents. The data stored in the database can be queried using XQuery, serialized, and exported into a desired format.
There are two major types of XML databases −
XML- enabled
Native XML (NXD)
XML enabled database is nothing but the extension provided for the conversion of XML document. This is a relational database, where data is stored in tables consisting of rows and columns. The tables contain set of records, which in turn consist of fields.
Native XML database is based on the container rather than table format. It can store large amount of XML document and data. Native XML database is queried by the XPath-expressions.
Native XML database has an advantage over the XML-enabled database. It is highly capable to store, query and maintain the XML document than XML-enabled database.
Following example demonstrates XML database −
<?xml version = "1.0"?>
<contact-info>
<contact1>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact1>
<contact2>
<name>Manisha Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 789-4567</phone>
</contact2>
</contact-info>
Here, a table of contacts is created that holds the records of contacts (contact1 and contact2), which in turn consists of three entities − name, company and phone.
84 Lectures
6 hours
Frahaan Hussain
29 Lectures
2 hours
YouAccel
27 Lectures
1 hours
Jordan Stanchev
16 Lectures
2 hours
Simon Sez IT
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2261,
"s": 1961,
"text": "XML Database is used to store huge amount of information in the XML format. As the use of XML is increasing in every field, it is required to have a secured place to store the XML documents. The data stored in the database can be queried using XQuery, serialized, and exported into a desired format."
},
{
"code": null,
"e": 2306,
"s": 2261,
"text": "There are two major types of XML databases −"
},
{
"code": null,
"e": 2319,
"s": 2306,
"text": "XML- enabled"
},
{
"code": null,
"e": 2336,
"s": 2319,
"text": "Native XML (NXD)"
},
{
"code": null,
"e": 2593,
"s": 2336,
"text": "XML enabled database is nothing but the extension provided for the conversion of XML document. This is a relational database, where data is stored in tables consisting of rows and columns. The tables contain set of records, which in turn consist of fields."
},
{
"code": null,
"e": 2774,
"s": 2593,
"text": "Native XML database is based on the container rather than table format. It can store large amount of XML document and data. Native XML database is queried by the XPath-expressions."
},
{
"code": null,
"e": 2936,
"s": 2774,
"text": "Native XML database has an advantage over the XML-enabled database. It is highly capable to store, query and maintain the XML document than XML-enabled database."
},
{
"code": null,
"e": 2982,
"s": 2936,
"text": "Following example demonstrates XML database −"
},
{
"code": null,
"e": 3314,
"s": 2982,
"text": "<?xml version = \"1.0\"?>\n<contact-info>\n <contact1>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n </contact1>\n\t\n <contact2>\n <name>Manisha Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 789-4567</phone>\n </contact2>\n</contact-info>"
},
{
"code": null,
"e": 3479,
"s": 3314,
"text": "Here, a table of contacts is created that holds the records of contacts (contact1 and contact2), which in turn consists of three entities − name, company and phone."
},
{
"code": null,
"e": 3512,
"s": 3479,
"text": "\n 84 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3529,
"s": 3512,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3562,
"s": 3529,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3572,
"s": 3562,
"text": " YouAccel"
},
{
"code": null,
"e": 3605,
"s": 3572,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3622,
"s": 3605,
"text": " Jordan Stanchev"
},
{
"code": null,
"e": 3655,
"s": 3622,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3669,
"s": 3655,
"text": " Simon Sez IT"
},
{
"code": null,
"e": 3676,
"s": 3669,
"text": " Print"
},
{
"code": null,
"e": 3687,
"s": 3676,
"text": " Add Notes"
}
] |
Batch Script - Files
|
In this chapter, we will learn how to create, save, execute, and modify batch files.
Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements.
:: Deletes All files in the Current Directory With Prompts and Warnings
::(Hidden, System, and Read-Only Files are Not Affected)
::
@ECHO OFF
DEL .
DR
After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −
Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts.
Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts.
Don’t name them after common batch files which are available in the system such as ping.cmd.
Don’t name them after common batch files which are available in the system such as ping.cmd.
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
Remember to put the .bat or .cmd at the end of the file name.
Choose the “Save as type” option as “All Files”.
Put the entire file name in quotes “”.
Following are the steps to execute a batch file −
Step 1 − Open the command prompt (cmd.exe).
Step 1 − Open the command prompt (cmd.exe).
Step 2 − Go to the location where the .bat or .cmd file is stored.
Step 2 − Go to the location where the .bat or .cmd file is stored.
Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file.
Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file.
Following are the steps for modifying an existing batch file.
Step 1 − Open windows explorer.
Step 1 − Open windows explorer.
Step 2 − Go to the location where the .bat or .cmd file is stored.
Step 2 − Go to the location where the .bat or .cmd file is stored.
Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing.
Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2254,
"s": 2169,
"text": "In this chapter, we will learn how to create, save, execute, and modify batch files."
},
{
"code": null,
"e": 2457,
"s": 2254,
"text": "Batch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements."
},
{
"code": null,
"e": 2613,
"s": 2457,
"text": ":: Deletes All files in the Current Directory With Prompts and Warnings \n::(Hidden, System, and Read-Only Files are Not Affected) \n:: \n@ECHO OFF \nDEL . \nDR"
},
{
"code": null,
"e": 2805,
"s": 2613,
"text": "After your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −"
},
{
"code": null,
"e": 2918,
"s": 2805,
"text": "Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts."
},
{
"code": null,
"e": 3031,
"s": 2918,
"text": "Try to avoid spaces when naming batch files, it sometime creates issues when they are called from other scripts."
},
{
"code": null,
"e": 3124,
"s": 3031,
"text": "Don’t name them after common batch files which are available in the system such as ping.cmd."
},
{
"code": null,
"e": 3217,
"s": 3124,
"text": "Don’t name them after common batch files which are available in the system such as ping.cmd."
},
{
"code": null,
"e": 3330,
"s": 3217,
"text": "The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind."
},
{
"code": null,
"e": 3392,
"s": 3330,
"text": "Remember to put the .bat or .cmd at the end of the file name."
},
{
"code": null,
"e": 3441,
"s": 3392,
"text": "Choose the “Save as type” option as “All Files”."
},
{
"code": null,
"e": 3480,
"s": 3441,
"text": "Put the entire file name in quotes “”."
},
{
"code": null,
"e": 3530,
"s": 3480,
"text": "Following are the steps to execute a batch file −"
},
{
"code": null,
"e": 3574,
"s": 3530,
"text": "Step 1 − Open the command prompt (cmd.exe)."
},
{
"code": null,
"e": 3618,
"s": 3574,
"text": "Step 1 − Open the command prompt (cmd.exe)."
},
{
"code": null,
"e": 3685,
"s": 3618,
"text": "Step 2 − Go to the location where the .bat or .cmd file is stored."
},
{
"code": null,
"e": 3752,
"s": 3685,
"text": "Step 2 − Go to the location where the .bat or .cmd file is stored."
},
{
"code": null,
"e": 3874,
"s": 3752,
"text": "Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file."
},
{
"code": null,
"e": 3996,
"s": 3874,
"text": "Step 3 − Write the name of the file as shown in the following image and press the Enter button to execute the batch file."
},
{
"code": null,
"e": 4058,
"s": 3996,
"text": "Following are the steps for modifying an existing batch file."
},
{
"code": null,
"e": 4090,
"s": 4058,
"text": "Step 1 − Open windows explorer."
},
{
"code": null,
"e": 4122,
"s": 4090,
"text": "Step 1 − Open windows explorer."
},
{
"code": null,
"e": 4189,
"s": 4122,
"text": "Step 2 − Go to the location where the .bat or .cmd file is stored."
},
{
"code": null,
"e": 4256,
"s": 4189,
"text": "Step 2 − Go to the location where the .bat or .cmd file is stored."
},
{
"code": null,
"e": 4389,
"s": 4256,
"text": "Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing."
},
{
"code": null,
"e": 4522,
"s": 4389,
"text": "Step 3 − Right-click the file and choose the “Edit” option from the context menu. The file will open in Notepad for further editing."
},
{
"code": null,
"e": 4529,
"s": 4522,
"text": " Print"
},
{
"code": null,
"e": 4540,
"s": 4529,
"text": " Add Notes"
}
] |
Dynamically Add/Delete HTML Table Rows Using Javascript
|
Theory of Computation
In this article, you will learn how to create a simple user interface where a user can add or delete multiple table rows in a form dynamically using Javascript.
Sometimes, there may be a requirement for the user to add multiple repeated row's fields in a form. We cannot assume how many fields we should provide on the webpage. Like, we need to provide some employees details. There is no surety of how many employee details, may be later we have to delete some. Let's discuss how we can achieve these tasks. In this post, we will write code to add or remove the entire row with there input fields dynamically using Javascript. We will provide two buttons, the first button to add new rows to the table and the second to remove rows.
As we know, Javascript is a dynamic language. It means it can control, access and manipulate the HTML elements dynamically on the client side. We can easily add and remove HTML elements in a web page using Javascript. In this article, we will provide you with a simple way to add or remove HTML table rows with there fields dynamically. The below code has an HTML form and two javascript functions addRows() and deleteRows() to add and delete the table rows respectively.
<html>
<head>
<title>Onclick increase Table Rows</title>
<script type="text/javascript">
function addRows(){
var table = document.getElementById('emptbl');
var rowCount = table.rows.length;
var cellCount = table.rows[0].cells.length;
var row = table.insertRow(rowCount);
for(var i =0; i <= cellCount; i++){
var cell = 'cell'+i;
cell = row.insertCell(i);
var copycel = document.getElementById('col'+i).innerHTML;
cell.innerHTML=copycel;
if(i == 3){
var radioinput = document.getElementById('col3').getElementsByTagName('input');
for(var j = 0; j <= radioinput.length; j++) {
if(radioinput[j].type == 'radio') {
var rownum = rowCount;
radioinput[j].name = 'gender['+rownum+']';
}
}
}
}
}
function deleteRows(){
var table = document.getElementById('emptbl');
var rowCount = table.rows.length;
if(rowCount > '2'){
var row = table.deleteRow(rowCount-1);
rowCount--;
}
else{
alert('There should be atleast one row');
}
}
</script>
</head>
<body>
<form action="#" method="post">
<table id="emptbl">
<tr>
<th>Employee Name</th>
<th>Phone</th>
<th>Department</th>
<th>Gender</th>
</tr>
<tr>
<td id="col0"><input type="text" name="empname[]" value="" /></td>
<td id="col1"><input type="text" name="phone[]" value="" /></td>
<td id="col2">
<select name="department[]" id="dept">
<option value="0">Select Department</option>
<option value="1">Sales</option>
<option value="2">IT</option>
<option value="3">Warehouse</option>
</select>
</td>
<td id="col3">
<input type="radio" name="gender[0]" value="male" />Male
<input type="radio" name="gender[1]" value="female" />Female
</td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRows()" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRows()" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
In the above code, we have taken a form element with three buttons to Add Row, Delete Row and Submit form data. Within the form element, we have taken a table to display the form input data. To perform dynamic operations on the table using Javascript, we have given an id 'emptbl' to the table.
These are the step-by-step code explanations on how a new row is dynamically created when user clicks on the 'Add Row' button.
addRows() - Within the head section, we have created a Javascript function name addRows() that is responsible for adding a new table row with input fields. For this, first we got the table element with table id and stored in a javascript variable table.
var table = document.getElementById('emptbl');
Next, we stored the number of <tr> element using the Javascript property rows.length in a variable rowCount and rows[0].cells.length property returns number of <td> elements of first row.
var rowCount = table.rows.length;
var cellCount = table.rows[0].cells.length;
Next, we have created an empty row using Javascript property insertRow().
var row = table.insertRow(rowCount);
Next, we have dynamically generated the cells within the empty row using a for loop and taken the innerHTML of the old cell with cell index and paste it in the new one.
for(var i =0; i <= cellCount; i++){
}
These are the step-by-step code explanations on how an existing row is dynamically deleted when a user clicks the 'Delete Row' button.
deleteRows() - Within the head section after addRows() function, we have created other Javascript function name deleteRows() that is responsible to delete existing table row with input fields. For this, first we got the table element with table id and stored in a variable table.
Next, we stored the number of <tr> element using property rows.length in a variable rowCount.
var rowCount = table.rows.length;
Next, using the IF Else statement, we have checked whether the number of table rows is greater than one or not.
if(rowCount > '2'){
}
If it is TRUE, then it deletes one row with the Javascript property deleteRow() and decrement the number of rows by one.
var row = table.deleteRow(rowCount-1);
rowCount--;
We hope this code helps someone. You can implement this easily with minor edits. During implementation, please take care of table id and columns id.
Download and open PDF file using Ajax
Javascript window location
How to reverse a number in Javascript
How to reverse string in Javascript
PHP script to read email inbox How to retrieve data from database without refreshing page Print specific part of webpage Store Emoji character in MySQL using PHP PHP Display PDF file from Database Jquery ajax loop through data Dynamically add/remove rows in html table using jquery Submit form without page refresh using javascript PHP Form Validation Tutorial Google reCAPTCHA v3 PHP example Select/deselect all checkboxes using Javascript
Javascript speech recognition example
Image popup on page load using HTML and jQuery
jQuery File upload progress bar with file size validation
Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...
Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...
In this article, we have mentioned the analyzed results of the best programming language for 2021...
Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...
Python has a set of useful Libraries and Packages that minimize the use of code...
July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...
Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...
eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.
|
[
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 273,
"s": 112,
"text": "In this article, you will learn how to create a simple user interface where a user can add or delete multiple table rows in a form dynamically using Javascript."
},
{
"code": null,
"e": 846,
"s": 273,
"text": "Sometimes, there may be a requirement for the user to add multiple repeated row's fields in a form. We cannot assume how many fields we should provide on the webpage. Like, we need to provide some employees details. There is no surety of how many employee details, may be later we have to delete some. Let's discuss how we can achieve these tasks. In this post, we will write code to add or remove the entire row with there input fields dynamically using Javascript. We will provide two buttons, the first button to add new rows to the table and the second to remove rows."
},
{
"code": null,
"e": 1318,
"s": 846,
"text": "As we know, Javascript is a dynamic language. It means it can control, access and manipulate the HTML elements dynamically on the client side. We can easily add and remove HTML elements in a web page using Javascript. In this article, we will provide you with a simple way to add or remove HTML table rows with there fields dynamically. The below code has an HTML form and two javascript functions addRows() and deleteRows() to add and delete the table rows respectively."
},
{
"code": null,
"e": 3342,
"s": 1318,
"text": "<html>\n<head>\n<title>Onclick increase Table Rows</title>\n<script type=\"text/javascript\">\nfunction addRows(){ \n\tvar table = document.getElementById('emptbl');\n\tvar rowCount = table.rows.length;\n\tvar cellCount = table.rows[0].cells.length; \n\tvar row = table.insertRow(rowCount);\n\tfor(var i =0; i <= cellCount; i++){\n\t\tvar cell = 'cell'+i;\n\t\tcell = row.insertCell(i);\n\t\tvar copycel = document.getElementById('col'+i).innerHTML;\n\t\tcell.innerHTML=copycel;\n\t\tif(i == 3){ \n\t\t\tvar radioinput = document.getElementById('col3').getElementsByTagName('input'); \n\t\t\tfor(var j = 0; j <= radioinput.length; j++) { \n\t\t\t\tif(radioinput[j].type == 'radio') { \n\t\t\t\t\tvar rownum = rowCount;\n\t\t\t\t\tradioinput[j].name = 'gender['+rownum+']';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nfunction deleteRows(){\n\tvar table = document.getElementById('emptbl');\n\tvar rowCount = table.rows.length;\n\tif(rowCount > '2'){\n\t\tvar row = table.deleteRow(rowCount-1);\n\t\trowCount--;\n\t}\n\telse{\n\t\talert('There should be atleast one row');\n\t}\n}\n</script>\n</head>\n<body>\n<form action=\"#\" method=\"post\"> \n\t<table id=\"emptbl\">\n\t\t<tr>\n\t\t\t<th>Employee Name</th>\n\t\t\t<th>Phone</th>\n\t\t\t<th>Department</th> \n\t\t\t<th>Gender</th> \n\t\t</tr> \n\t\t<tr> \n\t\t\t<td id=\"col0\"><input type=\"text\" name=\"empname[]\" value=\"\" /></td> \n\t\t\t<td id=\"col1\"><input type=\"text\" name=\"phone[]\" value=\"\" /></td> \n\t\t\t<td id=\"col2\"> \n\t\t\t<select name=\"department[]\" id=\"dept\"> \n\t\t\t<option value=\"0\">Select Department</option> \n\t\t\t<option value=\"1\">Sales</option>\n\t\t\t<option value=\"2\">IT</option>\n\t\t\t<option value=\"3\">Warehouse</option>\n\t\t\t</select> \n\t\t </td> \n\t\t <td id=\"col3\"> \n\t\t\t<input type=\"radio\" name=\"gender[0]\" value=\"male\" />Male \n\t\t\t<input type=\"radio\" name=\"gender[1]\" value=\"female\" />Female \n\t\t </td> \n\t\t</tr> \n\t</table> \n\t<table> \n\t\t<tr> \n\t\t\t<td><input type=\"button\" value=\"Add Row\" onclick=\"addRows()\" /></td> \n\t\t\t<td><input type=\"button\" value=\"Delete Row\" onclick=\"deleteRows()\" /></td> \n\t\t\t<td><input type=\"submit\" value=\"Submit\" /></td> \n\t\t</tr> \n\t</table> \n </form> \n</body> \n</html>\n"
},
{
"code": null,
"e": 3637,
"s": 3342,
"text": "In the above code, we have taken a form element with three buttons to Add Row, Delete Row and Submit form data. Within the form element, we have taken a table to display the form input data. To perform dynamic operations on the table using Javascript, we have given an id 'emptbl' to the table."
},
{
"code": null,
"e": 3764,
"s": 3637,
"text": "These are the step-by-step code explanations on how a new row is dynamically created when user clicks on the 'Add Row' button."
},
{
"code": null,
"e": 4018,
"s": 3764,
"text": "addRows() - Within the head section, we have created a Javascript function name addRows() that is responsible for adding a new table row with input fields. For this, first we got the table element with table id and stored in a javascript variable table."
},
{
"code": null,
"e": 4065,
"s": 4018,
"text": "var table = document.getElementById('emptbl');"
},
{
"code": null,
"e": 4253,
"s": 4065,
"text": "Next, we stored the number of <tr> element using the Javascript property rows.length in a variable rowCount and rows[0].cells.length property returns number of <td> elements of first row."
},
{
"code": null,
"e": 4331,
"s": 4253,
"text": "var rowCount = table.rows.length;\nvar cellCount = table.rows[0].cells.length;"
},
{
"code": null,
"e": 4405,
"s": 4331,
"text": "Next, we have created an empty row using Javascript property insertRow()."
},
{
"code": null,
"e": 4442,
"s": 4405,
"text": "var row = table.insertRow(rowCount);"
},
{
"code": null,
"e": 4611,
"s": 4442,
"text": "Next, we have dynamically generated the cells within the empty row using a for loop and taken the innerHTML of the old cell with cell index and paste it in the new one."
},
{
"code": null,
"e": 4650,
"s": 4611,
"text": "for(var i =0; i <= cellCount; i++){\n\n}"
},
{
"code": null,
"e": 4785,
"s": 4650,
"text": "These are the step-by-step code explanations on how an existing row is dynamically deleted when a user clicks the 'Delete Row' button."
},
{
"code": null,
"e": 5065,
"s": 4785,
"text": "deleteRows() - Within the head section after addRows() function, we have created other Javascript function name deleteRows() that is responsible to delete existing table row with input fields. For this, first we got the table element with table id and stored in a variable table."
},
{
"code": null,
"e": 5159,
"s": 5065,
"text": "Next, we stored the number of <tr> element using property rows.length in a variable rowCount."
},
{
"code": null,
"e": 5193,
"s": 5159,
"text": "var rowCount = table.rows.length;"
},
{
"code": null,
"e": 5305,
"s": 5193,
"text": "Next, using the IF Else statement, we have checked whether the number of table rows is greater than one or not."
},
{
"code": null,
"e": 5328,
"s": 5305,
"text": "if(rowCount > '2'){\n\n}"
},
{
"code": null,
"e": 5449,
"s": 5328,
"text": "If it is TRUE, then it deletes one row with the Javascript property deleteRow() and decrement the number of rows by one."
},
{
"code": null,
"e": 5500,
"s": 5449,
"text": "var row = table.deleteRow(rowCount-1);\nrowCount--;"
},
{
"code": null,
"e": 5649,
"s": 5500,
"text": "We hope this code helps someone. You can implement this easily with minor edits. During implementation, please take care of table id and columns id."
},
{
"code": null,
"e": 6384,
"s": 5649,
"text": "Download and open PDF file using Ajax\nJavascript window location \nHow to reverse a number in Javascript \nHow to reverse string in Javascript \nPHP script to read email inbox How to retrieve data from database without refreshing page Print specific part of webpage Store Emoji character in MySQL using PHP PHP Display PDF file from Database Jquery ajax loop through data Dynamically add/remove rows in html table using jquery Submit form without page refresh using javascript PHP Form Validation Tutorial Google reCAPTCHA v3 PHP example Select/deselect all checkboxes using Javascript\n Javascript speech recognition example\n Image popup on page load using HTML and jQuery\n jQuery File upload progress bar with file size validation\n "
},
{
"code": null,
"e": 6530,
"s": 6384,
"text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n"
},
{
"code": null,
"e": 6646,
"s": 6530,
"text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..."
},
{
"code": null,
"e": 6799,
"s": 6646,
"text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n"
},
{
"code": null,
"e": 6900,
"s": 6799,
"text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..."
},
{
"code": null,
"e": 7039,
"s": 6900,
"text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n"
},
{
"code": null,
"e": 7122,
"s": 7039,
"text": "Python has a set of useful Libraries and Packages that minimize the use of code..."
},
{
"code": null,
"e": 7288,
"s": 7122,
"text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n"
},
{
"code": null,
"e": 7422,
"s": 7288,
"text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..."
},
{
"code": null,
"e": 7589,
"s": 7422,
"text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n"
},
{
"code": null,
"e": 7710,
"s": 7589,
"text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..."
}
] |
C++ Break and Continue
|
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a
loop.
This example jumps out of the loop when i is equal to 4:
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
You can also use break and continue in while loops:
Stop the loop if i is 5:
for (int i = 0; i < 10; i++) {
if (i == 5) {
;
}
cout << i << "\n";
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 136,
"s": 0,
"text": "You have already seen the break statement used in an earlier chapter of this tutorial. It was used to \"jump out\" of a switch statement."
},
{
"code": null,
"e": 197,
"s": 136,
"text": "The break statement can also be used to jump out of a \nloop."
},
{
"code": null,
"e": 254,
"s": 197,
"text": "This example jumps out of the loop when i is equal to 4:"
},
{
"code": null,
"e": 397,
"s": 254,
"text": "The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop."
},
{
"code": null,
"e": 432,
"s": 397,
"text": "This example skips the value of 4:"
},
{
"code": null,
"e": 484,
"s": 432,
"text": "You can also use break and continue in while loops:"
},
{
"code": null,
"e": 509,
"s": 484,
"text": "Stop the loop if i is 5:"
},
{
"code": null,
"e": 593,
"s": 509,
"text": "for (int i = 0; i < 10; i++) {\n if (i == 5) { \n ;\n }\n cout << i << \"\\n\";\n}\n"
},
{
"code": null,
"e": 612,
"s": 593,
"text": "Start the Exercise"
},
{
"code": null,
"e": 645,
"s": 612,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 687,
"s": 645,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 794,
"s": 687,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 813,
"s": 794,
"text": "help@w3schools.com"
}
] |
Longest Mountain in Array in C++
|
Consider any (contiguous) subarray B (of A) a called mountain if the following properties hold −
size of B >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
Suppose we have an array A of integers; we have to find the length of the longest mountain. We have to return 0 if there is no mountain. So if the input is like [2,1,4,7,3,2,5], then the result will be 5. So the largest mountain will be [1,4,7,3,2], whose length is 5.
To solve this, we will follow these steps −
ret := 0, n := size of array a
i := 0 to n – 1, increase i by j + 1j := idown := false, up := falsewhile j + 1 < n and a[j + 1] > a[j]up := true and increase j by 1while up is true and j + 1 < n and a[j + 1] > a[j]down := true and increase j by 1if up and down both are true, set ret := max of j – i + 1 and ret, decrease j by 1
j := i
down := false, up := false
while j + 1 < n and a[j + 1] > a[j]up := true and increase j by 1
up := true and increase j by 1
while up is true and j + 1 < n and a[j + 1] > a[j]down := true and increase j by 1
down := true and increase j by 1
if up and down both are true, set ret := max of j – i + 1 and ret, decrease j by 1
return ret.
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestMountain(vector<int>& a) {
int ret = 0;
int n = a.size();
int j;
for(int i = 0; i < n; i = j + 1){
j = i;
bool down = false;
bool up = false;
while(j + 1 < n && a[j + 1] > a[j]) {
up = true;
j++;
}
while(up && j + 1 < n && a[j + 1] < a[j]){
down = true;
j++;
}
if(up && down){
ret = max(j - i + 1, ret);
j--;
}
}
return ret;
}
};
main(){
vector<int> v = {2,1,4,7,3,2,5};
Solution ob;
cout << (ob.longestMountain(v));
}
[2,1,4,7,3,2,5]
5
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Consider any (contiguous) subarray B (of A) a called mountain if the following properties hold −"
},
{
"code": null,
"e": 1174,
"s": 1159,
"text": "size of B >= 3"
},
{
"code": null,
"e": 1288,
"s": 1174,
"text": "There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]"
},
{
"code": null,
"e": 1557,
"s": 1288,
"text": "Suppose we have an array A of integers; we have to find the length of the longest mountain. We have to return 0 if there is no mountain. So if the input is like [2,1,4,7,3,2,5], then the result will be 5. So the largest mountain will be [1,4,7,3,2], whose length is 5."
},
{
"code": null,
"e": 1601,
"s": 1557,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1632,
"s": 1601,
"text": "ret := 0, n := size of array a"
},
{
"code": null,
"e": 1930,
"s": 1632,
"text": "i := 0 to n – 1, increase i by j + 1j := idown := false, up := falsewhile j + 1 < n and a[j + 1] > a[j]up := true and increase j by 1while up is true and j + 1 < n and a[j + 1] > a[j]down := true and increase j by 1if up and down both are true, set ret := max of j – i + 1 and ret, decrease j by 1"
},
{
"code": null,
"e": 1937,
"s": 1930,
"text": "j := i"
},
{
"code": null,
"e": 1964,
"s": 1937,
"text": "down := false, up := false"
},
{
"code": null,
"e": 2030,
"s": 1964,
"text": "while j + 1 < n and a[j + 1] > a[j]up := true and increase j by 1"
},
{
"code": null,
"e": 2061,
"s": 2030,
"text": "up := true and increase j by 1"
},
{
"code": null,
"e": 2144,
"s": 2061,
"text": "while up is true and j + 1 < n and a[j + 1] > a[j]down := true and increase j by 1"
},
{
"code": null,
"e": 2177,
"s": 2144,
"text": "down := true and increase j by 1"
},
{
"code": null,
"e": 2260,
"s": 2177,
"text": "if up and down both are true, set ret := max of j – i + 1 and ret, decrease j by 1"
},
{
"code": null,
"e": 2272,
"s": 2260,
"text": "return ret."
},
{
"code": null,
"e": 2342,
"s": 2272,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2353,
"s": 2342,
"text": " Live Demo"
},
{
"code": null,
"e": 3058,
"s": 2353,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int longestMountain(vector<int>& a) {\n int ret = 0;\n int n = a.size();\n int j;\n for(int i = 0; i < n; i = j + 1){\n j = i;\n bool down = false;\n bool up = false;\n while(j + 1 < n && a[j + 1] > a[j]) {\n up = true;\n j++;\n }\n while(up && j + 1 < n && a[j + 1] < a[j]){\n down = true;\n j++;\n }\n if(up && down){\n ret = max(j - i + 1, ret);\n j--;\n }\n }\n return ret;\n }\n};\nmain(){\n vector<int> v = {2,1,4,7,3,2,5};\n Solution ob;\n cout << (ob.longestMountain(v));\n}"
},
{
"code": null,
"e": 3074,
"s": 3058,
"text": "[2,1,4,7,3,2,5]"
},
{
"code": null,
"e": 3076,
"s": 3074,
"text": "5"
}
] |
How to delete a column from Pandas DataFrame
|
To delete a column from a DataFrame, use del(). You can also use pop() method to delete. Just drop it using square brackets. Mention the column to be deleted in the brackets and that’s it, for example −
del dataFrame[‘ColumnName’]
Import the required library with an alias −
import pandas as pd
Create a Pandas DataFrame −
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
Now, delete a column “Car” from a DataFrame −
del dataFrame['Car']
Following is the code −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame ...\n",dataFrame
# deleting a column
del dataFrame['Car']
print"\nDataFrame after deleting a column = \n",dataFrame
This will produce the following output −
DataFrame ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Mustang 80
4 Bentley 110
5 Jaguar 90
DataFrame after deleting a column =
Units
0 100
1 150
2 110
3 80
4 110
5 90
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "To delete a column from a DataFrame, use del(). You can also use pop() method to delete. Just drop it using square brackets. Mention the column to be deleted in the brackets and that’s it, for example −"
},
{
"code": null,
"e": 1293,
"s": 1265,
"text": "del dataFrame[‘ColumnName’]"
},
{
"code": null,
"e": 1337,
"s": 1293,
"text": "Import the required library with an alias −"
},
{
"code": null,
"e": 1357,
"s": 1337,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1385,
"s": 1357,
"text": "Create a Pandas DataFrame −"
},
{
"code": null,
"e": 1540,
"s": 1385,
"text": "dataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\n"
},
{
"code": null,
"e": 1586,
"s": 1540,
"text": "Now, delete a column “Car” from a DataFrame −"
},
{
"code": null,
"e": 1607,
"s": 1586,
"text": "del dataFrame['Car']"
},
{
"code": null,
"e": 1631,
"s": 1607,
"text": "Following is the code −"
},
{
"code": null,
"e": 1959,
"s": 1631,
"text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame ...\\n\",dataFrame\n\n# deleting a column\ndel dataFrame['Car']\n\nprint\"\\nDataFrame after deleting a column = \\n\",dataFrame"
},
{
"code": null,
"e": 2000,
"s": 1959,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2235,
"s": 2000,
"text": "DataFrame ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Mustang 80\n4 Bentley 110\n5 Jaguar 90\n\nDataFrame after deleting a column =\n Units\n0 100\n1 150\n2 110\n3 80\n4 110\n5 90"
}
] |
Python - Recursion
|
Recursion allows a function to call itself. Fixed steps of code get executed again and again for new values. We also have to set criteria for deciding when the recursive call ends. In the below example we see a recursive approach to the binary search. We take a sorted list and give its index range as input to the recursive function.
We implement the algorithm of binary search using python as shown below. We use an ordered list of items and design a recursive function to take in the list along with starting and ending index as input. Then, the binary search function calls itself till find the searched item or concludes about its absence in the list.
def bsearch(list, idx0, idxn, val):
if (idxn < idx0):
return None
else:
midval = idx0 + ((idxn - idx0) // 2)
# Compare the search item with middle most value
if list[midval] > val:
return bsearch(list, idx0, midval-1,val)
else if list[midval] < val:
return bsearch(list, midval+1, idxn, val)
else:
return midval
list = [8,11,24,56,88,131]
print(bsearch(list, 0, 5, 24))
print(bsearch(list, 0, 5, 51))
When the above code is executed, it produces the following result −
2
None
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2662,
"s": 2327,
"text": "Recursion allows a function to call itself. Fixed steps of code get executed again and again for new values. We also have to set criteria for deciding when the recursive call ends. In the below example we see a recursive approach to the binary search. We take a sorted list and give its index range as input to the recursive function."
},
{
"code": null,
"e": 2984,
"s": 2662,
"text": "We implement the algorithm of binary search using python as shown below. We use an ordered list of items and design a recursive function to take in the list along with starting and ending index as input. Then, the binary search function calls itself till find the searched item or concludes about its absence in the list."
},
{
"code": null,
"e": 3430,
"s": 2984,
"text": "def bsearch(list, idx0, idxn, val):\n if (idxn < idx0):\n return None\n else:\n midval = idx0 + ((idxn - idx0) // 2)\n# Compare the search item with middle most value\n if list[midval] > val:\n return bsearch(list, idx0, midval-1,val)\n else if list[midval] < val:\n return bsearch(list, midval+1, idxn, val)\n else:\n return midval\nlist = [8,11,24,56,88,131]\nprint(bsearch(list, 0, 5, 24))\nprint(bsearch(list, 0, 5, 51))"
},
{
"code": null,
"e": 3498,
"s": 3430,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3506,
"s": 3498,
"text": "2\nNone\n"
},
{
"code": null,
"e": 3543,
"s": 3506,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3559,
"s": 3543,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3592,
"s": 3559,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3611,
"s": 3592,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3646,
"s": 3611,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3668,
"s": 3646,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3702,
"s": 3668,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3730,
"s": 3702,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3765,
"s": 3730,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3779,
"s": 3765,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3812,
"s": 3779,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3829,
"s": 3812,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3836,
"s": 3829,
"text": " Print"
},
{
"code": null,
"e": 3847,
"s": 3836,
"text": " Add Notes"
}
] |
How to bitwise XOR of hex numbers in Python?
|
You can get the XOR of any type of numbers using the ^ operator. Specifically for hex numbers, you can use:
a = 0x12ef
b = 0xabcd
print(hex(a ^ b))
This will give the output:
0xb922
The 0x at the beginning of the numbers implies that the number is in hex representation. You can use the ^ operator for other integer representations as well.
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "You can get the XOR of any type of numbers using the ^ operator. Specifically for hex numbers, you can use:"
},
{
"code": null,
"e": 1210,
"s": 1170,
"text": "a = 0x12ef\nb = 0xabcd\nprint(hex(a ^ b))"
},
{
"code": null,
"e": 1237,
"s": 1210,
"text": "This will give the output:"
},
{
"code": null,
"e": 1244,
"s": 1237,
"text": "0xb922"
},
{
"code": null,
"e": 1403,
"s": 1244,
"text": "The 0x at the beginning of the numbers implies that the number is in hex representation. You can use the ^ operator for other integer representations as well."
}
] |
How to enable vertical scroll bar for android webview?
|
This example demonstrate about How to set default text encoded for android webview.
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"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show facebook.com.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.setVerticalScrollBarEnabled(true);
web_view.requestFocus();
web_view.getSettings().setDefaultTextEncodingName("utf-8");
web_view.getSettings().setJavaScriptEnabled(true);
web_view.loadUrl("https://touch.facebook.com/");
web_view.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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": 1146,
"s": 1062,
"text": "This example demonstrate about How to set default text encoded for android webview."
},
{
"code": null,
"e": 1275,
"s": 1146,
"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": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1907,
"s": 1340,
"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 android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1971,
"s": 1907,
"text": "In the above code, we have taken web view to show facebook.com."
},
{
"code": null,
"e": 2028,
"s": 1971,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3775,
"s": 2028,
"text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.CookieManager;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.setVerticalScrollBarEnabled(true);\n web_view.requestFocus();\n web_view.getSettings().setDefaultTextEncodingName(\"utf-8\");\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.loadUrl(\"https://touch.facebook.com/\");\n web_view.setWebViewClient(new WebViewClient() {\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n });\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3830,
"s": 3775,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4607,
"s": 3830,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4954,
"s": 4607,
"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": 4994,
"s": 4954,
"text": "Click here to download the project code"
}
] |
Capsule Neural Networks: The Next Neural Networks? Part 1: CNNs and their problems. | by Tomer Eldor | Towards Data Science
|
This is part of a series of posts built to teach about Capsule Neural Networks. This first post will explain about “normal” (convolutional) Neural Networks and their problems.
Neural Networks may be the hottest field in Machine Learning. In recent years, there were many new developments improving neural networks and building making them more accessible. However, they were mostly incremental, such as adding more layers or slightly improving the activation function, but did not introduce a new type of architecture or topic. Geoffery Hinton is one of the founding fathers of many highly utilized deep learning algorithms including many developments to Neural Networks — no wonder, for having Neurosciences and Artificial Intelligence background. At late October 2017, Geoffrey Hinton, Sara Sabour, and Nicholas Frosst Published a research paper under Google Brain named “Dynamic Routing Between Capsules”, introducing a true innovation to Neural Networks. This is exciting, since such development has been long awaited for, will likely spur much more research and progress around it, and is supposed to make neural networks even better than they are now.
Convolutional Neural Networks (CNNs) are extremely flexible machine learning models which were originally inspired by principles from how our brains are theorized to work.
Neural Networks utilize layers of “neurons” to process raw data into patterns and objects.
The primary building blocks of a Neural Network is a “Convolutional” layer (hence the name). What does it do? It takes raw information from a previous layer, makes sense of patterns in it, and send it onward to the next layer to make sense of a larger picture. If you are new to neural networks and want to understand it, I recommend:
Watching the animated videos by 3Blue1Brown.For a more detailed textual/visual guide, you can check out this beginner’s blogpostIf you can deal with some more math and greater details, you can read instead this guide from CS231 at Stanford. In case you didn’t do any of the above, and plan to continue, here is a hand-wavy brief overview.
Watching the animated videos by 3Blue1Brown.
For a more detailed textual/visual guide, you can check out this beginner’s blogpost
If you can deal with some more math and greater details, you can read instead this guide from CS231 at Stanford. In case you didn’t do any of the above, and plan to continue, here is a hand-wavy brief overview.
Let’s start from the beginning. The Neural Net receives raw input data. Let’s say it’s a doodle of a dog. When you see a dog, you brain automatically detects it’s a dog. But to the computer, the image is really just an array of numbers representing the colors intensity in the colors channels. Let’s say it’s just a Black&White doodle, so we can represent it with one array where each cell represents the brightness of the pixel from black to white.
What is our goal? Our goal is for the net to make visual sense of what is in the picture (which is for it just a sequence of numbers). One way to do it is bottom-up: start by looking at small groups of pixels, make sense of them (like small lines and curves: the curve of the dog’s ear, the small circle of its pupil, the small line in its leg), then build those up to bigger groups of these lines and curves (like: ear, nose, snout, eye), make sense of bigger groups of these shapes (like: face, leg, tail), and finally make sense of the entire picture of the dog. It does so with many layers transferring information in a sequence from one to another. If this was new to you, see my summary of Convolutional Networks Structure here: Understanding Convolutional Neural Networks. In case you didn’t read it but it’s still new to you, below is an even shorter summary of that summary:
Convolutional Layers. The first convolutional layer maps the image space to a lower space — summarizing what’s happening in each group of, say 5x5 pixels — is it a vertical line? horizontal line? curve of what shape? This happens with element wise multiplication and then summation of all the values in the filter with the original filter value and summing up to a single number.This leads to the Neuron, or convolutional filters. Each Filter / Neuron is designed to react to one specific form (a vertical line? a horizontal line? etc...). The groups of pixels from layer 1 reach these neurons, and lights up the neurons that match its structure according to how much this slice is similar to what the neuron looks for.Activation (usually “ReLU”) Layers — After each convolutional layer, we apply a nonlinear layer (or activation layer), which introduces non-linearity to the system, enabling it to discover also nonlinear relations in the data. ReLU is a very simple one: making any negative input to 0, or if it’s positive — keeping it the same. ReLU(x) = max(0,x).Pooling Layers. This allows to reduce “unnecessary” information, summarize what we know about a region, and continue to refine information. For example, this might be “MaxPooling” where the computer will just take the highest value of the passed this patch — so that the computer knows “around these 5x5 pixels, the most dominant value is 255. I don’t know exactly in which pixel but the exact location isn’t as important as that it’s around there. → Notice: This is not good. We loose information here. Capsule Networks don’t have this operation here, which is an improvement.Dropout Layers. This layer “drops out” a random set of activations in that layer by setting them to zero. This makes the network more robust (kind of like you eating dirt builds up your immunity system, the network is more immune to small changes) and reduces overfitting. This is only used when training the network.Last Fully Connected Layer. For a classification problem, we want each final neuron represents the final class. It looks at the output of the previous layer (which as we remember should represent the activation maps of high level features) and determines which features most correlate to a particular class.SoftMax — This layer is sometimes added as a another way to represent the outputs per classes that we can later pass on in a loss function. Softmax represents the distribution of probabilities to the various categories.
Convolutional Layers. The first convolutional layer maps the image space to a lower space — summarizing what’s happening in each group of, say 5x5 pixels — is it a vertical line? horizontal line? curve of what shape? This happens with element wise multiplication and then summation of all the values in the filter with the original filter value and summing up to a single number.
This leads to the Neuron, or convolutional filters. Each Filter / Neuron is designed to react to one specific form (a vertical line? a horizontal line? etc...). The groups of pixels from layer 1 reach these neurons, and lights up the neurons that match its structure according to how much this slice is similar to what the neuron looks for.
Activation (usually “ReLU”) Layers — After each convolutional layer, we apply a nonlinear layer (or activation layer), which introduces non-linearity to the system, enabling it to discover also nonlinear relations in the data. ReLU is a very simple one: making any negative input to 0, or if it’s positive — keeping it the same. ReLU(x) = max(0,x).
Pooling Layers. This allows to reduce “unnecessary” information, summarize what we know about a region, and continue to refine information. For example, this might be “MaxPooling” where the computer will just take the highest value of the passed this patch — so that the computer knows “around these 5x5 pixels, the most dominant value is 255. I don’t know exactly in which pixel but the exact location isn’t as important as that it’s around there. → Notice: This is not good. We loose information here. Capsule Networks don’t have this operation here, which is an improvement.
Dropout Layers. This layer “drops out” a random set of activations in that layer by setting them to zero. This makes the network more robust (kind of like you eating dirt builds up your immunity system, the network is more immune to small changes) and reduces overfitting. This is only used when training the network.
Last Fully Connected Layer. For a classification problem, we want each final neuron represents the final class. It looks at the output of the previous layer (which as we remember should represent the activation maps of high level features) and determines which features most correlate to a particular class.
SoftMax — This layer is sometimes added as a another way to represent the outputs per classes that we can later pass on in a loss function. Softmax represents the distribution of probabilities to the various categories.
Usually, there are more layers which provide nonlinearities and preservation of dimensions (like padding with 0’s around the edges) that help to improve the robustness of the network and control overfitting. But these are the basics you need to understand what comes after. Now, importantly, these layers are connected only SEQUENTIALLY. This is in contrast to the structure of capsule networks.
If this interests you, watch Hinton's lecture explaining exactly what it wrong with them. Below you'll get a couple of key points that are improved by Capsule Networks.
Hinton says that they have too few levels of substructures (nets are composed from layers composed from neurons, that's it); and that we need to group the neurons in each layer into “capsules”, like mini-columns, that do a lot of internal computations, and then output a summary result.
CNN use “pooling” or equivalent methods to “summarize” what's going on in the smaller regions and make sense of larger and larger chunks of the image. This was a solution that made CNNs work well, but it looses valuable information. Capsule networks will compute a pose (transnational and rotational) relationship between smaller features to make up a larger feature. This loss of information leads to loss of spatial information.
Subsampling (and pooling) loses the precise spatial relationships between higher-level parts like a nose and a mouth. The precise spatial relationships are needed for identity recognition.
(Hinton, 2012, in his lecture). CNNs don't account for spatial relationships between the underlying objects. By having these flat layers of neurons that light up according to which objects they've seen, they recognize the presence of such objects. But then they are passed on to other activation and pooling layers and on to the next layer of neurons (filters), without recognizing what are the relations between these objects we identified in that single layer. They just account for their presence. So a (simplistic) Neural network will not hesitate about categorizing both these dogs, Pablo and Picasso, as similarly good representations of “corgi-pit-bull-terrier mix”.
The network will categorize both these dogs as similarly good representations of “corgi-pit-bull-terrier mix” dogs because they both answer the same conditions at the face composition convolutional layer, for example:
if: (2 eyes & pitbullmix_snout + pitbullmix_wet_nose & mouth)then: pitbullmix_face
Incorrectly activating the neuron for pitbullmix_face, Instead of something like:
if: 2 eyes & BELOW: pitbullmix_snout & pitbullmix_wet_nose & BELOW: mouth then: pitbullmix_face
Conversely, capsule networks represent directionality along with content and connect between capsules of neurons to infer spatial relationships and retain pose information. Lacking a grouped capsule representation, pose calculations, and overlapping check between the capsules leads to the next problem.
This makes them more sensitive to the original image itself in order to classify images as the same category. CNNs are great for solving problems with data similar to what they have been trained on. It can classify images or objects within them which are very close to things it has seen before. But if the object is slightly rotated, photographed from a slightly different angle, especially in 3D, is tilted or in another orientation than what the CNN has seen - the network won't recognize it well. One solution is to artificially create tilted representation of the image or groups and add them to the “training” set. However, this still lacks a fundamentally more robust structure.
So how can we encode spatial relationships between 3D objects? Hinton took inspiration from a field that already solved that problem: 3D computer graphics. In 3D graphics, a pose matrix is a special technique to represent the relationships between objects. Poses are essentially matrices representing translation plus rotation. Now we got it. We can retain spatial relationships information using pose relationships between sub-objects; measuring the relative rotations and translations between objects as a 4D pose matrix. This would be key to understanding dynamic routing between capsules.
Now that we know the basics of Neural Networks and their spatial recognition problems, we can continue to learn about the recently developed solution to that: Capsule Neural Network. That will be the topic of my next post. Stay tuned!
|
[
{
"code": null,
"e": 347,
"s": 171,
"text": "This is part of a series of posts built to teach about Capsule Neural Networks. This first post will explain about “normal” (convolutional) Neural Networks and their problems."
},
{
"code": null,
"e": 1331,
"s": 347,
"text": "Neural Networks may be the hottest field in Machine Learning. In recent years, there were many new developments improving neural networks and building making them more accessible. However, they were mostly incremental, such as adding more layers or slightly improving the activation function, but did not introduce a new type of architecture or topic. Geoffery Hinton is one of the founding fathers of many highly utilized deep learning algorithms including many developments to Neural Networks — no wonder, for having Neurosciences and Artificial Intelligence background. At late October 2017, Geoffrey Hinton, Sara Sabour, and Nicholas Frosst Published a research paper under Google Brain named “Dynamic Routing Between Capsules”, introducing a true innovation to Neural Networks. This is exciting, since such development has been long awaited for, will likely spur much more research and progress around it, and is supposed to make neural networks even better than they are now."
},
{
"code": null,
"e": 1503,
"s": 1331,
"text": "Convolutional Neural Networks (CNNs) are extremely flexible machine learning models which were originally inspired by principles from how our brains are theorized to work."
},
{
"code": null,
"e": 1594,
"s": 1503,
"text": "Neural Networks utilize layers of “neurons” to process raw data into patterns and objects."
},
{
"code": null,
"e": 1930,
"s": 1594,
"text": "The primary building blocks of a Neural Network is a “Convolutional” layer (hence the name). What does it do? It takes raw information from a previous layer, makes sense of patterns in it, and send it onward to the next layer to make sense of a larger picture. If you are new to neural networks and want to understand it, I recommend:"
},
{
"code": null,
"e": 2270,
"s": 1930,
"text": "Watching the animated videos by 3Blue1Brown.For a more detailed textual/visual guide, you can check out this beginner’s blogpostIf you can deal with some more math and greater details, you can read instead this guide from CS231 at Stanford. In case you didn’t do any of the above, and plan to continue, here is a hand-wavy brief overview."
},
{
"code": null,
"e": 2315,
"s": 2270,
"text": "Watching the animated videos by 3Blue1Brown."
},
{
"code": null,
"e": 2400,
"s": 2315,
"text": "For a more detailed textual/visual guide, you can check out this beginner’s blogpost"
},
{
"code": null,
"e": 2612,
"s": 2400,
"text": "If you can deal with some more math and greater details, you can read instead this guide from CS231 at Stanford. In case you didn’t do any of the above, and plan to continue, here is a hand-wavy brief overview."
},
{
"code": null,
"e": 3063,
"s": 2612,
"text": "Let’s start from the beginning. The Neural Net receives raw input data. Let’s say it’s a doodle of a dog. When you see a dog, you brain automatically detects it’s a dog. But to the computer, the image is really just an array of numbers representing the colors intensity in the colors channels. Let’s say it’s just a Black&White doodle, so we can represent it with one array where each cell represents the brightness of the pixel from black to white."
},
{
"code": null,
"e": 3950,
"s": 3063,
"text": "What is our goal? Our goal is for the net to make visual sense of what is in the picture (which is for it just a sequence of numbers). One way to do it is bottom-up: start by looking at small groups of pixels, make sense of them (like small lines and curves: the curve of the dog’s ear, the small circle of its pupil, the small line in its leg), then build those up to bigger groups of these lines and curves (like: ear, nose, snout, eye), make sense of bigger groups of these shapes (like: face, leg, tail), and finally make sense of the entire picture of the dog. It does so with many layers transferring information in a sequence from one to another. If this was new to you, see my summary of Convolutional Networks Structure here: Understanding Convolutional Neural Networks. In case you didn’t read it but it’s still new to you, below is an even shorter summary of that summary:"
},
{
"code": null,
"e": 6438,
"s": 3950,
"text": "Convolutional Layers. The first convolutional layer maps the image space to a lower space — summarizing what’s happening in each group of, say 5x5 pixels — is it a vertical line? horizontal line? curve of what shape? This happens with element wise multiplication and then summation of all the values in the filter with the original filter value and summing up to a single number.This leads to the Neuron, or convolutional filters. Each Filter / Neuron is designed to react to one specific form (a vertical line? a horizontal line? etc...). The groups of pixels from layer 1 reach these neurons, and lights up the neurons that match its structure according to how much this slice is similar to what the neuron looks for.Activation (usually “ReLU”) Layers — After each convolutional layer, we apply a nonlinear layer (or activation layer), which introduces non-linearity to the system, enabling it to discover also nonlinear relations in the data. ReLU is a very simple one: making any negative input to 0, or if it’s positive — keeping it the same. ReLU(x) = max(0,x).Pooling Layers. This allows to reduce “unnecessary” information, summarize what we know about a region, and continue to refine information. For example, this might be “MaxPooling” where the computer will just take the highest value of the passed this patch — so that the computer knows “around these 5x5 pixels, the most dominant value is 255. I don’t know exactly in which pixel but the exact location isn’t as important as that it’s around there. → Notice: This is not good. We loose information here. Capsule Networks don’t have this operation here, which is an improvement.Dropout Layers. This layer “drops out” a random set of activations in that layer by setting them to zero. This makes the network more robust (kind of like you eating dirt builds up your immunity system, the network is more immune to small changes) and reduces overfitting. This is only used when training the network.Last Fully Connected Layer. For a classification problem, we want each final neuron represents the final class. It looks at the output of the previous layer (which as we remember should represent the activation maps of high level features) and determines which features most correlate to a particular class.SoftMax — This layer is sometimes added as a another way to represent the outputs per classes that we can later pass on in a loss function. Softmax represents the distribution of probabilities to the various categories."
},
{
"code": null,
"e": 6818,
"s": 6438,
"text": "Convolutional Layers. The first convolutional layer maps the image space to a lower space — summarizing what’s happening in each group of, say 5x5 pixels — is it a vertical line? horizontal line? curve of what shape? This happens with element wise multiplication and then summation of all the values in the filter with the original filter value and summing up to a single number."
},
{
"code": null,
"e": 7159,
"s": 6818,
"text": "This leads to the Neuron, or convolutional filters. Each Filter / Neuron is designed to react to one specific form (a vertical line? a horizontal line? etc...). The groups of pixels from layer 1 reach these neurons, and lights up the neurons that match its structure according to how much this slice is similar to what the neuron looks for."
},
{
"code": null,
"e": 7508,
"s": 7159,
"text": "Activation (usually “ReLU”) Layers — After each convolutional layer, we apply a nonlinear layer (or activation layer), which introduces non-linearity to the system, enabling it to discover also nonlinear relations in the data. ReLU is a very simple one: making any negative input to 0, or if it’s positive — keeping it the same. ReLU(x) = max(0,x)."
},
{
"code": null,
"e": 8086,
"s": 7508,
"text": "Pooling Layers. This allows to reduce “unnecessary” information, summarize what we know about a region, and continue to refine information. For example, this might be “MaxPooling” where the computer will just take the highest value of the passed this patch — so that the computer knows “around these 5x5 pixels, the most dominant value is 255. I don’t know exactly in which pixel but the exact location isn’t as important as that it’s around there. → Notice: This is not good. We loose information here. Capsule Networks don’t have this operation here, which is an improvement."
},
{
"code": null,
"e": 8404,
"s": 8086,
"text": "Dropout Layers. This layer “drops out” a random set of activations in that layer by setting them to zero. This makes the network more robust (kind of like you eating dirt builds up your immunity system, the network is more immune to small changes) and reduces overfitting. This is only used when training the network."
},
{
"code": null,
"e": 8712,
"s": 8404,
"text": "Last Fully Connected Layer. For a classification problem, we want each final neuron represents the final class. It looks at the output of the previous layer (which as we remember should represent the activation maps of high level features) and determines which features most correlate to a particular class."
},
{
"code": null,
"e": 8932,
"s": 8712,
"text": "SoftMax — This layer is sometimes added as a another way to represent the outputs per classes that we can later pass on in a loss function. Softmax represents the distribution of probabilities to the various categories."
},
{
"code": null,
"e": 9329,
"s": 8932,
"text": "Usually, there are more layers which provide nonlinearities and preservation of dimensions (like padding with 0’s around the edges) that help to improve the robustness of the network and control overfitting. But these are the basics you need to understand what comes after. Now, importantly, these layers are connected only SEQUENTIALLY. This is in contrast to the structure of capsule networks."
},
{
"code": null,
"e": 9498,
"s": 9329,
"text": "If this interests you, watch Hinton's lecture explaining exactly what it wrong with them. Below you'll get a couple of key points that are improved by Capsule Networks."
},
{
"code": null,
"e": 9785,
"s": 9498,
"text": "Hinton says that they have too few levels of substructures (nets are composed from layers composed from neurons, that's it); and that we need to group the neurons in each layer into “capsules”, like mini-columns, that do a lot of internal computations, and then output a summary result."
},
{
"code": null,
"e": 10218,
"s": 9785,
"text": "CNN use “pooling” or equivalent methods to “summarize” what's going on in the smaller regions and make sense of larger and larger chunks of the image. This was a solution that made CNNs work well, but it looses valuable information. Capsule networks will compute a pose (transnational and rotational) relationship between smaller features to make up a larger feature. This loss of information leads to loss of spatial information."
},
{
"code": null,
"e": 10407,
"s": 10218,
"text": "Subsampling (and pooling) loses the precise spatial relationships between higher-level parts like a nose and a mouth. The precise spatial relationships are needed for identity recognition."
},
{
"code": null,
"e": 11085,
"s": 10407,
"text": "(Hinton, 2012, in his lecture). CNNs don't account for spatial relationships between the underlying objects. By having these flat layers of neurons that light up according to which objects they've seen, they recognize the presence of such objects. But then they are passed on to other activation and pooling layers and on to the next layer of neurons (filters), without recognizing what are the relations between these objects we identified in that single layer. They just account for their presence. So a (simplistic) Neural network will not hesitate about categorizing both these dogs, Pablo and Picasso, as similarly good representations of “corgi-pit-bull-terrier mix”."
},
{
"code": null,
"e": 11303,
"s": 11085,
"text": "The network will categorize both these dogs as similarly good representations of “corgi-pit-bull-terrier mix” dogs because they both answer the same conditions at the face composition convolutional layer, for example:"
},
{
"code": null,
"e": 11391,
"s": 11303,
"text": "if: (2 eyes & pitbullmix_snout + pitbullmix_wet_nose & mouth)then: pitbullmix_face"
},
{
"code": null,
"e": 11473,
"s": 11391,
"text": "Incorrectly activating the neuron for pitbullmix_face, Instead of something like:"
},
{
"code": null,
"e": 11574,
"s": 11473,
"text": "if: 2 eyes & BELOW: pitbullmix_snout & pitbullmix_wet_nose & BELOW: mouth then: pitbullmix_face"
},
{
"code": null,
"e": 11880,
"s": 11574,
"text": "Conversely, capsule networks represent directionality along with content and connect between capsules of neurons to infer spatial relationships and retain pose information. Lacking a grouped capsule representation, pose calculations, and overlapping check between the capsules leads to the next problem."
},
{
"code": null,
"e": 12572,
"s": 11880,
"text": "This makes them more sensitive to the original image itself in order to classify images as the same category. CNNs are great for solving problems with data similar to what they have been trained on. It can classify images or objects within them which are very close to things it has seen before. But if the object is slightly rotated, photographed from a slightly different angle, especially in 3D, is tilted or in another orientation than what the CNN has seen - the network won't recognize it well. One solution is to artificially create tilted representation of the image or groups and add them to the “training” set. However, this still lacks a fundamentally more robust structure."
},
{
"code": null,
"e": 13165,
"s": 12572,
"text": "So how can we encode spatial relationships between 3D objects? Hinton took inspiration from a field that already solved that problem: 3D computer graphics. In 3D graphics, a pose matrix is a special technique to represent the relationships between objects. Poses are essentially matrices representing translation plus rotation. Now we got it. We can retain spatial relationships information using pose relationships between sub-objects; measuring the relative rotations and translations between objects as a 4D pose matrix. This would be key to understanding dynamic routing between capsules."
}
] |
UnitTest Framework - Doctest
|
Python' standard distribution contains 'Doctest' module. This module's functionality makes it possible to search for pieces of text that look like interactive Python sessions, and executes these sessions to see if they work exactly as shown.
Doctest can be very useful in the following scenarios −
To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.
To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.
To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
To write tutorial documentation for a package, liberally illustrated with input-output examples
To write tutorial documentation for a package, liberally illustrated with input-output examples
In Python, a 'docstring' is a string literal which appears as the first expression in a class, function or module. It is ignored when the suite is executed, but it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object.
It is a usual practice to put example usage of different parts of Python code inside the docstring. The doctest module allows to verify that these docstrings are up-to-date with the intermittent revisions in code.
In the following code, a factorial function is defined interspersed with example usage. In order to verify if the example usage is correct, call the testmod() function in doctest module.
"""
This is the "example" module.
The example module supplies one function, factorial(). For example,
>>> factorial(5)
120
"""
def factorial(x):
"""Return the factorial of n, an exact integer >= 0.
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: x must be >= 0
"""
if not x >= 0:
raise ValueError("x must be >= 0")
f = 1
for i in range(1,x+1):
f = f*i
return f
if __name__ == "__main__":
import doctest
doctest.testmod()
Enter and save the above script as FactDocTest.py and try to execute this script from the command line.
Python FactDocTest.py
No output will be shown unless the example fails. Now, change the command line to the following −
Python FactDocTest.py –v
The console will now show the following output −
C:\Python27>python FactDocTest.py -v
Trying:
factorial(5)
Expecting:
120
ok
Trying:
factorial(-1)
Expecting:
Traceback (most recent call last):
...
ValueError: x must be >= 0
ok
2 items passed all tests:
1 tests in __main__
1 tests in __main__.factorial
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
If, on the other hand, the code of factorial() function doesn't give expected result in docstring, failure result will be displayed. For instance, change f = 2 in place of f = 1 in the above script and run the doctest again. The result will be as follows −
Trying:
factorial(5)
Expecting:
120
**********************************************************************
File "docfacttest.py", line 6, in __main__
Failed example:
factorial(5)
Expected:
120
Got:
240
Trying:
factorial(-1)
Expecting:
Traceback (most recent call last):
...
ValueError: x must be >= 0
ok
1 items passed all tests:
1 tests in __main__.factorial
**********************************************************************
1 items had failures:
1 of 1 in __main__
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.
Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function.
The following text is stored in a text file named 'example.txt'.
Using ''factorial''
-------------------
This is an example text file in reStructuredText format. First import
''factorial'' from the ''example'' module:
>>> from example import factorial
Now use it:
>>> factorial(5)
120
The file content is treated as docstring. In order to verify the examples in the text file, use the testfile() function of doctest module.
def factorial(x):
if not x >= 0:
raise ValueError("x must be >= 0")
f = 1
for i in range(1,x+1):
f = f*i
return f
if __name__ == "__main__":
import doctest
doctest.testfile("example.txt")
As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod().
As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod().
In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell.
In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell.
Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.
Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.
Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected.
Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2340,
"s": 2098,
"text": "Python' standard distribution contains 'Doctest' module. This module's functionality makes it possible to search for pieces of text that look like interactive Python sessions, and executes these sessions to see if they work exactly as shown."
},
{
"code": null,
"e": 2396,
"s": 2340,
"text": "Doctest can be very useful in the following scenarios −"
},
{
"code": null,
"e": 2516,
"s": 2396,
"text": "To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented."
},
{
"code": null,
"e": 2636,
"s": 2516,
"text": "To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented."
},
{
"code": null,
"e": 2757,
"s": 2636,
"text": "To perform regression testing by verifying that interactive examples from a test file or a test object work as expected."
},
{
"code": null,
"e": 2878,
"s": 2757,
"text": "To perform regression testing by verifying that interactive examples from a test file or a test object work as expected."
},
{
"code": null,
"e": 2974,
"s": 2878,
"text": "To write tutorial documentation for a package, liberally illustrated with input-output examples"
},
{
"code": null,
"e": 3070,
"s": 2974,
"text": "To write tutorial documentation for a package, liberally illustrated with input-output examples"
},
{
"code": null,
"e": 3443,
"s": 3070,
"text": "In Python, a 'docstring' is a string literal which appears as the first expression in a class, function or module. It is ignored when the suite is executed, but it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object."
},
{
"code": null,
"e": 3657,
"s": 3443,
"text": "It is a usual practice to put example usage of different parts of Python code inside the docstring. The doctest module allows to verify that these docstrings are up-to-date with the intermittent revisions in code."
},
{
"code": null,
"e": 3844,
"s": 3657,
"text": "In the following code, a factorial function is defined interspersed with example usage. In order to verify if the example usage is correct, call the testmod() function in doctest module."
},
{
"code": null,
"e": 4348,
"s": 3844,
"text": "\"\"\"\nThis is the \"example\" module.\n\nThe example module supplies one function, factorial(). For example,\n\n>>> factorial(5)\n120\n\"\"\"\n\ndef factorial(x):\n \"\"\"Return the factorial of n, an exact integer >= 0.\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\n \"\"\"\n \n if not x >= 0:\n raise ValueError(\"x must be >= 0\")\n f = 1\n for i in range(1,x+1):\n f = f*i\n return f\n \nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()"
},
{
"code": null,
"e": 4452,
"s": 4348,
"text": "Enter and save the above script as FactDocTest.py and try to execute this script from the command line."
},
{
"code": null,
"e": 4475,
"s": 4452,
"text": "Python FactDocTest.py\n"
},
{
"code": null,
"e": 4573,
"s": 4475,
"text": "No output will be shown unless the example fails. Now, change the command line to the following −"
},
{
"code": null,
"e": 4599,
"s": 4573,
"text": "Python FactDocTest.py –v\n"
},
{
"code": null,
"e": 4648,
"s": 4599,
"text": "The console will now show the following output −"
},
{
"code": null,
"e": 4986,
"s": 4648,
"text": "C:\\Python27>python FactDocTest.py -v\nTrying:\n factorial(5)\nExpecting:\n 120\nok\nTrying:\n factorial(-1)\nExpecting:\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\nok\n2 items passed all tests:\n 1 tests in __main__\n 1 tests in __main__.factorial\n2 tests in 2 items.\n2 passed and 0 failed.\nTest passed.\n"
},
{
"code": null,
"e": 5243,
"s": 4986,
"text": "If, on the other hand, the code of factorial() function doesn't give expected result in docstring, failure result will be displayed. For instance, change f = 2 in place of f = 1 in the above script and run the doctest again. The result will be as follows −"
},
{
"code": null,
"e": 5822,
"s": 5243,
"text": "Trying:\n factorial(5)\nExpecting:\n 120\n**********************************************************************\nFile \"docfacttest.py\", line 6, in __main__\nFailed example:\nfactorial(5)\nExpected:\n 120\nGot:\n 240\nTrying:\n factorial(-1)\nExpecting:\n Traceback (most recent call last):\n ...\n ValueError: x must be >= 0\nok\n1 items passed all tests:\n 1 tests in __main__.factorial\n**********************************************************************\n1 items had failures:\n 1 of 1 in __main__\n2 tests in 2 items.\n1 passed and 1 failed.\n***Test Failed*** 1 failures.\n"
},
{
"code": null,
"e": 5955,
"s": 5822,
"text": "Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function."
},
{
"code": null,
"e": 6020,
"s": 5955,
"text": "The following text is stored in a text file named 'example.txt'."
},
{
"code": null,
"e": 6249,
"s": 6020,
"text": "Using ''factorial''\n-------------------\nThis is an example text file in reStructuredText format. First import\n''factorial'' from the ''example'' module:\n >>> from example import factorial\nNow use it:\n >>> factorial(5)\n 120"
},
{
"code": null,
"e": 6388,
"s": 6249,
"text": "The file content is treated as docstring. In order to verify the examples in the text file, use the testfile() function of doctest module."
},
{
"code": null,
"e": 6610,
"s": 6388,
"text": "def factorial(x):\n if not x >= 0:\n raise ValueError(\"x must be >= 0\")\n f = 1\n for i in range(1,x+1):\n f = f*i\n return f\n \nif __name__ == \"__main__\":\n import doctest\n doctest.testfile(\"example.txt\")"
},
{
"code": null,
"e": 6840,
"s": 6610,
"text": "As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod()."
},
{
"code": null,
"e": 7070,
"s": 6840,
"text": "As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod()."
},
{
"code": null,
"e": 7227,
"s": 7070,
"text": "In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell."
},
{
"code": null,
"e": 7384,
"s": 7227,
"text": "In most cases a copy-and-paste of an interactive console session works fine, but doctest isn’t trying to do an exact emulation of any specific Python shell."
},
{
"code": null,
"e": 7565,
"s": 7384,
"text": "Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line."
},
{
"code": null,
"e": 7746,
"s": 7565,
"text": "Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line."
},
{
"code": null,
"e": 7989,
"s": 7746,
"text": "Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected."
},
{
"code": null,
"e": 8232,
"s": 7989,
"text": "Expected output cannot contain an all-whitespace line, since such a line is taken to signal the end of expected output. If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected."
},
{
"code": null,
"e": 8239,
"s": 8232,
"text": " Print"
},
{
"code": null,
"e": 8250,
"s": 8239,
"text": " Add Notes"
}
] |
Cohort Analysis Visualization with R | by Pararawendy Indarjo | Towards Data Science
|
If you are a data practitioner in the B2C (Business to Consumer) industry, or simply a data-geek who has analyzed some consumer data, chances are you must be familiar with cohort analysis.
Cohort analysis is an analytic method where we first group individuals who belong to the dataset into different cohorts with specific time-span, within which the individuals in the same cohort group shared the same certain experience. An appropriate analysis is then carried out, taking these cohorts as the unit of analysis.
Among other use cases, cohort analysis allows us to look at the movement of user retention in performing a specific metric over time. This is done by comparing the performance of the cohorts on the basis of their ages.
In this article, I will share how to create cohort analysis visualization. To this end, we will use R and its popular ggplot2 package. There are two types of cohort analysis visualization that will be shown: line plot and heatmap.
The data used is relay-food data available at this Github repository. The data contains the order details of a certain food retailer. Throughout this article, we are only interested to visualize the user purchasing cohort on a monthly basis. Therefore, we will only consider two columns of the data as follows:
OrderDate : the date when the order occurredUserId : the user ID
OrderDate : the date when the order occurred
UserId : the user ID
As always, the first thing to do is to import the necessary libraries.
# import librarieslibrary(dplyr) #handy data manipulationlibrary(ggplot2) #our today's super starlibrary(stringr) #to manipulate string datelibrary(ggthemes) #many nice themeslibrary(mdthemes) #handy text in plot formattinglibrary(gghighlight) #will abuse it a bit to show nice label
Loading the data comes next.
#load the datadf = read.csv("relay-foods.csv")#inspect first 5 rows of the datadf %>% select(OrderDate, UserId) %>% head(5)
Apparently, the date format in the columnOrderDate is not standard yet. Therefore we need to adjust it.
# adjust date formatting of OrderDate columndf$OrderDate = format(as.Date(df$OrderDate, '%m/%d/%Y'), '%Y/%m/%d')df$OrderDate = gsub('00','20',df$OrderDate)
Next, since we want to look at the monthly cohort, we need to derive OrderMonth column from OrderDate column.
# create OrderMonth column from OrderDate (to make monthly cohort)df$OrderMonth = str_sub(df$OrderDate,end = 7)
Cohort analysis requires cohort group information for each user in the dataset, so we build one.
# create reference data frame of cohort group (month level)cohort_group_df = df %>% group_by(UserId) %>% summarize(CohortGroup = min(OrderDate))cohort_group_df$CohortGroup = str_sub(cohort_group_df$CohortGroup, end = 7) # join with the initial dfdf = inner_join(df, cohort_group_df, by = 'UserId')
Next, we create a reference dataframe containing the total users for each cohort group, as well as the monthly count of users who made purchases.
# create reference data frame of total users for each cohort groupbase_cohort_df = df %>% group_by(CohortGroup) %>% summarise( TotalUsers = n_distinct(UserId) )# create purchase activity data frameactivity_cohort_df = df %>% group_by(CohortGroup, OrderMonth) %>% summarise( BuyingUsers = n_distinct(UserId) )# join activity_cohort_df and base_cohort_dfuser_cohort_df = inner_join(activity_cohort_df, base_cohort_df, by = 'CohortGroup')
Data checkpoint. What we have got so far?
user_cohort_df %>% head(5)
Notice OrderMonth column is still in string format as above. For plotting, we want it to be in integer format to become the x-axis.
# transform OrderMonth to integeruser_cohort_df = user_cohort_df %>% group_by(CohortGroup) %>% mutate(MonthNumber = 1:n())
Finally, we will only plot a subset of the data to avoid overplotting.
# subsetting the dataplot_user_cohort_df = inner_join(base_cohort_df[seq(1,11,2),c(“CohortGroup”)], user_cohort_df, by = “CohortGroup”)
In the plot to be drawn, I wanted to have nice legends where they are put right at the end of the lines. To do so, I use gghighlight package. I know this is somewhat hacky, so please comment below if you guys know a more proper way to do it.
# dummy column for in-place legendplot_user_cohort_df$dummy_col = 1
Alright, we are done with data preparation for the line plot. Below is the final form of the data.
plot_user_cohort_df %>% head(5)
So, we are ready to have our first plot!
# plotting line plotggplot(plot_user_cohort_df) + geom_line(aes(x = MonthNumber, y = BuyingUsers/TotalUsers, col = CohortGroup)) + gghighlight(dummy_col == 1) + scale_x_continuous(breaks = seq(from = 1, to = 15, by = 2)) + scale_y_continuous(labels = scales::percent_format()) + mdthemes::md_theme_solarized() + labs( title = "**Monthly User Purchasing Cohort**", caption = "*Data: Relay Food order details (Source: github.com/ethen8181)*", x = "K-th Month", y = "Retention", col = "Cohort Group" )
It can be concluded from the plot that Relay Food tends to experience reduced user retention issues, as the younger cohort retention rate (2009–11) is smaller than that of older cohorts (2009–01).
According to my experience, some people prefer to see a heatmap kind of plot to visualize the cohorts. So let’s draw one too.
Instead of working from scratch, we will continue our work in the above. Particularly we will start upon user_cohort_df .
# create base dataframe for heat map visualizationcohort_heatmap_df = user_cohort_df %>% select(CohortGroup, MonthNumber, BuyingUsers) %>% spread(MonthNumber, BuyingUsers)# inspect datacohort_heatmap_df %>% head(5)
We also create the percentage version of the data.
# the percentage version of the dataframecohort_heatmap_df_pct = data.frame( cohort_heatmap_df$CohortGroup, cohort_heatmap_df[,2:ncol(cohort_heatmap_df)] / cohort_heatmap_df[["1"]])# assign the same column namescolnames(cohort_heatmap_df_pct) = colnames(cohort_heatmap_df)
Next, we melt both dataframes to please ggplot2.
# melt the dataframes for plottingplot_data_abs = gather(cohort_heatmap_df, "MonthNumber", "BuyingUsers", 2:ncol(cohort_heatmap_df))plot_data_pct = gather(cohort_heatmap_df_pct, "MonthNumber", "Retention", 2:ncol(cohort_heatmap_df_pct))
We prepare labels for the heatmap.
# prepare label names containing absolute number of buyers for the first month and retention percentages for the rest monthslabel_names = c(plot_data_abs$BuyingUsers[1:(ncol(cohort_heatmap_df)-1)],plot_data_pct$Retention[(ncol(cohort_heatmap_df_pct)):(nrow(plot_data_pct))])
Finally, we put everything together into a dataframe ready for plotting.
# beautify percentage labelsbeauty_print <- function(n) { case_when( n <= 1 ~ sprintf("%1.0f %%", n*100), n > 1 ~ as.character(n), TRUE ~ " ") # for NA values, skip the label}# create dataframe ready for plottingplot_data = data.frame( CohortGroup = plot_data_pct$CohortGroup, MonthNumber = plot_data_pct$MonthNumber, Retention = plot_data_pct$Retention, Label = beauty_print(label_names))plot_data$MonthNumber = as.numeric(plot_data$MonthNumber)
The final form of the dataframe for heatmap visualization is as follows.
plot_data %>% head(5)
Drum roll! The code for generating the heatmap is as follows.
# plotting heatmapggplot(plot_data) + geom_raster(aes(x = MonthNumber, y = reorder(CohortGroup, desc(CohortGroup)), fill = Retention)) + scale_fill_continuous(guide = FALSE, type = "gradient", low = "deepskyblue", high = "darkblue") + scale_x_continuous(breaks = seq(from = 1, to = 15, by = 1), expand = c(0,0)) + geom_text(aes(x = MonthNumber, y = reorder(CohortGroup, desc(CohortGroup)), label = Label), col = "white") + mdthemes::md_theme_gray() + labs( title = "**Monthly User Purchasing Cohort**", caption = "*Data: Relay Food order details (Source: github.com/ethen8181)*", x = "K-th Month", y = "Cohort Group" )
Notice that the first column of the heatmap displays the absolute number of users who made purchases in corresponding months. Thus, this heatmap version of cohort visualization is somewhat richer than its line plot counterpart since provides more context on the absolute size of the cohort groups.
In this article, we have gone through a step-by-step R code tutorial to generate elegant visualizations of cohort analysis, in the form of a line plot and heatmap. For readers who more enjoy following codes from Github, the full codes in this article are available on my Github repository here.
Finally, thanks for reading, and let’s connect with me on LinkedIn! 👋
|
[
{
"code": null,
"e": 361,
"s": 172,
"text": "If you are a data practitioner in the B2C (Business to Consumer) industry, or simply a data-geek who has analyzed some consumer data, chances are you must be familiar with cohort analysis."
},
{
"code": null,
"e": 687,
"s": 361,
"text": "Cohort analysis is an analytic method where we first group individuals who belong to the dataset into different cohorts with specific time-span, within which the individuals in the same cohort group shared the same certain experience. An appropriate analysis is then carried out, taking these cohorts as the unit of analysis."
},
{
"code": null,
"e": 906,
"s": 687,
"text": "Among other use cases, cohort analysis allows us to look at the movement of user retention in performing a specific metric over time. This is done by comparing the performance of the cohorts on the basis of their ages."
},
{
"code": null,
"e": 1137,
"s": 906,
"text": "In this article, I will share how to create cohort analysis visualization. To this end, we will use R and its popular ggplot2 package. There are two types of cohort analysis visualization that will be shown: line plot and heatmap."
},
{
"code": null,
"e": 1448,
"s": 1137,
"text": "The data used is relay-food data available at this Github repository. The data contains the order details of a certain food retailer. Throughout this article, we are only interested to visualize the user purchasing cohort on a monthly basis. Therefore, we will only consider two columns of the data as follows:"
},
{
"code": null,
"e": 1513,
"s": 1448,
"text": "OrderDate : the date when the order occurredUserId : the user ID"
},
{
"code": null,
"e": 1558,
"s": 1513,
"text": "OrderDate : the date when the order occurred"
},
{
"code": null,
"e": 1579,
"s": 1558,
"text": "UserId : the user ID"
},
{
"code": null,
"e": 1650,
"s": 1579,
"text": "As always, the first thing to do is to import the necessary libraries."
},
{
"code": null,
"e": 1934,
"s": 1650,
"text": "# import librarieslibrary(dplyr) #handy data manipulationlibrary(ggplot2) #our today's super starlibrary(stringr) #to manipulate string datelibrary(ggthemes) #many nice themeslibrary(mdthemes) #handy text in plot formattinglibrary(gghighlight) #will abuse it a bit to show nice label"
},
{
"code": null,
"e": 1963,
"s": 1934,
"text": "Loading the data comes next."
},
{
"code": null,
"e": 2087,
"s": 1963,
"text": "#load the datadf = read.csv(\"relay-foods.csv\")#inspect first 5 rows of the datadf %>% select(OrderDate, UserId) %>% head(5)"
},
{
"code": null,
"e": 2191,
"s": 2087,
"text": "Apparently, the date format in the columnOrderDate is not standard yet. Therefore we need to adjust it."
},
{
"code": null,
"e": 2347,
"s": 2191,
"text": "# adjust date formatting of OrderDate columndf$OrderDate = format(as.Date(df$OrderDate, '%m/%d/%Y'), '%Y/%m/%d')df$OrderDate = gsub('00','20',df$OrderDate)"
},
{
"code": null,
"e": 2457,
"s": 2347,
"text": "Next, since we want to look at the monthly cohort, we need to derive OrderMonth column from OrderDate column."
},
{
"code": null,
"e": 2570,
"s": 2457,
"text": "# create OrderMonth column from OrderDate (to make monthly cohort)df$OrderMonth = str_sub(df$OrderDate,end = 7)"
},
{
"code": null,
"e": 2667,
"s": 2570,
"text": "Cohort analysis requires cohort group information for each user in the dataset, so we build one."
},
{
"code": null,
"e": 3005,
"s": 2667,
"text": "# create reference data frame of cohort group (month level)cohort_group_df = df %>% group_by(UserId) %>% summarize(CohortGroup = min(OrderDate))cohort_group_df$CohortGroup = str_sub(cohort_group_df$CohortGroup, end = 7) # join with the initial dfdf = inner_join(df, cohort_group_df, by = 'UserId')"
},
{
"code": null,
"e": 3151,
"s": 3005,
"text": "Next, we create a reference dataframe containing the total users for each cohort group, as well as the monthly count of users who made purchases."
},
{
"code": null,
"e": 3610,
"s": 3151,
"text": "# create reference data frame of total users for each cohort groupbase_cohort_df = df %>% group_by(CohortGroup) %>% summarise( TotalUsers = n_distinct(UserId) )# create purchase activity data frameactivity_cohort_df = df %>% group_by(CohortGroup, OrderMonth) %>% summarise( BuyingUsers = n_distinct(UserId) )# join activity_cohort_df and base_cohort_dfuser_cohort_df = inner_join(activity_cohort_df, base_cohort_df, by = 'CohortGroup')"
},
{
"code": null,
"e": 3652,
"s": 3610,
"text": "Data checkpoint. What we have got so far?"
},
{
"code": null,
"e": 3679,
"s": 3652,
"text": "user_cohort_df %>% head(5)"
},
{
"code": null,
"e": 3811,
"s": 3679,
"text": "Notice OrderMonth column is still in string format as above. For plotting, we want it to be in integer format to become the x-axis."
},
{
"code": null,
"e": 3934,
"s": 3811,
"text": "# transform OrderMonth to integeruser_cohort_df = user_cohort_df %>% group_by(CohortGroup) %>% mutate(MonthNumber = 1:n())"
},
{
"code": null,
"e": 4005,
"s": 3934,
"text": "Finally, we will only plot a subset of the data to avoid overplotting."
},
{
"code": null,
"e": 4141,
"s": 4005,
"text": "# subsetting the dataplot_user_cohort_df = inner_join(base_cohort_df[seq(1,11,2),c(“CohortGroup”)], user_cohort_df, by = “CohortGroup”)"
},
{
"code": null,
"e": 4383,
"s": 4141,
"text": "In the plot to be drawn, I wanted to have nice legends where they are put right at the end of the lines. To do so, I use gghighlight package. I know this is somewhat hacky, so please comment below if you guys know a more proper way to do it."
},
{
"code": null,
"e": 4451,
"s": 4383,
"text": "# dummy column for in-place legendplot_user_cohort_df$dummy_col = 1"
},
{
"code": null,
"e": 4550,
"s": 4451,
"text": "Alright, we are done with data preparation for the line plot. Below is the final form of the data."
},
{
"code": null,
"e": 4582,
"s": 4550,
"text": "plot_user_cohort_df %>% head(5)"
},
{
"code": null,
"e": 4623,
"s": 4582,
"text": "So, we are ready to have our first plot!"
},
{
"code": null,
"e": 5175,
"s": 4623,
"text": "# plotting line plotggplot(plot_user_cohort_df) + geom_line(aes(x = MonthNumber, y = BuyingUsers/TotalUsers, col = CohortGroup)) + gghighlight(dummy_col == 1) + scale_x_continuous(breaks = seq(from = 1, to = 15, by = 2)) + scale_y_continuous(labels = scales::percent_format()) + mdthemes::md_theme_solarized() + labs( title = \"**Monthly User Purchasing Cohort**\", caption = \"*Data: Relay Food order details (Source: github.com/ethen8181)*\", x = \"K-th Month\", y = \"Retention\", col = \"Cohort Group\" )"
},
{
"code": null,
"e": 5372,
"s": 5175,
"text": "It can be concluded from the plot that Relay Food tends to experience reduced user retention issues, as the younger cohort retention rate (2009–11) is smaller than that of older cohorts (2009–01)."
},
{
"code": null,
"e": 5498,
"s": 5372,
"text": "According to my experience, some people prefer to see a heatmap kind of plot to visualize the cohorts. So let’s draw one too."
},
{
"code": null,
"e": 5620,
"s": 5498,
"text": "Instead of working from scratch, we will continue our work in the above. Particularly we will start upon user_cohort_df ."
},
{
"code": null,
"e": 5849,
"s": 5620,
"text": "# create base dataframe for heat map visualizationcohort_heatmap_df = user_cohort_df %>% select(CohortGroup, MonthNumber, BuyingUsers) %>% spread(MonthNumber, BuyingUsers)# inspect datacohort_heatmap_df %>% head(5)"
},
{
"code": null,
"e": 5900,
"s": 5849,
"text": "We also create the percentage version of the data."
},
{
"code": null,
"e": 6175,
"s": 5900,
"text": "# the percentage version of the dataframecohort_heatmap_df_pct = data.frame( cohort_heatmap_df$CohortGroup, cohort_heatmap_df[,2:ncol(cohort_heatmap_df)] / cohort_heatmap_df[[\"1\"]])# assign the same column namescolnames(cohort_heatmap_df_pct) = colnames(cohort_heatmap_df)"
},
{
"code": null,
"e": 6224,
"s": 6175,
"text": "Next, we melt both dataframes to please ggplot2."
},
{
"code": null,
"e": 6461,
"s": 6224,
"text": "# melt the dataframes for plottingplot_data_abs = gather(cohort_heatmap_df, \"MonthNumber\", \"BuyingUsers\", 2:ncol(cohort_heatmap_df))plot_data_pct = gather(cohort_heatmap_df_pct, \"MonthNumber\", \"Retention\", 2:ncol(cohort_heatmap_df_pct))"
},
{
"code": null,
"e": 6496,
"s": 6461,
"text": "We prepare labels for the heatmap."
},
{
"code": null,
"e": 6771,
"s": 6496,
"text": "# prepare label names containing absolute number of buyers for the first month and retention percentages for the rest monthslabel_names = c(plot_data_abs$BuyingUsers[1:(ncol(cohort_heatmap_df)-1)],plot_data_pct$Retention[(ncol(cohort_heatmap_df_pct)):(nrow(plot_data_pct))])"
},
{
"code": null,
"e": 6844,
"s": 6771,
"text": "Finally, we put everything together into a dataframe ready for plotting."
},
{
"code": null,
"e": 7326,
"s": 6844,
"text": "# beautify percentage labelsbeauty_print <- function(n) { case_when( n <= 1 ~ sprintf(\"%1.0f %%\", n*100), n > 1 ~ as.character(n), TRUE ~ \" \") # for NA values, skip the label}# create dataframe ready for plottingplot_data = data.frame( CohortGroup = plot_data_pct$CohortGroup, MonthNumber = plot_data_pct$MonthNumber, Retention = plot_data_pct$Retention, Label = beauty_print(label_names))plot_data$MonthNumber = as.numeric(plot_data$MonthNumber)"
},
{
"code": null,
"e": 7399,
"s": 7326,
"text": "The final form of the dataframe for heatmap visualization is as follows."
},
{
"code": null,
"e": 7421,
"s": 7399,
"text": "plot_data %>% head(5)"
},
{
"code": null,
"e": 7483,
"s": 7421,
"text": "Drum roll! The code for generating the heatmap is as follows."
},
{
"code": null,
"e": 8229,
"s": 7483,
"text": "# plotting heatmapggplot(plot_data) + geom_raster(aes(x = MonthNumber, y = reorder(CohortGroup, desc(CohortGroup)), fill = Retention)) + scale_fill_continuous(guide = FALSE, type = \"gradient\", low = \"deepskyblue\", high = \"darkblue\") + scale_x_continuous(breaks = seq(from = 1, to = 15, by = 1), expand = c(0,0)) + geom_text(aes(x = MonthNumber, y = reorder(CohortGroup, desc(CohortGroup)), label = Label), col = \"white\") + mdthemes::md_theme_gray() + labs( title = \"**Monthly User Purchasing Cohort**\", caption = \"*Data: Relay Food order details (Source: github.com/ethen8181)*\", x = \"K-th Month\", y = \"Cohort Group\" )"
},
{
"code": null,
"e": 8527,
"s": 8229,
"text": "Notice that the first column of the heatmap displays the absolute number of users who made purchases in corresponding months. Thus, this heatmap version of cohort visualization is somewhat richer than its line plot counterpart since provides more context on the absolute size of the cohort groups."
},
{
"code": null,
"e": 8822,
"s": 8527,
"text": "In this article, we have gone through a step-by-step R code tutorial to generate elegant visualizations of cohort analysis, in the form of a line plot and heatmap. For readers who more enjoy following codes from Github, the full codes in this article are available on my Github repository here."
}
] |
JavaScript Events
|
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can
"react" on
these events.
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
With double quotes:
In the following example, an onclick attribute (with code), is added to a
<button> element:
In the example above, the JavaScript code changes the content of
the element with id="demo".
In the next example, the code changes the content of
its own element (using this.innerHTML):
JavaScript code is often several lines long. It is more common to see event attributes calling functions:
Here is a list of some common HTML events:
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
Event handlers can be used to handle and verify user input, user actions,
and browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
Many different methods can be used to let JavaScript work with events:
HTML event attributes can execute JavaScript code directly
HTML event attributes can call JavaScript functions
You can assign your own event handler functions to HTML elements
You can prevent events from being sent or being handled
And more ...
You will learn a lot more about events and event handlers in the HTML DOM chapters.
The <button> element should do something when someone clicks on it. Try to fix it!
<button ="alert('Hello')">Click me.</button>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 55,
"s": 0,
"text": "HTML events are \"things\" that happen to HTML elements."
},
{
"code": null,
"e": 136,
"s": 55,
"text": "When JavaScript is used in HTML pages, JavaScript can \n\"react\" on \nthese events."
},
{
"code": null,
"e": 211,
"s": 136,
"text": "An HTML event can be something the browser does, or something a user does."
},
{
"code": null,
"e": 250,
"s": 211,
"text": "Here are some examples of HTML events:"
},
{
"code": null,
"e": 288,
"s": 250,
"text": "An HTML web page has finished loading"
},
{
"code": null,
"e": 320,
"s": 288,
"text": "An HTML input field was changed"
},
{
"code": null,
"e": 347,
"s": 320,
"text": "An HTML button was clicked"
},
{
"code": null,
"e": 404,
"s": 347,
"text": "Often, when events happen, you may want to do something."
},
{
"code": null,
"e": 463,
"s": 404,
"text": "JavaScript lets you execute code when events are detected."
},
{
"code": null,
"e": 553,
"s": 463,
"text": "HTML allows event handler attributes, with JavaScript code, to be added to HTML elements."
},
{
"code": null,
"e": 573,
"s": 553,
"text": "With single quotes:"
},
{
"code": null,
"e": 593,
"s": 573,
"text": "With double quotes:"
},
{
"code": null,
"e": 686,
"s": 593,
"text": "In the following example, an onclick attribute (with code), is added to a \n<button> element:"
},
{
"code": null,
"e": 780,
"s": 686,
"text": "In the example above, the JavaScript code changes the content of \nthe element with id=\"demo\"."
},
{
"code": null,
"e": 875,
"s": 780,
"text": "In the next example, the code changes the content of \nits own element (using this.innerHTML): "
},
{
"code": null,
"e": 981,
"s": 875,
"text": "JavaScript code is often several lines long. It is more common to see event attributes calling functions:"
},
{
"code": null,
"e": 1024,
"s": 981,
"text": "Here is a list of some common HTML events:"
},
{
"code": null,
"e": 1097,
"s": 1024,
"text": "The list is much longer: W3Schools JavaScript Reference HTML DOM Events."
},
{
"code": null,
"e": 1193,
"s": 1097,
"text": "Event handlers can be used to handle and verify user input, user actions, \nand browser actions:"
},
{
"code": null,
"e": 1244,
"s": 1193,
"text": "Things that should be done every time a page loads"
},
{
"code": null,
"e": 1295,
"s": 1244,
"text": "Things that should be done when the page is closed"
},
{
"code": null,
"e": 1355,
"s": 1295,
"text": "Action that should be performed when a user clicks a button"
},
{
"code": null,
"e": 1411,
"s": 1355,
"text": "Content that should be verified when a user inputs data"
},
{
"code": null,
"e": 1424,
"s": 1411,
"text": "And more ..."
},
{
"code": null,
"e": 1495,
"s": 1424,
"text": "Many different methods can be used to let JavaScript work with events:"
},
{
"code": null,
"e": 1554,
"s": 1495,
"text": "HTML event attributes can execute JavaScript code directly"
},
{
"code": null,
"e": 1606,
"s": 1554,
"text": "HTML event attributes can call JavaScript functions"
},
{
"code": null,
"e": 1671,
"s": 1606,
"text": "You can assign your own event handler functions to HTML elements"
},
{
"code": null,
"e": 1727,
"s": 1671,
"text": "You can prevent events from being sent or being handled"
},
{
"code": null,
"e": 1740,
"s": 1727,
"text": "And more ..."
},
{
"code": null,
"e": 1824,
"s": 1740,
"text": "You will learn a lot more about events and event handlers in the HTML DOM chapters."
},
{
"code": null,
"e": 1907,
"s": 1824,
"text": "The <button> element should do something when someone clicks on it. Try to fix it!"
},
{
"code": null,
"e": 1953,
"s": 1907,
"text": "<button =\"alert('Hello')\">Click me.</button>\n"
},
{
"code": null,
"e": 1972,
"s": 1953,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2005,
"s": 1972,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2047,
"s": 2005,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2154,
"s": 2047,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2173,
"s": 2154,
"text": "help@w3schools.com"
}
] |
CSS3 - Rounded Corners
|
CSS3 Rounded corners are used to add special colored corner to body or text by using the border-radius property.A simple syntax of rounded corners is as follows −
#rcorners7 {
border-radius: 60px/15px;
background: #FF0000;
padding: 20px;
width: 200px;
height: 150px;
}
The following table shows the possible values for Rounded corners as follows −
border-radius
Use this element for setting four boarder radius property
border-top-left-radius
Use this element for setting the boarder of top left corner
border-top-right-radius
Use this element for setting the boarder of top right corner
border-bottom-right-radius
Use this element for setting the boarder of bottom right corner
border-bottom-left-radius
Use this element for setting the boarder of bottom left corner
This property can have three values. The following example uses both the values −
<html>
<head>
<style>
#rcorners1 {
border-radius: 25px;
background: #8AC007;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners2 {
border-radius: 25px;
border: 2px solid #8AC007;
padding: 20px;
width: 200px;
height: 150px;
}
#rcorners3 {
border-radius: 25px;
background: url(/css/images/logo.png);
background-position: left top;
background-repeat: repeat;
padding: 20px;
width: 200px;
height: 150px;
}
</style>
</head>
<body>
<p id = "rcorners1">Rounded corners!</p>
<p id = "rcorners2">Rounded corners!</p>
<p id = "rcorners3">Rounded corners!</p>
</body>
</html>
It will produce the following result −
Rounded corners!
Rounded corners!
Rounded corners!
We can specify the each corner property as shown below example −
<html>
<head>
<style>
#rcorners1 {
border-radius: 15px 50px 30px 5px;
background: #a44170;
padding: 20px;
width: 100px;
height: 100px;
}
#rcorners2 {
border-radius: 15px 50px 30px;
background: #a44170;
padding: 20px;
width: 100px;
height: 100px;
}
#rcorners3 {
border-radius: 15px 50px;
background: #a44170;
padding: 20px;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<p id = "rcorners1"></p>
<p id = "rcorners2"></p>
<p id = "rcorners3"></p>
</body>
<body>
It will produce the following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2789,
"s": 2626,
"text": "CSS3 Rounded corners are used to add special colored corner to body or text by using the border-radius property.A simple syntax of rounded corners is as follows −"
},
{
"code": null,
"e": 2912,
"s": 2789,
"text": "#rcorners7 {\n border-radius: 60px/15px;\n background: #FF0000;\n padding: 20px; \n width: 200px;\n height: 150px; \n}"
},
{
"code": null,
"e": 2992,
"s": 2912,
"text": "The following table shows the possible values for Rounded corners as follows −"
},
{
"code": null,
"e": 3006,
"s": 2992,
"text": "border-radius"
},
{
"code": null,
"e": 3064,
"s": 3006,
"text": "Use this element for setting four boarder radius property"
},
{
"code": null,
"e": 3087,
"s": 3064,
"text": "border-top-left-radius"
},
{
"code": null,
"e": 3147,
"s": 3087,
"text": "Use this element for setting the boarder of top left corner"
},
{
"code": null,
"e": 3171,
"s": 3147,
"text": "border-top-right-radius"
},
{
"code": null,
"e": 3232,
"s": 3171,
"text": "Use this element for setting the boarder of top right corner"
},
{
"code": null,
"e": 3259,
"s": 3232,
"text": "border-bottom-right-radius"
},
{
"code": null,
"e": 3323,
"s": 3259,
"text": "Use this element for setting the boarder of bottom right corner"
},
{
"code": null,
"e": 3349,
"s": 3323,
"text": "border-bottom-left-radius"
},
{
"code": null,
"e": 3412,
"s": 3349,
"text": "Use this element for setting the boarder of bottom left corner"
},
{
"code": null,
"e": 3494,
"s": 3412,
"text": "This property can have three values. The following example uses both the values −"
},
{
"code": null,
"e": 4367,
"s": 3494,
"text": "<html>\n <head>\n <style>\n #rcorners1 {\n border-radius: 25px;\n background: #8AC007;\n padding: 20px;\n width: 200px;\n height: 150px;\n }\n #rcorners2 {\n border-radius: 25px;\n border: 2px solid #8AC007;\n padding: 20px; \n width: 200px;\n height: 150px;\n }\n #rcorners3 {\n border-radius: 25px;\n background: url(/css/images/logo.png);\n background-position: left top;\n background-repeat: repeat;\n padding: 20px; \n width: 200px;\n height: 150px;\n }\n </style>\n </head>\n\n <body>\n <p id = \"rcorners1\">Rounded corners!</p>\n <p id = \"rcorners2\">Rounded corners!</p>\n <p id = \"rcorners3\">Rounded corners!</p>\n </body>\n</html>"
},
{
"code": null,
"e": 4406,
"s": 4367,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4423,
"s": 4406,
"text": "Rounded corners!"
},
{
"code": null,
"e": 4440,
"s": 4423,
"text": "Rounded corners!"
},
{
"code": null,
"e": 4457,
"s": 4440,
"text": "Rounded corners!"
},
{
"code": null,
"e": 4522,
"s": 4457,
"text": "We can specify the each corner property as shown below example −"
},
{
"code": null,
"e": 5272,
"s": 4522,
"text": "<html>\n <head>\n <style>\n #rcorners1 {\n border-radius: 15px 50px 30px 5px;\n background: #a44170;\n padding: 20px; \n width: 100px;\n height: 100px; \n }\n #rcorners2 {\n border-radius: 15px 50px 30px;\n background: #a44170;\n padding: 20px;\n width: 100px;\n height: 100px; \n }\n #rcorners3 {\n border-radius: 15px 50px;\n background: #a44170;\n padding: 20px; \n width: 100px;\n height: 100px; \n }\n </style>\n </head>\n\n <body>\n <p id = \"rcorners1\"></p>\n <p id = \"rcorners2\"></p>\n <p id = \"rcorners3\"></p>\n </body>\n<body>"
},
{
"code": null,
"e": 5311,
"s": 5272,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5346,
"s": 5311,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5360,
"s": 5346,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5395,
"s": 5360,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5412,
"s": 5395,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5447,
"s": 5412,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5478,
"s": 5447,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5513,
"s": 5478,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5544,
"s": 5513,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5579,
"s": 5544,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5610,
"s": 5579,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5643,
"s": 5610,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5674,
"s": 5643,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5681,
"s": 5674,
"text": " Print"
},
{
"code": null,
"e": 5692,
"s": 5681,
"text": " Add Notes"
}
] |
Boyce-Codd Normal Form (BCNF) - GeeksforGeeks
|
27 Jan, 2020
Application of the general definitions of 2NF and 3NF may identify additional redundancy caused by dependencies that violate one or more candidate keys. However, despite these additional constraints, dependencies can still exist that will cause redundancy to be present in 3NF relations. This weakness in 3NF, resulted in the presentation of a stronger normal form called Boyce–Codd Normal Form (Codd, 1974).
Although, 3NF is adequate normal form for relational database, still, this (3NF) normal form may not remove 100% redundancy because of X?Y functional dependency, if X is not a candidate key of given relation. This can be solve by Boyce-Codd Normal Form (BCNF).
Boyce-Codd Normal Form (BCNF):Boyce–Codd Normal Form (BCNF) is based on functional dependencies that take into account all candidate keys in a relation; however, BCNF also has additional constraints compared with the general definition of 3NF.
A relation is in BCNF iff, X is superkey for every functional dependency (FD) X?Y in given relation.
In other words,
A relation is in BCNF, if and only if, every determinant is a Form (BCNF) candidate key.
Note – To test whether a relation is in BCNF, we identify all the determinants and make sure that they are candidate keys.
The Normal Form Hierarchy
You came across a similar hierarchy known as Chomsky Normal Form in Theory of Computation. Now, carefully study the hierarchy above. It can be inferred that every relation in BCNF is also in 3NF. To put it another way, a relation in 3NF need not to be in BCNF. Ponder over this statement for a while.To determine the highest normal form of a given relation R with functional dependencies, the first step is to check whether the BCNF condition holds. If R is found to be in BCNF, it can be safely deduced that the relation is also in 3NF, 2NF and 1NF as the hierarchy shows. The 1NF has the least restrictive constraint – it only requires a relation R to have atomic values in each tuple. The 2NF has a slightly more restrictive constraint.Read this for a clear understanding of 2NFThe 3NF has more restrictive constraint than the first two normal forms but is less restrictive than the BCNF. In this manner, the restriction increases as we traverse down the hierarchy.
Example-1:Find the highest normal form of a relation R(A, B, C, D, E) with FD set as:
{ BC->D, AC->BE, B->E }
Explanation:
Step-1: As we can see, (AC)+ ={A, C, B, E, D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.
Step-2: Prime attributes are those attribute which are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.
Step-3: The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.
The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).
The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute. So the highest normal form of relation will be 2nd Normal form.
Note –A prime attribute cannot be transitively dependent on a key in BCNF relation.
Consider these functional dependencies of some relation R,
AB ->CC ->BAB ->B
Suppose, it is known that the only candidate key of R is AB. A careful observation is required to conclude that the above dependency is a Transitive Dependency as the prime attribute B transitively depends on the key AB through C. Now, the first and the third FD are in BCNF as they both contain the candidate key (or simply KEY) on their left sides. The second dependency, however, is not in BCNF but is definitely in 3NF due to the presence of the prime attribute on the right side. So, the highest normal form of R is 3NF as all three FD’s satisfy the necessary conditions to be in 3NF.
Example-2:For example consider relation R(A, B, C)
A -> BC,
B -> A
A and B both are super keys so above relation is in BCNF.
Note –BCNF decomposition may always not possible with dependency preserving, however, it always satisfies lossless join condition. For example, relation R (V, W, X, Y, Z), with functional dependencies:
V, W -> X
Y, Z -> X
W -> Y
It would not satisfy dependency preserving BCNF decomposition.Note -:Redundancies are sometimes still present in a BCNF relation as it is not always possible to eliminate them completely.
Refer for:4th and 5th Normal form and finding the highest normal form of a given relation.
RaunakMitra2
DBMS-Normalization
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
Introduction of ER Model
Layers of OSI Model
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Differences between TCP and UDP
|
[
{
"code": null,
"e": 24660,
"s": 24632,
"text": "\n27 Jan, 2020"
},
{
"code": null,
"e": 25069,
"s": 24660,
"text": "Application of the general definitions of 2NF and 3NF may identify additional redundancy caused by dependencies that violate one or more candidate keys. However, despite these additional constraints, dependencies can still exist that will cause redundancy to be present in 3NF relations. This weakness in 3NF, resulted in the presentation of a stronger normal form called Boyce–Codd Normal Form (Codd, 1974)."
},
{
"code": null,
"e": 25330,
"s": 25069,
"text": "Although, 3NF is adequate normal form for relational database, still, this (3NF) normal form may not remove 100% redundancy because of X?Y functional dependency, if X is not a candidate key of given relation. This can be solve by Boyce-Codd Normal Form (BCNF)."
},
{
"code": null,
"e": 25574,
"s": 25330,
"text": "Boyce-Codd Normal Form (BCNF):Boyce–Codd Normal Form (BCNF) is based on functional dependencies that take into account all candidate keys in a relation; however, BCNF also has additional constraints compared with the general definition of 3NF."
},
{
"code": null,
"e": 25675,
"s": 25574,
"text": "A relation is in BCNF iff, X is superkey for every functional dependency (FD) X?Y in given relation."
},
{
"code": null,
"e": 25691,
"s": 25675,
"text": "In other words,"
},
{
"code": null,
"e": 25780,
"s": 25691,
"text": "A relation is in BCNF, if and only if, every determinant is a Form (BCNF) candidate key."
},
{
"code": null,
"e": 25903,
"s": 25780,
"text": "Note – To test whether a relation is in BCNF, we identify all the determinants and make sure that they are candidate keys."
},
{
"code": null,
"e": 25929,
"s": 25903,
"text": "The Normal Form Hierarchy"
},
{
"code": null,
"e": 26898,
"s": 25929,
"text": "You came across a similar hierarchy known as Chomsky Normal Form in Theory of Computation. Now, carefully study the hierarchy above. It can be inferred that every relation in BCNF is also in 3NF. To put it another way, a relation in 3NF need not to be in BCNF. Ponder over this statement for a while.To determine the highest normal form of a given relation R with functional dependencies, the first step is to check whether the BCNF condition holds. If R is found to be in BCNF, it can be safely deduced that the relation is also in 3NF, 2NF and 1NF as the hierarchy shows. The 1NF has the least restrictive constraint – it only requires a relation R to have atomic values in each tuple. The 2NF has a slightly more restrictive constraint.Read this for a clear understanding of 2NFThe 3NF has more restrictive constraint than the first two normal forms but is less restrictive than the BCNF. In this manner, the restriction increases as we traverse down the hierarchy."
},
{
"code": null,
"e": 26984,
"s": 26898,
"text": "Example-1:Find the highest normal form of a relation R(A, B, C, D, E) with FD set as:"
},
{
"code": null,
"e": 27009,
"s": 26984,
"text": "{ BC->D, AC->BE, B->E } "
},
{
"code": null,
"e": 27022,
"s": 27009,
"text": "Explanation:"
},
{
"code": null,
"e": 27271,
"s": 27022,
"text": "Step-1: As we can see, (AC)+ ={A, C, B, E, D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}."
},
{
"code": null,
"e": 27427,
"s": 27271,
"text": "Step-2: Prime attributes are those attribute which are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example."
},
{
"code": null,
"e": 27545,
"s": 27427,
"text": "Step-3: The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute."
},
{
"code": null,
"e": 27798,
"s": 27545,
"text": "The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC)."
},
{
"code": null,
"e": 28144,
"s": 27798,
"text": "The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute. So the highest normal form of relation will be 2nd Normal form."
},
{
"code": null,
"e": 28228,
"s": 28144,
"text": "Note –A prime attribute cannot be transitively dependent on a key in BCNF relation."
},
{
"code": null,
"e": 28287,
"s": 28228,
"text": "Consider these functional dependencies of some relation R,"
},
{
"code": null,
"e": 28305,
"s": 28287,
"text": "AB ->CC ->BAB ->B"
},
{
"code": null,
"e": 28895,
"s": 28305,
"text": "Suppose, it is known that the only candidate key of R is AB. A careful observation is required to conclude that the above dependency is a Transitive Dependency as the prime attribute B transitively depends on the key AB through C. Now, the first and the third FD are in BCNF as they both contain the candidate key (or simply KEY) on their left sides. The second dependency, however, is not in BCNF but is definitely in 3NF due to the presence of the prime attribute on the right side. So, the highest normal form of R is 3NF as all three FD’s satisfy the necessary conditions to be in 3NF."
},
{
"code": null,
"e": 28946,
"s": 28895,
"text": "Example-2:For example consider relation R(A, B, C)"
},
{
"code": null,
"e": 28963,
"s": 28946,
"text": "A -> BC, \nB -> A"
},
{
"code": null,
"e": 29021,
"s": 28963,
"text": "A and B both are super keys so above relation is in BCNF."
},
{
"code": null,
"e": 29223,
"s": 29021,
"text": "Note –BCNF decomposition may always not possible with dependency preserving, however, it always satisfies lossless join condition. For example, relation R (V, W, X, Y, Z), with functional dependencies:"
},
{
"code": null,
"e": 29253,
"s": 29223,
"text": "V, W -> X\nY, Z -> X\n W -> Y "
},
{
"code": null,
"e": 29441,
"s": 29253,
"text": "It would not satisfy dependency preserving BCNF decomposition.Note -:Redundancies are sometimes still present in a BCNF relation as it is not always possible to eliminate them completely."
},
{
"code": null,
"e": 29532,
"s": 29441,
"text": "Refer for:4th and 5th Normal form and finding the highest normal form of a given relation."
},
{
"code": null,
"e": 29545,
"s": 29532,
"text": "RaunakMitra2"
},
{
"code": null,
"e": 29564,
"s": 29545,
"text": "DBMS-Normalization"
},
{
"code": null,
"e": 29569,
"s": 29564,
"text": "DBMS"
},
{
"code": null,
"e": 29577,
"s": 29569,
"text": "GATE CS"
},
{
"code": null,
"e": 29582,
"s": 29577,
"text": "DBMS"
},
{
"code": null,
"e": 29680,
"s": 29582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29711,
"s": 29680,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 29734,
"s": 29711,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 29787,
"s": 29734,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 29798,
"s": 29787,
"text": "CTE in SQL"
},
{
"code": null,
"e": 29823,
"s": 29798,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 29843,
"s": 29823,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 29856,
"s": 29843,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 29905,
"s": 29856,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 29932,
"s": 29905,
"text": "Types of Operating Systems"
}
] |
Fortran - Logical Operators
|
The following table shows all the logical operators supported by Fortran. Assume variable A holds .true. and variable B holds .false. , then −
Try the following example to understand all the logical operators available in Fortran −
program logicalOp
! this program checks logical operators
implicit none
! variable declaration
logical :: a, b
! assigning values
a = .true.
b = .false.
if (a .and. b) then
print *, "Line 1 - Condition is true"
else
print *, "Line 1 - Condition is false"
end if
if (a .or. b) then
print *, "Line 2 - Condition is true"
else
print *, "Line 2 - Condition is false"
end if
! changing values
a = .false.
b = .true.
if (.not.(a .and. b)) then
print *, "Line 3 - Condition is true"
else
print *, "Line 3 - Condition is false"
end if
if (b .neqv. a) then
print *, "Line 4 - Condition is true"
else
print *, "Line 4 - Condition is false"
end if
if (b .eqv. a) then
print *, "Line 5 - Condition is true"
else
print *, "Line 5 - Condition is false"
end if
end program logicalOp
When you compile and execute the above program it produces the following result −
Line 1 - Condition is false
Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is false
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2289,
"s": 2146,
"text": "The following table shows all the logical operators supported by Fortran. Assume variable A holds .true. and variable B holds .false. , then −"
},
{
"code": null,
"e": 2378,
"s": 2289,
"text": "Try the following example to understand all the logical operators available in Fortran −"
},
{
"code": null,
"e": 3308,
"s": 2378,
"text": "program logicalOp\n! this program checks logical operators\nimplicit none\n\n ! variable declaration\n logical :: a, b\n \n ! assigning values\n a = .true.\n b = .false.\n \n if (a .and. b) then\n print *, \"Line 1 - Condition is true\"\n else\n print *, \"Line 1 - Condition is false\"\n end if\n \n if (a .or. b) then\n print *, \"Line 2 - Condition is true\"\n else\n print *, \"Line 2 - Condition is false\"\n end if\n \n ! changing values\n a = .false.\n b = .true.\n \n if (.not.(a .and. b)) then\n print *, \"Line 3 - Condition is true\"\n else\n print *, \"Line 3 - Condition is false\"\n end if\n \n if (b .neqv. a) then\n print *, \"Line 4 - Condition is true\"\n else\n print *, \"Line 4 - Condition is false\"\n end if\n \n if (b .eqv. a) then\n print *, \"Line 5 - Condition is true\"\n else\n print *, \"Line 5 - Condition is false\"\n end if\n \nend program logicalOp"
},
{
"code": null,
"e": 3390,
"s": 3308,
"text": "When you compile and execute the above program it produces the following result −"
},
{
"code": null,
"e": 3528,
"s": 3390,
"text": "Line 1 - Condition is false\nLine 2 - Condition is true\nLine 3 - Condition is true\nLine 4 - Condition is true\nLine 5 - Condition is false\n"
},
{
"code": null,
"e": 3535,
"s": 3528,
"text": " Print"
},
{
"code": null,
"e": 3546,
"s": 3535,
"text": " Add Notes"
}
] |
Swift - Literals
|
A literal is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of literals −
42 // Integer literal
3.14159 // Floating-point literal
"Hello, world!" // String literal
An integer literal can be a decimal, binary, octal, or hexadecimal constant. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x and nothing for decimal.
Here are some examples of integer literals −
let decimalInteger = 17 // 17 in decimal notation
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or hexadecimal form.
Decimal floating-point literals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both.
Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent.
Here are some examples of floating-point literals −
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
A string literal is a sequence of characters surrounded by double quotes, with the following form −
"characters"
String literals cannot contain an unescaped double quote ("), an unescaped backslash (\), a carriage return, or a line feed. Special characters can be included in string literals using the following escape sequences −
The following example shows how to use a few string literals −
let stringL = "Hello\tWorld\n\nHello\'Swift 4\'"
print(stringL)
When we run the above program using playground, we get the following result −
Hello World
Hello'Swift 4'
There are three Boolean literals and they are part of standard Swift 4 keywords −
A value of true representing true.
A value of true representing true.
A value of false representing false.
A value of false representing false.
A value of nil representing no value.
A value of nil representing no value.
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2403,
"s": 2253,
"text": "A literal is the source code representation of a value of an integer, floating-point number, or string type. The following are examples of literals −"
},
{
"code": null,
"e": 2521,
"s": 2403,
"text": "42 // Integer literal\n3.14159 // Floating-point literal\n\"Hello, world!\" // String literal\n"
},
{
"code": null,
"e": 2723,
"s": 2521,
"text": "An integer literal can be a decimal, binary, octal, or hexadecimal constant. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x and nothing for decimal."
},
{
"code": null,
"e": 2768,
"s": 2723,
"text": "Here are some examples of integer literals −"
},
{
"code": null,
"e": 3002,
"s": 2768,
"text": "let decimalInteger = 17 // 17 in decimal notation\nlet binaryInteger = 0b10001 // 17 in binary notation\nlet octalInteger = 0o21 // 17 in octal notation\nlet hexadecimalInteger = 0x11 // 17 in hexadecimal notation\n"
},
{
"code": null,
"e": 3192,
"s": 3002,
"text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or hexadecimal form."
},
{
"code": null,
"e": 3332,
"s": 3192,
"text": "Decimal floating-point literals consist of a sequence of decimal digits followed by either a decimal fraction, a decimal exponent, or both."
},
{
"code": null,
"e": 3474,
"s": 3332,
"text": "Hexadecimal floating-point literals consist of a 0x prefix, followed by an optional hexadecimal fraction, followed by a hexadecimal exponent."
},
{
"code": null,
"e": 3526,
"s": 3474,
"text": "Here are some examples of floating-point literals −"
},
{
"code": null,
"e": 3618,
"s": 3526,
"text": "let decimalDouble = 12.1875\nlet exponentDouble = 1.21875e1\nlet hexadecimalDouble = 0xC.3p0\n"
},
{
"code": null,
"e": 3718,
"s": 3618,
"text": "A string literal is a sequence of characters surrounded by double quotes, with the following form −"
},
{
"code": null,
"e": 3732,
"s": 3718,
"text": "\"characters\"\n"
},
{
"code": null,
"e": 3950,
"s": 3732,
"text": "String literals cannot contain an unescaped double quote (\"), an unescaped backslash (\\), a carriage return, or a line feed. Special characters can be included in string literals using the following escape sequences −"
},
{
"code": null,
"e": 4013,
"s": 3950,
"text": "The following example shows how to use a few string literals −"
},
{
"code": null,
"e": 4077,
"s": 4013,
"text": "let stringL = \"Hello\\tWorld\\n\\nHello\\'Swift 4\\'\"\nprint(stringL)"
},
{
"code": null,
"e": 4155,
"s": 4077,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 4184,
"s": 4155,
"text": "Hello World\n\nHello'Swift 4'\n"
},
{
"code": null,
"e": 4266,
"s": 4184,
"text": "There are three Boolean literals and they are part of standard Swift 4 keywords −"
},
{
"code": null,
"e": 4301,
"s": 4266,
"text": "A value of true representing true."
},
{
"code": null,
"e": 4336,
"s": 4301,
"text": "A value of true representing true."
},
{
"code": null,
"e": 4373,
"s": 4336,
"text": "A value of false representing false."
},
{
"code": null,
"e": 4410,
"s": 4373,
"text": "A value of false representing false."
},
{
"code": null,
"e": 4448,
"s": 4410,
"text": "A value of nil representing no value."
},
{
"code": null,
"e": 4486,
"s": 4448,
"text": "A value of nil representing no value."
},
{
"code": null,
"e": 4519,
"s": 4486,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4534,
"s": 4519,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 4567,
"s": 4534,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4586,
"s": 4567,
"text": " Three Millennials"
},
{
"code": null,
"e": 4618,
"s": 4586,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4637,
"s": 4618,
"text": " Three Millennials"
},
{
"code": null,
"e": 4670,
"s": 4637,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4687,
"s": 4670,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4719,
"s": 4687,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 4739,
"s": 4719,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 4774,
"s": 4739,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4791,
"s": 4774,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 4798,
"s": 4791,
"text": " Print"
},
{
"code": null,
"e": 4809,
"s": 4798,
"text": " Add Notes"
}
] |
How to Get the Datatype of a Column of a Table using JDBC? - GeeksforGeeks
|
21 Aug, 2021
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity.
MySQL: mysql-connector-java-8.0.22 or similar mysql connectors with different versions. In this article, we are using mysql-connector-java-8.0.22
SQL Server: sqljdbc4.jar
Oracle: ojdbc14.jar
MongoDB (NoSQL database): mongo-java-driver-3.12.7
First, need to decide, which database we are using and accordingly, we need to add the jars. For another database like Progress, Cassandra, etc also we have jars and need to include them in the build path. For various data processing-related matters from RDBMS(MySQL, SQL Server, etc.) we have a java.sql package. To get the ResultSetMetaData object, we need to follow the below steps.
1. Register the driver
For database wise it differs. As we are using MySQL, we can do via
Class.forName("com.mysql.cj.jdbc.Driver");
or
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver");
2. Get the connection of MySQL way
test is a database name used in the code.
serverTimezone=UTC, If not provided we will have java.sql.SQLException. The server time zone value xxxx is unrecognized or represents more than one time zone.
We need to configure either the server or JDBC driver via the serverTimezone configuration property) to use a more specific time zone value if we want to utilize time zone support.
So either in MySQL configuration we can set or like below we can provide Credentials here are root/”” i.e. username is root and password is “”.
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?serverTimezone=UTC”, “root”, “”);
3. Create a statement object
Statement st = connection.createStatement();
4. Execute the query
String query = "Select * from doctorsdetails";
// Executing the query
ResultSet resultSet = statement.executeQuery(query);
5. Get the ResultSetMetaData object:
Retrieve the ResultSetMetadata object of the current ResultSet by invoking the getMetaData() method. Below methods are there in ResultSetMetadata object and they are printed in the program
int getColumnCount(): Returns the number of columns of a table.
String getColumnName(int columnNumber): Returns the name of the column whose index number is passed as a parameter.
int getColumnType(int columnNumber): Returns the name of the column as an integer value whose index number is passed as parameter.
For example, 3 indicates DECIMAL, and 12 indicates VARCHAR, and 4 indicates INT.
12 is represented as java.sql.Types.VARCHAR
4 is represented as java.sql.Types.INTEGER
Following is the list of values returned by various datatypes of java.sql.Type − i.e. getColumnType() gives these results.
Array: 2003
Big int: -5
Binary: -2
Bit: -7
Blob: 2004
Boolean: 16
Char: 1
Clob: 2005
Date: 91
Datalink:70
Decimal: 3
Distinct: 2001
Double: 8
Float: 6
Integer: 4
JavaObject: 2000
Long var char: -16
Nchar: -15
NClob: 2011
Varchar: 12
VarBinary: -3
Tiny int: -6
Time stamp with time zone: 2014
Timestamp: 93
Time: 92
Struct: 2002
SqlXml: 2009
Smallint: 5
Rowid: -8
Refcursor: 2012
Ref: 2006
Real: 7
Nvarchar: -9
Numeric: 2
Null: 0
Smallint: 5
Let us check that by creating a table in MySQL and find the datatype by using ResultSetMetaData
Let a table named doctorsdetails available in MySQL under test database,
CREATE TABLE `doctorsdetails` (
`id` int(6) unsigned NOT NULL,
`Name` varchar(50) DEFAULT NULL,
`AvailableDays` varchar(200) DEFAULT NULL,
`consultation_fees` int(11) DEFAULT NULL,
`qualification` varchar(20) DEFAULT NULL,
`experience` int(11) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
As per the above table, getColumnType() for the columns of the above table are as follows
In the code, let us use the steps, and they are given as comments
Java
// Java program to get the column type in JDBC import java.sql.*; public class GetColumnTypeInJdbc { public static void main(String[] args) { System.out.println( "Methods of column to get column type in JDBC"); Connection con = null; try { // We need to have mysql-connector-java-8.0.22 // or relevant jars in build path of project // Class.forName("com.mysql.jdbc.Driver"); // //Earlier these were supported. If we use , // we will be getting warning messages This // driver is the latest one // 1. Register the driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Get the connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", ""); try { // Create statement so that we can execute // all of our queries // 3. Create a statement object Statement statement = con.createStatement(); // Query to retrieve records String query = "Select * from doctorsdetails"; // 4. Executing the query ResultSet resultSet = statement.executeQuery(query); // 5. Get the ResultSetMetaData object ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) { System.out.println( "ColumnName = " + resultSetMetaData.getColumnName( i)); System.out.println( "ColumnType = " + resultSetMetaData.getColumnType(i) + " "); System.out.println( "ColumnLabel = " + resultSetMetaData.getColumnLabel( i) + " "); System.out.println( "ColumnDisplaySize = " + resultSetMetaData .getColumnDisplaySize(i) + " "); System.out.println( "ColumnTypeName = " + resultSetMetaData .getColumnTypeName(i) + " "); System.out.println( "------------------"); } } // in case of any SQL exceptions catch (SQLException s) { System.out.println( "SQL statement is not executed!"); } } // in case of general exceptions // other than SQLException catch (Exception e) { e.printStackTrace(); } finally { // After completing the operations, we // need to null resultSet and connection resultSet = null; con = null; } }}
On execution of the program, we will get the output as below. i.e. similar to the table value that is shown above
anikakapoor
simmytarika5
JDBC
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 23717,
"s": 23557,
"text": "Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity."
},
{
"code": null,
"e": 23863,
"s": 23717,
"text": "MySQL: mysql-connector-java-8.0.22 or similar mysql connectors with different versions. In this article, we are using mysql-connector-java-8.0.22"
},
{
"code": null,
"e": 23888,
"s": 23863,
"text": "SQL Server: sqljdbc4.jar"
},
{
"code": null,
"e": 23908,
"s": 23888,
"text": "Oracle: ojdbc14.jar"
},
{
"code": null,
"e": 23959,
"s": 23908,
"text": "MongoDB (NoSQL database): mongo-java-driver-3.12.7"
},
{
"code": null,
"e": 24345,
"s": 23959,
"text": "First, need to decide, which database we are using and accordingly, we need to add the jars. For another database like Progress, Cassandra, etc also we have jars and need to include them in the build path. For various data processing-related matters from RDBMS(MySQL, SQL Server, etc.) we have a java.sql package. To get the ResultSetMetaData object, we need to follow the below steps."
},
{
"code": null,
"e": 24368,
"s": 24345,
"text": "1. Register the driver"
},
{
"code": null,
"e": 24435,
"s": 24368,
"text": "For database wise it differs. As we are using MySQL, we can do via"
},
{
"code": null,
"e": 24542,
"s": 24435,
"text": "Class.forName(\"com.mysql.cj.jdbc.Driver\");\nor\nDriverManager.registerDriver(new com.mysql.cj.jdbc.Driver\");"
},
{
"code": null,
"e": 24577,
"s": 24542,
"text": "2. Get the connection of MySQL way"
},
{
"code": null,
"e": 24619,
"s": 24577,
"text": "test is a database name used in the code."
},
{
"code": null,
"e": 24778,
"s": 24619,
"text": "serverTimezone=UTC, If not provided we will have java.sql.SQLException. The server time zone value xxxx is unrecognized or represents more than one time zone."
},
{
"code": null,
"e": 24959,
"s": 24778,
"text": "We need to configure either the server or JDBC driver via the serverTimezone configuration property) to use a more specific time zone value if we want to utilize time zone support."
},
{
"code": null,
"e": 25103,
"s": 24959,
"text": "So either in MySQL configuration we can set or like below we can provide Credentials here are root/”” i.e. username is root and password is “”."
},
{
"code": null,
"e": 25223,
"s": 25103,
"text": "Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?serverTimezone=UTC”, “root”, “”);"
},
{
"code": null,
"e": 25252,
"s": 25223,
"text": "3. Create a statement object"
},
{
"code": null,
"e": 25297,
"s": 25252,
"text": "Statement st = connection.createStatement();"
},
{
"code": null,
"e": 25318,
"s": 25297,
"text": "4. Execute the query"
},
{
"code": null,
"e": 25441,
"s": 25318,
"text": "String query = \"Select * from doctorsdetails\";\n// Executing the query\nResultSet resultSet = statement.executeQuery(query);"
},
{
"code": null,
"e": 25479,
"s": 25441,
"text": "5. Get the ResultSetMetaData object: "
},
{
"code": null,
"e": 25668,
"s": 25479,
"text": "Retrieve the ResultSetMetadata object of the current ResultSet by invoking the getMetaData() method. Below methods are there in ResultSetMetadata object and they are printed in the program"
},
{
"code": null,
"e": 25732,
"s": 25668,
"text": "int getColumnCount(): Returns the number of columns of a table."
},
{
"code": null,
"e": 25848,
"s": 25732,
"text": "String getColumnName(int columnNumber): Returns the name of the column whose index number is passed as a parameter."
},
{
"code": null,
"e": 25979,
"s": 25848,
"text": "int getColumnType(int columnNumber): Returns the name of the column as an integer value whose index number is passed as parameter."
},
{
"code": null,
"e": 26062,
"s": 25979,
"text": "For example, 3 indicates DECIMAL, and 12 indicates VARCHAR, and 4 indicates INT. "
},
{
"code": null,
"e": 26106,
"s": 26062,
"text": "12 is represented as java.sql.Types.VARCHAR"
},
{
"code": null,
"e": 26149,
"s": 26106,
"text": "4 is represented as java.sql.Types.INTEGER"
},
{
"code": null,
"e": 26272,
"s": 26149,
"text": "Following is the list of values returned by various datatypes of java.sql.Type − i.e. getColumnType() gives these results."
},
{
"code": null,
"e": 26284,
"s": 26272,
"text": "Array: 2003"
},
{
"code": null,
"e": 26296,
"s": 26284,
"text": "Big int: -5"
},
{
"code": null,
"e": 26307,
"s": 26296,
"text": "Binary: -2"
},
{
"code": null,
"e": 26315,
"s": 26307,
"text": "Bit: -7"
},
{
"code": null,
"e": 26326,
"s": 26315,
"text": "Blob: 2004"
},
{
"code": null,
"e": 26338,
"s": 26326,
"text": "Boolean: 16"
},
{
"code": null,
"e": 26346,
"s": 26338,
"text": "Char: 1"
},
{
"code": null,
"e": 26357,
"s": 26346,
"text": "Clob: 2005"
},
{
"code": null,
"e": 26366,
"s": 26357,
"text": "Date: 91"
},
{
"code": null,
"e": 26378,
"s": 26366,
"text": "Datalink:70"
},
{
"code": null,
"e": 26389,
"s": 26378,
"text": "Decimal: 3"
},
{
"code": null,
"e": 26404,
"s": 26389,
"text": "Distinct: 2001"
},
{
"code": null,
"e": 26414,
"s": 26404,
"text": "Double: 8"
},
{
"code": null,
"e": 26423,
"s": 26414,
"text": "Float: 6"
},
{
"code": null,
"e": 26434,
"s": 26423,
"text": "Integer: 4"
},
{
"code": null,
"e": 26451,
"s": 26434,
"text": "JavaObject: 2000"
},
{
"code": null,
"e": 26470,
"s": 26451,
"text": "Long var char: -16"
},
{
"code": null,
"e": 26481,
"s": 26470,
"text": "Nchar: -15"
},
{
"code": null,
"e": 26493,
"s": 26481,
"text": "NClob: 2011"
},
{
"code": null,
"e": 26505,
"s": 26493,
"text": "Varchar: 12"
},
{
"code": null,
"e": 26519,
"s": 26505,
"text": "VarBinary: -3"
},
{
"code": null,
"e": 26532,
"s": 26519,
"text": "Tiny int: -6"
},
{
"code": null,
"e": 26564,
"s": 26532,
"text": "Time stamp with time zone: 2014"
},
{
"code": null,
"e": 26578,
"s": 26564,
"text": "Timestamp: 93"
},
{
"code": null,
"e": 26587,
"s": 26578,
"text": "Time: 92"
},
{
"code": null,
"e": 26600,
"s": 26587,
"text": "Struct: 2002"
},
{
"code": null,
"e": 26613,
"s": 26600,
"text": "SqlXml: 2009"
},
{
"code": null,
"e": 26625,
"s": 26613,
"text": "Smallint: 5"
},
{
"code": null,
"e": 26635,
"s": 26625,
"text": "Rowid: -8"
},
{
"code": null,
"e": 26651,
"s": 26635,
"text": "Refcursor: 2012"
},
{
"code": null,
"e": 26661,
"s": 26651,
"text": "Ref: 2006"
},
{
"code": null,
"e": 26669,
"s": 26661,
"text": "Real: 7"
},
{
"code": null,
"e": 26682,
"s": 26669,
"text": "Nvarchar: -9"
},
{
"code": null,
"e": 26693,
"s": 26682,
"text": "Numeric: 2"
},
{
"code": null,
"e": 26701,
"s": 26693,
"text": "Null: 0"
},
{
"code": null,
"e": 26713,
"s": 26701,
"text": "Smallint: 5"
},
{
"code": null,
"e": 26809,
"s": 26713,
"text": "Let us check that by creating a table in MySQL and find the datatype by using ResultSetMetaData"
},
{
"code": null,
"e": 26882,
"s": 26809,
"text": "Let a table named doctorsdetails available in MySQL under test database,"
},
{
"code": null,
"e": 27242,
"s": 26882,
"text": "CREATE TABLE `doctorsdetails` (\n `id` int(6) unsigned NOT NULL,\n `Name` varchar(50) DEFAULT NULL,\n `AvailableDays` varchar(200) DEFAULT NULL,\n `consultation_fees` int(11) DEFAULT NULL,\n `qualification` varchar(20) DEFAULT NULL,\n `experience` int(11) DEFAULT NULL,\n `gender` varchar(10) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 27332,
"s": 27242,
"text": "As per the above table, getColumnType() for the columns of the above table are as follows"
},
{
"code": null,
"e": 27398,
"s": 27332,
"text": "In the code, let us use the steps, and they are given as comments"
},
{
"code": null,
"e": 27403,
"s": 27398,
"text": "Java"
},
{
"code": "// Java program to get the column type in JDBC import java.sql.*; public class GetColumnTypeInJdbc { public static void main(String[] args) { System.out.println( \"Methods of column to get column type in JDBC\"); Connection con = null; try { // We need to have mysql-connector-java-8.0.22 // or relevant jars in build path of project // Class.forName(\"com.mysql.jdbc.Driver\"); // //Earlier these were supported. If we use , // we will be getting warning messages This // driver is the latest one // 1. Register the driver Class.forName(\"com.mysql.cj.jdbc.Driver\"); // 2. Get the connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/test?serverTimezone=UTC\", \"root\", \"\"); try { // Create statement so that we can execute // all of our queries // 3. Create a statement object Statement statement = con.createStatement(); // Query to retrieve records String query = \"Select * from doctorsdetails\"; // 4. Executing the query ResultSet resultSet = statement.executeQuery(query); // 5. Get the ResultSetMetaData object ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) { System.out.println( \"ColumnName = \" + resultSetMetaData.getColumnName( i)); System.out.println( \"ColumnType = \" + resultSetMetaData.getColumnType(i) + \" \"); System.out.println( \"ColumnLabel = \" + resultSetMetaData.getColumnLabel( i) + \" \"); System.out.println( \"ColumnDisplaySize = \" + resultSetMetaData .getColumnDisplaySize(i) + \" \"); System.out.println( \"ColumnTypeName = \" + resultSetMetaData .getColumnTypeName(i) + \" \"); System.out.println( \"------------------\"); } } // in case of any SQL exceptions catch (SQLException s) { System.out.println( \"SQL statement is not executed!\"); } } // in case of general exceptions // other than SQLException catch (Exception e) { e.printStackTrace(); } finally { // After completing the operations, we // need to null resultSet and connection resultSet = null; con = null; } }}",
"e": 30648,
"s": 27403,
"text": null
},
{
"code": null,
"e": 30763,
"s": 30648,
"text": "On execution of the program, we will get the output as below. i.e. similar to the table value that is shown above "
},
{
"code": null,
"e": 30777,
"s": 30765,
"text": "anikakapoor"
},
{
"code": null,
"e": 30790,
"s": 30777,
"text": "simmytarika5"
},
{
"code": null,
"e": 30795,
"s": 30790,
"text": "JDBC"
},
{
"code": null,
"e": 30802,
"s": 30795,
"text": "Picked"
},
{
"code": null,
"e": 30826,
"s": 30802,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30831,
"s": 30826,
"text": "Java"
},
{
"code": null,
"e": 30845,
"s": 30831,
"text": "Java Programs"
},
{
"code": null,
"e": 30864,
"s": 30845,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30869,
"s": 30864,
"text": "Java"
},
{
"code": null,
"e": 30967,
"s": 30869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30976,
"s": 30967,
"text": "Comments"
},
{
"code": null,
"e": 30989,
"s": 30976,
"text": "Old Comments"
},
{
"code": null,
"e": 31007,
"s": 30989,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 31028,
"s": 31007,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31074,
"s": 31028,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31117,
"s": 31074,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31157,
"s": 31117,
"text": "Java Math random() method with Examples"
},
{
"code": null,
"e": 31201,
"s": 31157,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 31227,
"s": 31201,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31261,
"s": 31227,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 31308,
"s": 31261,
"text": "Implementing a Linked List in Java using Class"
}
] |
\pmb - Tex Command
|
\pmb - poor man's bold.
{ \pmb #1 }
\pmb command turns on poor man's bold. It works by duplicating its argument slightly offset, giving a bold effect (at least in the horizontal direction); doesn't work well for horizontal lines, like - or +.
a \pmb a \boldsymbol a
aaaa
\pmb{a+b-c}\ \ a+b-c
a+b−ca+b−c a+b−c
a \pmb a \boldsymbol a
aaaa
a \pmb a \boldsymbol a
\pmb{a+b-c}\ \ a+b-c
a+b−ca+b−c a+b−c
\pmb{a+b-c}\ \ a+b-c
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8010,
"s": 7986,
"text": "\\pmb - poor man's bold."
},
{
"code": null,
"e": 8022,
"s": 8010,
"text": "{ \\pmb #1 }"
},
{
"code": null,
"e": 8229,
"s": 8022,
"text": "\\pmb command turns on poor man's bold. It works by duplicating its argument slightly offset, giving a bold effect (at least in the horizontal direction); doesn't work well for horizontal lines, like - or +."
},
{
"code": null,
"e": 8304,
"s": 8229,
"text": "\na \\pmb a \\boldsymbol a\n\naaaa\n\n\n\\pmb{a+b-c}\\ \\ a+b-c\n\na+b−ca+b−c a+b−c\n\n\n"
},
{
"code": null,
"e": 8335,
"s": 8304,
"text": "a \\pmb a \\boldsymbol a\n\naaaa\n\n"
},
{
"code": null,
"e": 8358,
"s": 8335,
"text": "a \\pmb a \\boldsymbol a"
},
{
"code": null,
"e": 8400,
"s": 8358,
"text": "\\pmb{a+b-c}\\ \\ a+b-c\n\na+b−ca+b−c a+b−c\n\n"
},
{
"code": null,
"e": 8421,
"s": 8400,
"text": "\\pmb{a+b-c}\\ \\ a+b-c"
},
{
"code": null,
"e": 8453,
"s": 8421,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8466,
"s": 8453,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8499,
"s": 8466,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8512,
"s": 8499,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8544,
"s": 8512,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8580,
"s": 8544,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8615,
"s": 8580,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8632,
"s": 8615,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8665,
"s": 8632,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8679,
"s": 8665,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8711,
"s": 8679,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8726,
"s": 8711,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8733,
"s": 8726,
"text": " Print"
},
{
"code": null,
"e": 8744,
"s": 8733,
"text": " Add Notes"
}
] |
final vs Immutability in Java - GeeksforGeeks
|
02 Mar, 2022
final: In Java, final is a modifier that is used for class, method, and variable also. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means we can’t change anything to the existing String objects.
Differences between final and immutability
final means that you can’t change the object’s reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object’s actual value can’t be changed, but you can change its reference to another one.
final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables.
By declaring a reference variable as final, we won’t get any immutability nature, Even though reference variable is final. We can perform any type of change in the corresponding Object. But we can’t perform reassignment for that variable.
final ensures that the address of the object remains the same whereas the Immutable suggests that we can’t change the state of the object once created.
JAVA
// Java program to illustrate// difference between final// and immutability class Geeks { public static void main(String[] args) { final StringBuffer sb = new StringBuffer("Hello"); // Even though reference variable sb is final // We can perform any changes sb.append("GFG"); System.out.println(sb); // Here we will get Compile time error // Because reassignment is not possible for final variable sb = new StringBuffer("Hello World"); System.out.println(sb); }}
Output:
Geeks.java:14: error: cannot assign a value to final variable sb
sb = new StringBuffer("Hello World");
^
1 error
Pictorial Representation of the above Program
Explanation: In the above picture, we can see that we are creating an object of StringBuffer class by making reference final.
Declaring reference variable as final, does not mean that the object is immutable.
In the next line we are performing append() operation on the created object and it is successfully changed.
If the object is immutable, then the above append operation can’t be done.
But it is executed successfully as we declare the reference variable as final. final means we can’t reassign anything to that reference variable again.
Therefore when we try to create a new object of StringBuffer then it won’t create an object by throwing an error to the console.
vedprksh79
adnanirshad158
sachithsenarathnes
final keyword
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23583,
"s": 23555,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 23991,
"s": 23583,
"text": "final: In Java, final is a modifier that is used for class, method, and variable also. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means we can’t change anything to the existing String objects."
},
{
"code": null,
"e": 24034,
"s": 23991,
"text": "Differences between final and immutability"
},
{
"code": null,
"e": 24325,
"s": 24034,
"text": "final means that you can’t change the object’s reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object’s actual value can’t be changed, but you can change its reference to another one."
},
{
"code": null,
"e": 24457,
"s": 24325,
"text": "final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables."
},
{
"code": null,
"e": 24696,
"s": 24457,
"text": "By declaring a reference variable as final, we won’t get any immutability nature, Even though reference variable is final. We can perform any type of change in the corresponding Object. But we can’t perform reassignment for that variable."
},
{
"code": null,
"e": 24849,
"s": 24696,
"text": "final ensures that the address of the object remains the same whereas the Immutable suggests that we can’t change the state of the object once created. "
},
{
"code": null,
"e": 24854,
"s": 24849,
"text": "JAVA"
},
{
"code": "// Java program to illustrate// difference between final// and immutability class Geeks { public static void main(String[] args) { final StringBuffer sb = new StringBuffer(\"Hello\"); // Even though reference variable sb is final // We can perform any changes sb.append(\"GFG\"); System.out.println(sb); // Here we will get Compile time error // Because reassignment is not possible for final variable sb = new StringBuffer(\"Hello World\"); System.out.println(sb); }}",
"e": 25393,
"s": 24854,
"text": null
},
{
"code": null,
"e": 25402,
"s": 25393,
"text": "Output: "
},
{
"code": null,
"e": 25531,
"s": 25402,
"text": "Geeks.java:14: error: cannot assign a value to final variable sb\n sb = new StringBuffer(\"Hello World\");\n ^\n1 error"
},
{
"code": null,
"e": 25577,
"s": 25531,
"text": "Pictorial Representation of the above Program"
},
{
"code": null,
"e": 25703,
"s": 25577,
"text": "Explanation: In the above picture, we can see that we are creating an object of StringBuffer class by making reference final."
},
{
"code": null,
"e": 25786,
"s": 25703,
"text": "Declaring reference variable as final, does not mean that the object is immutable."
},
{
"code": null,
"e": 25894,
"s": 25786,
"text": "In the next line we are performing append() operation on the created object and it is successfully changed."
},
{
"code": null,
"e": 25969,
"s": 25894,
"text": "If the object is immutable, then the above append operation can’t be done."
},
{
"code": null,
"e": 26121,
"s": 25969,
"text": "But it is executed successfully as we declare the reference variable as final. final means we can’t reassign anything to that reference variable again."
},
{
"code": null,
"e": 26250,
"s": 26121,
"text": "Therefore when we try to create a new object of StringBuffer then it won’t create an object by throwing an error to the console."
},
{
"code": null,
"e": 26261,
"s": 26250,
"text": "vedprksh79"
},
{
"code": null,
"e": 26276,
"s": 26261,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26295,
"s": 26276,
"text": "sachithsenarathnes"
},
{
"code": null,
"e": 26309,
"s": 26295,
"text": "final keyword"
},
{
"code": null,
"e": 26314,
"s": 26309,
"text": "Java"
},
{
"code": null,
"e": 26319,
"s": 26314,
"text": "Java"
},
{
"code": null,
"e": 26417,
"s": 26319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26426,
"s": 26417,
"text": "Comments"
},
{
"code": null,
"e": 26439,
"s": 26426,
"text": "Old Comments"
},
{
"code": null,
"e": 26469,
"s": 26439,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26484,
"s": 26469,
"text": "Stream In Java"
},
{
"code": null,
"e": 26505,
"s": 26484,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26551,
"s": 26505,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26570,
"s": 26551,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26587,
"s": 26570,
"text": "Generics in Java"
},
{
"code": null,
"e": 26630,
"s": 26587,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26646,
"s": 26630,
"text": "Strings in Java"
},
{
"code": null,
"e": 26702,
"s": 26646,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Lolcode - Quick Guide
|
LOLCODE is an esoteric programming language inspired by the funny things on the Internet. It is designed to test the boundaries of programming language design.
This chapter will make you familiar with setting up the local environment for LOLCODE, installing it on Windows, and executing its script online at Tutorialspoint-codingground.
The LOLCODE interpreter is written in C Language. It interprets the code written in LOLCODE language on multiple platforms. The LOLCODE interpreter is known as lci, which stands for LOLCODE Interpreter.
Please note that LOLCODE officially supports direct installation of interpreter for MAC operating Systems only. To install LOLCODE in your operating system, you need to follow the steps given below −
Press Command+Space, and type Terminal and press enter/return key
Run in Terminal app
$ git clone https://github.com/justinmeza/lci.git
$ cd lci
$ cmake.
$ make && make install
If you need to install LOLCODE on Windows operating system, please take these steps −
First add MinGW and Python to your environment variables path. To do this, right click on My Computer, choose Properties, then select Advanced system settings. Select Environment Variables. In this box, select the PATH variable and then click Edit.
First add MinGW and Python to your environment variables path. To do this, right click on My Computer, choose Properties, then select Advanced system settings. Select Environment Variables. In this box, select the PATH variable and then click Edit.
Now, add ";C:\MinGW\bin;C:\Python32" to the end of that path.
Now, add ";C:\MinGW\bin;C:\Python32" to the end of that path.
Next, open the Command Prompt and navigate to the project directory using the "cd" command, for example.
Next, open the Command Prompt and navigate to the project directory using the "cd" command, for example.
Run the script install.py.
Run the script install.py.
To execute your scripts easily and swiftly, use the codingground platform provided by TutorialsPoint. For this, go to the following link to execute your scripts online −
The LOLCODE constructs are slang words. The following table shows the alphabetical list of constructs implemented so far −
BTW
It starts a single line comment.
DOWN <variable>!!<times>
This corresponds to variable = variable - times. Note that "times" is a wut-only language extension.
GIMMEH <variable>
This represents the input statement.
GTFO
This is similar to break in other languages and provides a way to break out of a loop.
HAI
This corresponds to main () function in other languages. It is the program entry point in LOLCODE.
HEREZ <label>
This is another wut-only language extension and declares a label for use with SHOO
I HAS A <type> <variable>
This declares a variable of said type.
There are three built-in types in LOLCODE −
NUMBAH (int)
DECINUMBAH (double)
WORDZ (std::string)
Note that types are a wut-only language extension.
IM IN YR LOOP
This starts an infinite loop. The only way to exit the loop is using GTFO. Corresponds to for(;;) in other languages
IZ <expr1> <operator> <expr2>?: Conditional structure
This is similar to if operator in other languages. Operator is one of: BIGGER THAN, SMALLER THAN, SAEM AS. Note that the ? at the end is optional.
KTHX
It ends a block. Corresponds to }
KTHXBAI
This ends a program
NOWAI
This corresponds to else
PURR <expr>
This prints argument on screen, followed by a newline. It is a wut-only language extension.
RELSE
This corresponds to else (if)
SHOO
This is another wut-only language extension, that corresponds to goto (the horror!)
UP <variable>!!<times>
This corresponds to variables = variable + times. Here "times" is a wut-only language extension.
VISIBLE <expr>
This prints the argument on screen. Note that this does not print a newline.
YARLY
This denotes the start of the "true" conditional block
Some examples of slang terms in LOLCODE are −
HAI is hi
KTHXBYE is okay, thanks, bye
BTW is by the way
OBTW is oh, by the way
TLDR is too long; didn't read
In most programming languages, keywords or tokens may not have spaces between them. However, in some languages, spaces are used in tokens to differentiate them.
The comma behaves like a newline keyword in most languages, for example, \n in Java and C. You can write many commands in a single line in LOLCODE, provided that you separate them using a comma (,).
The three periods (...) enables you to combine multiple lines of code into a single line or a single command by including (...) at the end of the line. This makes the compiler to treat the content of the next line as the content of previous line only. Infinite lines of code can be written together as a single command, as long as each line is ended with three periods.
A comment is terminated by a newline. Please note that the line continuation (...) and (,) after the comment (BTW) are ignored by the lci.
Single line comments are written followed by the BTW keyword. They may occur anywhere inside a program body: it can be at the first line of program, in between the program, in between some line, or at the end of a program.
All of these are valid single line comments−
I HAS A VAL ITZ 19 BTW VAL = 19
I HAS A VAL ITZ 19, BTW VAL = 19
I HAS A VAL ITZ 14
BTW VAR = 14
In LOLCODE, multiple line comments are written followed by OBTW and they are ended with TLDR.
This is a valid multi−line comment −
I HAS A VAL ITZ 51
OBTW this is a comment
No it’s a two line comment
Oops no.. it has many lines here
TLDR
A LOLCODE program begins with HAI keyword and it should end with KTHXBYE. As LOLCODE uses shorthand language HAI basically stands for Hi and KTHXBYE can be remembered as “Ok, thanks, bye ”.
HAI 1.2
I HAS A NAME
VISIBLE "NAME::"!
GIMMEH NAME
VISIBLE "tutorialsPoint " NAME "!"
KTHXBYE
As in any other programming language, LOLCODE allows you to define variables of various types. This chapter will make you familiar with working with variables in LOLCODE.
The scope of a variable is local to the function or to the program block, i.e. a variable defined in one scope cannot be called in any other scope of the same program. Variables are accessible only after they are declared.
Please note that there is no global scope of variables in LOLCODE.
Variable names are usually called identifiers. Here are some of the conventions for naming variables in LOLCODE −
Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two).
Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two).
They can only begin with a letter and then may be followed by other letters, numbers, and underscores.
They can only begin with a letter and then may be followed by other letters, numbers, and underscores.
LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable.
LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable.
Variable identifiers are case sensitive.
Variable identifiers are case sensitive.
Here are some of the rules for valid and invalid names for variables in LOLCODE−
The name should always begin with an alphabet. For example, name, Name are valid.
The name should always begin with an alphabet. For example, name, Name are valid.
The name of a variable cannot begin with a digit. For example, 2var is invalid.
The name of a variable cannot begin with a digit. For example, 2var is invalid.
The name of a variable cannot begin with a special character.
The name of a variable cannot begin with a special character.
A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name.
A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name.
Some examples of valid names in LOLCODE are shown below −
HAI 1.2
I HAS A food ITZ "111.00033"
I HAS A food2 ITZ "111"
I HAS A fo_od ITZ "1"
VISIBLE food
VISIBLE food2
VISIBLE fo_od
KTHXBYE
All the declaration statements in the above code are valid and will produce the following output when executed −
sh-4.3$ lci main.lo
111.00033
111
1
Some examples of invalid statements and their output are given below −
HAI 1.2
I HAS A 2food ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Expected: identifier; Got: int(2).
HAI 1.2
I HAS A _food ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Unrecognized sequence at: _food ITZ "111.00033".
HAI 1.2
I HAS A f$ood ITZ "111.00033"
KTHXBYE
The above code will give the following output when you execute it −
sh-4.3$ lci main.lo
Line 2: Unrecognized sequence at: $ood ITZ "111.00033".
To declare a variable, LOLCODE provides a keyword “I HAS A” which is followed by the variable name. You can find below the syntax for declaring a variable.
I HAS A VAR BTW VAR is empty now, You can use any name instead of var
To assign the variable a value in the same statement, you can then follow the variable name with “ITZ” and then give the value you want to assign. Use the following syntax to assign a value to a variable −
<variable> R <expression>
VAR R "Green" BTW VAR is now a YARN and equals "Green"
VAR R 30 BTW VAR is now a NUMBR and equals 30
You can also declare and assign variables at the same time using the following syntax−
I HAS A VAR ITZ VALUE
I HAS A NAME ITS “TUTORIALS POINT”
HAI 1.2
BTW this is how we declare variables
I HAS A food
I HAS A bird
BTW this is how we assign variables
food R 1
bird R 5
BTW this is how initialize variables
I HAS A biz ITZ "OMG!"
VISIBLE food
VISIBLE biz
VISIBLE bird
KTHXBYE
The above program shows the declaration of variables and prints them. The output is −
sh-
4.3$ lci main.lo
1
OMG!
5
To convert a value of one type to another type, we use type casting. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number. Casting a NUMBAR to a YARN (by printing it, for example), truncates the output to a default 2 decimal places.
HAI 1.2
I HAS A food ITZ "111.00033"
VISIBLE food
BTW this is how we do type casting
MAEK food A NUMBAR
VISIBLE food
KTHXBYE
The above line of code will produce the following output −
sh-4.3$ lci main.lo
111.00033
111.00033
All the variables declared in a LOLCODE program are local variables and there is no global scope in this language for any variable.
LOLCODE is designed to test the boundaries of the programming language design. It is an esoteric programming language inspired by the funny things on the Internet. This chapter gives you an understanding of LOLCODE types.
Currently, the variable types in LOLCODE are −
strings (YARN)
integers (NUMBR)
floats (NUMBAR)
and booleans (TROOF)
Arrays (BUKKIT)
In LOLCODE the variable type is handled dynamically by the compiler. If a variable does not have an initial value, it is called untyped (known as NOOB in LOLCODE).
The syntax for declaring and using different types in LOLCODE is shown below −
I HAS A <VARIABLE> ITZ A <DATA TYPE>
I HAS A <VARIABLE> ITZ <EXPRESSION<
<VARIABLE> R <EXPRESSION>
The untyped data type (known as NOOB), cannot be converted into any other type except into a TROOF data type. The implicit casting of a NOOB into TROOF makes the variable FAIL. After that any operation on a NOOB results in an error.
Explicit casts of a NOOB data type (i.e. the types that are uninitialized and do not have any initial value) variable results to zero values for all other types.
To define an untyped variable, just declare a variable and assign a value as shown in this example −
HAI 1.2
I HAS A VAR3
VAR3 R "ANYVALUE"
VISIBLE VAR3
BTW Or declare in same line
I HAS A VAR4 ITZ 44
VISIBLE VAR4
KTHXBYE
When you run the above program, you will find the following result −
sh-
4.3$ lci main.lo
ANYVALUE
44
In LOLCODE, the Boolean values are of two types. BOOLEAN generally have two values- true and false. But, in LOLCODE, the Boolean is known as TROOF, and the true/ false values are known as WIN/FAIL respectively. All the uninitialized values like an empty string (""), or an empty array will all cast to FAIL. All other initialized values evaluate to WIN.
HAI 1.2
I HAS A VAR3 ITZ A TROOF
VAR3 R "FAIL"
VISIBLE VAR3
KTHXBYE
You can see the following output when you execute the above code −
sh-4.3$ lci main.lo
FAIL
In LOLCODE, a NUMBR stands for an integer. Any sequence of digits is considered as a NUMBR, unless it has a decimal appearing anywhere in between the sequence. To make any number negative, it may be preceded by a hyphen (-) which signifies a negative number.
HAI 1.2
I HAS A VAR3 ITZ A NUMBR
VISIBLE VAR3
KTHXBYE
The above code shows you the following result when you run it−
sh-
4.3$ lci main.lo
0
Similar to NUMBR, LOLCODE has another data type, which represents a decimal or a float in many programming languages. In LOLCODE, a NUMBAR is a float containing one decimal point. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number and returns it as a NUMBR, without any decimal.
In LOLCODE, value containing strings, i.e. string literals (YARN) should start and end with double quotation marks ("”).
Anything may be written inside the string, like space, comma, full stop, exclamation or any other symbol. A string where any single quote is missing may cause an error. Colons are used as escape characters in LOLCODE, and any value following a colon gets a special meaning.
:) − A closing bracket following a colon represents a newline (\n)
:) − A closing bracket following a colon represents a newline (\n)
:> − A closing angle bracket following a colon represents a tab (\t)
:> − A closing angle bracket following a colon represents a tab (\t)
:o − A ‘o’ character following a colon represents a bell (beep) (\g)
:o − A ‘o’ character following a colon represents a bell (beep) (\g)
:" − A “ following a colon represents a literal double quote (")
:" − A “ following a colon represents a literal double quote (")
:: − A colon following a colon represents a single literal colon (:)
:: − A colon following a colon represents a single literal colon (:)
HAI 1.2
I HAS A VAR3 ITZ A YARN
VAR3 R "XYZ"
VISIBLE VAR3
KTHXBYE
The code given above produces the following output upon execution −
sh-
4.3$ lci main.lo
XYZ
This type represents an array. It has named slots, which can contain either variables or functions. A BUKKIT can be declared in the following way −
BTW declaration of the BUKKIT
I HAS A [object] ITZ A BUKKIT BTW creating a variable in a slots
[object] HAS A [var] ITZ [value] BTW creating a function inside the BUKKIT
HOW IZ [object] [function name] (YR [argument1] (AN YR [argument2] (AN YR [argument3] ...)))
[function code]
IF U SAY SO
A function inside a BUKKIT may also access variables and other functions of the BUKKIT by using ME'Z [var] or ME IZ [function name] (YR [argument1] (AN YR [argument2] (AN YR [argument3] ...))) MKAY.
HAI 1.2
I HAS A VAR6 ITZ A BUKKIT
BTW DECLARING AN ARRAY
VAR6 HAS A VAR7 ITZ "DOGE"
BTW VAR7 IS A STRING VARIABLE THAT IS INSERTED INTO ARRAY VAR6
VISIBLE VAR6'Z VAR7
BTW GET THE ELEMENT OF ARRAY
KTHXBYE
This is the output you will find when you run the code given above −
sh-
4.3$ lci main.lo
DOGE
Operators play an important role to perform various operations on variables. This chapter brings you various operators in LOLCODE and their usage.
Mathematical operators depend on a prefix notation i.e. the notation that comes before the operand. When all the operators have known number of arguments or operands, then no grouping markers are necessary. In cases where operators don’t have fixed arguments or operands, the operation is closed with MKAY.
An MKAY may not be used if it coincides with the end of the statement. In such cases, the EOL keyword should be used. To use unary mathematical operators , use the following syntax −
<operator> <expression>
The AN keyword can optionally be used to separate arguments, and apply a single operation on more than one operand, so a binary operator expression has the following syntax −
<operator> <expression1> AN <expression2>
Any expression containing an operator with infinite number of arguments can be expressed with the following syntax −
<operator> <expression1> [[AN <expression2>] AN <expression3> ...] MKAY
Following are the basic mathematical operations in LOLCODE −
SUM OF <a> AN <b> BTW This is a plus + operator
DIFF OF <a> AN <n> BTW This is a minus - operator
PRODUKT OF <a> AN <n> BTW This is a multiply operator *
QUOSHUNT OF <a> AN <n> BTW This is a divide operator
MOD OF <a> AN <n> BTW This is a modulo operator
BIGGR OF <a> AN <n> BTW This is a max operator
SMALLR OF <a> AN <n> BTW This is a min operator
<a> and <b> can each be unique expressions in the above, so mathematical operators can be nested and grouped indefinitely.
Math is performed considering arguments as integer math in the presence of two NUMBRs, but if either of the expressions is NUMBAR, then operations are considered as floating point operations.
HAI 1.2
I HAS A m ITZ 4
I HAS A n ITZ 2
VISIBLE SUM OF m AN n BTW +
VISIBLE DIFF OF m AN n BTW -
VISIBLE PRODUKT OF m AN n BTW *
VISIBLE QUOSHUNT OF m AN n BTW /
VISIBLE MOD OF m AN n BTW modulo
VISIBLE BIGGR OF m AN n BTW max
VISIBLE SMALLR OF m AN n BTW min
KTHXBYE
The above code will produce the following output when you run it −
sh-
4.3$ lci main.lo
6
2
8
2
0
4
2
Consider the following important points related to working with mathematical operators in LOLCODE−
If one or both arguments in an expression are YARN, they are treated as NUMBARs.
If one or both arguments in an expression are YARN, they are treated as NUMBARs.
If any of the arguments cannot be safely casted internally to a numerical type, then it fails with an error
If any of the arguments cannot be safely casted internally to a numerical type, then it fails with an error
Boolean operators are applied on those values that may be true or false. Boolean operators working on TROOFs are as following −
BOTH OF <m> AN <n> BTW its and operation: WIN if m = WIN and n = WIN
EITHER OF <m> AN <n> BTW its or operation: FAIL iff m = FAIL, n = FAIL
WON OF <m> AN <n> BTW its xor operation: FAIL if m = n
NOT <m> BTW its an unary negation: WIN if m = FAIL
ALL OF <m> AN <n> ... MKAY BTW it will take infinite arguments and apply AND
ANY OF <m> AN <n> ... MKAY BTW it will take infinite arguments and apply OR.
Please note that <m> and <n> in the expression syntax above are automatically cast as TROOF values if they are not already TROOF Values.
When you want to compare two or more operands in LOLCODE, you can do so in any of the following methods −
You can compare two binary operands using equality operators. The syntax is shown below −
BOTH SAEM <m> AN <n> BTW this will return WIN if m is equal to n
DIFFRINT <m> AN <n> BTW this will return WIN if m is not equal to n
You can compare if both the values are of NUMBRs type. Remember that if either of the values are NUMBARs, then they are compared as floating point values.
You can also perform comparison using the minimum and maximum operators. The syntax is shown below −
BOTH SAEM <m> AN BIGGR OF <m> AN <n>
BOTH SAEM <m> AN SMALLR OF <m> AN <n>
DIFFRINT <m> AN SMALLR OF <m> AN <n>
DIFFRINT <m> AN BIGGR OF <m> AN <n>
Example
HAI 1.2
I HAS A VAR11 ITZ 7
BOTH SAEM VAR11 SMALLR OF VAR11 AN 8, O RLY?
YA RLY
VISIBLE "TRUE"
NO WAI
VISIBLE "FALSE"
OIC
KTHXBY
You can see the following output when you execute the given code −
sh-
4.3$ lci main.lo
TRUE
LOLCODE allows you to explicitly concatenate infinite number of YARNs using the SMOOSH...MKAY operator. For concatenation, multiple arguments can be separated with the AN operator.
HAI 1.2
I HAS A VAR1 ITZ A YARN
VAR1 R "TRUE"
I HAS A VAR2 ITZ A YARN
VAR2 R "ANOTHER TRUE"
I HAS A VAR3 ITZ A YARN
VAR3 R "ONE MORE TRUE"
VISIBLE SMOOSH VAR1 " " VAR3 " " VAR2 MKAY
KTHXBYE
The above given code will produce the following result upon execution −
sh-
4.3$ lci main.lo
TRUE ONE MORE TRUE ANOTHER TRUE
Operators that work on specific types implicitly cast or convert the values of one type to other type safely. If the value cannot be safely converted to other type, then it results in an error.
An expression's value may be explicitly casted or converted to some other type with the binary MAEK operator. The syntax of MAEK Operator is −
MAEK <expression> A <type>
where, <type> can be one of TROOF, YARN, NUMBR, NUMBAR, or NOOB.
To explicitly cast a variable to some other type, a normal assignment statement with the MAEK operator can be used, or a casting assignment statement may be used as follows −
<Any_variable> IS NOW A <type> BTW this code will be equal to
<Any_variable> R MAEK <variable> A <type>
HAI 1.2
I HAS A food ITZ "111.00033"
VISIBLE food
BTW this is how we do type casting
MAEK food A NUMBAR
VISIBLE food
KTHXBYE
The above code will produce the following output−
sh-4.3$ lci main.lo
111.00033
This chapter will explain you how to input a value through LOLCODE terminal and how to output it onto the terminal.
You can use the keyword VISIBLE to print something in LOLCODE. VISIBLE is a function which can take an infinite number of characters as input, and prints them all at once by internally concatenating them, and converting them to strings or YARN.
The VISIBLE function ends or terminates by a delimiter, which is either a line end or a comma.
The output is automatically terminated by the compiler with a carriage return. If the final token is terminated with an exclamation symbol (!), then the carriage returned is over-ridden by this symbol.
VISIBLE <any_expression> [<any_expression> ...][!]
Please note that in LOLCODE, currently there is no defined standard for printing some data to a file.
To take some input from the user, the keyword used is GIMMEH. It is a function which can take any number of variables as input. It takes YARN as the input and stores the value in any given variable.
GIMMEH <any_variable>
HAI 1.2
I HAS A VAR ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE
VISIBLE "TYPE SOMETHING AND ENTER"
GIMMEH VAR BTW GET INPUT (STRING) INTO VARIABLE
VISIBLE VAR
KTHXBYE
When this code is run, it will ask you to enter a number and then prints the number back in the next line automatically. When you run this code, it will print the following output −
sh-
4.3$ lci main.lo
TYPE SOMETHING AND ENTER
67
67
LOLCODE allows you to control the flow of program through various statements. This chapter explains different types of statements available in LOLCODE.
An expression without any assignment, i.e. simply calling a mathematical operation or any function, is a legal statement in LOLCODE. Once the expression is evaluated, its final value is placed in the temporary variable IT. The value of IT remains in the local scope, and exists until the next time it is replaced with an expression.
Assignment statements are used to assign the output of any expression to a given variable. They are generally of the form −
<any_variable> <assignment operator> <any expression>
Please note that, you can use a variable in the expression, even before it is being assigned.
The if−then statement is a very simple operation working on the IT variable. It is similar to if−else statements in other programming languages like C and Java.
There are four keywords to apply the if–then statements.
O RLY?
YA RLY
NO WAI
OIC
The general form is −
<any_expression>
O RLY?
YA RLY
<code to execute if above condition is true>
NO WAI
<code to execute in this block>
OIC
All of the above statements can be written in the same line separated by commas like −
BOTH SAEM NAMES AN "Name", O RLY?
YA RLY, VISIBLE "My name is ABCD"
NO WAI, VISIBLE "Your name is ABCD"
OIC
While using the if-then statements, an optional MEBBE <any expression> may be used between the YA RLY and NO WAI blocks.
If the <any expression> following MEBBE is True (WIN), then that block is executed. Otherwise, if that expression is false, the block is skipped until the next MEBBE, NO WAI, or OIC statements.
<any expression>
O RLY?
YA RLY
<code to be executed if true>
MEBBE <expression>
<code to be executed mebbe is true>
MEBBE <expression>
<code to be executed mebbe is true>
NO WAI
<code to be executed if above are false>
OIC
BOTH SAEM NAMES AN "NAME"
O RLY?
YA RLY, VISIBLE "YOUR NAME IS ABCD"
MEBBE BOTH SAEM ANIMAL AN "OUR NAME IS ABCD"
VISIBLE "NO ABCD"
OIC
In LOLCODE, the keyword ‘WTF?’ is similar to switch in many other languages. The keyword WTF? takes IT as the expression value for comparison. To use WTF, a comparison block is opened by OMG which should be a literal, and not an expression.
Please remember that each literal must be unique, similar to the case in other languages.
The OMG block must be terminated by a GTFO statement. If an OMG block is not terminated by a GTFO, then the next OMG block is executed till GTFO is reached.
If none of the literals evaluate as true, then default case is signified by OMGWTF.
WTF?
OMG <any value to compare>
<code block to execute if expression is satisfied>
OMG <any value to compare>
<code block to execute if expression is satisfied>
OMGWTF
<code block to execute as a default case>
OIC
NAME, WTF?
OMG "A"
VISIBLE "ABCD"
GTFO
OMG "E"
VISIBLE "EFGH"
GTFO
OMGWTF
VISIBLE "ZYXW"
OIC
The output results of the above code will be −
"E":
EFGH
Loops are used in programming languages to execute a set of statements multiple times. For example, if you want to print the digit 5 for five times, then instead of writing the VISIBLE “5” statement five times, you can run a loop with single VISIBLE “5” statement for five times.
Simple loops are represented with IM IN YR <label> and IM OUTTA YR <label>. Loops defined in this way are infinite loops and they should be terminated with a GTFO break statement.
Iteration loops have the following structure−
IM IN YR <label> <any_operation> YR <any_variable> [TIL|WILE <expression>]
<code block to execute inside the loop multiple times>
IM OUTTA YR <label>
Please note that inside the function body, UPPIN (increment by one), NERFIN (decrement by one), or any unary function can be used.
The TIL keyword calculates the expression as a TROOF: if it evaluates as FAIL, the loop continues once more, if it evaluates as WIN, then the loop execution stops, and continues after the matching IM OUTTA YR statement.
The WILE keyword is the opposite of TIL keyword, if the expression is WIN, execution continues, otherwise the loop exits.
HAI 1.2
I HAS A VAR ITZ 0
IM IN YR LOOPY UPPIN YR VAR TIL BOTH SAEM VAR AN 10
VISIBLE SUM OF VAR AN 1
IM OUTTA YR LOOPY
KTHXBYE
When the above code is compiled on any LOLCODE compiler, or on our online codingground, this will produce the following output.
sh-
4.3$ lci main.lo
1
2
3
4
5
6
7
8
9
10
Functions are useful in programming because they reduce time and effort for writing the code again and again. A well written function code offers high reusability. This chapter explains you how to write and work with functions in LOLCODE.
A function is a set of statements that are executed all at once by calling that function. In LOLCODE, a function’s definition starts with the keyword “HOW IZ I” and the closing keyword is “IF U SAY SO”.
The syntax for writing a function in LOLCODE is−
HOW IZ I <function name> [YR <parameter/argument> [AN YR <other _arguments..> ...]]
<code block to execute / Set of statements to execute>
IF U SAY SO
Consider the following important points when you are defining a LOLCODE function −
In LOLCODE, the function can accept only a certain fixed number of arguments as an input.
In LOLCODE, the function can accept only a certain fixed number of arguments as an input.
The arguments or parameters, are the identifiers that become a variable to the function.
The arguments or parameters, are the identifiers that become a variable to the function.
Functions in LOLCODE can’t access any other values other than the values passed to them as arguments.
Functions in LOLCODE can’t access any other values other than the values passed to them as arguments.
Return in coding means something that is given back. In programming, a function can return some value to the program when its execution is completed. In LOLCODE, functions return varying values as explained below −
FOUND YR <any_expression> returns the value of the expression when function block is executed completely.
FOUND YR <any_expression> returns the value of the expression when function block is executed completely.
GTFO returns no value (NOOB), which is similar to return 0 in other programming languages like C and Java.
GTFO returns no value (NOOB), which is similar to return 0 in other programming languages like C and Java.
If no other return statement is found, then IF U SAY SO is executed and the value in the IT variable is returned.
If no other return statement is found, then IF U SAY SO is executed and the value in the IT variable is returned
A function is defined in the body of program and is later called for execution. A function which accepts a given number of arguments is called as shown below −
I IZ <function_name> [YR <expression_One> [AN YR <expression_Two> [AN YR <expression_Three> ...]]] MKAY
While calling a function, the expression is formed by the function name, followed by the number of arguments that the function will accept. These arguments can be simple variables or any expressions. If a function accepts any expression instead of a simple value, then the expressions' values are calculated before the function is called.
Please remember that the number of arguments a function will accept, should be defined in the definition of the function.
HAI
HOW DUZ I MAINUMBA
I HAS A NUMBA
GIMMEH NUMBA
FOUND YR NUMBA
IF U SAY SO
VISIBLE MAINUMBA
KTHXBYE
When you run the above code, it will ask for an input, and then when you submit the input, you’ll see the same as the result. For example, if we enter 55, it will print 55.
HAI 1.2
HOW IZ I MULTIPLY YR FIRSTOPERANT AN YR SECONDOPERANT
FOUND YR PRODUKT OF FIRSTOPERANT AN SECONDOPERANT
IF U SAY SO
VISIBLE I IZ MULTIPLY YR 2 AN YR 3
KTHXBYE
The above function that performs multiplication of input operands will print the following output when you run it−
sh-
4.3$ lci main.lo
6
HAI 1.2
I HAS A STRINGARRAY ITZ A BUKKIT
STRINGARRAY HAS A VAR17 ITZ "OBJECT1"
STRINGARRAY HAS A VAR18 ITZ "OBJECT2"
HOW IZ STRINGARRAY ACCESS YR VARIABLE
FOUND YR STRINGARRAY'Z SRS VARIABLE
IF U SAY SO
I HAS A STRING ITZ "VAR17"
VISIBLE STRINGARRAY IZ ACCESS YR STRING MKAY
KTHXBYE
The output that the above code will produce is −
sh-
4.3$ lci main.lo
OBJECT1
Exception handling is one of the powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained. LOLCODE does not have a lot of support for exception handling like other programming Languages. Similar to the Try-Catch block in other languages, LOLCODE has the PLZ-block.
For example, if you want to open a file that may or may not exist, use −
PLZ OPEN FILE "filename.TXT"?
AWSUM THX
VISIBLE FILE
O NOES
INVISIBLE "ERROR!"
KTHX
The code that may cause an exception is written in the PLZ block, and the exception is handled in the O NOES block. Here, the INVISIBLE keyword sends an inner message to the debugger.
Please note that as LOLCODE is not maintained regularly, there are no more updates available for LOLCODE exception handling and many other features.
The previous chapters explained you the programming in LOLCODE. In this chapter, you will learn some examples that lets you code at an advanced level in LOLCODE.
In this example, you will find the code to calculate the power of an input number. For example, 2 raised to power 4 is equal to 16.
HAI 1.2
HOW IZ I POWERTWO YR NUM
BTW RETURN 1 IF 2 TO POWER OF 0
BOTH SAEM NUM AN 0, O RLY?
YA RLY, FOUND YR 1
OIC
BTW CALCULATE 2 TO POWER OF NUM
I HAS A INDEX ITZ 0
I HAS A TOTAL ITZ 1
IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX AN NUM
TOTAL R PRODUKT OF TOTAL AN 2
IM OUTTA YR LOOP
FOUND YR TOTAL
IF U SAY SO
BTW OUTPUT: 8
VISIBLE I IZ POWERTWO YR 4 MKAY
KTHXBYE
The above code will print the following output once it runs succesfully −
sh-
4.3$ lci main.lo
16
This example shows the code for making an array with five elements and each element with value 10.
HAI 1.3
OBTW
CREATES A ONE DIMENSIONAL ARRAY WITH N ELEMENTS, EACH IS A 0
TLDR
HOW IZ I MAKEMATRIX YR N
I HAS A MATRIX ITZ A BUKKIT
IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX N
MATRIX HAS A SRS INDEX ITZ 10
IM OUTTA YR LOOP
FOUND YR MATRIX
IF U SAY SO
I HAS A N ITZ 5
I HAS A MATRIX ITZ A BUKKIT
MATRIX R I IZ MAKEMATRIX YR N MKAY
BTW PRINTS THE CONTENTS OF THE ARRAY
IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX N
VISIBLE MATRIX'Z SRS INDEX
IM OUTTA YR LOOP
KTHXBYE
You can see the following output when you execute the above code −
sh-4.3$ lci main.lo
10
10
10
10
10
This program shows the code to calculate the factorial of an input number.
HAI 1.3
HOW IZ I FACTORIAL YR N
BOTH SAEM N AN 0
O RLY?
YA RLY, FOUND YR 1
NO WAI
FOUND YR PRODUKT OF N AN I IZ FACTORIAL YR DIFF OF N AN 1
MKAY
OIC
IF U SAY SO
VISIBLE I IZ FACTORIAL YR 6 MKAY
KTHXBYE
The above program prints the factorial of the number 6 and you can see the output as shown below −
sh-
4.3$ lci main.lo
720
You can design a calculator to perform basic math operations using LOLCODE programming. Observe the code given below −
HAI 1.2
I HAS A V1
I HAS A V2
I HAS A CHOICE
VISIBLE "VALUE1"
GIMMEH V1
VISIBLE "VALUE2"
GIMMEH V2VISIBLE "Choose Operation? + - * /"
GIMMEH CHOICE CHOICE, WTF?
OMG "+"
VISIBLE SUM OF V1 AN V2
GTFO
OMG "-"
VISIBLE DIFF OF V1 AN V2
GTFO
OMG "*"
VISIBLE PRODUKT OF V1 AN V2
GTFO
OMG "/"
VISIBLE QUOSHUNT OF V1 AN V2
GTFO
OMGWTF
VISIBLE "CHOOSE SOME OPERATION"
OIC
KTHXBYE
When we execute the above program with following input −
3
4
+
Upon execution, the above program will generate the following output −
VALUE1
VALUE2
Choose Operation? + - * /
7
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2000,
"s": 1840,
"text": "LOLCODE is an esoteric programming language inspired by the funny things on the Internet. It is designed to test the boundaries of programming language design."
},
{
"code": null,
"e": 2177,
"s": 2000,
"text": "This chapter will make you familiar with setting up the local environment for LOLCODE, installing it on Windows, and executing its script online at Tutorialspoint-codingground."
},
{
"code": null,
"e": 2380,
"s": 2177,
"text": "The LOLCODE interpreter is written in C Language. It interprets the code written in LOLCODE language on multiple platforms. The LOLCODE interpreter is known as lci, which stands for LOLCODE Interpreter."
},
{
"code": null,
"e": 2580,
"s": 2380,
"text": "Please note that LOLCODE officially supports direct installation of interpreter for MAC operating Systems only. To install LOLCODE in your operating system, you need to follow the steps given below −"
},
{
"code": null,
"e": 2646,
"s": 2580,
"text": "Press Command+Space, and type Terminal and press enter/return key"
},
{
"code": null,
"e": 2666,
"s": 2646,
"text": "Run in Terminal app"
},
{
"code": null,
"e": 2716,
"s": 2666,
"text": "$ git clone https://github.com/justinmeza/lci.git"
},
{
"code": null,
"e": 2725,
"s": 2716,
"text": "$ cd lci"
},
{
"code": null,
"e": 2734,
"s": 2725,
"text": "$ cmake."
},
{
"code": null,
"e": 2757,
"s": 2734,
"text": "$ make && make install"
},
{
"code": null,
"e": 2843,
"s": 2757,
"text": "If you need to install LOLCODE on Windows operating system, please take these steps −"
},
{
"code": null,
"e": 3093,
"s": 2843,
"text": "First add MinGW and Python to your environment variables path. To do this, right click on My Computer, choose Properties, then select Advanced system settings. Select Environment Variables. In this box, select the PATH variable and then click Edit."
},
{
"code": null,
"e": 3343,
"s": 3093,
"text": "First add MinGW and Python to your environment variables path. To do this, right click on My Computer, choose Properties, then select Advanced system settings. Select Environment Variables. In this box, select the PATH variable and then click Edit."
},
{
"code": null,
"e": 3405,
"s": 3343,
"text": "Now, add \";C:\\MinGW\\bin;C:\\Python32\" to the end of that path."
},
{
"code": null,
"e": 3467,
"s": 3405,
"text": "Now, add \";C:\\MinGW\\bin;C:\\Python32\" to the end of that path."
},
{
"code": null,
"e": 3572,
"s": 3467,
"text": "Next, open the Command Prompt and navigate to the project directory using the \"cd\" command, for example."
},
{
"code": null,
"e": 3677,
"s": 3572,
"text": "Next, open the Command Prompt and navigate to the project directory using the \"cd\" command, for example."
},
{
"code": null,
"e": 3704,
"s": 3677,
"text": "Run the script install.py."
},
{
"code": null,
"e": 3731,
"s": 3704,
"text": "Run the script install.py."
},
{
"code": null,
"e": 3901,
"s": 3731,
"text": "To execute your scripts easily and swiftly, use the codingground platform provided by TutorialsPoint. For this, go to the following link to execute your scripts online −"
},
{
"code": null,
"e": 4024,
"s": 3901,
"text": "The LOLCODE constructs are slang words. The following table shows the alphabetical list of constructs implemented so far −"
},
{
"code": null,
"e": 4028,
"s": 4024,
"text": "BTW"
},
{
"code": null,
"e": 4061,
"s": 4028,
"text": "It starts a single line comment."
},
{
"code": null,
"e": 4086,
"s": 4061,
"text": "DOWN <variable>!!<times>"
},
{
"code": null,
"e": 4187,
"s": 4086,
"text": "This corresponds to variable = variable - times. Note that \"times\" is a wut-only language extension."
},
{
"code": null,
"e": 4205,
"s": 4187,
"text": "GIMMEH <variable>"
},
{
"code": null,
"e": 4242,
"s": 4205,
"text": "This represents the input statement."
},
{
"code": null,
"e": 4247,
"s": 4242,
"text": "GTFO"
},
{
"code": null,
"e": 4334,
"s": 4247,
"text": "This is similar to break in other languages and provides a way to break out of a loop."
},
{
"code": null,
"e": 4338,
"s": 4334,
"text": "HAI"
},
{
"code": null,
"e": 4437,
"s": 4338,
"text": "This corresponds to main () function in other languages. It is the program entry point in LOLCODE."
},
{
"code": null,
"e": 4451,
"s": 4437,
"text": "HEREZ <label>"
},
{
"code": null,
"e": 4534,
"s": 4451,
"text": "This is another wut-only language extension and declares a label for use with SHOO"
},
{
"code": null,
"e": 4560,
"s": 4534,
"text": "I HAS A <type> <variable>"
},
{
"code": null,
"e": 4599,
"s": 4560,
"text": "This declares a variable of said type."
},
{
"code": null,
"e": 4643,
"s": 4599,
"text": "There are three built-in types in LOLCODE −"
},
{
"code": null,
"e": 4656,
"s": 4643,
"text": "NUMBAH (int)"
},
{
"code": null,
"e": 4676,
"s": 4656,
"text": "DECINUMBAH (double)"
},
{
"code": null,
"e": 4696,
"s": 4676,
"text": "WORDZ (std::string)"
},
{
"code": null,
"e": 4747,
"s": 4696,
"text": "Note that types are a wut-only language extension."
},
{
"code": null,
"e": 4761,
"s": 4747,
"text": "IM IN YR LOOP"
},
{
"code": null,
"e": 4878,
"s": 4761,
"text": "This starts an infinite loop. The only way to exit the loop is using GTFO. Corresponds to for(;;) in other languages"
},
{
"code": null,
"e": 4932,
"s": 4878,
"text": "IZ <expr1> <operator> <expr2>?: Conditional structure"
},
{
"code": null,
"e": 5079,
"s": 4932,
"text": "This is similar to if operator in other languages. Operator is one of: BIGGER THAN, SMALLER THAN, SAEM AS. Note that the ? at the end is optional."
},
{
"code": null,
"e": 5084,
"s": 5079,
"text": "KTHX"
},
{
"code": null,
"e": 5118,
"s": 5084,
"text": "It ends a block. Corresponds to }"
},
{
"code": null,
"e": 5126,
"s": 5118,
"text": "KTHXBAI"
},
{
"code": null,
"e": 5146,
"s": 5126,
"text": "This ends a program"
},
{
"code": null,
"e": 5152,
"s": 5146,
"text": "NOWAI"
},
{
"code": null,
"e": 5177,
"s": 5152,
"text": "This corresponds to else"
},
{
"code": null,
"e": 5189,
"s": 5177,
"text": "PURR <expr>"
},
{
"code": null,
"e": 5281,
"s": 5189,
"text": "This prints argument on screen, followed by a newline. It is a wut-only language extension."
},
{
"code": null,
"e": 5287,
"s": 5281,
"text": "RELSE"
},
{
"code": null,
"e": 5317,
"s": 5287,
"text": "This corresponds to else (if)"
},
{
"code": null,
"e": 5322,
"s": 5317,
"text": "SHOO"
},
{
"code": null,
"e": 5406,
"s": 5322,
"text": "This is another wut-only language extension, that corresponds to goto (the horror!)"
},
{
"code": null,
"e": 5429,
"s": 5406,
"text": "UP <variable>!!<times>"
},
{
"code": null,
"e": 5526,
"s": 5429,
"text": "This corresponds to variables = variable + times. Here \"times\" is a wut-only language extension."
},
{
"code": null,
"e": 5541,
"s": 5526,
"text": "VISIBLE <expr>"
},
{
"code": null,
"e": 5618,
"s": 5541,
"text": "This prints the argument on screen. Note that this does not print a newline."
},
{
"code": null,
"e": 5624,
"s": 5618,
"text": "YARLY"
},
{
"code": null,
"e": 5679,
"s": 5624,
"text": "This denotes the start of the \"true\" conditional block"
},
{
"code": null,
"e": 5725,
"s": 5679,
"text": "Some examples of slang terms in LOLCODE are −"
},
{
"code": null,
"e": 5735,
"s": 5725,
"text": "HAI is hi"
},
{
"code": null,
"e": 5764,
"s": 5735,
"text": "KTHXBYE is okay, thanks, bye"
},
{
"code": null,
"e": 5782,
"s": 5764,
"text": "BTW is by the way"
},
{
"code": null,
"e": 5805,
"s": 5782,
"text": "OBTW is oh, by the way"
},
{
"code": null,
"e": 5835,
"s": 5805,
"text": "TLDR is too long; didn't read"
},
{
"code": null,
"e": 5996,
"s": 5835,
"text": "In most programming languages, keywords or tokens may not have spaces between them. However, in some languages, spaces are used in tokens to differentiate them."
},
{
"code": null,
"e": 6195,
"s": 5996,
"text": "The comma behaves like a newline keyword in most languages, for example, \\n in Java and C. You can write many commands in a single line in LOLCODE, provided that you separate them using a comma (,)."
},
{
"code": null,
"e": 6565,
"s": 6195,
"text": "The three periods (...) enables you to combine multiple lines of code into a single line or a single command by including (...) at the end of the line. This makes the compiler to treat the content of the next line as the content of previous line only. Infinite lines of code can be written together as a single command, as long as each line is ended with three periods."
},
{
"code": null,
"e": 6704,
"s": 6565,
"text": "A comment is terminated by a newline. Please note that the line continuation (...) and (,) after the comment (BTW) are ignored by the lci."
},
{
"code": null,
"e": 6927,
"s": 6704,
"text": "Single line comments are written followed by the BTW keyword. They may occur anywhere inside a program body: it can be at the first line of program, in between the program, in between some line, or at the end of a program."
},
{
"code": null,
"e": 6972,
"s": 6927,
"text": "All of these are valid single line comments−"
},
{
"code": null,
"e": 7077,
"s": 6972,
"text": "I HAS A VAL ITZ 19 BTW VAL = 19\nI HAS A VAL ITZ 19, BTW VAL = 19\nI HAS A VAL ITZ 14\nBTW VAR = 14\n"
},
{
"code": null,
"e": 7171,
"s": 7077,
"text": "In LOLCODE, multiple line comments are written followed by OBTW and they are ended with TLDR."
},
{
"code": null,
"e": 7208,
"s": 7171,
"text": "This is a valid multi−line comment −"
},
{
"code": null,
"e": 7334,
"s": 7208,
"text": "I HAS A VAL ITZ 51\n OBTW this is a comment\n No it’s a two line comment\n Oops no.. it has many lines here\n TLDR\n"
},
{
"code": null,
"e": 7524,
"s": 7334,
"text": "A LOLCODE program begins with HAI keyword and it should end with KTHXBYE. As LOLCODE uses shorthand language HAI basically stands for Hi and KTHXBYE can be remembered as “Ok, thanks, bye ”."
},
{
"code": null,
"e": 7618,
"s": 7524,
"text": "HAI 1.2\nI HAS A NAME\nVISIBLE \"NAME::\"!\nGIMMEH NAME\nVISIBLE \"tutorialsPoint \" NAME \"!\"\nKTHXBYE"
},
{
"code": null,
"e": 7789,
"s": 7618,
"text": "As in any other programming language, LOLCODE allows you to define variables of various types. This chapter will make you familiar with working with variables in LOLCODE."
},
{
"code": null,
"e": 8012,
"s": 7789,
"text": "The scope of a variable is local to the function or to the program block, i.e. a variable defined in one scope cannot be called in any other scope of the same program. Variables are accessible only after they are declared."
},
{
"code": null,
"e": 8079,
"s": 8012,
"text": "Please note that there is no global scope of variables in LOLCODE."
},
{
"code": null,
"e": 8193,
"s": 8079,
"text": "Variable names are usually called identifiers. Here are some of the conventions for naming variables in LOLCODE −"
},
{
"code": null,
"e": 8284,
"s": 8193,
"text": "Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two)."
},
{
"code": null,
"e": 8375,
"s": 8284,
"text": "Variable identifiers may be in all CAPITAL or lowercase letters (or a mixture of the two)."
},
{
"code": null,
"e": 8478,
"s": 8375,
"text": "They can only begin with a letter and then may be followed by other letters, numbers, and underscores."
},
{
"code": null,
"e": 8581,
"s": 8478,
"text": "They can only begin with a letter and then may be followed by other letters, numbers, and underscores."
},
{
"code": null,
"e": 8669,
"s": 8581,
"text": "LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable."
},
{
"code": null,
"e": 8757,
"s": 8669,
"text": "LOLCODE does not allow use of spaces, dashes, or other symbols while naming a variable."
},
{
"code": null,
"e": 8798,
"s": 8757,
"text": "Variable identifiers are case sensitive."
},
{
"code": null,
"e": 8839,
"s": 8798,
"text": "Variable identifiers are case sensitive."
},
{
"code": null,
"e": 8920,
"s": 8839,
"text": "Here are some of the rules for valid and invalid names for variables in LOLCODE−"
},
{
"code": null,
"e": 9002,
"s": 8920,
"text": "The name should always begin with an alphabet. For example, name, Name are valid."
},
{
"code": null,
"e": 9084,
"s": 9002,
"text": "The name should always begin with an alphabet. For example, name, Name are valid."
},
{
"code": null,
"e": 9164,
"s": 9084,
"text": "The name of a variable cannot begin with a digit. For example, 2var is invalid."
},
{
"code": null,
"e": 9244,
"s": 9164,
"text": "The name of a variable cannot begin with a digit. For example, 2var is invalid."
},
{
"code": null,
"e": 9306,
"s": 9244,
"text": "The name of a variable cannot begin with a special character."
},
{
"code": null,
"e": 9368,
"s": 9306,
"text": "The name of a variable cannot begin with a special character."
},
{
"code": null,
"e": 9498,
"s": 9368,
"text": "A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name."
},
{
"code": null,
"e": 9628,
"s": 9498,
"text": "A variable can contain _ or a digit anywhere inside its name, except at the starting index. For example, name2_m is a valid name."
},
{
"code": null,
"e": 9686,
"s": 9628,
"text": "Some examples of valid names in LOLCODE are shown below −"
},
{
"code": null,
"e": 9818,
"s": 9686,
"text": "HAI 1.2\nI HAS A food ITZ \"111.00033\"\nI HAS A food2 ITZ \"111\"\nI HAS A fo_od ITZ \"1\"\nVISIBLE food\nVISIBLE food2\nVISIBLE fo_od\nKTHXBYE"
},
{
"code": null,
"e": 9931,
"s": 9818,
"text": "All the declaration statements in the above code are valid and will produce the following output when executed −"
},
{
"code": null,
"e": 9968,
"s": 9931,
"text": "sh-4.3$ lci main.lo\n111.00033\n111\n1\n"
},
{
"code": null,
"e": 10039,
"s": 9968,
"text": "Some examples of invalid statements and their output are given below −"
},
{
"code": null,
"e": 10086,
"s": 10039,
"text": "HAI 1.2\nI HAS A 2food ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 10154,
"s": 10086,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 10218,
"s": 10154,
"text": "sh-4.3$ lci main.lo\nLine 2: Expected: identifier; Got: int(2).\n"
},
{
"code": null,
"e": 10265,
"s": 10218,
"text": "HAI 1.2\nI HAS A _food ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 10333,
"s": 10265,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 10411,
"s": 10333,
"text": "sh-4.3$ lci main.lo\nLine 2: Unrecognized sequence at: _food ITZ \"111.00033\".\n"
},
{
"code": null,
"e": 10458,
"s": 10411,
"text": "HAI 1.2\nI HAS A f$ood ITZ \"111.00033\"\nKTHXBYE\n"
},
{
"code": null,
"e": 10526,
"s": 10458,
"text": "The above code will give the following output when you execute it −"
},
{
"code": null,
"e": 10603,
"s": 10526,
"text": "sh-4.3$ lci main.lo\nLine 2: Unrecognized sequence at: $ood ITZ \"111.00033\".\n"
},
{
"code": null,
"e": 10759,
"s": 10603,
"text": "To declare a variable, LOLCODE provides a keyword “I HAS A” which is followed by the variable name. You can find below the syntax for declaring a variable."
},
{
"code": null,
"e": 10830,
"s": 10759,
"text": "I HAS A VAR BTW VAR is empty now, You can use any name instead of var\n"
},
{
"code": null,
"e": 11036,
"s": 10830,
"text": "To assign the variable a value in the same statement, you can then follow the variable name with “ITZ” and then give the value you want to assign. Use the following syntax to assign a value to a variable −"
},
{
"code": null,
"e": 11063,
"s": 11036,
"text": "<variable> R <expression>\n"
},
{
"code": null,
"e": 11165,
"s": 11063,
"text": "VAR R \"Green\" BTW VAR is now a YARN and equals \"Green\"\nVAR R 30 BTW VAR is now a NUMBR and equals 30\n"
},
{
"code": null,
"e": 11252,
"s": 11165,
"text": "You can also declare and assign variables at the same time using the following syntax−"
},
{
"code": null,
"e": 11275,
"s": 11252,
"text": "I HAS A VAR ITZ VALUE\n"
},
{
"code": null,
"e": 11311,
"s": 11275,
"text": "I HAS A NAME ITS “TUTORIALS POINT”\n"
},
{
"code": null,
"e": 11543,
"s": 11311,
"text": "HAI 1.2\nBTW this is how we declare variables\nI HAS A food\nI HAS A bird\nBTW this is how we assign variables\nfood R 1\nbird R 5\nBTW this is how initialize variables\nI HAS A biz ITZ \"OMG!\"\nVISIBLE food\nVISIBLE biz\nVISIBLE bird\nKTHXBYE\n"
},
{
"code": null,
"e": 11629,
"s": 11543,
"text": "The above program shows the declaration of variables and prints them. The output is −"
},
{
"code": null,
"e": 11660,
"s": 11629,
"text": "sh-\n4.3$ lci main.lo\n1\nOMG!\n5\n"
},
{
"code": null,
"e": 11927,
"s": 11660,
"text": "To convert a value of one type to another type, we use type casting. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number. Casting a NUMBAR to a YARN (by printing it, for example), truncates the output to a default 2 decimal places."
},
{
"code": null,
"e": 12053,
"s": 11927,
"text": "HAI 1.2\nI HAS A food ITZ \"111.00033\"\nVISIBLE food\nBTW this is how we do type casting\nMAEK food A NUMBAR\nVISIBLE food\nKTHXBYE\n"
},
{
"code": null,
"e": 12112,
"s": 12053,
"text": "The above line of code will produce the following output −"
},
{
"code": null,
"e": 12153,
"s": 12112,
"text": "sh-4.3$ lci main.lo\n111.00033\n111.00033\n"
},
{
"code": null,
"e": 12285,
"s": 12153,
"text": "All the variables declared in a LOLCODE program are local variables and there is no global scope in this language for any variable."
},
{
"code": null,
"e": 12507,
"s": 12285,
"text": "LOLCODE is designed to test the boundaries of the programming language design. It is an esoteric programming language inspired by the funny things on the Internet. This chapter gives you an understanding of LOLCODE types."
},
{
"code": null,
"e": 12554,
"s": 12507,
"text": "Currently, the variable types in LOLCODE are −"
},
{
"code": null,
"e": 12569,
"s": 12554,
"text": "strings (YARN)"
},
{
"code": null,
"e": 12586,
"s": 12569,
"text": "integers (NUMBR)"
},
{
"code": null,
"e": 12602,
"s": 12586,
"text": "floats (NUMBAR)"
},
{
"code": null,
"e": 12623,
"s": 12602,
"text": "and booleans (TROOF)"
},
{
"code": null,
"e": 12639,
"s": 12623,
"text": "Arrays (BUKKIT)"
},
{
"code": null,
"e": 12803,
"s": 12639,
"text": "In LOLCODE the variable type is handled dynamically by the compiler. If a variable does not have an initial value, it is called untyped (known as NOOB in LOLCODE)."
},
{
"code": null,
"e": 12882,
"s": 12803,
"text": "The syntax for declaring and using different types in LOLCODE is shown below −"
},
{
"code": null,
"e": 12920,
"s": 12882,
"text": "I HAS A <VARIABLE> ITZ A <DATA TYPE>\n"
},
{
"code": null,
"e": 12957,
"s": 12920,
"text": "I HAS A <VARIABLE> ITZ <EXPRESSION<\n"
},
{
"code": null,
"e": 12984,
"s": 12957,
"text": "<VARIABLE> R <EXPRESSION>\n"
},
{
"code": null,
"e": 13217,
"s": 12984,
"text": "The untyped data type (known as NOOB), cannot be converted into any other type except into a TROOF data type. The implicit casting of a NOOB into TROOF makes the variable FAIL. After that any operation on a NOOB results in an error."
},
{
"code": null,
"e": 13379,
"s": 13217,
"text": "Explicit casts of a NOOB data type (i.e. the types that are uninitialized and do not have any initial value) variable results to zero values for all other types."
},
{
"code": null,
"e": 13480,
"s": 13379,
"text": "To define an untyped variable, just declare a variable and assign a value as shown in this example −"
},
{
"code": null,
"e": 13602,
"s": 13480,
"text": "HAI 1.2\nI HAS A VAR3\nVAR3 R \"ANYVALUE\"\nVISIBLE VAR3\nBTW Or declare in same line\nI HAS A VAR4 ITZ 44\nVISIBLE VAR4\nKTHXBYE\n"
},
{
"code": null,
"e": 13671,
"s": 13602,
"text": "When you run the above program, you will find the following result −"
},
{
"code": null,
"e": 13706,
"s": 13671,
"text": "sh-\n4.3$ lci main.lo \nANYVALUE\n44\n"
},
{
"code": null,
"e": 14060,
"s": 13706,
"text": "In LOLCODE, the Boolean values are of two types. BOOLEAN generally have two values- true and false. But, in LOLCODE, the Boolean is known as TROOF, and the true/ false values are known as WIN/FAIL respectively. All the uninitialized values like an empty string (\"\"), or an empty array will all cast to FAIL. All other initialized values evaluate to WIN."
},
{
"code": null,
"e": 14132,
"s": 14060,
"text": "HAI 1.2\nI HAS A VAR3 ITZ A TROOF\nVAR3 R \"FAIL\"\n VISIBLE VAR3\nKTHXBYE\n"
},
{
"code": null,
"e": 14199,
"s": 14132,
"text": "You can see the following output when you execute the above code −"
},
{
"code": null,
"e": 14225,
"s": 14199,
"text": "sh-4.3$ lci main.lo\nFAIL\n"
},
{
"code": null,
"e": 14484,
"s": 14225,
"text": "In LOLCODE, a NUMBR stands for an integer. Any sequence of digits is considered as a NUMBR, unless it has a decimal appearing anywhere in between the sequence. To make any number negative, it may be preceded by a hyphen (-) which signifies a negative number."
},
{
"code": null,
"e": 14542,
"s": 14484,
"text": "HAI 1.2\nI HAS A VAR3 ITZ A NUMBR\n VISIBLE VAR3\nKTHXBYE\n"
},
{
"code": null,
"e": 14605,
"s": 14542,
"text": "The above code shows you the following result when you run it−"
},
{
"code": null,
"e": 14630,
"s": 14605,
"text": "sh- \n4.3$ lci main.lo\n0\n"
},
{
"code": null,
"e": 14945,
"s": 14630,
"text": "Similar to NUMBR, LOLCODE has another data type, which represents a decimal or a float in many programming languages. In LOLCODE, a NUMBAR is a float containing one decimal point. Casting a NUMBAR to a NUMBR truncates the decimal portion of the floating point number and returns it as a NUMBR, without any decimal."
},
{
"code": null,
"e": 15066,
"s": 14945,
"text": "In LOLCODE, value containing strings, i.e. string literals (YARN) should start and end with double quotation marks (\"”)."
},
{
"code": null,
"e": 15340,
"s": 15066,
"text": "Anything may be written inside the string, like space, comma, full stop, exclamation or any other symbol. A string where any single quote is missing may cause an error. Colons are used as escape characters in LOLCODE, and any value following a colon gets a special meaning."
},
{
"code": null,
"e": 15407,
"s": 15340,
"text": ":) − A closing bracket following a colon represents a newline (\\n)"
},
{
"code": null,
"e": 15474,
"s": 15407,
"text": ":) − A closing bracket following a colon represents a newline (\\n)"
},
{
"code": null,
"e": 15543,
"s": 15474,
"text": ":> − A closing angle bracket following a colon represents a tab (\\t)"
},
{
"code": null,
"e": 15612,
"s": 15543,
"text": ":> − A closing angle bracket following a colon represents a tab (\\t)"
},
{
"code": null,
"e": 15681,
"s": 15612,
"text": ":o − A ‘o’ character following a colon represents a bell (beep) (\\g)"
},
{
"code": null,
"e": 15750,
"s": 15681,
"text": ":o − A ‘o’ character following a colon represents a bell (beep) (\\g)"
},
{
"code": null,
"e": 15815,
"s": 15750,
"text": ":\" − A “ following a colon represents a literal double quote (\")"
},
{
"code": null,
"e": 15880,
"s": 15815,
"text": ":\" − A “ following a colon represents a literal double quote (\")"
},
{
"code": null,
"e": 15949,
"s": 15880,
"text": ":: − A colon following a colon represents a single literal colon (:)"
},
{
"code": null,
"e": 16018,
"s": 15949,
"text": ":: − A colon following a colon represents a single literal colon (:)"
},
{
"code": null,
"e": 16088,
"s": 16018,
"text": "HAI 1.2\nI HAS A VAR3 ITZ A YARN\nVAR3 R \"XYZ\"\n VISIBLE VAR3\nKTHXBYE\n"
},
{
"code": null,
"e": 16156,
"s": 16088,
"text": "The code given above produces the following output upon execution −"
},
{
"code": null,
"e": 16183,
"s": 16156,
"text": "sh-\n4.3$ lci main.lo \nXYZ\n"
},
{
"code": null,
"e": 16331,
"s": 16183,
"text": "This type represents an array. It has named slots, which can contain either variables or functions. A BUKKIT can be declared in the following way −"
},
{
"code": null,
"e": 16623,
"s": 16331,
"text": "BTW declaration of the BUKKIT\nI HAS A [object] ITZ A BUKKIT BTW creating a variable in a slots\n[object] HAS A [var] ITZ [value] BTW creating a function inside the BUKKIT\nHOW IZ [object] [function name] (YR [argument1] (AN YR [argument2] (AN YR [argument3] ...)))\n[function code]\nIF U SAY SO\n"
},
{
"code": null,
"e": 16822,
"s": 16623,
"text": "A function inside a BUKKIT may also access variables and other functions of the BUKKIT by using ME'Z [var] or ME IZ [function name] (YR [argument1] (AN YR [argument2] (AN YR [argument3] ...))) MKAY."
},
{
"code": null,
"e": 17045,
"s": 16822,
"text": "HAI 1.2\n I HAS A VAR6 ITZ A BUKKIT\n BTW DECLARING AN ARRAY\n VAR6 HAS A VAR7 ITZ \"DOGE\"\n BTW VAR7 IS A STRING VARIABLE THAT IS INSERTED INTO ARRAY VAR6\n VISIBLE VAR6'Z VAR7\n BTW GET THE ELEMENT OF ARRAY\nKTHXBYE"
},
{
"code": null,
"e": 17114,
"s": 17045,
"text": "This is the output you will find when you run the code given above −"
},
{
"code": null,
"e": 17142,
"s": 17114,
"text": "sh-\n4.3$ lci main.lo \nDOGE\n"
},
{
"code": null,
"e": 17289,
"s": 17142,
"text": "Operators play an important role to perform various operations on variables. This chapter brings you various operators in LOLCODE and their usage."
},
{
"code": null,
"e": 17596,
"s": 17289,
"text": "Mathematical operators depend on a prefix notation i.e. the notation that comes before the operand. When all the operators have known number of arguments or operands, then no grouping markers are necessary. In cases where operators don’t have fixed arguments or operands, the operation is closed with MKAY."
},
{
"code": null,
"e": 17779,
"s": 17596,
"text": "An MKAY may not be used if it coincides with the end of the statement. In such cases, the EOL keyword should be used. To use unary mathematical operators , use the following syntax −"
},
{
"code": null,
"e": 17804,
"s": 17779,
"text": "<operator> <expression>\n"
},
{
"code": null,
"e": 17979,
"s": 17804,
"text": "The AN keyword can optionally be used to separate arguments, and apply a single operation on more than one operand, so a binary operator expression has the following syntax −"
},
{
"code": null,
"e": 18022,
"s": 17979,
"text": "<operator> <expression1> AN <expression2>\n"
},
{
"code": null,
"e": 18139,
"s": 18022,
"text": "Any expression containing an operator with infinite number of arguments can be expressed with the following syntax −"
},
{
"code": null,
"e": 18212,
"s": 18139,
"text": "<operator> <expression1> [[AN <expression2>] AN <expression3> ...] MKAY\n"
},
{
"code": null,
"e": 18273,
"s": 18212,
"text": "Following are the basic mathematical operations in LOLCODE −"
},
{
"code": null,
"e": 18644,
"s": 18273,
"text": "SUM OF <a> AN <b> BTW This is a plus + operator\nDIFF OF <a> AN <n> BTW This is a minus - operator\nPRODUKT OF <a> AN <n> BTW This is a multiply operator *\nQUOSHUNT OF <a> AN <n> BTW This is a divide operator\nMOD OF <a> AN <n> BTW This is a modulo operator\nBIGGR OF <a> AN <n> BTW This is a max operator\nSMALLR OF <a> AN <n> BTW This is a min operator\n"
},
{
"code": null,
"e": 18767,
"s": 18644,
"text": "<a> and <b> can each be unique expressions in the above, so mathematical operators can be nested and grouped indefinitely."
},
{
"code": null,
"e": 18959,
"s": 18767,
"text": "Math is performed considering arguments as integer math in the presence of two NUMBRs, but if either of the expressions is NUMBAR, then operations are considered as floating point operations."
},
{
"code": null,
"e": 19254,
"s": 18959,
"text": "HAI 1.2\n I HAS A m ITZ 4\n I HAS A n ITZ 2\nVISIBLE SUM OF m AN n BTW +\nVISIBLE DIFF OF m AN n BTW -\nVISIBLE PRODUKT OF m AN n BTW *\nVISIBLE QUOSHUNT OF m AN n BTW /\nVISIBLE MOD OF m AN n BTW modulo\nVISIBLE BIGGR OF m AN n BTW max\nVISIBLE SMALLR OF m AN n BTW min\nKTHXBYE\n"
},
{
"code": null,
"e": 19321,
"s": 19254,
"text": "The above code will produce the following output when you run it −"
},
{
"code": null,
"e": 19364,
"s": 19321,
"text": "sh-\n4.3$ lci main.lo\n\n6\n\n2\n\n8\n\n2\n\n0\n\n4\n\n2\n"
},
{
"code": null,
"e": 19463,
"s": 19364,
"text": "Consider the following important points related to working with mathematical operators in LOLCODE−"
},
{
"code": null,
"e": 19544,
"s": 19463,
"text": "If one or both arguments in an expression are YARN, they are treated as NUMBARs."
},
{
"code": null,
"e": 19625,
"s": 19544,
"text": "If one or both arguments in an expression are YARN, they are treated as NUMBARs."
},
{
"code": null,
"e": 19733,
"s": 19625,
"text": "If any of the arguments cannot be safely casted internally to a numerical type, then it fails with an error"
},
{
"code": null,
"e": 19841,
"s": 19733,
"text": "If any of the arguments cannot be safely casted internally to a numerical type, then it fails with an error"
},
{
"code": null,
"e": 19969,
"s": 19841,
"text": "Boolean operators are applied on those values that may be true or false. Boolean operators working on TROOFs are as following −"
},
{
"code": null,
"e": 20435,
"s": 19969,
"text": "BOTH OF <m> AN <n> BTW its and operation: WIN if m = WIN and n = WIN\nEITHER OF <m> AN <n> BTW its or operation: FAIL iff m = FAIL, n = FAIL\nWON OF <m> AN <n> BTW its xor operation: FAIL if m = n\nNOT <m> BTW its an unary negation: WIN if m = FAIL\nALL OF <m> AN <n> ... MKAY BTW it will take infinite arguments and apply AND\nANY OF <m> AN <n> ... MKAY BTW it will take infinite arguments and apply OR."
},
{
"code": null,
"e": 20572,
"s": 20435,
"text": "Please note that <m> and <n> in the expression syntax above are automatically cast as TROOF values if they are not already TROOF Values."
},
{
"code": null,
"e": 20678,
"s": 20572,
"text": "When you want to compare two or more operands in LOLCODE, you can do so in any of the following methods −"
},
{
"code": null,
"e": 20768,
"s": 20678,
"text": "You can compare two binary operands using equality operators. The syntax is shown below −"
},
{
"code": null,
"e": 20906,
"s": 20768,
"text": "BOTH SAEM <m> AN <n> BTW this will return WIN if m is equal to n\nDIFFRINT <m> AN <n> BTW this will return WIN if m is not equal to n"
},
{
"code": null,
"e": 21061,
"s": 20906,
"text": "You can compare if both the values are of NUMBRs type. Remember that if either of the values are NUMBARs, then they are compared as floating point values."
},
{
"code": null,
"e": 21162,
"s": 21061,
"text": "You can also perform comparison using the minimum and maximum operators. The syntax is shown below −"
},
{
"code": null,
"e": 21315,
"s": 21162,
"text": "BOTH SAEM <m> AN BIGGR OF <m> AN <n>\n\nBOTH SAEM <m> AN SMALLR OF <m> AN <n>\nDIFFRINT <m> AN SMALLR OF <m> AN <n>\nDIFFRINT <m> AN BIGGR OF <m> AN <n>"
},
{
"code": null,
"e": 21323,
"s": 21315,
"text": "Example"
},
{
"code": null,
"e": 21491,
"s": 21323,
"text": "HAI 1.2\n I HAS A VAR11 ITZ 7\n BOTH SAEM VAR11 SMALLR OF VAR11 AN 8, O RLY?\n YA RLY\n VISIBLE \"TRUE\"\n NO WAI\n VISIBLE \"FALSE\"\n OIC\nKTHXBY"
},
{
"code": null,
"e": 21558,
"s": 21491,
"text": "You can see the following output when you execute the given code −"
},
{
"code": null,
"e": 21586,
"s": 21558,
"text": "sh-\n4.3$ lci main.lo\n\nTRUE\n"
},
{
"code": null,
"e": 21767,
"s": 21586,
"text": "LOLCODE allows you to explicitly concatenate infinite number of YARNs using the SMOOSH...MKAY operator. For concatenation, multiple arguments can be separated with the AN operator."
},
{
"code": null,
"e": 21957,
"s": 21767,
"text": "HAI 1.2\nI HAS A VAR1 ITZ A YARN\nVAR1 R \"TRUE\"\nI HAS A VAR2 ITZ A YARN\nVAR2 R \"ANOTHER TRUE\"\nI HAS A VAR3 ITZ A YARN\nVAR3 R \"ONE MORE TRUE\"\nVISIBLE SMOOSH VAR1 \" \" VAR3 \" \" VAR2 MKAY\nKTHXBYE"
},
{
"code": null,
"e": 22029,
"s": 21957,
"text": "The above given code will produce the following result upon execution −"
},
{
"code": null,
"e": 22083,
"s": 22029,
"text": "sh-\n4.3$ lci main.lo\n\nTRUE ONE MORE TRUE ANOTHER TRUE"
},
{
"code": null,
"e": 22277,
"s": 22083,
"text": "Operators that work on specific types implicitly cast or convert the values of one type to other type safely. If the value cannot be safely converted to other type, then it results in an error."
},
{
"code": null,
"e": 22420,
"s": 22277,
"text": "An expression's value may be explicitly casted or converted to some other type with the binary MAEK operator. The syntax of MAEK Operator is −"
},
{
"code": null,
"e": 22448,
"s": 22420,
"text": "MAEK <expression> A <type>\n"
},
{
"code": null,
"e": 22513,
"s": 22448,
"text": "where, <type> can be one of TROOF, YARN, NUMBR, NUMBAR, or NOOB."
},
{
"code": null,
"e": 22688,
"s": 22513,
"text": "To explicitly cast a variable to some other type, a normal assignment statement with the MAEK operator can be used, or a casting assignment statement may be used as follows −"
},
{
"code": null,
"e": 22793,
"s": 22688,
"text": "<Any_variable> IS NOW A <type> BTW this code will be equal to\n<Any_variable> R MAEK <variable> A <type>"
},
{
"code": null,
"e": 22918,
"s": 22793,
"text": "HAI 1.2\nI HAS A food ITZ \"111.00033\"\nVISIBLE food\nBTW this is how we do type casting\nMAEK food A NUMBAR\nVISIBLE food\nKTHXBYE"
},
{
"code": null,
"e": 22968,
"s": 22918,
"text": "The above code will produce the following output−"
},
{
"code": null,
"e": 22998,
"s": 22968,
"text": "sh-4.3$ lci main.lo\n111.00033"
},
{
"code": null,
"e": 23114,
"s": 22998,
"text": "This chapter will explain you how to input a value through LOLCODE terminal and how to output it onto the terminal."
},
{
"code": null,
"e": 23359,
"s": 23114,
"text": "You can use the keyword VISIBLE to print something in LOLCODE. VISIBLE is a function which can take an infinite number of characters as input, and prints them all at once by internally concatenating them, and converting them to strings or YARN."
},
{
"code": null,
"e": 23454,
"s": 23359,
"text": "The VISIBLE function ends or terminates by a delimiter, which is either a line end or a comma."
},
{
"code": null,
"e": 23656,
"s": 23454,
"text": "The output is automatically terminated by the compiler with a carriage return. If the final token is terminated with an exclamation symbol (!), then the carriage returned is over-ridden by this symbol."
},
{
"code": null,
"e": 23708,
"s": 23656,
"text": "VISIBLE <any_expression> [<any_expression> ...][!]\n"
},
{
"code": null,
"e": 23810,
"s": 23708,
"text": "Please note that in LOLCODE, currently there is no defined standard for printing some data to a file."
},
{
"code": null,
"e": 24009,
"s": 23810,
"text": "To take some input from the user, the keyword used is GIMMEH. It is a function which can take any number of variables as input. It takes YARN as the input and stores the value in any given variable."
},
{
"code": null,
"e": 24032,
"s": 24009,
"text": "GIMMEH <any_variable>\n"
},
{
"code": null,
"e": 24215,
"s": 24032,
"text": "HAI 1.2\n I HAS A VAR ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE\n VISIBLE \"TYPE SOMETHING AND ENTER\"\n GIMMEH VAR BTW GET INPUT (STRING) INTO VARIABLE\n VISIBLE VAR\nKTHXBYE"
},
{
"code": null,
"e": 24397,
"s": 24215,
"text": "When this code is run, it will ask you to enter a number and then prints the number back in the next line automatically. When you run this code, it will print the following output −"
},
{
"code": null,
"e": 24451,
"s": 24397,
"text": "sh-\n4.3$ lci main.lo\n\nTYPE SOMETHING AND ENTER\n67\n\n67"
},
{
"code": null,
"e": 24603,
"s": 24451,
"text": "LOLCODE allows you to control the flow of program through various statements. This chapter explains different types of statements available in LOLCODE."
},
{
"code": null,
"e": 24936,
"s": 24603,
"text": "An expression without any assignment, i.e. simply calling a mathematical operation or any function, is a legal statement in LOLCODE. Once the expression is evaluated, its final value is placed in the temporary variable IT. The value of IT remains in the local scope, and exists until the next time it is replaced with an expression."
},
{
"code": null,
"e": 25060,
"s": 24936,
"text": "Assignment statements are used to assign the output of any expression to a given variable. They are generally of the form −"
},
{
"code": null,
"e": 25114,
"s": 25060,
"text": "<any_variable> <assignment operator> <any expression>"
},
{
"code": null,
"e": 25208,
"s": 25114,
"text": "Please note that, you can use a variable in the expression, even before it is being assigned."
},
{
"code": null,
"e": 25369,
"s": 25208,
"text": "The if−then statement is a very simple operation working on the IT variable. It is similar to if−else statements in other programming languages like C and Java."
},
{
"code": null,
"e": 25426,
"s": 25369,
"text": "There are four keywords to apply the if–then statements."
},
{
"code": null,
"e": 25433,
"s": 25426,
"text": "O RLY?"
},
{
"code": null,
"e": 25440,
"s": 25433,
"text": "YA RLY"
},
{
"code": null,
"e": 25447,
"s": 25440,
"text": "NO WAI"
},
{
"code": null,
"e": 25451,
"s": 25447,
"text": "OIC"
},
{
"code": null,
"e": 25473,
"s": 25451,
"text": "The general form is −"
},
{
"code": null,
"e": 25610,
"s": 25473,
"text": "<any_expression>\nO RLY?\n YA RLY\n <code to execute if above condition is true>\n NO WAI\n <code to execute in this block>\nOIC"
},
{
"code": null,
"e": 25697,
"s": 25610,
"text": "All of the above statements can be written in the same line separated by commas like −"
},
{
"code": null,
"e": 25815,
"s": 25697,
"text": " BOTH SAEM NAMES AN \"Name\", O RLY?\n YA RLY, VISIBLE \"My name is ABCD\"\n NO WAI, VISIBLE \"Your name is ABCD\"\n OIC\n "
},
{
"code": null,
"e": 25936,
"s": 25815,
"text": "While using the if-then statements, an optional MEBBE <any expression> may be used between the YA RLY and NO WAI blocks."
},
{
"code": null,
"e": 26130,
"s": 25936,
"text": "If the <any expression> following MEBBE is True (WIN), then that block is executed. Otherwise, if that expression is false, the block is skipped until the next MEBBE, NO WAI, or OIC statements."
},
{
"code": null,
"e": 26390,
"s": 26130,
"text": "<any expression>\nO RLY?\n YA RLY\n <code to be executed if true>\n MEBBE <expression>\n <code to be executed mebbe is true>\n MEBBE <expression>\n <code to be executed mebbe is true>\n NO WAI\n <code to be executed if above are false>\nOIC "
},
{
"code": null,
"e": 26535,
"s": 26390,
"text": "BOTH SAEM NAMES AN \"NAME\"\nO RLY?\n YA RLY, VISIBLE \"YOUR NAME IS ABCD\"\n MEBBE BOTH SAEM ANIMAL AN \"OUR NAME IS ABCD\"\n VISIBLE \"NO ABCD\"\nOIC"
},
{
"code": null,
"e": 26776,
"s": 26535,
"text": "In LOLCODE, the keyword ‘WTF?’ is similar to switch in many other languages. The keyword WTF? takes IT as the expression value for comparison. To use WTF, a comparison block is opened by OMG which should be a literal, and not an expression."
},
{
"code": null,
"e": 26866,
"s": 26776,
"text": "Please remember that each literal must be unique, similar to the case in other languages."
},
{
"code": null,
"e": 27023,
"s": 26866,
"text": "The OMG block must be terminated by a GTFO statement. If an OMG block is not terminated by a GTFO, then the next OMG block is executed till GTFO is reached."
},
{
"code": null,
"e": 27107,
"s": 27023,
"text": "If none of the literals evaluate as true, then default case is signified by OMGWTF."
},
{
"code": null,
"e": 27480,
"s": 27107,
"text": "WTF?\n OMG <any value to compare>\n <code block to execute if expression is satisfied>\n OMG <any value to compare>\n <code block to execute if expression is satisfied>\n OMGWTF\n <code block to execute as a default case>\nOIC\nNAME, WTF?\n OMG \"A\"\n VISIBLE \"ABCD\"\n GTFO\n OMG \"E\"\n VISIBLE \"EFGH\"\n GTFO\n OMGWTF\n VISIBLE \"ZYXW\"\nOIC"
},
{
"code": null,
"e": 27527,
"s": 27480,
"text": "The output results of the above code will be −"
},
{
"code": null,
"e": 27532,
"s": 27527,
"text": "\"E\":"
},
{
"code": null,
"e": 27538,
"s": 27532,
"text": "EFGH\n"
},
{
"code": null,
"e": 27818,
"s": 27538,
"text": "Loops are used in programming languages to execute a set of statements multiple times. For example, if you want to print the digit 5 for five times, then instead of writing the VISIBLE “5” statement five times, you can run a loop with single VISIBLE “5” statement for five times."
},
{
"code": null,
"e": 27998,
"s": 27818,
"text": "Simple loops are represented with IM IN YR <label> and IM OUTTA YR <label>. Loops defined in this way are infinite loops and they should be terminated with a GTFO break statement."
},
{
"code": null,
"e": 28044,
"s": 27998,
"text": "Iteration loops have the following structure−"
},
{
"code": null,
"e": 28198,
"s": 28044,
"text": "IM IN YR <label> <any_operation> YR <any_variable> [TIL|WILE <expression>]\n <code block to execute inside the loop multiple times>\nIM OUTTA YR <label>\n"
},
{
"code": null,
"e": 28329,
"s": 28198,
"text": "Please note that inside the function body, UPPIN (increment by one), NERFIN (decrement by one), or any unary function can be used."
},
{
"code": null,
"e": 28549,
"s": 28329,
"text": "The TIL keyword calculates the expression as a TROOF: if it evaluates as FAIL, the loop continues once more, if it evaluates as WIN, then the loop execution stops, and continues after the matching IM OUTTA YR statement."
},
{
"code": null,
"e": 28671,
"s": 28549,
"text": "The WILE keyword is the opposite of TIL keyword, if the expression is WIN, execution continues, otherwise the loop exits."
},
{
"code": null,
"e": 28802,
"s": 28671,
"text": "HAI 1.2\nI HAS A VAR ITZ 0\nIM IN YR LOOPY UPPIN YR VAR TIL BOTH SAEM VAR AN 10\n VISIBLE SUM OF VAR AN 1\nIM OUTTA YR LOOPY\nKTHXBYE"
},
{
"code": null,
"e": 28930,
"s": 28802,
"text": "When the above code is compiled on any LOLCODE compiler, or on our online codingground, this will produce the following output."
},
{
"code": null,
"e": 28982,
"s": 28930,
"text": "sh-\n4.3$ lci main.lo\n1\n\n2\n\n3\n\n4\n\n5\n\n6\n\n7\n\n8\n\n9\n\n10\n"
},
{
"code": null,
"e": 29221,
"s": 28982,
"text": "Functions are useful in programming because they reduce time and effort for writing the code again and again. A well written function code offers high reusability. This chapter explains you how to write and work with functions in LOLCODE."
},
{
"code": null,
"e": 29424,
"s": 29221,
"text": "A function is a set of statements that are executed all at once by calling that function. In LOLCODE, a function’s definition starts with the keyword “HOW IZ I” and the closing keyword is “IF U SAY SO”."
},
{
"code": null,
"e": 29473,
"s": 29424,
"text": "The syntax for writing a function in LOLCODE is−"
},
{
"code": null,
"e": 29627,
"s": 29473,
"text": "HOW IZ I <function name> [YR <parameter/argument> [AN YR <other _arguments..> ...]]\n <code block to execute / Set of statements to execute>\nIF U SAY SO"
},
{
"code": null,
"e": 29710,
"s": 29627,
"text": "Consider the following important points when you are defining a LOLCODE function −"
},
{
"code": null,
"e": 29800,
"s": 29710,
"text": "In LOLCODE, the function can accept only a certain fixed number of arguments as an input."
},
{
"code": null,
"e": 29890,
"s": 29800,
"text": "In LOLCODE, the function can accept only a certain fixed number of arguments as an input."
},
{
"code": null,
"e": 29979,
"s": 29890,
"text": "The arguments or parameters, are the identifiers that become a variable to the function."
},
{
"code": null,
"e": 30068,
"s": 29979,
"text": "The arguments or parameters, are the identifiers that become a variable to the function."
},
{
"code": null,
"e": 30170,
"s": 30068,
"text": "Functions in LOLCODE can’t access any other values other than the values passed to them as arguments."
},
{
"code": null,
"e": 30272,
"s": 30170,
"text": "Functions in LOLCODE can’t access any other values other than the values passed to them as arguments."
},
{
"code": null,
"e": 30487,
"s": 30272,
"text": "Return in coding means something that is given back. In programming, a function can return some value to the program when its execution is completed. In LOLCODE, functions return varying values as explained below −"
},
{
"code": null,
"e": 30593,
"s": 30487,
"text": "FOUND YR <any_expression> returns the value of the expression when function block is executed completely."
},
{
"code": null,
"e": 30699,
"s": 30593,
"text": "FOUND YR <any_expression> returns the value of the expression when function block is executed completely."
},
{
"code": null,
"e": 30807,
"s": 30699,
"text": " GTFO returns no value (NOOB), which is similar to return 0 in other programming languages like C and Java."
},
{
"code": null,
"e": 30914,
"s": 30807,
"text": "GTFO returns no value (NOOB), which is similar to return 0 in other programming languages like C and Java."
},
{
"code": null,
"e": 31028,
"s": 30914,
"text": "If no other return statement is found, then IF U SAY SO is executed and the value in the IT variable is returned."
},
{
"code": null,
"e": 31141,
"s": 31028,
"text": "If no other return statement is found, then IF U SAY SO is executed and the value in the IT variable is returned"
},
{
"code": null,
"e": 31301,
"s": 31141,
"text": "A function is defined in the body of program and is later called for execution. A function which accepts a given number of arguments is called as shown below −"
},
{
"code": null,
"e": 31406,
"s": 31301,
"text": "I IZ <function_name> [YR <expression_One> [AN YR <expression_Two> [AN YR <expression_Three> ...]]] MKAY\n"
},
{
"code": null,
"e": 31745,
"s": 31406,
"text": "While calling a function, the expression is formed by the function name, followed by the number of arguments that the function will accept. These arguments can be simple variables or any expressions. If a function accepts any expression instead of a simple value, then the expressions' values are calculated before the function is called."
},
{
"code": null,
"e": 31867,
"s": 31745,
"text": "Please remember that the number of arguments a function will accept, should be defined in the definition of the function."
},
{
"code": null,
"e": 31979,
"s": 31867,
"text": "HAI\n\n\nHOW DUZ I MAINUMBA\n I HAS A NUMBA\n GIMMEH NUMBA\n FOUND YR NUMBA\nIF U SAY SO\n\nVISIBLE MAINUMBA\n\nKTHXBYE"
},
{
"code": null,
"e": 32152,
"s": 31979,
"text": "When you run the above code, it will ask for an input, and then when you submit the input, you’ll see the same as the result. For example, if we enter 55, it will print 55."
},
{
"code": null,
"e": 32325,
"s": 32152,
"text": "HAI 1.2\nHOW IZ I MULTIPLY YR FIRSTOPERANT AN YR SECONDOPERANT\n FOUND YR PRODUKT OF FIRSTOPERANT AN SECONDOPERANT\n IF U SAY SO\n VISIBLE I IZ MULTIPLY YR 2 AN YR 3\nKTHXBYE"
},
{
"code": null,
"e": 32440,
"s": 32325,
"text": "The above function that performs multiplication of input operands will print the following output when you run it−"
},
{
"code": null,
"e": 32465,
"s": 32440,
"text": "sh-\n4.3$ lci main.lo\n\n6\n"
},
{
"code": null,
"e": 32763,
"s": 32465,
"text": "HAI 1.2\nI HAS A STRINGARRAY ITZ A BUKKIT\n STRINGARRAY HAS A VAR17 ITZ \"OBJECT1\"\n STRINGARRAY HAS A VAR18 ITZ \"OBJECT2\"\n HOW IZ STRINGARRAY ACCESS YR VARIABLE\n FOUND YR STRINGARRAY'Z SRS VARIABLE\n IF U SAY SO\n I HAS A STRING ITZ \"VAR17\"\n VISIBLE STRINGARRAY IZ ACCESS YR STRING MKAY\nKTHXBYE"
},
{
"code": null,
"e": 32812,
"s": 32763,
"text": "The output that the above code will produce is −"
},
{
"code": null,
"e": 32843,
"s": 32812,
"text": "sh-\n4.3$ lci main.lo \nOBJECT1\n"
},
{
"code": null,
"e": 33161,
"s": 32843,
"text": "Exception handling is one of the powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained. LOLCODE does not have a lot of support for exception handling like other programming Languages. Similar to the Try-Catch block in other languages, LOLCODE has the PLZ-block."
},
{
"code": null,
"e": 33234,
"s": 33161,
"text": "For example, if you want to open a file that may or may not exist, use −"
},
{
"code": null,
"e": 33337,
"s": 33234,
"text": "PLZ OPEN FILE \"filename.TXT\"?\n AWSUM THX\n VISIBLE FILE\n O NOES\n INVISIBLE \"ERROR!\"\nKTHX\n"
},
{
"code": null,
"e": 33521,
"s": 33337,
"text": "The code that may cause an exception is written in the PLZ block, and the exception is handled in the O NOES block. Here, the INVISIBLE keyword sends an inner message to the debugger."
},
{
"code": null,
"e": 33670,
"s": 33521,
"text": "Please note that as LOLCODE is not maintained regularly, there are no more updates available for LOLCODE exception handling and many other features."
},
{
"code": null,
"e": 33832,
"s": 33670,
"text": "The previous chapters explained you the programming in LOLCODE. In this chapter, you will learn some examples that lets you code at an advanced level in LOLCODE."
},
{
"code": null,
"e": 33964,
"s": 33832,
"text": "In this example, you will find the code to calculate the power of an input number. For example, 2 raised to power 4 is equal to 16."
},
{
"code": null,
"e": 34389,
"s": 33964,
"text": "HAI 1.2\nHOW IZ I POWERTWO YR NUM\n BTW RETURN 1 IF 2 TO POWER OF 0\n BOTH SAEM NUM AN 0, O RLY?\n YA RLY, FOUND YR 1\n OIC\n \n BTW CALCULATE 2 TO POWER OF NUM\n I HAS A INDEX ITZ 0\n I HAS A TOTAL ITZ 1\n IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX AN NUM\n TOTAL R PRODUKT OF TOTAL AN 2\n IM OUTTA YR LOOP\n \n FOUND YR TOTAL\n IF U SAY SO\n BTW OUTPUT: 8\n VISIBLE I IZ POWERTWO YR 4 MKAY\nKTHXBYE"
},
{
"code": null,
"e": 34463,
"s": 34389,
"text": "The above code will print the following output once it runs succesfully −"
},
{
"code": null,
"e": 34488,
"s": 34463,
"text": "sh-\n4.3$ lci main.lo\n16\n"
},
{
"code": null,
"e": 34587,
"s": 34488,
"text": "This example shows the code for making an array with five elements and each element with value 10."
},
{
"code": null,
"e": 35158,
"s": 34587,
"text": "HAI 1.3\n OBTW\n CREATES A ONE DIMENSIONAL ARRAY WITH N ELEMENTS, EACH IS A 0\n TLDR\n\tHOW IZ I MAKEMATRIX YR N\n I HAS A MATRIX ITZ A BUKKIT\n IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX N\n MATRIX HAS A SRS INDEX ITZ 10\n IM OUTTA YR LOOP\n \n FOUND YR MATRIX\n IF U SAY SO\n\n I HAS A N ITZ 5\n I HAS A MATRIX ITZ A BUKKIT\n MATRIX R I IZ MAKEMATRIX YR N MKAY\n\n\t BTW PRINTS THE CONTENTS OF THE ARRAY\n IM IN YR LOOP UPPIN YR INDEX TIL BOTH SAEM INDEX N\n VISIBLE MATRIX'Z SRS INDEX\n IM OUTTA YR LOOP\nKTHXBYE"
},
{
"code": null,
"e": 35225,
"s": 35158,
"text": "You can see the following output when you execute the above code −"
},
{
"code": null,
"e": 35261,
"s": 35225,
"text": "sh-4.3$ lci main.lo\n10\n10\n10\n10\n10\n"
},
{
"code": null,
"e": 35336,
"s": 35261,
"text": "This program shows the code to calculate the factorial of an input number."
},
{
"code": null,
"e": 35577,
"s": 35336,
"text": "HAI 1.3\n HOW IZ I FACTORIAL YR N\n BOTH SAEM N AN 0\n O RLY?\n\t YA RLY, FOUND YR 1\n NO WAI\n FOUND YR PRODUKT OF N AN I IZ FACTORIAL YR DIFF OF N AN 1 \n MKAY\n OIC\n IF U SAY SO\n\n VISIBLE I IZ FACTORIAL YR 6 MKAY\nKTHXBYE"
},
{
"code": null,
"e": 35676,
"s": 35577,
"text": "The above program prints the factorial of the number 6 and you can see the output as shown below −"
},
{
"code": null,
"e": 35703,
"s": 35676,
"text": "sh-\n4.3$ lci main.lo\n\n720\n"
},
{
"code": null,
"e": 35822,
"s": 35703,
"text": "You can design a calculator to perform basic math operations using LOLCODE programming. Observe the code given below −"
},
{
"code": null,
"e": 36288,
"s": 35822,
"text": "HAI 1.2\n\n I HAS A V1\n I HAS A V2\n I HAS A CHOICE\n VISIBLE \"VALUE1\"\n GIMMEH V1\n VISIBLE \"VALUE2\"\n GIMMEH V2VISIBLE \"Choose Operation? + - * /\"\n GIMMEH CHOICE CHOICE, WTF?\n OMG \"+\"\n VISIBLE SUM OF V1 AN V2\n \n\t\tGTFO\n\n\tOMG \"-\"\n VISIBLE DIFF OF V1 AN V2\n\n\t\tGTFO\n OMG \"*\"\n VISIBLE PRODUKT OF V1 AN V2\n \n\t\tGTFO\n\n OMG \"/\"\n VISIBLE QUOSHUNT OF V1 AN V2\n\n GTFO\n OMGWTF\n VISIBLE \"CHOOSE SOME OPERATION\"\n OIC\n\nKTHXBYE"
},
{
"code": null,
"e": 36345,
"s": 36288,
"text": "When we execute the above program with following input −"
},
{
"code": null,
"e": 36352,
"s": 36345,
"text": "3\n4\n+\n"
},
{
"code": null,
"e": 36423,
"s": 36352,
"text": "Upon execution, the above program will generate the following output −"
},
{
"code": null,
"e": 36466,
"s": 36423,
"text": "VALUE1\nVALUE2\nChoose Operation? + - * /\n7\n"
},
{
"code": null,
"e": 36473,
"s": 36466,
"text": " Print"
},
{
"code": null,
"e": 36484,
"s": 36473,
"text": " Add Notes"
}
] |
Deploy and Host your Data Science Project | by Merlin Schäfer | Towards Data Science
|
You’ve analyzed a data set and found interesting insights, you have built a machine learning pipeline, but so far they just live within your jupyter notebook. If others want to view your work they have to read through your notebook and view every output, that’s only ideal in a few cases. It’s time to take your work and showcase it interactively.
This does not have to be hard and you don’t require the help of a front-end developer. You, as a data scientist or someone on the path to becoming one, can deploy and host your project or application.
All you need is streamlit.
Streamlit allows you to create apps with a lot of functionality using just a few lines of code. You can host these apps locally or deploy them online. In the past, you had to use Heroku or a similar service to deploy your apps online, but now streamlit has its own sharing platform which makes deployment very easy.
I will start with a quick overview of some basic streamlit functions so you can begin building your application and then go over the process of hosting an app on streamlit sharing.
If you already know how to use streamlit feel free to skip to part two, where I quickly explain streamlit sharing.
For this tutorial, I chose the California Housing dataset. You can find it here.You can transfer anything I show here to your own projects and that’s really the goal. Let’s get started.
The first thing to do is to install streamlit this can be done via pip or conda.
pip install streamlitconda install streamlit
To check if your installation worked you can type
streamlit hello
After installing everything you can get started with your app. The first thing you need to do is import streamlit (usually as “st”) and all the other libraries you require.Now you can read in any data you need and modify it if necessary. Here I read in the housing data and add another column which I will use later in the machine learning part.
Now you can focus on the streamlit part. Your app should have a title, to give it one you just need to type st.title("Your chosen title") .
If you like to display an image you can use the st.image() function which accepts a wide range of inputs such as image-URLs or numpy arrays and displays your image. You can manually adjust the image size (e.g. width = 700).
To give your users some context you probably want to display some introductory text or instruction on how to use the app. Streamlit has many functions for that, I opted for the st.write() function which is a “swiss-army-knife” that can display text in a markdown format (# for titles, * to highlight, etc.) but also accepts dataframes and other objects.
The results of the code above are this:
Now let’s get to the functions that let you display your work!If you want to display a dataframe you can usest.dataframe(), which will dynamically display the dataframe, allowing you to scroll through it.
Giving the users some option to filter the dataframe and only look at specific columns is not very hard and can be implemented via st.mulitselect().This function takes in 3 arguments: the text to display above the selector, the selectable fields as a list and the default fields to display. You can use the funtions ouput as a list to subset your dataframe and thus only display selected columns.
A dataframe is nice, but often a good data visualization is a better choice if you want to present your insights. Streamlit makes it very easy to display them.
All you need to do is create a figure via matplotlib and/or seaborn and then pass that figure to st.pyplot(). You need to explicitly create a figure with axes and can’t just call a seaborn or pyplot function without. This only works in jupyter notebooks with some jupyter magic.
If you want to showcase any geographical data I recommend using st.map() as it automatically creates an interactive map with your data points, as long as the data contains longitude and latitude.
In the following part, I will quickly showcase an example machine learning app that takes in some user input and outputs a prediction. The model used here is not good and only serves as a dummy for the tutorial.
After you’ve trained a model that you want to deploy, save it in a pickle file and load it into your streamlit file. You can use the loaded model like any sklearn model object and simply call .predict() on a given set of inputs. Just remember to pass all of the inputs the model was trained on otherwise you will get an error.To keep it simple I chose only four numeric inputs for the model.
The user input can be placed in a sidebar, where all of the features can be set. To place something in a sidebar you need to add st.sidebar before your function. In this example, I use a .slider() for every input feature. This function takes a description as a string, the start, end, and default value for the display of the slider.
The slider is a good choice if you have numeric continuous variables, if you have categories or binary inputs a selectbox or other functions are good choices.
The slider values are all placed inside a function and collected in a DataFrame which the function returns.
This dataframe is used by the model to get a prediction. You can use st.write() and some minimal formatting to display your prediction in a simple but clear manner.
To host your application locally open your terminal or command/anaconda prompt navigate to the directory your Python file is located in and type streamlit run {your_file_name}.py. A browser window with your app should open automatically, if this doesn’t happen, use the localhost provided(normally it’s localhost:8501)directly.
You can find more info about how to use streamlit in the excellent docs.
Not long ago Streamlit created their own hosting service called streamlit sharing. It’s still in a testing phase but you can (and should) request an invite to you it.
Request an invite link to streamlit sharing here.
Once you have your invite link you need to sign up with the email address you use for GitHub. This is necessary because streamlit sharing needs to access your public repositories to host your app. After the login you should see this:
Before you can host anything, streamlit python script, all necessary files (e.g. model files, csv-files) need to be in a public repository. You also need a requirements.txt file that lists all packages(including their versions) your app uses. If you are unsure how to create one check out the streamlit docs.
Now you only have to enter your repository name, branch, and the name of your streamlit python script.
After you’ve hit deploy you should see some animations. You can check the progress (or any Error Messages) in the bottom right corner under “Manage app”. Once your app is deployed it should work like the local variant, but now you can share it with whomever you want!
I hope this helped you to get started with deploying and hosting your Data Science and Machine Learning Projects. It’s time to show everyone what you’ve created!
|
[
{
"code": null,
"e": 520,
"s": 172,
"text": "You’ve analyzed a data set and found interesting insights, you have built a machine learning pipeline, but so far they just live within your jupyter notebook. If others want to view your work they have to read through your notebook and view every output, that’s only ideal in a few cases. It’s time to take your work and showcase it interactively."
},
{
"code": null,
"e": 721,
"s": 520,
"text": "This does not have to be hard and you don’t require the help of a front-end developer. You, as a data scientist or someone on the path to becoming one, can deploy and host your project or application."
},
{
"code": null,
"e": 748,
"s": 721,
"text": "All you need is streamlit."
},
{
"code": null,
"e": 1064,
"s": 748,
"text": "Streamlit allows you to create apps with a lot of functionality using just a few lines of code. You can host these apps locally or deploy them online. In the past, you had to use Heroku or a similar service to deploy your apps online, but now streamlit has its own sharing platform which makes deployment very easy."
},
{
"code": null,
"e": 1245,
"s": 1064,
"text": "I will start with a quick overview of some basic streamlit functions so you can begin building your application and then go over the process of hosting an app on streamlit sharing."
},
{
"code": null,
"e": 1360,
"s": 1245,
"text": "If you already know how to use streamlit feel free to skip to part two, where I quickly explain streamlit sharing."
},
{
"code": null,
"e": 1546,
"s": 1360,
"text": "For this tutorial, I chose the California Housing dataset. You can find it here.You can transfer anything I show here to your own projects and that’s really the goal. Let’s get started."
},
{
"code": null,
"e": 1627,
"s": 1546,
"text": "The first thing to do is to install streamlit this can be done via pip or conda."
},
{
"code": null,
"e": 1672,
"s": 1627,
"text": "pip install streamlitconda install streamlit"
},
{
"code": null,
"e": 1722,
"s": 1672,
"text": "To check if your installation worked you can type"
},
{
"code": null,
"e": 1738,
"s": 1722,
"text": "streamlit hello"
},
{
"code": null,
"e": 2084,
"s": 1738,
"text": "After installing everything you can get started with your app. The first thing you need to do is import streamlit (usually as “st”) and all the other libraries you require.Now you can read in any data you need and modify it if necessary. Here I read in the housing data and add another column which I will use later in the machine learning part."
},
{
"code": null,
"e": 2224,
"s": 2084,
"text": "Now you can focus on the streamlit part. Your app should have a title, to give it one you just need to type st.title(\"Your chosen title\") ."
},
{
"code": null,
"e": 2448,
"s": 2224,
"text": "If you like to display an image you can use the st.image() function which accepts a wide range of inputs such as image-URLs or numpy arrays and displays your image. You can manually adjust the image size (e.g. width = 700)."
},
{
"code": null,
"e": 2802,
"s": 2448,
"text": "To give your users some context you probably want to display some introductory text or instruction on how to use the app. Streamlit has many functions for that, I opted for the st.write() function which is a “swiss-army-knife” that can display text in a markdown format (# for titles, * to highlight, etc.) but also accepts dataframes and other objects."
},
{
"code": null,
"e": 2842,
"s": 2802,
"text": "The results of the code above are this:"
},
{
"code": null,
"e": 3047,
"s": 2842,
"text": "Now let’s get to the functions that let you display your work!If you want to display a dataframe you can usest.dataframe(), which will dynamically display the dataframe, allowing you to scroll through it."
},
{
"code": null,
"e": 3444,
"s": 3047,
"text": "Giving the users some option to filter the dataframe and only look at specific columns is not very hard and can be implemented via st.mulitselect().This function takes in 3 arguments: the text to display above the selector, the selectable fields as a list and the default fields to display. You can use the funtions ouput as a list to subset your dataframe and thus only display selected columns."
},
{
"code": null,
"e": 3604,
"s": 3444,
"text": "A dataframe is nice, but often a good data visualization is a better choice if you want to present your insights. Streamlit makes it very easy to display them."
},
{
"code": null,
"e": 3883,
"s": 3604,
"text": "All you need to do is create a figure via matplotlib and/or seaborn and then pass that figure to st.pyplot(). You need to explicitly create a figure with axes and can’t just call a seaborn or pyplot function without. This only works in jupyter notebooks with some jupyter magic."
},
{
"code": null,
"e": 4079,
"s": 3883,
"text": "If you want to showcase any geographical data I recommend using st.map() as it automatically creates an interactive map with your data points, as long as the data contains longitude and latitude."
},
{
"code": null,
"e": 4291,
"s": 4079,
"text": "In the following part, I will quickly showcase an example machine learning app that takes in some user input and outputs a prediction. The model used here is not good and only serves as a dummy for the tutorial."
},
{
"code": null,
"e": 4683,
"s": 4291,
"text": "After you’ve trained a model that you want to deploy, save it in a pickle file and load it into your streamlit file. You can use the loaded model like any sklearn model object and simply call .predict() on a given set of inputs. Just remember to pass all of the inputs the model was trained on otherwise you will get an error.To keep it simple I chose only four numeric inputs for the model."
},
{
"code": null,
"e": 5017,
"s": 4683,
"text": "The user input can be placed in a sidebar, where all of the features can be set. To place something in a sidebar you need to add st.sidebar before your function. In this example, I use a .slider() for every input feature. This function takes a description as a string, the start, end, and default value for the display of the slider."
},
{
"code": null,
"e": 5176,
"s": 5017,
"text": "The slider is a good choice if you have numeric continuous variables, if you have categories or binary inputs a selectbox or other functions are good choices."
},
{
"code": null,
"e": 5284,
"s": 5176,
"text": "The slider values are all placed inside a function and collected in a DataFrame which the function returns."
},
{
"code": null,
"e": 5449,
"s": 5284,
"text": "This dataframe is used by the model to get a prediction. You can use st.write() and some minimal formatting to display your prediction in a simple but clear manner."
},
{
"code": null,
"e": 5777,
"s": 5449,
"text": "To host your application locally open your terminal or command/anaconda prompt navigate to the directory your Python file is located in and type streamlit run {your_file_name}.py. A browser window with your app should open automatically, if this doesn’t happen, use the localhost provided(normally it’s localhost:8501)directly."
},
{
"code": null,
"e": 5850,
"s": 5777,
"text": "You can find more info about how to use streamlit in the excellent docs."
},
{
"code": null,
"e": 6017,
"s": 5850,
"text": "Not long ago Streamlit created their own hosting service called streamlit sharing. It’s still in a testing phase but you can (and should) request an invite to you it."
},
{
"code": null,
"e": 6067,
"s": 6017,
"text": "Request an invite link to streamlit sharing here."
},
{
"code": null,
"e": 6301,
"s": 6067,
"text": "Once you have your invite link you need to sign up with the email address you use for GitHub. This is necessary because streamlit sharing needs to access your public repositories to host your app. After the login you should see this:"
},
{
"code": null,
"e": 6610,
"s": 6301,
"text": "Before you can host anything, streamlit python script, all necessary files (e.g. model files, csv-files) need to be in a public repository. You also need a requirements.txt file that lists all packages(including their versions) your app uses. If you are unsure how to create one check out the streamlit docs."
},
{
"code": null,
"e": 6713,
"s": 6610,
"text": "Now you only have to enter your repository name, branch, and the name of your streamlit python script."
},
{
"code": null,
"e": 6981,
"s": 6713,
"text": "After you’ve hit deploy you should see some animations. You can check the progress (or any Error Messages) in the bottom right corner under “Manage app”. Once your app is deployed it should work like the local variant, but now you can share it with whomever you want!"
}
] |
How to read a text file in Python?
|
A text file is the file containing simple text. Python provides inbuilt functions to read, create and write text files. We will discuss how to read a text file in Python.
There are three ways to read a text file in Python −
read() − This method reads the entire file and returns a single string containing all the contents of the file .
read() − This method reads the entire file and returns a single string containing all the contents of the file .
readline() − This method reads a single line from the file and returns it as string.
readline() − This method reads a single line from the file and returns it as string.
readlines() − This method reads all the lines and return them as the list of strings.
readlines() − This method reads all the lines and return them as the list of strings.
Let there be a text file named “myfile.txt”. We need to open the file in read mode. The read mode is specified by “r”. The file can be opened using open(). The two parameters passed are the name of the file and the mode in which the file needs to be opened.
file=open("myfile.txt","r")
print("read function: ")
print(file.read())
print()
file.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file
print("readline function:")
print(file.readline())
print()
file.seek(0) #Take the cursor back to beginning of file
print("readlines function:")
print(file.readlines())
file.close()
read function:
This is an article on reading text files in Python.
Python has inbuilt functions to read a text file.
We can read files in three different ways.
Create a text file which you will read later.
readline function:
This is an article on reading text files in Python.
readlines function:
['This is an article on reading text files in Python.\n', 'Python has
inbuilt functions to read a text file.\n', 'We can read files in three
different ways.\n', 'Create a text file which you will read later.']
As clear from the output −
The read function() reads and returns the whole file.
The readline() function reads and returns only one line.
The readlines() function reads and returns all the lines as list of the strings.
|
[
{
"code": null,
"e": 1233,
"s": 1062,
"text": "A text file is the file containing simple text. Python provides inbuilt functions to read, create and write text files. We will discuss how to read a text file in Python."
},
{
"code": null,
"e": 1286,
"s": 1233,
"text": "There are three ways to read a text file in Python −"
},
{
"code": null,
"e": 1399,
"s": 1286,
"text": "read() − This method reads the entire file and returns a single string containing all the contents of the file ."
},
{
"code": null,
"e": 1512,
"s": 1399,
"text": "read() − This method reads the entire file and returns a single string containing all the contents of the file ."
},
{
"code": null,
"e": 1597,
"s": 1512,
"text": "readline() − This method reads a single line from the file and returns it as string."
},
{
"code": null,
"e": 1682,
"s": 1597,
"text": "readline() − This method reads a single line from the file and returns it as string."
},
{
"code": null,
"e": 1768,
"s": 1682,
"text": "readlines() − This method reads all the lines and return them as the list of strings."
},
{
"code": null,
"e": 1854,
"s": 1768,
"text": "readlines() − This method reads all the lines and return them as the list of strings."
},
{
"code": null,
"e": 2112,
"s": 1854,
"text": "Let there be a text file named “myfile.txt”. We need to open the file in read mode. The read mode is specified by “r”. The file can be opened using open(). The two parameters passed are the name of the file and the mode in which the file needs to be opened."
},
{
"code": null,
"e": 2490,
"s": 2112,
"text": "file=open(\"myfile.txt\",\"r\")\n\nprint(\"read function: \")\nprint(file.read())\nprint()\n\nfile.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file\n\nprint(\"readline function:\")\nprint(file.readline())\nprint()\n\nfile.seek(0) #Take the cursor back to beginning of file\n\nprint(\"readlines function:\")\nprint(file.readlines())\nfile.close()"
},
{
"code": null,
"e": 2999,
"s": 2490,
"text": "read function:\nThis is an article on reading text files in Python.\nPython has inbuilt functions to read a text file.\nWe can read files in three different ways.\nCreate a text file which you will read later.\n\nreadline function:\nThis is an article on reading text files in Python.\n\nreadlines function:\n['This is an article on reading text files in Python.\\n', 'Python has\ninbuilt functions to read a text file.\\n', 'We can read files in three\ndifferent ways.\\n', 'Create a text file which you will read later.']"
},
{
"code": null,
"e": 3026,
"s": 2999,
"text": "As clear from the output −"
},
{
"code": null,
"e": 3080,
"s": 3026,
"text": "The read function() reads and returns the whole file."
},
{
"code": null,
"e": 3137,
"s": 3080,
"text": "The readline() function reads and returns only one line."
},
{
"code": null,
"e": 3218,
"s": 3137,
"text": "The readlines() function reads and returns all the lines as list of the strings."
}
] |
Difference between background and background-color - GeeksforGeeks
|
16 Jul, 2019
Background PropertyThe background property in CSS is very commonly used and contains many variants. The background property consists of all the following properties:background-colorbackground-imagebackground-positionbackground-sizebackground-repeatbackground-originbackground-clipbackground-attachmentBackground Color:Syntax:body
{
background-color:color name
}A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”.Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body
{
background-image : link;
}Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:Background-color Property:The background-color property in CSS is used to specify the background color of an element. On the other hand, if you only use “Background:” Property, you can either specify it’s valued as an image URL or as a color code or specify the value of each background property in the below-given order.Syntax:element {
background-color property
}Example:<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>Output:
Background PropertyThe background property in CSS is very commonly used and contains many variants. The background property consists of all the following properties:background-colorbackground-imagebackground-positionbackground-sizebackground-repeatbackground-originbackground-clipbackground-attachmentBackground Color:Syntax:body
{
background-color:color name
}A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”.Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body
{
background-image : link;
}Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:
background-color
background-image
background-position
background-size
background-repeat
background-origin
background-clip
background-attachment
Background Color:Syntax:
body
{
background-color:color name
}
A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”.
Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body
{
background-image : link;
}
<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>
Output:
Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.
Syntax:
body
{
background-image : link;
}
Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:
<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>
Output:
Background-color Property:The background-color property in CSS is used to specify the background color of an element. On the other hand, if you only use “Background:” Property, you can either specify it’s valued as an image URL or as a color code or specify the value of each background property in the below-given order.Syntax:element {
background-color property
}Example:<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>Output:
Syntax:
element {
background-color property
}
Example:
<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>
Output:
CSS-Misc
Picked
CSS
Difference Between
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
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 Process and Thread
|
[
{
"code": null,
"e": 24261,
"s": 24233,
"text": "\n16 Jul, 2019"
},
{
"code": null,
"e": 26134,
"s": 24261,
"text": "Background PropertyThe background property in CSS is very commonly used and contains many variants. The background property consists of all the following properties:background-colorbackground-imagebackground-positionbackground-sizebackground-repeatbackground-originbackground-clipbackground-attachmentBackground Color:Syntax:body\n{\n background-color:color name\n}A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”.Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body\n{\n background-image : link;\n}Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:Background-color Property:The background-color property in CSS is used to specify the background color of an element. On the other hand, if you only use “Background:” Property, you can either specify it’s valued as an image URL or as a color code or specify the value of each background property in the below-given order.Syntax:element {\n background-color property\n}Example:<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>Output:"
},
{
"code": null,
"e": 27067,
"s": 26134,
"text": "Background PropertyThe background property in CSS is very commonly used and contains many variants. The background property consists of all the following properties:background-colorbackground-imagebackground-positionbackground-sizebackground-repeatbackground-originbackground-clipbackground-attachmentBackground Color:Syntax:body\n{\n background-color:color name\n}A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”.Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body\n{\n background-image : link;\n}Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:"
},
{
"code": null,
"e": 27084,
"s": 27067,
"text": "background-color"
},
{
"code": null,
"e": 27101,
"s": 27084,
"text": "background-image"
},
{
"code": null,
"e": 27121,
"s": 27101,
"text": "background-position"
},
{
"code": null,
"e": 27137,
"s": 27121,
"text": "background-size"
},
{
"code": null,
"e": 27155,
"s": 27137,
"text": "background-repeat"
},
{
"code": null,
"e": 27173,
"s": 27155,
"text": "background-origin"
},
{
"code": null,
"e": 27189,
"s": 27173,
"text": "background-clip"
},
{
"code": null,
"e": 27211,
"s": 27189,
"text": "background-attachment"
},
{
"code": null,
"e": 27236,
"s": 27211,
"text": "Background Color:Syntax:"
},
{
"code": null,
"e": 27276,
"s": 27236,
"text": "body\n{\n background-color:color name\n}"
},
{
"code": null,
"e": 27381,
"s": 27276,
"text": "A color name can also be given as: “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”."
},
{
"code": null,
"e": 27700,
"s": 27381,
"text": "Example:<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>Output:Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element.Syntax:body\n{\n background-image : link;\n}"
},
{
"code": "<style> h1 { background-color: blue; }</style> <body> <h1> Geeksforgeeks</h1></body>",
"e": 27806,
"s": 27700,
"text": null
},
{
"code": null,
"e": 27814,
"s": 27806,
"text": "Output:"
},
{
"code": null,
"e": 27970,
"s": 27814,
"text": "Background Image: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element."
},
{
"code": null,
"e": 27978,
"s": 27970,
"text": "Syntax:"
},
{
"code": null,
"e": 28015,
"s": 27978,
"text": "body\n{\n background-image : link;\n}"
},
{
"code": null,
"e": 28162,
"s": 28015,
"text": "Example:<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>Output:"
},
{
"code": "<style> body { background-image: url(gfgpolaroidimagefunction.png); }</style> <body> <h1>Geeksforgeeks</h1></body>",
"e": 28294,
"s": 28162,
"text": null
},
{
"code": null,
"e": 28302,
"s": 28294,
"text": "Output:"
},
{
"code": null,
"e": 29243,
"s": 28302,
"text": "Background-color Property:The background-color property in CSS is used to specify the background color of an element. On the other hand, if you only use “Background:” Property, you can either specify it’s valued as an image URL or as a color code or specify the value of each background property in the below-given order.Syntax:element {\n background-color property\n}Example:<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>Output:"
},
{
"code": null,
"e": 29251,
"s": 29243,
"text": "Syntax:"
},
{
"code": null,
"e": 29293,
"s": 29251,
"text": "element {\n background-color property\n}"
},
{
"code": null,
"e": 29302,
"s": 29293,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>",
"e": 29859,
"s": 29302,
"text": null
},
{
"code": null,
"e": 29867,
"s": 29859,
"text": "Output:"
},
{
"code": null,
"e": 29876,
"s": 29867,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29883,
"s": 29876,
"text": "Picked"
},
{
"code": null,
"e": 29887,
"s": 29883,
"text": "CSS"
},
{
"code": null,
"e": 29906,
"s": 29887,
"text": "Difference Between"
},
{
"code": null,
"e": 29923,
"s": 29906,
"text": "Web Technologies"
},
{
"code": null,
"e": 30021,
"s": 29923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30030,
"s": 30021,
"text": "Comments"
},
{
"code": null,
"e": 30043,
"s": 30030,
"text": "Old Comments"
},
{
"code": null,
"e": 30101,
"s": 30043,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30138,
"s": 30101,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30179,
"s": 30138,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 30216,
"s": 30179,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30280,
"s": 30216,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30311,
"s": 30280,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 30351,
"s": 30311,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 30383,
"s": 30351,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 30444,
"s": 30383,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How Ternary operator in PowerShell Works?
|
The ternary operator in PowerShell was introduced with the PowerShell version7.0. The ternary operator has ‘?’ (question mark) symbol and its syntax is,
[Condition] ? (output if True) : (output if false)
The left side of the ternary operator is condition and the right side is output based on the condition statement. The output from the condition is in the forms of the Boolean, if the condition is true, the True block will be executed and if the condition is false, the False block will be executed. For example,
$a = 5; $b = 6
($a -gt $b) ? "True" : "false"
false
As you can see the value 5 is less than 6 so the above condition is false and the second block is executed. You can also modify the statement like,
($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")
5 is less than 6
You can see that the amount of code is reduced by just one line and if we have written the same with if/else condition then,
$a = 5; $b = 6
if($a -gt $b){"$a is greater than $b"}
else{"$b is greater than $a"}
So the use of the ternary operator seems simple. You can also use cmdlet on the left side of the operator which returns the Boolean value.
(Test-Connection google.com -Count 2 -Quiet) ? "Google.Com server is reachable" : "Google.Com server is unrechable"
Google.Com server is reachable
Try to make this ternary operator as simple as possible. It won’t work always if the right side part of the ternary operator is used for scripting purposes.
|
[
{
"code": null,
"e": 1215,
"s": 1062,
"text": "The ternary operator in PowerShell was introduced with the PowerShell version7.0. The ternary operator has ‘?’ (question mark) symbol and its syntax is,"
},
{
"code": null,
"e": 1266,
"s": 1215,
"text": "[Condition] ? (output if True) : (output if false)"
},
{
"code": null,
"e": 1578,
"s": 1266,
"text": "The left side of the ternary operator is condition and the right side is output based on the condition statement. The output from the condition is in the forms of the Boolean, if the condition is true, the True block will be executed and if the condition is false, the False block will be executed. For example,"
},
{
"code": null,
"e": 1624,
"s": 1578,
"text": "$a = 5; $b = 6\n($a -gt $b) ? \"True\" : \"false\""
},
{
"code": null,
"e": 1631,
"s": 1624,
"text": "false\n"
},
{
"code": null,
"e": 1779,
"s": 1631,
"text": "As you can see the value 5 is less than 6 so the above condition is false and the second block is executed. You can also modify the statement like,"
},
{
"code": null,
"e": 1844,
"s": 1779,
"text": "($a -gt $b) ? (\"$a is greater than $b\") : (\"$a is less than $b\")"
},
{
"code": null,
"e": 1862,
"s": 1844,
"text": "5 is less than 6\n"
},
{
"code": null,
"e": 1987,
"s": 1862,
"text": "You can see that the amount of code is reduced by just one line and if we have written the same with if/else condition then,"
},
{
"code": null,
"e": 2072,
"s": 1987,
"text": "$a = 5; $b = 6\n\nif($a -gt $b){\"$a is greater than $b\"}\nelse{\"$b is greater than $a\"}"
},
{
"code": null,
"e": 2211,
"s": 2072,
"text": "So the use of the ternary operator seems simple. You can also use cmdlet on the left side of the operator which returns the Boolean value."
},
{
"code": null,
"e": 2328,
"s": 2211,
"text": "(Test-Connection google.com -Count 2 -Quiet) ? \"Google.Com server is reachable\" : \"Google.Com server is unrechable\"\n"
},
{
"code": null,
"e": 2359,
"s": 2328,
"text": "Google.Com server is reachable"
},
{
"code": null,
"e": 2516,
"s": 2359,
"text": "Try to make this ternary operator as simple as possible. It won’t work always if the right side part of the ternary operator is used for scripting purposes."
}
] |
K-nearest Neighbors Algorithm with Examples in R (Simply Explained knn) | by Kshitiz Sirohi | Towards Data Science
|
In this post I am going to exampling what k- nearest neighbor algorithm is and how does it help us. But before we move ahead, we aware that my target audience is the one who wants to get intuitive understanding of the concept and not very in-dept understanding, that is why I have avoided being too pedantic about this topic with very less focus on theoretical concept. Let’s get started.
Let’ s say we are given certain number of objects and each object has its own unique attribute associated with it, for example, you have 5 chairs 10 beds and 15 tables and each for each one of them we know the length, breadth and height. Now, if someone give us a new object with new attributes and ask us to predict as to which category does that new object belongs to, that means we are given the dimension and asked to predict if it is a chair, bed or table, then we would have to use knn algorithm to determine that.
Therefore, attributes means the property of each object, and each object can be considered as a category. Our job is to check how closely are the properties of the new object is related to any one of the already known categories. Now, I am going to show you many kinds of scenarios and I will try to explain those as simply possible as I can.
When we are given the attributes, we try and plot them on graph. The graphical representation of those attributes will help us to calculate Euclidian distance between the new value and the ones that we already know we have. By doing so, we can be sure as to which category does the new object is closest to.
Don’t get intimidated by the name, it just simply means the distance between two points in a plane. By simple using this formula you can calculate distance between two points no matter how many attributes or properties you are given like height, breadth, width, weight and so on upto n where n could be the last property of the object you have. The formula is √(x2−x1)2+(y2−y1)2+(z2−z1)2 ...... (n2-n1)2
We have two categories called male and female with their respective heights given in the table below. Then, if a new member shows up and you are asked to determine if it is a male or female given you already know his/her height, then you can plot that height in 1D plane and the check the proximity of that new height with other already drawn heights. Ideally speaking, we would calculate the Euclidean distance on that graph to determine the closest heights to height of new member. We see that if we draw 180cm in height graph, it lies closer to the male heights than it is from female height. That is how we determine it is a male. (a) shows the table (b) shows the representation on graph (c) shows introduction of new member (d) shows the predicted value to be male.
Let’s say we bring up a new attribute called weight that can also describe the characteristic of male and female as shown in the table below. Now we create a 2D plane and follow the same procedure of calculating the distance of new object from the older ones, and the closer it is to either one of the categories will be considered its own category. In the example below, we can see that new member with 169cm of height and 68kg of weight is in proximity with females more than males. Hence, we predict that the new member is a female.
Most often than not, you will be having a lot of attributes associated with your categorical object and they cannot simply be drawn on a 2D or 1D plane on a white board. However, as long as you understand the functionality you are good to go. Let’s say you have 5 attributes viz. sex, height, weight, color, hair_length and voice_pitch then you simply use the above stated Euclidean formula to calculate distance of new upcoming object from the already given objects. You take the square root of (sex1-sex2)2 + (height1- height2)2 + (weight1 — weight2)2 + (color1 — color2)2 + (hair_length1 — hair_length2)2 + (voice_pitch1)2 — (voice_pitch2)2 where 1 is representing already drawn data point and 2 is representing the new data point that you want to determine the category of. Remember, this single formula above will be used with each and every data point available, that means, it will run as many times as there are rows in your dataset.
Before we move on to implementing them in R, be aware of these following notes:
1- The nearest neighbor you want to check will be called defined by value “k”. If k is 5 then you will check 5 closest neighbors in order to determine the category. If majority of neighbor belongs to a certain category from within those five nearest neighbors, then that will be chosen as the category of upcoming object. Shown in the picture below.
2- Different variables have different scaling units, like weight in kg and height in cm. Then how do we suppose to use them in the Euclidean formula? Well, we normalize each one of the variables using the formula (x-min(x))/(min(x) — max(x)) that we will also see in the examples below. Now if you have one variable of 200kg and another with 50kg, after normalization both will be represented by the value between 0 and 1. Just imagine you have created a box that can hold things that are in range of 0 and 1 only, but since you have used normalization formula to converted everything into values between 0 and 1, you are good to use that box. Note: That box is your plot.
3- The knn algorithm works well with the numeric variables, this is not to say that it cannot work with categorical variables, but it’s just if you have mix of both categorical and numeric variables as the predictors then it demands little bit of different approach. But if all predictors are numeric, then knn is best because we are dealing with the distance and for that we need hard numbers.
4- When we split our data into training and testing sets, the data should have already be normalized. That mean we first normalize the data and then split it.
5- The knn algorithm does not works with ordered-factors in R but rather with factors. We will see that in the code below.
6- The k-mean algorithm is different than K- nearest neighbor algorithm. K-mean is used for clustering and is a unsupervised learning algorithm whereas Knn is supervised leaning algorithm that works on classification problems.
df <- data(iris) ##load data head(iris) ## see the studcture## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa##Generate a random number that is 90% of the total number of rows in dataset. ran <- sample(1:nrow(iris), 0.9 * nrow(iris)) ##the normalization function is created nor <-function(x) { (x -min(x))/(max(x)-min(x)) } ##Run nomalization on first 4 coulumns of dataset because they are the predictors iris_norm <- as.data.frame(lapply(iris[,c(1,2,3,4)], nor)) summary(iris_norm)## Sepal.Length Sepal.Width Petal.Length Petal.Width ## Min. :0.0000 Min. :0.0000 Min. :0.0000 Min. :0.00 ## 1st Qu.:0.2222 1st Qu.:0.3333 1st Qu.:0.1017 1st Qu.:0.08 ## Median :0.4167 Median :0.4167 Median :0.5678 Median :0.50 ## Mean :0.4287 Mean :0.4406 Mean :0.4675 Mean :0.45 ## 3rd Qu.:0.5833 3rd Qu.:0.5417 3rd Qu.:0.6949 3rd Qu.:0.70 ## Max. :1.0000 Max. :1.0000 Max. :1.0000 Max. :1.00##extract training setiris_train <- iris_norm[ran,] ##extract testing set iris_test <- iris_norm[-ran,] ##extract 5th column of train dataset because it will be used as 'cl' argument in knn function. iris_target_category <- iris[ran,5] ##extract 5th column if test dataset to measure the accuracy iris_test_category <- iris[-ran,5]##load the package class library(class) ##run knn function pr <- knn(iris_train,iris_test,cl=iris_target_category,k=13) ##create confusion matrix tab <- table(pr,iris_test_category) ##this function divides the correct predictions by total number of predictions that tell us how accurate teh model is. accuracy <- function(x){sum(diag(x)/(sum(rowSums(x)))) * 100} accuracy(tab)## [1] 80
In the iris dataset that is already available in R, I have run the k-nearest neighbor algorithm that gave me 80% accurate result. First, I normalized the data to convert petal.length, sepal.length, petal.width and sepal.length into a standardized 0-to-1 form so that we can fit them into one box (one graph) and also because our main objective is to predict whether a flower is virginica, Versicolor, or setosa and that is why I excluded the column 5 and stored it into another variable called iris_target_category. Then, I separated the normalized values into training and testing dataset. Imagine it this way, that the values from training dataset are firstly drawn on a graph and after we run knn function with all the necessary arguments, we introduce testing dataset’s values into the graph and calculate Euclidean distance with each and every already stored point in graph. Now, although we know which flower it is in testing dataset, we still predict the values and store them in variable called ‘pr’ so that we can compare predicted values with original testing dataset’s values. This way we understand the accuracy of our model and if we are to get new 50 values in future and we are asked to predict the category of those 50 values, we can do that with this model.
##because diamonds dataset is in ggplot2 package library(ggplot2)##load data data(diamonds) ##store it as data frame dia <- data.frame(diamonds) ##create a random number equal 90% of total number of rows ran <- sample(1:nrow(dia),0.9 * nrow(dia)) ##the normalization function is created nor <-function(x) { (x -min(x))/(max(x)-min(x)) } ##normalization function is created dia_nor <- as.data.frame(lapply(dia[,c(1,5,6,7,8,9,10)], nor)) ##training dataset extracted dia_train <- dia_nor[ran,] ##test dataset extracted dia_test <- dia_nor[-ran,]##the 2nd column of training dataset because that is what we need to predict about testing dataset ##also convert ordered factor to normal factor dia_target <- as.factor(dia[ran,2]) ##the actual values of 2nd couln of testing dataset to compaire it with values that will be predicted ##also convert ordered factor to normal factor test_target <- as.factor(dia[-ran,2]) ##run knn function library(class) pr <- knn(dia_train,dia_test,cl=dia_target,k=20) ##create the confucion matrix tb <- table(pr,test_target) ##check the accuracy accuracy <- function(x){sum(diag(x)/(sum(rowSums(x)))) * 100} accuracy(tb)## [1] 71.09752
In this model I have tried to predict the “cut” variable since it is a categorical variable and we know knn works better for classification problems. I have not taken the 3rd and 4th column into consideration since they were also categorical and would cause ambiguity because other predictive variables are integers. Note that there are ways to run knn on mixture of categorical and integer variables, but we are not discussing it here. The rest of the procedure is same as the iris dataset, and in the end we get the accurate result 71% of the times.
Anonymous. (9 Mar 2015). “R — kNN — k nearest neighbor (part 1)”. Jalayer Academy. https://www.youtube.com/watch?v=GtgJEVxl7DY
Kumar, S. (8 Oct 2017). “kNN(k-Nearest Neighbors) Algorithm in R”. RSTUDIO. https://rstudio-pubs-static.s3.amazonaws.com/316172_a857ca788d1441f8be1bcd1e31f0e875.html
Bhalla, D. (18 Dec 2017). “K Nearest Neighbor: Step by Step Tutorial”. RBLOGGERS. https://www.r-bloggers.com/k-nearest-neighbor-step-by-step-tutorial/
|
[
{
"code": null,
"e": 561,
"s": 172,
"text": "In this post I am going to exampling what k- nearest neighbor algorithm is and how does it help us. But before we move ahead, we aware that my target audience is the one who wants to get intuitive understanding of the concept and not very in-dept understanding, that is why I have avoided being too pedantic about this topic with very less focus on theoretical concept. Let’s get started."
},
{
"code": null,
"e": 1082,
"s": 561,
"text": "Let’ s say we are given certain number of objects and each object has its own unique attribute associated with it, for example, you have 5 chairs 10 beds and 15 tables and each for each one of them we know the length, breadth and height. Now, if someone give us a new object with new attributes and ask us to predict as to which category does that new object belongs to, that means we are given the dimension and asked to predict if it is a chair, bed or table, then we would have to use knn algorithm to determine that."
},
{
"code": null,
"e": 1425,
"s": 1082,
"text": "Therefore, attributes means the property of each object, and each object can be considered as a category. Our job is to check how closely are the properties of the new object is related to any one of the already known categories. Now, I am going to show you many kinds of scenarios and I will try to explain those as simply possible as I can."
},
{
"code": null,
"e": 1733,
"s": 1425,
"text": "When we are given the attributes, we try and plot them on graph. The graphical representation of those attributes will help us to calculate Euclidian distance between the new value and the ones that we already know we have. By doing so, we can be sure as to which category does the new object is closest to."
},
{
"code": null,
"e": 2137,
"s": 1733,
"text": "Don’t get intimidated by the name, it just simply means the distance between two points in a plane. By simple using this formula you can calculate distance between two points no matter how many attributes or properties you are given like height, breadth, width, weight and so on upto n where n could be the last property of the object you have. The formula is √(x2−x1)2+(y2−y1)2+(z2−z1)2 ...... (n2-n1)2"
},
{
"code": null,
"e": 2909,
"s": 2137,
"text": "We have two categories called male and female with their respective heights given in the table below. Then, if a new member shows up and you are asked to determine if it is a male or female given you already know his/her height, then you can plot that height in 1D plane and the check the proximity of that new height with other already drawn heights. Ideally speaking, we would calculate the Euclidean distance on that graph to determine the closest heights to height of new member. We see that if we draw 180cm in height graph, it lies closer to the male heights than it is from female height. That is how we determine it is a male. (a) shows the table (b) shows the representation on graph (c) shows introduction of new member (d) shows the predicted value to be male."
},
{
"code": null,
"e": 3445,
"s": 2909,
"text": "Let’s say we bring up a new attribute called weight that can also describe the characteristic of male and female as shown in the table below. Now we create a 2D plane and follow the same procedure of calculating the distance of new object from the older ones, and the closer it is to either one of the categories will be considered its own category. In the example below, we can see that new member with 169cm of height and 68kg of weight is in proximity with females more than males. Hence, we predict that the new member is a female."
},
{
"code": null,
"e": 4387,
"s": 3445,
"text": "Most often than not, you will be having a lot of attributes associated with your categorical object and they cannot simply be drawn on a 2D or 1D plane on a white board. However, as long as you understand the functionality you are good to go. Let’s say you have 5 attributes viz. sex, height, weight, color, hair_length and voice_pitch then you simply use the above stated Euclidean formula to calculate distance of new upcoming object from the already given objects. You take the square root of (sex1-sex2)2 + (height1- height2)2 + (weight1 — weight2)2 + (color1 — color2)2 + (hair_length1 — hair_length2)2 + (voice_pitch1)2 — (voice_pitch2)2 where 1 is representing already drawn data point and 2 is representing the new data point that you want to determine the category of. Remember, this single formula above will be used with each and every data point available, that means, it will run as many times as there are rows in your dataset."
},
{
"code": null,
"e": 4467,
"s": 4387,
"text": "Before we move on to implementing them in R, be aware of these following notes:"
},
{
"code": null,
"e": 4817,
"s": 4467,
"text": "1- The nearest neighbor you want to check will be called defined by value “k”. If k is 5 then you will check 5 closest neighbors in order to determine the category. If majority of neighbor belongs to a certain category from within those five nearest neighbors, then that will be chosen as the category of upcoming object. Shown in the picture below."
},
{
"code": null,
"e": 5490,
"s": 4817,
"text": "2- Different variables have different scaling units, like weight in kg and height in cm. Then how do we suppose to use them in the Euclidean formula? Well, we normalize each one of the variables using the formula (x-min(x))/(min(x) — max(x)) that we will also see in the examples below. Now if you have one variable of 200kg and another with 50kg, after normalization both will be represented by the value between 0 and 1. Just imagine you have created a box that can hold things that are in range of 0 and 1 only, but since you have used normalization formula to converted everything into values between 0 and 1, you are good to use that box. Note: That box is your plot."
},
{
"code": null,
"e": 5885,
"s": 5490,
"text": "3- The knn algorithm works well with the numeric variables, this is not to say that it cannot work with categorical variables, but it’s just if you have mix of both categorical and numeric variables as the predictors then it demands little bit of different approach. But if all predictors are numeric, then knn is best because we are dealing with the distance and for that we need hard numbers."
},
{
"code": null,
"e": 6044,
"s": 5885,
"text": "4- When we split our data into training and testing sets, the data should have already be normalized. That mean we first normalize the data and then split it."
},
{
"code": null,
"e": 6167,
"s": 6044,
"text": "5- The knn algorithm does not works with ordered-factors in R but rather with factors. We will see that in the code below."
},
{
"code": null,
"e": 6394,
"s": 6167,
"text": "6- The k-mean algorithm is different than K- nearest neighbor algorithm. K-mean is used for clustering and is a unsupervised learning algorithm whereas Knn is supervised leaning algorithm that works on classification problems."
},
{
"code": null,
"e": 8475,
"s": 6394,
"text": "df <- data(iris) ##load data head(iris) ## see the studcture## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa##Generate a random number that is 90% of the total number of rows in dataset. ran <- sample(1:nrow(iris), 0.9 * nrow(iris)) ##the normalization function is created nor <-function(x) { (x -min(x))/(max(x)-min(x)) } ##Run nomalization on first 4 coulumns of dataset because they are the predictors iris_norm <- as.data.frame(lapply(iris[,c(1,2,3,4)], nor)) summary(iris_norm)## Sepal.Length Sepal.Width Petal.Length Petal.Width ## Min. :0.0000 Min. :0.0000 Min. :0.0000 Min. :0.00 ## 1st Qu.:0.2222 1st Qu.:0.3333 1st Qu.:0.1017 1st Qu.:0.08 ## Median :0.4167 Median :0.4167 Median :0.5678 Median :0.50 ## Mean :0.4287 Mean :0.4406 Mean :0.4675 Mean :0.45 ## 3rd Qu.:0.5833 3rd Qu.:0.5417 3rd Qu.:0.6949 3rd Qu.:0.70 ## Max. :1.0000 Max. :1.0000 Max. :1.0000 Max. :1.00##extract training setiris_train <- iris_norm[ran,] ##extract testing set iris_test <- iris_norm[-ran,] ##extract 5th column of train dataset because it will be used as 'cl' argument in knn function. iris_target_category <- iris[ran,5] ##extract 5th column if test dataset to measure the accuracy iris_test_category <- iris[-ran,5]##load the package class library(class) ##run knn function pr <- knn(iris_train,iris_test,cl=iris_target_category,k=13) ##create confusion matrix tab <- table(pr,iris_test_category) ##this function divides the correct predictions by total number of predictions that tell us how accurate teh model is. accuracy <- function(x){sum(diag(x)/(sum(rowSums(x)))) * 100} accuracy(tab)## [1] 80"
},
{
"code": null,
"e": 9750,
"s": 8475,
"text": "In the iris dataset that is already available in R, I have run the k-nearest neighbor algorithm that gave me 80% accurate result. First, I normalized the data to convert petal.length, sepal.length, petal.width and sepal.length into a standardized 0-to-1 form so that we can fit them into one box (one graph) and also because our main objective is to predict whether a flower is virginica, Versicolor, or setosa and that is why I excluded the column 5 and stored it into another variable called iris_target_category. Then, I separated the normalized values into training and testing dataset. Imagine it this way, that the values from training dataset are firstly drawn on a graph and after we run knn function with all the necessary arguments, we introduce testing dataset’s values into the graph and calculate Euclidean distance with each and every already stored point in graph. Now, although we know which flower it is in testing dataset, we still predict the values and store them in variable called ‘pr’ so that we can compare predicted values with original testing dataset’s values. This way we understand the accuracy of our model and if we are to get new 50 values in future and we are asked to predict the category of those 50 values, we can do that with this model."
},
{
"code": null,
"e": 10926,
"s": 9750,
"text": "##because diamonds dataset is in ggplot2 package library(ggplot2)##load data data(diamonds) ##store it as data frame dia <- data.frame(diamonds) ##create a random number equal 90% of total number of rows ran <- sample(1:nrow(dia),0.9 * nrow(dia)) ##the normalization function is created nor <-function(x) { (x -min(x))/(max(x)-min(x)) } ##normalization function is created dia_nor <- as.data.frame(lapply(dia[,c(1,5,6,7,8,9,10)], nor)) ##training dataset extracted dia_train <- dia_nor[ran,] ##test dataset extracted dia_test <- dia_nor[-ran,]##the 2nd column of training dataset because that is what we need to predict about testing dataset ##also convert ordered factor to normal factor dia_target <- as.factor(dia[ran,2]) ##the actual values of 2nd couln of testing dataset to compaire it with values that will be predicted ##also convert ordered factor to normal factor test_target <- as.factor(dia[-ran,2]) ##run knn function library(class) pr <- knn(dia_train,dia_test,cl=dia_target,k=20) ##create the confucion matrix tb <- table(pr,test_target) ##check the accuracy accuracy <- function(x){sum(diag(x)/(sum(rowSums(x)))) * 100} accuracy(tb)## [1] 71.09752"
},
{
"code": null,
"e": 11478,
"s": 10926,
"text": "In this model I have tried to predict the “cut” variable since it is a categorical variable and we know knn works better for classification problems. I have not taken the 3rd and 4th column into consideration since they were also categorical and would cause ambiguity because other predictive variables are integers. Note that there are ways to run knn on mixture of categorical and integer variables, but we are not discussing it here. The rest of the procedure is same as the iris dataset, and in the end we get the accurate result 71% of the times."
},
{
"code": null,
"e": 11605,
"s": 11478,
"text": "Anonymous. (9 Mar 2015). “R — kNN — k nearest neighbor (part 1)”. Jalayer Academy. https://www.youtube.com/watch?v=GtgJEVxl7DY"
},
{
"code": null,
"e": 11771,
"s": 11605,
"text": "Kumar, S. (8 Oct 2017). “kNN(k-Nearest Neighbors) Algorithm in R”. RSTUDIO. https://rstudio-pubs-static.s3.amazonaws.com/316172_a857ca788d1441f8be1bcd1e31f0e875.html"
}
] |
Powershell - Check File Existence
|
Test-Path cmdlet is used to check existence of a file.
In this example, we're having a file test.txt in D:\temp\test directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test\test.txt
You can see following output in PowerShell console.
Test-Path D:\temp\test\test.txt
True
In this example, we're not having a file named test2.txt in D:\temp\test directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test\test2.txt
You can see following output in PowerShell console.
Test-Path D:\temp\test\test2.txt
False
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2089,
"s": 2034,
"text": "Test-Path cmdlet is used to check existence of a file."
},
{
"code": null,
"e": 2161,
"s": 2089,
"text": "In this example, we're having a file test.txt in D:\\temp\\test directory"
},
{
"code": null,
"e": 2214,
"s": 2161,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2246,
"s": 2214,
"text": "Test-Path D:\\temp\\test\\test.txt"
},
{
"code": null,
"e": 2298,
"s": 2246,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2336,
"s": 2298,
"text": "Test-Path D:\\temp\\test\\test.txt\nTrue\n"
},
{
"code": null,
"e": 2419,
"s": 2336,
"text": "In this example, we're not having a file named test2.txt in D:\\temp\\test directory"
},
{
"code": null,
"e": 2472,
"s": 2419,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2505,
"s": 2472,
"text": "Test-Path D:\\temp\\test\\test2.txt"
},
{
"code": null,
"e": 2557,
"s": 2505,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2597,
"s": 2557,
"text": "Test-Path D:\\temp\\test\\test2.txt\nFalse\n"
},
{
"code": null,
"e": 2632,
"s": 2597,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2653,
"s": 2632,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2688,
"s": 2653,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2701,
"s": 2688,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2738,
"s": 2701,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2750,
"s": 2738,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2757,
"s": 2750,
"text": " Print"
},
{
"code": null,
"e": 2768,
"s": 2757,
"text": " Add Notes"
}
] |
Appending values at the end of an NumPy array - GeeksforGeeks
|
02 Sep, 2020
Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task we can use numpy.append(). This function can help us to append a single value as well as multiple values at the end of the array.
Syntax : numpy.append(array, values, axis = None)Parameters :
array : Input array.
values : values to be added in the array.
axis : Axis along which we want to insert the values.
Returns : An copy of array with values being appended at the end as per the mentioned objectalong a given axis.
Examples 1 : Appending a single value to a 1D array. For 1D array, using the axis argument is not necessary as the array is flattened by default.
# importing the moduleimport numpy as np # creating an arrayarr = np.array([1, 8, 3, 3, 5])print('Original Array : ', arr) # appending to the arrayarr = np.append(arr, [7])print('Array after appending : ', arr)
Output :
Original Array : [1 8 3 3 5]
Array after appending : [1 8 3 3 5 7]
Example 2 : Appending another array at the end of 1D array. You may pass a list or an array to the append function, the result will be the same.
# importing the moduleimport numpy as np # creating an arrayarr1 = np.array([1, 2, 3])print('First array is : ', arr1) # creating another arrayarr2 = np.array([4, 5, 6])print('Second array is : ', arr2) # appending arr2 to arr1arr = np.append(arr1, arr2)print('Array after appending : ', arr)
Output :
First array is : [1 2 3]
Second array is : [4 5 6]
Array after appending : [1 2 3 4 5 6]
Example 3 : Appending values at the end of the n-dimensional array. It is important that the dimensions of both the array matches otherwise it will give an error.
# importing the moduleimport numpy as np # create an arrayarr = np.arange(1, 13).reshape(2, 6)print('Original Array')print(arr, '\n') # create another array which is# to be appended column-wisecol = np.arange(5, 11).reshape(1, 6)print('Array to be appended column wise')print(col)arr_col = np.append(arr, col, axis = 0)print('Array after appending the values column wise')print(arr_col, '\n') # create an array which is# to be appended row wiserow = np.array([1, 2]).reshape(2, 1)print('Array to be appended row wise')print(row)arr_row = np.append(arr, row, axis = 1)print('Array after appending the values row wise')print(arr_row)
Output :
Original Array
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Array to be appended column wise
[[ 5 6 7 8 9 10]]
Array after appending the values column wise
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[ 5 6 7 8 9 10]]
Array to be appended row wise
[[1]
[2]]
Array after appending the values row wise
[[ 1 2 3 4 5 6 1]
[ 7 8 9 10 11 12 2]]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 24641,
"s": 24316,
"text": "Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task we can use numpy.append(). This function can help us to append a single value as well as multiple values at the end of the array."
},
{
"code": null,
"e": 24703,
"s": 24641,
"text": "Syntax : numpy.append(array, values, axis = None)Parameters :"
},
{
"code": null,
"e": 24724,
"s": 24703,
"text": "array : Input array."
},
{
"code": null,
"e": 24766,
"s": 24724,
"text": "values : values to be added in the array."
},
{
"code": null,
"e": 24820,
"s": 24766,
"text": "axis : Axis along which we want to insert the values."
},
{
"code": null,
"e": 24932,
"s": 24820,
"text": "Returns : An copy of array with values being appended at the end as per the mentioned objectalong a given axis."
},
{
"code": null,
"e": 25078,
"s": 24932,
"text": "Examples 1 : Appending a single value to a 1D array. For 1D array, using the axis argument is not necessary as the array is flattened by default."
},
{
"code": "# importing the moduleimport numpy as np # creating an arrayarr = np.array([1, 8, 3, 3, 5])print('Original Array : ', arr) # appending to the arrayarr = np.append(arr, [7])print('Array after appending : ', arr)",
"e": 25291,
"s": 25078,
"text": null
},
{
"code": null,
"e": 25300,
"s": 25291,
"text": "Output :"
},
{
"code": null,
"e": 25370,
"s": 25300,
"text": "Original Array : [1 8 3 3 5]\nArray after appending : [1 8 3 3 5 7]\n"
},
{
"code": null,
"e": 25515,
"s": 25370,
"text": "Example 2 : Appending another array at the end of 1D array. You may pass a list or an array to the append function, the result will be the same."
},
{
"code": "# importing the moduleimport numpy as np # creating an arrayarr1 = np.array([1, 2, 3])print('First array is : ', arr1) # creating another arrayarr2 = np.array([4, 5, 6])print('Second array is : ', arr2) # appending arr2 to arr1arr = np.append(arr1, arr2)print('Array after appending : ', arr)",
"e": 25811,
"s": 25515,
"text": null
},
{
"code": null,
"e": 25820,
"s": 25811,
"text": "Output :"
},
{
"code": null,
"e": 25913,
"s": 25820,
"text": "First array is : [1 2 3]\nSecond array is : [4 5 6]\nArray after appending : [1 2 3 4 5 6]\n"
},
{
"code": null,
"e": 26076,
"s": 25913,
"text": "Example 3 : Appending values at the end of the n-dimensional array. It is important that the dimensions of both the array matches otherwise it will give an error."
},
{
"code": "# importing the moduleimport numpy as np # create an arrayarr = np.arange(1, 13).reshape(2, 6)print('Original Array')print(arr, '\\n') # create another array which is# to be appended column-wisecol = np.arange(5, 11).reshape(1, 6)print('Array to be appended column wise')print(col)arr_col = np.append(arr, col, axis = 0)print('Array after appending the values column wise')print(arr_col, '\\n') # create an array which is# to be appended row wiserow = np.array([1, 2]).reshape(2, 1)print('Array to be appended row wise')print(row)arr_row = np.append(arr, row, axis = 1)print('Array after appending the values row wise')print(arr_row)",
"e": 26711,
"s": 26076,
"text": null
},
{
"code": null,
"e": 26720,
"s": 26711,
"text": "Output :"
},
{
"code": null,
"e": 27079,
"s": 26720,
"text": "Original Array\n[[ 1 2 3 4 5 6]\n [ 7 8 9 10 11 12]] \n\nArray to be appended column wise\n[[ 5 6 7 8 9 10]]\nArray after appending the values column wise\n[[ 1 2 3 4 5 6]\n [ 7 8 9 10 11 12]\n [ 5 6 7 8 9 10]] \n\nArray to be appended row wise\n[[1]\n [2]]\nArray after appending the values row wise\n[[ 1 2 3 4 5 6 1]\n [ 7 8 9 10 11 12 2]]\n"
},
{
"code": null,
"e": 27110,
"s": 27079,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 27123,
"s": 27110,
"text": "Python-numpy"
},
{
"code": null,
"e": 27130,
"s": 27123,
"text": "Python"
},
{
"code": null,
"e": 27228,
"s": 27130,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27260,
"s": 27228,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27302,
"s": 27260,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27358,
"s": 27302,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27400,
"s": 27358,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27455,
"s": 27400,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27486,
"s": 27455,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27508,
"s": 27486,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27537,
"s": 27508,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27576,
"s": 27537,
"text": "Python | Get unique values from a list"
}
] |
Cool Custom Welcome Messages on Linux terminal - GeeksforGeeks
|
31 Jan, 2019
There is a Linux hack which can be used to display a custom message on the terminal every time we open it. This can be done by manipulating the .bashrc shell script.
What is .bashrc ?
It is a shell script that Bash runs whenever it is started interactively. You can put any command in that file that you could type at the command prompt.
Steps on how to do it :
Firstly, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used) .vim ~/.bashrc
The file will open in vim editor as shown in the figure below:Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.echo "Welcome MAZHAR"
Now, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE
Firstly, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used) .vim ~/.bashrc
The file will open in vim editor as shown in the figure below:
vim ~/.bashrc
The file will open in vim editor as shown in the figure below:
Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.echo "Welcome MAZHAR"
Now, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE
echo "Welcome MAZHAR"
Now, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE
There is one another interesting way to do it It can be done by the combination of two command-line tools:
fortune and cowsay
fortune: This prints out a random interesting proverb.
cowsay: This utility displays a speaking cow in terminal window.
Let’s see how to do this:
On Ubuntu or Linux mint, install the fortune cowsay as follows:sudo apt-get install fortune cowsay
Now, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used)vim ~/.bashrc
Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.fortune | cowsay -pn
Now, close the terminal and open a new terminal, you will see the message as shown below:Amazing!!! Isn’t it. You are done.
On Ubuntu or Linux mint, install the fortune cowsay as follows:sudo apt-get install fortune cowsay
sudo apt-get install fortune cowsay
Now, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used)vim ~/.bashrc
vim ~/.bashrc
Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.fortune | cowsay -pn
fortune | cowsay -pn
Now, close the terminal and open a new terminal, you will see the message as shown below:Amazing!!! Isn’t it. You are done.
More Examples
Now, once fortune and cowsay is installed, by adding different parameters, different cool beings can replace the cow.Lets see each of them one by one:
Showing a Tux : add -f tux with fortune | cowsay and save and exit.fortune | cowsay -f tux
Now, open a new terminal and see the tux appearing with a message as shown below:Showing a stegosaurus : add -f stegosaurus with fortune | cowsay and save and exit.fortune | cowsay -f stegosaurus
Now,open a new terminal and see the tux appearing with a message as shown below:Many Linux terminal commands can also be piped with cowsay such as ls command.For example: Type the following command in the terminal to show the contents of a directory as the fortune message.ls | cowsay -f stegosaurus
Here is the output:One can also show a custom text as the fortune message .Type this command in the Linux terminalcowsay -f tux "GeeksForGeeks Technical Scripter Event"
Here is the output:
Showing a Tux : add -f tux with fortune | cowsay and save and exit.fortune | cowsay -f tux
Now, open a new terminal and see the tux appearing with a message as shown below:
fortune | cowsay -f tux
Now, open a new terminal and see the tux appearing with a message as shown below:
Showing a stegosaurus : add -f stegosaurus with fortune | cowsay and save and exit.fortune | cowsay -f stegosaurus
Now,open a new terminal and see the tux appearing with a message as shown below:
fortune | cowsay -f stegosaurus
Now,open a new terminal and see the tux appearing with a message as shown below:
Many Linux terminal commands can also be piped with cowsay such as ls command.For example: Type the following command in the terminal to show the contents of a directory as the fortune message.ls | cowsay -f stegosaurus
Here is the output:
ls | cowsay -f stegosaurus
Here is the output:
One can also show a custom text as the fortune message .Type this command in the Linux terminalcowsay -f tux "GeeksForGeeks Technical Scripter Event"
Here is the output:
cowsay -f tux "GeeksForGeeks Technical Scripter Event"
Here is the output:
Reference: Wiki
linux-command
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 23865,
"s": 23837,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24031,
"s": 23865,
"text": "There is a Linux hack which can be used to display a custom message on the terminal every time we open it. This can be done by manipulating the .bashrc shell script."
},
{
"code": null,
"e": 24049,
"s": 24031,
"text": "What is .bashrc ?"
},
{
"code": null,
"e": 24203,
"s": 24049,
"text": "It is a shell script that Bash runs whenever it is started interactively. You can put any command in that file that you could type at the command prompt."
},
{
"code": null,
"e": 24227,
"s": 24203,
"text": "Steps on how to do it :"
},
{
"code": null,
"e": 24628,
"s": 24227,
"text": "Firstly, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used) .vim ~/.bashrc\nThe file will open in vim editor as shown in the figure below:Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.echo \"Welcome MAZHAR\"\nNow, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE "
},
{
"code": null,
"e": 24813,
"s": 24628,
"text": "Firstly, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used) .vim ~/.bashrc\nThe file will open in vim editor as shown in the figure below:"
},
{
"code": null,
"e": 24828,
"s": 24813,
"text": "vim ~/.bashrc\n"
},
{
"code": null,
"e": 24891,
"s": 24828,
"text": "The file will open in vim editor as shown in the figure below:"
},
{
"code": null,
"e": 25108,
"s": 24891,
"text": "Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.echo \"Welcome MAZHAR\"\nNow, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE "
},
{
"code": null,
"e": 25131,
"s": 25108,
"text": "echo \"Welcome MAZHAR\"\n"
},
{
"code": null,
"e": 25234,
"s": 25131,
"text": "Now, close the terminal and open a new terminal, you will see the message as shown below:YOU ARE DONE "
},
{
"code": null,
"e": 25341,
"s": 25234,
"text": "There is one another interesting way to do it It can be done by the combination of two command-line tools:"
},
{
"code": null,
"e": 25481,
"s": 25341,
"text": "fortune and cowsay\nfortune: This prints out a random interesting proverb.\ncowsay: This utility displays a speaking cow in terminal window.\n"
},
{
"code": null,
"e": 25507,
"s": 25481,
"text": "Let’s see how to do this:"
},
{
"code": null,
"e": 25959,
"s": 25507,
"text": "On Ubuntu or Linux mint, install the fortune cowsay as follows:sudo apt-get install fortune cowsay\nNow, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used)vim ~/.bashrc\nNow, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.fortune | cowsay -pn\nNow, close the terminal and open a new terminal, you will see the message as shown below:Amazing!!! Isn’t it. You are done."
},
{
"code": null,
"e": 26059,
"s": 25959,
"text": "On Ubuntu or Linux mint, install the fortune cowsay as follows:sudo apt-get install fortune cowsay\n"
},
{
"code": null,
"e": 26096,
"s": 26059,
"text": "sudo apt-get install fortune cowsay\n"
},
{
"code": null,
"e": 26213,
"s": 26096,
"text": "Now, open the terminal and open the ./bashrc file using any editor of your choice. (Here, vim is used)vim ~/.bashrc\n"
},
{
"code": null,
"e": 26228,
"s": 26213,
"text": "vim ~/.bashrc\n"
},
{
"code": null,
"e": 26342,
"s": 26228,
"text": "Now, add a small line(shown below) at the beginning of ~/.bashrc and save the file and exit.fortune | cowsay -pn\n"
},
{
"code": null,
"e": 26364,
"s": 26342,
"text": "fortune | cowsay -pn\n"
},
{
"code": null,
"e": 26488,
"s": 26364,
"text": "Now, close the terminal and open a new terminal, you will see the message as shown below:Amazing!!! Isn’t it. You are done."
},
{
"code": null,
"e": 26502,
"s": 26488,
"text": "More Examples"
},
{
"code": null,
"e": 26653,
"s": 26502,
"text": "Now, once fortune and cowsay is installed, by adding different parameters, different cool beings can replace the cow.Lets see each of them one by one:"
},
{
"code": null,
"e": 27429,
"s": 26653,
"text": "Showing a Tux : add -f tux with fortune | cowsay and save and exit.fortune | cowsay -f tux\nNow, open a new terminal and see the tux appearing with a message as shown below:Showing a stegosaurus : add -f stegosaurus with fortune | cowsay and save and exit.fortune | cowsay -f stegosaurus\nNow,open a new terminal and see the tux appearing with a message as shown below:Many Linux terminal commands can also be piped with cowsay such as ls command.For example: Type the following command in the terminal to show the contents of a directory as the fortune message.ls | cowsay -f stegosaurus\nHere is the output:One can also show a custom text as the fortune message .Type this command in the Linux terminalcowsay -f tux \"GeeksForGeeks Technical Scripter Event\"\nHere is the output:"
},
{
"code": null,
"e": 27602,
"s": 27429,
"text": "Showing a Tux : add -f tux with fortune | cowsay and save and exit.fortune | cowsay -f tux\nNow, open a new terminal and see the tux appearing with a message as shown below:"
},
{
"code": null,
"e": 27627,
"s": 27602,
"text": "fortune | cowsay -f tux\n"
},
{
"code": null,
"e": 27709,
"s": 27627,
"text": "Now, open a new terminal and see the tux appearing with a message as shown below:"
},
{
"code": null,
"e": 27905,
"s": 27709,
"text": "Showing a stegosaurus : add -f stegosaurus with fortune | cowsay and save and exit.fortune | cowsay -f stegosaurus\nNow,open a new terminal and see the tux appearing with a message as shown below:"
},
{
"code": null,
"e": 27938,
"s": 27905,
"text": "fortune | cowsay -f stegosaurus\n"
},
{
"code": null,
"e": 28019,
"s": 27938,
"text": "Now,open a new terminal and see the tux appearing with a message as shown below:"
},
{
"code": null,
"e": 28259,
"s": 28019,
"text": "Many Linux terminal commands can also be piped with cowsay such as ls command.For example: Type the following command in the terminal to show the contents of a directory as the fortune message.ls | cowsay -f stegosaurus\nHere is the output:"
},
{
"code": null,
"e": 28287,
"s": 28259,
"text": "ls | cowsay -f stegosaurus\n"
},
{
"code": null,
"e": 28307,
"s": 28287,
"text": "Here is the output:"
},
{
"code": null,
"e": 28477,
"s": 28307,
"text": "One can also show a custom text as the fortune message .Type this command in the Linux terminalcowsay -f tux \"GeeksForGeeks Technical Scripter Event\"\nHere is the output:"
},
{
"code": null,
"e": 28533,
"s": 28477,
"text": "cowsay -f tux \"GeeksForGeeks Technical Scripter Event\"\n"
},
{
"code": null,
"e": 28553,
"s": 28533,
"text": "Here is the output:"
},
{
"code": null,
"e": 28569,
"s": 28553,
"text": "Reference: Wiki"
},
{
"code": null,
"e": 28583,
"s": 28569,
"text": "linux-command"
},
{
"code": null,
"e": 28594,
"s": 28583,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28613,
"s": 28594,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28711,
"s": 28613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28720,
"s": 28711,
"text": "Comments"
},
{
"code": null,
"e": 28733,
"s": 28720,
"text": "Old Comments"
},
{
"code": null,
"e": 28771,
"s": 28733,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28806,
"s": 28771,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 28841,
"s": 28806,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28877,
"s": 28841,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28915,
"s": 28877,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28951,
"s": 28915,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 28989,
"s": 28951,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 29008,
"s": 28989,
"text": "Compiling with g++"
},
{
"code": null,
"e": 29044,
"s": 29008,
"text": "Tail command in Linux with examples"
}
] |
Sort a multidimensional array by date element in PHP
|
07 Jan, 2020
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
Syntax:
boolean usort( $array, "function_name")
Parameters: This function accepts two parameters as shown in the above syntax and are described below:
$array: This parameter specifies the array which u want to sort.
function_name: This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
Return Value: This function returns Boolean type value. It returns TRUE in case of success and FALSE in case of failure.
We use strtotime to convert given time string to a timestamp object. Once we have timestamps, we subtract them to decide greater.
Program:
<?php // Declare a multidimensional array// and initialize it$array = Array ( Array ( "gfg" => "GFG_1", "datetime" => "2019-02-22 11:29:45", ), Array ( "gfg" => "GFG_2", "datetime" => "2019-02-13 11:29:45", ), Array ( "gfg" => "GFG_3", "datetime" => "2019-02-15 11:29:45", )); // Comparison functionfunction date_compare($element1, $element2) { $datetime1 = strtotime($element1['datetime']); $datetime2 = strtotime($element2['datetime']); return $datetime1 - $datetime2;} // Sort the array usort($array, 'date_compare'); // Print the arrayprint_r($array) ?>
Array
(
[0] => Array
(
[gfg] => GFG_2
[datetime] => 2019-02-13 11:29:45
)
[1] => Array
(
[gfg] => GFG_3
[datetime] => 2019-02-15 11:29:45
)
[2] => Array
(
[gfg] => GFG_1
[datetime] => 2019-02-22 11:29:45
)
)
Akanksha_Rai
date-time-program
PHP-date-time
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements."
},
{
"code": null,
"e": 329,
"s": 321,
"text": "Syntax:"
},
{
"code": null,
"e": 369,
"s": 329,
"text": "boolean usort( $array, \"function_name\")"
},
{
"code": null,
"e": 472,
"s": 369,
"text": "Parameters: This function accepts two parameters as shown in the above syntax and are described below:"
},
{
"code": null,
"e": 537,
"s": 472,
"text": "$array: This parameter specifies the array which u want to sort."
},
{
"code": null,
"e": 928,
"s": 537,
"text": "function_name: This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1."
},
{
"code": null,
"e": 1049,
"s": 928,
"text": "Return Value: This function returns Boolean type value. It returns TRUE in case of success and FALSE in case of failure."
},
{
"code": null,
"e": 1179,
"s": 1049,
"text": "We use strtotime to convert given time string to a timestamp object. Once we have timestamps, we subtract them to decide greater."
},
{
"code": null,
"e": 1188,
"s": 1179,
"text": "Program:"
},
{
"code": "<?php // Declare a multidimensional array// and initialize it$array = Array ( Array ( \"gfg\" => \"GFG_1\", \"datetime\" => \"2019-02-22 11:29:45\", ), Array ( \"gfg\" => \"GFG_2\", \"datetime\" => \"2019-02-13 11:29:45\", ), Array ( \"gfg\" => \"GFG_3\", \"datetime\" => \"2019-02-15 11:29:45\", )); // Comparison functionfunction date_compare($element1, $element2) { $datetime1 = strtotime($element1['datetime']); $datetime2 = strtotime($element2['datetime']); return $datetime1 - $datetime2;} // Sort the array usort($array, 'date_compare'); // Print the arrayprint_r($array) ?>",
"e": 1825,
"s": 1188,
"text": null
},
{
"code": null,
"e": 2169,
"s": 1825,
"text": "Array\n(\n [0] => Array\n (\n [gfg] => GFG_2\n [datetime] => 2019-02-13 11:29:45\n )\n\n [1] => Array\n (\n [gfg] => GFG_3\n [datetime] => 2019-02-15 11:29:45\n )\n\n [2] => Array\n (\n [gfg] => GFG_1\n [datetime] => 2019-02-22 11:29:45\n )\n\n)\n"
},
{
"code": null,
"e": 2182,
"s": 2169,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2200,
"s": 2182,
"text": "date-time-program"
},
{
"code": null,
"e": 2214,
"s": 2200,
"text": "PHP-date-time"
},
{
"code": null,
"e": 2221,
"s": 2214,
"text": "Picked"
},
{
"code": null,
"e": 2225,
"s": 2221,
"text": "PHP"
},
{
"code": null,
"e": 2238,
"s": 2225,
"text": "PHP Programs"
},
{
"code": null,
"e": 2255,
"s": 2238,
"text": "Web Technologies"
},
{
"code": null,
"e": 2259,
"s": 2255,
"text": "PHP"
}
] |
How to get file creation and modification date or time in Python?
|
08 Jul, 2022
A Timestamp is a sequence of characters, that signify the occurrence of an event. Timestamps are required extensively in computer science. This exists of varying precision and accuracy i.e. some timestamps have the precision of up to milliseconds for the occurrence of the even, while others do not. This allows Timestamps of different forms (and standards) to exist. In this article, we will take a look at methods for finding the creation and modification timestamps of a file in Python. We will be using the file with the following properties for the demonstration.
We will use getctime() and getmtime() function found inside the path module in the os library, for getting the creation and modification times of the file. Both the above functions return time in seconds since EPOCH (00:00:00 UTC on 1 January 1970) (time is of float datatype). Since that number doesn’t resemble an understandable timestamp, we would have to convert that time i.e. it becomes recognizable. For that purpose, we would be using ctime() function found inside the time library.
Example 1: Converting the time in seconds to a timestamp
The timestamp of the above code has the following format qualifiers –
[Day](3) [Month](3) [day](2) [Hours:Minutes:Seconds](8) [Year](4)
Python3
import osimport time # Path to the file/directorypath = r"myfile.txt" # Both the variables would contain time# elapsed since EPOCH in floatti_c = os.path.getctime(path)ti_m = os.path.getmtime(path) # Converting the time in seconds to a timestampc_ti = time.ctime(ti_c)m_ti = time.ctime(ti_m) print( f"The file located at the path {path} was \ created at {c_ti} and was last modified at {m_ti}")
Output:
The file located at the path myfile.txt was created at Mon Jun 27 14:16:30 2022 and
was last modified at Thu Jul 7 16:25:52 2022
Where the word inside the bracket is the cue for what is being displayed, and the number following it within the parenthesis displays the length it will occupy.
Example 2: Timestamp in ISO 8601 format
By default, the ctime() function would return a timestamp of the aforementioned syntax. In order to change it, we would have to pass it to strptime() function (also found inside the time library) to create a time structure (object) out of it. Then we can pass format specifiers to strftime(), to create a custom timestamp out of the time structure. In the following code, we will be getting the modification time of the same file in ISO 8601 timestamp format.
Python3
import osimport time path = r"myfile.txt" ti_m = os.path.getmtime(path) m_ti = time.ctime(ti_m) # Using the timestamp string to create a# time object/structuret_obj = time.strptime(m_ti) # Transforming the time object to a timestamp# of ISO 8601 formatT_stamp = time.strftime("%Y-%m-%d %H:%M:%S", t_obj) print(f"The file located at the path {path} was last modified at {T_stamp}")
Output:
The file located at the path myfile.txt was last modified at 2022-07-07 16:25:52
Classes for working with date and time are provided by the Python Datetime module. Numerous capabilities to deal with dates, times, and time intervals are provided by these classes. Python treats date and DateTime as objects, so when you work with them, you’re really working with objects rather than strings or timestamps.
Example 1: Using os.path.getmtime
Python’s os.path module, a submodule of the OS module, is used to manipulate common path names. Python’s os.path.getmtime() method can be used to determine when the given path was last modified.
Python3
import datetimeimport os path = r"myfile.txt" # file modificationtimestamp = os.path.getmtime(path) # convert timestamp into DateTime objectdatestamp = datetime.datetime.fromtimestamp(timestamp)print('Modified Date/Time:', datestamp) # file creationc_timestamp = os.path.getctime(path) # convert creation timestamp into DateTime objectc_datestamp = datetime.datetime.fromtimestamp(c_timestamp) print('Created Date/Time on:', c_datestamp)
Output:
Modified Date/Time: 2022-07-07 16:25:52.490759
Created Date/Time on: 2022-06-27 14:16:30.123721
Example 2: Using pathlib.Path
os.path module is sub-module of the OS module in Python used for common path name manipulation. Return an os.stat result object, similar to os.stat, that contains details about this path (). Each time this method is called, the outcome is checked.
Python3
import datetimeimport pathlib # create a file pathpath = pathlib.Path(r'myfile.txt') # get modification timetimestamp = path.stat().st_mtime # convert time to dd-mm-yyyy hh:mm:ssm_time = datetime.datetime.fromtimestamp(timestamp)print('Modified Date/Time:', m_time) # get creation time on windowscurrent_timestamp = path.stat().st_ctimec_time = datetime.datetime.fromtimestamp(current_timestamp)print('Created Date/Time on:', c_time)
Output:
Modified Date/Time: 2022-07-07 16:25:52.490759
Created Date/Time on: 2022-06-27 14:16:30.123721
surajkumarguptaintern
Picked
Python os-module-programs
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 597,
"s": 28,
"text": "A Timestamp is a sequence of characters, that signify the occurrence of an event. Timestamps are required extensively in computer science. This exists of varying precision and accuracy i.e. some timestamps have the precision of up to milliseconds for the occurrence of the even, while others do not. This allows Timestamps of different forms (and standards) to exist. In this article, we will take a look at methods for finding the creation and modification timestamps of a file in Python. We will be using the file with the following properties for the demonstration."
},
{
"code": null,
"e": 1088,
"s": 597,
"text": "We will use getctime() and getmtime() function found inside the path module in the os library, for getting the creation and modification times of the file. Both the above functions return time in seconds since EPOCH (00:00:00 UTC on 1 January 1970) (time is of float datatype). Since that number doesn’t resemble an understandable timestamp, we would have to convert that time i.e. it becomes recognizable. For that purpose, we would be using ctime() function found inside the time library."
},
{
"code": null,
"e": 1145,
"s": 1088,
"text": "Example 1: Converting the time in seconds to a timestamp"
},
{
"code": null,
"e": 1215,
"s": 1145,
"text": "The timestamp of the above code has the following format qualifiers –"
},
{
"code": null,
"e": 1281,
"s": 1215,
"text": "[Day](3) [Month](3) [day](2) [Hours:Minutes:Seconds](8) [Year](4)"
},
{
"code": null,
"e": 1289,
"s": 1281,
"text": "Python3"
},
{
"code": "import osimport time # Path to the file/directorypath = r\"myfile.txt\" # Both the variables would contain time# elapsed since EPOCH in floatti_c = os.path.getctime(path)ti_m = os.path.getmtime(path) # Converting the time in seconds to a timestampc_ti = time.ctime(ti_c)m_ti = time.ctime(ti_m) print( f\"The file located at the path {path} was \\ created at {c_ti} and was last modified at {m_ti}\")",
"e": 1690,
"s": 1289,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1690,
"text": "Output:"
},
{
"code": null,
"e": 1829,
"s": 1698,
"text": "The file located at the path myfile.txt was created at Mon Jun 27 14:16:30 2022 and \nwas last modified at Thu Jul 7 16:25:52 2022"
},
{
"code": null,
"e": 1990,
"s": 1829,
"text": "Where the word inside the bracket is the cue for what is being displayed, and the number following it within the parenthesis displays the length it will occupy."
},
{
"code": null,
"e": 2030,
"s": 1990,
"text": "Example 2: Timestamp in ISO 8601 format"
},
{
"code": null,
"e": 2491,
"s": 2030,
"text": "By default, the ctime() function would return a timestamp of the aforementioned syntax. In order to change it, we would have to pass it to strptime() function (also found inside the time library) to create a time structure (object) out of it. Then we can pass format specifiers to strftime(), to create a custom timestamp out of the time structure. In the following code, we will be getting the modification time of the same file in ISO 8601 timestamp format. "
},
{
"code": null,
"e": 2499,
"s": 2491,
"text": "Python3"
},
{
"code": "import osimport time path = r\"myfile.txt\" ti_m = os.path.getmtime(path) m_ti = time.ctime(ti_m) # Using the timestamp string to create a# time object/structuret_obj = time.strptime(m_ti) # Transforming the time object to a timestamp# of ISO 8601 formatT_stamp = time.strftime(\"%Y-%m-%d %H:%M:%S\", t_obj) print(f\"The file located at the path {path} was last modified at {T_stamp}\")",
"e": 2880,
"s": 2499,
"text": null
},
{
"code": null,
"e": 2888,
"s": 2880,
"text": "Output:"
},
{
"code": null,
"e": 2969,
"s": 2888,
"text": "The file located at the path myfile.txt was last modified at 2022-07-07 16:25:52"
},
{
"code": null,
"e": 3293,
"s": 2969,
"text": "Classes for working with date and time are provided by the Python Datetime module. Numerous capabilities to deal with dates, times, and time intervals are provided by these classes. Python treats date and DateTime as objects, so when you work with them, you’re really working with objects rather than strings or timestamps."
},
{
"code": null,
"e": 3327,
"s": 3293,
"text": "Example 1: Using os.path.getmtime"
},
{
"code": null,
"e": 3522,
"s": 3327,
"text": "Python’s os.path module, a submodule of the OS module, is used to manipulate common path names. Python’s os.path.getmtime() method can be used to determine when the given path was last modified."
},
{
"code": null,
"e": 3530,
"s": 3522,
"text": "Python3"
},
{
"code": "import datetimeimport os path = r\"myfile.txt\" # file modificationtimestamp = os.path.getmtime(path) # convert timestamp into DateTime objectdatestamp = datetime.datetime.fromtimestamp(timestamp)print('Modified Date/Time:', datestamp) # file creationc_timestamp = os.path.getctime(path) # convert creation timestamp into DateTime objectc_datestamp = datetime.datetime.fromtimestamp(c_timestamp) print('Created Date/Time on:', c_datestamp)",
"e": 3968,
"s": 3530,
"text": null
},
{
"code": null,
"e": 3976,
"s": 3968,
"text": "Output:"
},
{
"code": null,
"e": 4072,
"s": 3976,
"text": "Modified Date/Time: 2022-07-07 16:25:52.490759\nCreated Date/Time on: 2022-06-27 14:16:30.123721"
},
{
"code": null,
"e": 4102,
"s": 4072,
"text": "Example 2: Using pathlib.Path"
},
{
"code": null,
"e": 4350,
"s": 4102,
"text": "os.path module is sub-module of the OS module in Python used for common path name manipulation. Return an os.stat result object, similar to os.stat, that contains details about this path (). Each time this method is called, the outcome is checked."
},
{
"code": null,
"e": 4358,
"s": 4350,
"text": "Python3"
},
{
"code": "import datetimeimport pathlib # create a file pathpath = pathlib.Path(r'myfile.txt') # get modification timetimestamp = path.stat().st_mtime # convert time to dd-mm-yyyy hh:mm:ssm_time = datetime.datetime.fromtimestamp(timestamp)print('Modified Date/Time:', m_time) # get creation time on windowscurrent_timestamp = path.stat().st_ctimec_time = datetime.datetime.fromtimestamp(current_timestamp)print('Created Date/Time on:', c_time)",
"e": 4792,
"s": 4358,
"text": null
},
{
"code": null,
"e": 4800,
"s": 4792,
"text": "Output:"
},
{
"code": null,
"e": 4896,
"s": 4800,
"text": "Modified Date/Time: 2022-07-07 16:25:52.490759\nCreated Date/Time on: 2022-06-27 14:16:30.123721"
},
{
"code": null,
"e": 4918,
"s": 4896,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 4925,
"s": 4918,
"text": "Picked"
},
{
"code": null,
"e": 4951,
"s": 4925,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 4968,
"s": 4951,
"text": "python-os-module"
},
{
"code": null,
"e": 4975,
"s": 4968,
"text": "Python"
}
] |
How to combine two dataframe in Python – Pandas?
|
02 Dec, 2020
Prerequisites: Pandas
In many real-life situations, the data that we want to use comes in multiple files. We often have a need to combine these files into a single DataFrame to analyze the data. Pandas provide such facilities for easily combining Series or DataFrame with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations. In addition, pandas also provide utilities to compare two Series or DataFrame and summarize their differences.
The concat() function in pandas is used to append either columns or rows from one DataFrame to another. The concat() function does all the heavy lifting of performing concatenation operations along an axis while performing optional set logic (union or intersection) of the indexes (if any) on the other axes.
Python3
import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) frames = [df1, df2] result = pd.concat(frames)display(result)
Output:
When we concatenated our DataFrames we simply added them to each other i.e. stacked them either vertically or side by side. Another way to combine DataFrames is to use columns in each dataset that contain common values (a common unique id). Combining DataFrames using a common field is called “joining”. The columns containing the common values are called “join key(s)”. Joining DataFrames in this way is often useful when one DataFrame is a “lookup table” containing additional data that we want to include in the other.
Note: This process of joining tables is similar to what we do with tables in an SQL database.
When gluing together multiple DataFrames, you have a choice of how to handle the other axes (other than the one being concatenated). This can be done in the following two ways :
Take the union of them all, join=’outer’. This is the default option as it results in zero information loss.
Take the intersection, join=’inner’.
Example:
Python3
import pandas as pd df1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) df3 = pd.DataFrame({'City': ['MUMBAI', 'PUNE', 'MUMBAI', 'DELHI'], 'Age': ['12', '13', '14', '12']}) # the default behaviour is join='outer'# inner join result = pd.concat([df1, df3], axis=1, join='inner')display(result)
Output:
A useful shortcut to concat() is append() instance method on Series and DataFrame. These methods actually predated concat.
Example:
Python3
import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) # append methodresult = df1.append(df2)display(result)
Output:
Note: append() may take multiple objects to concatenate.
Example:
Python3
import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) df3 = pd.DataFrame({'City': ['MUMBAI', 'PUNE', 'MUMBAI', 'DELHI'], 'Age': ['12', '13', '14', '12']}) # appending multiple DataFrameresult = df1.append([df2, df3])display(result)
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 76,
"s": 54,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 562,
"s": 76,
"text": "In many real-life situations, the data that we want to use comes in multiple files. We often have a need to combine these files into a single DataFrame to analyze the data. Pandas provide such facilities for easily combining Series or DataFrame with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations. In addition, pandas also provide utilities to compare two Series or DataFrame and summarize their differences."
},
{
"code": null,
"e": 871,
"s": 562,
"text": "The concat() function in pandas is used to append either columns or rows from one DataFrame to another. The concat() function does all the heavy lifting of performing concatenation operations along an axis while performing optional set logic (union or intersection) of the indexes (if any) on the other axes."
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Python3"
},
{
"code": "import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) frames = [df1, df2] result = pd.concat(frames)display(result)",
"e": 1228,
"s": 879,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Output:"
},
{
"code": null,
"e": 1758,
"s": 1236,
"text": "When we concatenated our DataFrames we simply added them to each other i.e. stacked them either vertically or side by side. Another way to combine DataFrames is to use columns in each dataset that contain common values (a common unique id). Combining DataFrames using a common field is called “joining”. The columns containing the common values are called “join key(s)”. Joining DataFrames in this way is often useful when one DataFrame is a “lookup table” containing additional data that we want to include in the other."
},
{
"code": null,
"e": 1852,
"s": 1758,
"text": "Note: This process of joining tables is similar to what we do with tables in an SQL database."
},
{
"code": null,
"e": 2030,
"s": 1852,
"text": "When gluing together multiple DataFrames, you have a choice of how to handle the other axes (other than the one being concatenated). This can be done in the following two ways :"
},
{
"code": null,
"e": 2139,
"s": 2030,
"text": "Take the union of them all, join=’outer’. This is the default option as it results in zero information loss."
},
{
"code": null,
"e": 2176,
"s": 2139,
"text": "Take the intersection, join=’inner’."
},
{
"code": null,
"e": 2185,
"s": 2176,
"text": "Example:"
},
{
"code": null,
"e": 2193,
"s": 2185,
"text": "Python3"
},
{
"code": "import pandas as pd df1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) df3 = pd.DataFrame({'City': ['MUMBAI', 'PUNE', 'MUMBAI', 'DELHI'], 'Age': ['12', '13', '14', '12']}) # the default behaviour is join='outer'# inner join result = pd.concat([df1, df3], axis=1, join='inner')display(result)",
"e": 2571,
"s": 2193,
"text": null
},
{
"code": null,
"e": 2579,
"s": 2571,
"text": "Output:"
},
{
"code": null,
"e": 2703,
"s": 2579,
"text": "A useful shortcut to concat() is append() instance method on Series and DataFrame. These methods actually predated concat. "
},
{
"code": null,
"e": 2712,
"s": 2703,
"text": "Example:"
},
{
"code": null,
"e": 2720,
"s": 2712,
"text": "Python3"
},
{
"code": "import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) # append methodresult = df1.append(df2)display(result)",
"e": 3059,
"s": 2720,
"text": null
},
{
"code": null,
"e": 3067,
"s": 3059,
"text": "Output:"
},
{
"code": null,
"e": 3124,
"s": 3067,
"text": "Note: append() may take multiple objects to concatenate."
},
{
"code": null,
"e": 3133,
"s": 3124,
"text": "Example:"
},
{
"code": null,
"e": 3141,
"s": 3133,
"text": "Python3"
},
{
"code": "import pandas as pd# First DataFramedf1 = pd.DataFrame({'id': ['A01', 'A02', 'A03', 'A04'], 'Name': ['ABC', 'PQR', 'DEF', 'GHI']}) # Second DataFramedf2 = pd.DataFrame({'id': ['B05', 'B06', 'B07', 'B08'], 'Name': ['XYZ', 'TUV', 'MNO', 'JKL']}) df3 = pd.DataFrame({'City': ['MUMBAI', 'PUNE', 'MUMBAI', 'DELHI'], 'Age': ['12', '13', '14', '12']}) # appending multiple DataFrameresult = df1.append([df2, df3])display(result)",
"e": 3625,
"s": 3141,
"text": null
},
{
"code": null,
"e": 3633,
"s": 3625,
"text": "Output:"
},
{
"code": null,
"e": 3657,
"s": 3633,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3680,
"s": 3657,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3694,
"s": 3680,
"text": "Python-pandas"
},
{
"code": null,
"e": 3718,
"s": 3694,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3725,
"s": 3718,
"text": "Python"
},
{
"code": null,
"e": 3744,
"s": 3725,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3842,
"s": 3744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3874,
"s": 3842,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3901,
"s": 3874,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3922,
"s": 3901,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3945,
"s": 3922,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3976,
"s": 3945,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4032,
"s": 3976,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4074,
"s": 4032,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4116,
"s": 4074,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4155,
"s": 4116,
"text": "Python | Get unique values from a list"
}
] |
Lodash _.isFunction() Method
|
10 Sep, 2020
The Lodash _.isFunction() Method checks whether the given value is a function object or not and returns the corresponding boolean value.
Syntax:
_.isFunction( value )
Parameters: This method accepts single parameter as mentioned above and described below:
value: This parameter holds the value that to be checked for a function object.
Return Value: This method returns a Boolean value(Returns true if the given value is Function object number, else false).
Example 1:
Javascript
// Defining Lodash variable const _ = require('lodash'); function Geeks(){ var a="gfg";}// Checking for Functionconsole.log("The Value is Function : " + _.isFunction(Geeks));
Output:
The Value is Function : true
Example 2:
Javascript
// Defining Lodash variable const _ = require('lodash'); // Checking for Functionconsole.log("The Value is Function : " + _.isFunction("Function"));
Output:
The Value is Function : false
Example 3: For _ object, it returns true.
Javascript
// Defining Lodash variable const _ = require('lodash'); // Checking for Functionconsole.log("The Value is Function : " + _.isFunction(_));
Output:
The Value is Function : true
JavaScript-Lodash
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": "\n10 Sep, 2020"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "The Lodash _.isFunction() Method checks whether the given value is a function object or not and returns the corresponding boolean value."
},
{
"code": null,
"e": 173,
"s": 165,
"text": "Syntax:"
},
{
"code": null,
"e": 196,
"s": 173,
"text": "_.isFunction( value )\n"
},
{
"code": null,
"e": 285,
"s": 196,
"text": "Parameters: This method accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 365,
"s": 285,
"text": "value: This parameter holds the value that to be checked for a function object."
},
{
"code": null,
"e": 487,
"s": 365,
"text": "Return Value: This method returns a Boolean value(Returns true if the given value is Function object number, else false)."
},
{
"code": null,
"e": 499,
"s": 487,
"text": "Example 1: "
},
{
"code": null,
"e": 510,
"s": 499,
"text": "Javascript"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); function Geeks(){ var a=\"gfg\";}// Checking for Functionconsole.log(\"The Value is Function : \" + _.isFunction(Geeks));",
"e": 697,
"s": 510,
"text": null
},
{
"code": null,
"e": 705,
"s": 697,
"text": "Output:"
},
{
"code": null,
"e": 735,
"s": 705,
"text": "The Value is Function : true\n"
},
{
"code": null,
"e": 747,
"s": 735,
"text": "Example 2: "
},
{
"code": null,
"e": 758,
"s": 747,
"text": "Javascript"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); // Checking for Functionconsole.log(\"The Value is Function : \" + _.isFunction(\"Function\"));",
"e": 916,
"s": 758,
"text": null
},
{
"code": null,
"e": 924,
"s": 916,
"text": "Output:"
},
{
"code": null,
"e": 956,
"s": 924,
"text": "The Value is Function : false \n"
},
{
"code": null,
"e": 998,
"s": 956,
"text": "Example 3: For _ object, it returns true."
},
{
"code": null,
"e": 1009,
"s": 998,
"text": "Javascript"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); // Checking for Functionconsole.log(\"The Value is Function : \" + _.isFunction(_));",
"e": 1158,
"s": 1009,
"text": null
},
{
"code": null,
"e": 1166,
"s": 1158,
"text": "Output:"
},
{
"code": null,
"e": 1196,
"s": 1166,
"text": "The Value is Function : true\n"
},
{
"code": null,
"e": 1214,
"s": 1196,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": "JavaScript"
},
{
"code": null,
"e": 1242,
"s": 1225,
"text": "Web Technologies"
}
] |
Find the length of largest subarray with 0 sum
|
28 Jun, 2022
Given an array of integers, find the length of the longest sub-array with a sum that equals 0.
Examples:
Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
Output: 5
Explanation: The longest sub-array with
elements summing up-to 0 is {-2, 2, -8, 1, 7}
Input: arr[] = {1, 2, 3}
Output: 0
Explanation:There is no subarray with 0 sum
Input: arr[] = {1, 0, 3}
Output: 1
Explanation: The longest sub-array with
elements summing up-to 0 is {0}
Naive Approach: This involves the use of brute force where two nested loops are used. The outer loop is used to fix the starting position of the sub-array, and the inner loop is used for the ending position of the sub-array and if the sum of elements is equal to zero, then increase the count.
Algorithm:
Consider all sub-arrays one by one and check the sum of every sub-array.Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i.
Consider all sub-arrays one by one and check the sum of every sub-array.
Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
/* A simple C++ program to findlargest subarray with 0 sum */#include <bits/stdc++.h>using namespace std; // Returns length of the largest// subarray with 0 sumint maxLen(int arr[], int n){ // Initialize result int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize currr_sum for // every starting point int curr_sum = 0; // try all subarrays starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len // if required if (curr_sum == 0) max_len = max(max_len, j - i + 1); } } return max_len;} // Driver Codeint main(){ int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length of the longest 0 sum subarray is " << maxLen(arr, n); return 0;}
// Java code to find the largest subarray// with 0 sumclass GFG { // Returns length of the largest subarray // with 0 sum static int maxLen(int arr[], int n) { int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize curr_sum for every // starting point int curr_sum = 0; // try all subarrays starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, then update // max_len if (curr_sum == 0) max_len = Math.max(max_len, j - i + 1); } } return max_len; } public static void main(String args[]) { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = arr.length; System.out.println("Length of the longest 0 sum " + "subarray is " + maxLen(arr, n)); }}// This code is contributed by Kamal Rawal
# Python program to find the length of largest subarray with 0 sum # returns the lengthdef maxLen(arr): # initialize result max_len = 0 # pick a starting point for i in range(len(arr)): # initialize sum for every starting point curr_sum = 0 # try all subarrays starting with 'i' for j in range(i, len(arr)): curr_sum += arr[j] # if curr_sum becomes 0, then update max_len if curr_sum == 0: max_len = max(max_len, j-i + 1) return max_len # test arrayarr = [15, -2, 2, -8, 1, 7, 10, 13] print ("Length of the longest 0 sum subarray is % d" % maxLen(arr))
// C# code to find the largest// subarray with 0 sumusing System; class GFG { // Returns length of the // largest subarray with 0 sum static int maxLen(int[] arr, int n) { int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize curr_sum // for every starting point int curr_sum = 0; // try all subarrays // starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len if (curr_sum == 0) max_len = Math.Max(max_len, j - i + 1); } } return max_len; } // Driver code static public void Main() { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = arr.Length; Console.WriteLine("Length of the longest 0 sum " + "subarray is " + maxLen(arr, n)); }} // This code is contributed by ajit
<?php// A simple PHP program to find// largest subarray with 0 sum // Returns length of the// largest subarray with 0 sumfunction maxLen($arr, $n){ $max_len = 0; // Initialize result // Pick a starting point for ($i = 0; $i < $n; $i++) { // Initialize currr_sum // for every starting point $curr_sum = 0; // try all subarrays // starting with 'i' for ($j = $i; $j < $n; $j++) { $curr_sum += $arr[$j]; // If curr_sum becomes 0, // then update max_len // if required if ($curr_sum == 0) $max_len = max($max_len, $j - $i + 1); } } return $max_len;} // Driver Code$arr = array(15, -2, 2, -8, 1, 7, 10, 23);$n = sizeof($arr);echo "Length of the longest 0 " . "sum subarray is ", maxLen($arr, $n); // This code is contributed by aj_36?>
<script> // Javascript code to find the largest // subarray with 0 sum // Returns length of the // largest subarray with 0 sum function maxLen(arr, n) { let max_len = 0; // Pick a starting point for (let i = 0; i < n; i++) { // Initialize curr_sum // for every starting point let curr_sum = 0; // try all subarrays // starting with 'i' for (let j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len if (curr_sum == 0) max_len = Math.max(max_len, j - i + 1); } } return max_len; } let arr = [ 15, -2, 2, -8, 1, 7, 10, 23 ]; let n = arr.length; document.write("Length of the longest 0 sum " + "subarray is " + maxLen(arr, n)); </script>
Length of the longest 0 sum subarray is 5
Complexity Analysis:
Time Complexity: O(n^2) due to the use of nested loops.
Space complexity: O(1) as no extra space is used.
Efficient Approach: The brute force solution is calculating the sum of each and every sub-array and checking whether the sum is zero or not. Let’s now try to improve the time complexity by taking an extra space of ‘n’ length. The new array will store the sum of all the elements up to that index. The sum-index pair will be stored in a hash-map. A Hash map allows insertion and deletion of key-value pair in constant time. Therefore, the time complexity remains unaffected. So, if the same value appears twice in the array, it will be guaranteed that the particular array will be a zero-sum sub-array.
Mathematical Proof:
prefix(i) = arr[0] + arr[1] +...+ arr[i] prefix(j) = arr[0] + arr[1] +...+ arr[j], j>i ifprefix(i) == prefix(j) then prefix(j) – prefix(i) = 0 that means arr[i+1] + .. + arr[j] = 0, So a sub-array has zero sum , and the length of that sub-array is j-i+1
Algorithm:
Create an extra space, an array of length n (prefix), a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair.Move along the input array from the start to the end.For every index, update the value of sum = sum + array[i].Check every index, if the current sum is present in the hash map or not.If present, update the value of max_len to a maximum difference of two indices (current index and index in the hash-map) and max_len.Else, put the value (sum) in the hash map, with the index as a key-value pair.Print the maximum length (max_len).
Create an extra space, an array of length n (prefix), a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair.
Move along the input array from the start to the end.
For every index, update the value of sum = sum + array[i].
Check every index, if the current sum is present in the hash map or not.
If present, update the value of max_len to a maximum difference of two indices (current index and index in the hash-map) and max_len.
Else, put the value (sum) in the hash map, with the index as a key-value pair.
Print the maximum length (max_len).
Below is a dry run of the above approach:
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find the length of largest subarray// with 0 sum#include <bits/stdc++.h>using namespace std; // Returns Length of the required subarrayint maxLen(int arr[], int n){ // Map to store the previous sums unordered_map<int, int> presum; int sum = 0; // Initialize the sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look for this sum in Hash table if (presum.find(sum) != presum.end()) { // If this sum is seen before, then update max_len max_len = max(max_len, i - presum[sum]); } else { // Else insert this sum with index in hash table presum[sum] = i; } } return max_len;} // Driver Codeint main(){ int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length of the longest 0 sum subarray is " << maxLen(arr, n); return 0;}
// A Java program to find maximum length subarray with 0 sumimport java.util.HashMap; class MaxLenZeroSumSub { // Returns length of the maximum length subarray with 0 sum static int maxLen(int arr[]) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < arr.length; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table Integer prev_i = hM.get(sum); // If this sum is seen before, then update max_len // if required if (prev_i != null) max_len = Math.max(max_len, i - prev_i); else // Else put this sum in hash table hM.put(sum, i); } return max_len; } // Drive method public static void main(String arg[]) { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; System.out.println("Length of the longest 0 sum subarray is " + maxLen(arr)); }}
# A python program to find maximum length subarray# with 0 sum in o(n) time # Returns the maximum lengthdef maxLen(arr): # NOTE: Dictionary in python in implemented as Hash Maps # Create an empty hash map (dictionary) hash_map = {} # Initialize result max_len = 0 # Initialize sum of elements curr_sum = 0 # Traverse through the given array for i in range(len(arr)): # Add the current element to the sum curr_sum += arr[i] if arr[i] is 0 and max_len is 0: max_len = 1 if curr_sum is 0: max_len = i + 1 # NOTE: 'in' operation in dictionary to search # key takes O(1). Look if current sum is seen # before if curr_sum in hash_map: max_len = max(max_len, i - hash_map[curr_sum] ) else: # else put this sum in dictionary hash_map[curr_sum] = i return max_len # test arrayarr = [15, -2, 2, -8, 1, 7, 10, 13] print ("Length of the longest 0 sum subarray is % d" % maxLen(arr))
// C# program to find maximum// length subarray with 0 sumusing System;using System.Collections.Generic; public class MaxLenZeroSumSub { // Returns length of the maximum // length subarray with 0 sum static int maxLen(int[] arr) { // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < arr.GetLength(0); i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table int prev_i = 0; if (hM.ContainsKey(sum)) { prev_i = hM[sum]; } // If this sum is seen before, then update max_len // if required if (hM.ContainsKey(sum)) max_len = Math.Max(max_len, i - prev_i); else { // Else put this sum in hash table if (hM.ContainsKey(sum)) hM.Remove(sum); hM.Add(sum, i); } } return max_len; } // Driver code public static void Main() { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; Console.WriteLine("Length of the longest 0 sum subarray is " + maxLen(arr)); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to find maximum length subarray with 0 sum // Returns length of the maximum length subarray with 0 sum function maxLen(arr) { // Creates an empty hashMap hM let hM = new Map(); let sum = 0; // Initialize sum of elements let max_len = 0; // Initialize result // Traverse through the given array for (let i = 0; i < arr.length; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table let prev_i = hM.get(sum); // If this sum is seen before, then update max_len // if required if (prev_i != null) max_len = Math.max(max_len, i - prev_i); else // Else put this sum in hash table hM.set(sum, i); } return max_len; } // Driver program let arr = [ 15, -2, 2, -8, 1, 7, 10, 23 ]; document.write("Length of the longest 0 sum subarray is " + maxLen(arr)); </script>
Length of the longest 0 sum subarray is 5
Complexity Analysis:
Time Complexity: O(n), as use of the good hashing function, will allow insertion and retrieval operations in O(1) time.
Space Complexity: O(n), for the use of extra space to store the prefix array and hashmap.
Alternative and efficient approach:
The above efficient approach can be tweaked a little bit to handle all if conditions in one.
Algorithm:
In this approach, the Hash Map will store (Cumulative Sum, index+1).It starts with inserting (0,0) to the Hash Map at the beginning and initializing cumSum = 0 and length = -1;Traverse throughout the array.Find cumulative sum till that point by Cumulative sum = Cumulative sum + current value of array;if the cumulative sum is already present in the Hash Map as a key then update length as maximum of (length, index+1 – value corresponding to cumulative sum in Hash Map)else insert (cumulative sum, index + 1) to the Hash Map.
In this approach, the Hash Map will store (Cumulative Sum, index+1).
It starts with inserting (0,0) to the Hash Map at the beginning and initializing cumSum = 0 and length = -1;
Traverse throughout the array.
Find cumulative sum till that point by Cumulative sum = Cumulative sum + current value of array;
if the cumulative sum is already present in the Hash Map as a key then update length as maximum of (length, index+1 – value corresponding to cumulative sum in Hash Map)
else insert (cumulative sum, index + 1) to the Hash Map.
Explanation:
Let’s consider array [ 0, -2, 2, 2, -2].initial Hash Map {0, 0}, cumSum = 0, length = -1.Iterating over the array with index ranging from 0 to array length – 1.
Let’s consider array [ 0, -2, 2, 2, -2].
initial Hash Map {0, 0}, cumSum = 0, length = -1.
Iterating over the array with index ranging from 0 to array length – 1.
index = 0, cumSum = 0, cumSum is present in Hash Map as a key. length = Max(length, index+1 – hm.get(cumSum)) => length = max(-1 , 1) = 1
index = 1, cumSum = -2, cumSum is not present in Hash Map as a key. Inserting (cumSum, index + 1). Hash Map becomes { 0 = 0, -2 = 2}
index = 2, cumSum = 0, cumSum is present in Hash Map as a key. So, length = Max(1 , 2+1-0). Hence, length = 3.
index = 3, cumSum = 2, cumSum is not present in Hash Map key. Hash Map = { 0 = 0, -2 = 2, 2 = 4}
index = 4, cumSum = 0, cumSum is present as a key, length = max(3 , 4+1-0) = 5
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // to find maximum length of sub array having sum 0int maxSubArrayLen(vector<int>arr){ map<int,int>hm; hm[0] = 0; int length = -1; int cumSum = 0; for (int i = 0; i < arr.size(); i++) { cumSum = cumSum + arr[i]; if (hm.find(cumSum) != hm.end()) { length = max(length, i + 1 - hm[cumSum]); } else { hm[cumSum] = i + 1; } } return length;} // Driver Codeint main(){ vector<int>arr = {15, -2, 2, -8, 1, 7, 10, 23};cout<<maxSubArrayLen(arr)<<endl; } // This code is contributed by shinjanpatra
// to find maximum length of sub array having sum 0import java.io.*;import java.util.HashMap; class GFG { public static int maxSubArrayLen(int[] arr) { HashMap<Integer, Integer> hm = new HashMap<>(); hm.put(0, 0); int length = -1; int cumSum = 0; for (int i = 0; i < arr.length; i++) { cumSum = cumSum + arr[i]; if (hm.containsKey(cumSum)) { length = Math.max(length, i + 1 - hm.get(cumSum)); } else { hm.put(cumSum, i + 1); } } return length; } public static void main(String[] args) { int[] arr = new int[] { 15, -2, 2, -8, 1, 7, 10, 23 }; System.out.println(maxSubArrayLen(arr)); }}// Contributed by Bibhu Parambrahma Patra (bibhup)
# to find maximum length of sub array having sum 0def maxSubArrayLen(arr): hm = {} hm[0] = 0 length = -1 cumSum = 0 for i in range(len(arr)): cumSum = cumSum + arr[i] if (cumSum in hm): length = max(length,i + 1 - hm[cumSum]) else: hm[cumSum] = i + 1 return length # driver codearr = [15, -2, 2, -8, 1, 7, 10, 23]print(maxSubArrayLen(arr)) # This code is contributed by shinjanpatra
// C# program to find maximum length of sub array having sum// 0using System;using System.Collections.Generic; public class GFG{ // function to find the length of the longest // of the sub array with its sum equal to 0 static int maxSubArrayLen(int[] arr) { // declaring a dictionary to maintain the length and // sum of each subarray IDictionary<int, int> hm = new Dictionary<int, int>(); hm[0] = 0; int length = -1; int cumSum = 0; // iterating over the array and building the // dictionary for (int i = 0; i < arr.Length; i++) { cumSum = cumSum + arr[i]; if (hm.ContainsKey(cumSum)) { length = Math.Max(length, i + 1 - hm[cumSum]); } else { hm[cumSum] = i + 1; } } return length; } // driver call public static void Main(string[] args) { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; // function call Console.WriteLine(maxSubArrayLen(arr)); }} // This code is contributed by phasing17
<script> // to find maximum length of sub array having sum 0function maxSubArrayLen(arr){ let hm = new Map(); hm.set(0,0); let length = -1; let cumSum = 0; for (let i = 0; i < arr.length; i++) { cumSum = cumSum + arr[i]; if (hm.has(cumSum)) { length = Math.max(length, i + 1 - hm.get(cumSum)); } else { hm.set(cumSum, i + 1); } } return length;} // driver codelet arr = [15, -2, 2, -8, 1, 7, 10, 23];document.write(maxSubArrayLen(arr),"</br>"); // This code is contributed by shinjanpatra </script>
5
Complexity Analysis:
Time Complexity: O(n).Space Complexity: O(n), for the Hash Map
jit_t
Mahin_251
princiraj1992
andrew1234
ankitdoot
decode2207
target_2
amartyaghoshgfg
simmytarika5
bibhup
shinjanpatra
phasing17
hardikkoriintern
Amazon
MakeMyTrip
subarray
subarray-sum
Arrays
Hash
Amazon
MakeMyTrip
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 149,
"s": 54,
"text": "Given an array of integers, find the length of the longest sub-array with a sum that equals 0."
},
{
"code": null,
"e": 160,
"s": 149,
"text": "Examples: "
},
{
"code": null,
"e": 494,
"s": 160,
"text": "Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23};\nOutput: 5\nExplanation: The longest sub-array with \nelements summing up-to 0 is {-2, 2, -8, 1, 7}\n\nInput: arr[] = {1, 2, 3}\nOutput: 0\nExplanation:There is no subarray with 0 sum\n\nInput: arr[] = {1, 0, 3}\nOutput: 1\nExplanation: The longest sub-array with \nelements summing up-to 0 is {0}"
},
{
"code": null,
"e": 788,
"s": 494,
"text": "Naive Approach: This involves the use of brute force where two nested loops are used. The outer loop is used to fix the starting position of the sub-array, and the inner loop is used for the ending position of the sub-array and if the sum of elements is equal to zero, then increase the count."
},
{
"code": null,
"e": 800,
"s": 788,
"text": "Algorithm: "
},
{
"code": null,
"e": 986,
"s": 800,
"text": "Consider all sub-arrays one by one and check the sum of every sub-array.Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i."
},
{
"code": null,
"e": 1059,
"s": 986,
"text": "Consider all sub-arrays one by one and check the sum of every sub-array."
},
{
"code": null,
"e": 1173,
"s": 1059,
"text": "Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i."
},
{
"code": null,
"e": 1190,
"s": 1173,
"text": "Implementation: "
},
{
"code": null,
"e": 1194,
"s": 1190,
"text": "C++"
},
{
"code": null,
"e": 1199,
"s": 1194,
"text": "Java"
},
{
"code": null,
"e": 1207,
"s": 1199,
"text": "Python3"
},
{
"code": null,
"e": 1210,
"s": 1207,
"text": "C#"
},
{
"code": null,
"e": 1214,
"s": 1210,
"text": "PHP"
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": "Javascript"
},
{
"code": "/* A simple C++ program to findlargest subarray with 0 sum */#include <bits/stdc++.h>using namespace std; // Returns length of the largest// subarray with 0 sumint maxLen(int arr[], int n){ // Initialize result int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize currr_sum for // every starting point int curr_sum = 0; // try all subarrays starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len // if required if (curr_sum == 0) max_len = max(max_len, j - i + 1); } } return max_len;} // Driver Codeint main(){ int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Length of the longest 0 sum subarray is \" << maxLen(arr, n); return 0;}",
"e": 2150,
"s": 1225,
"text": null
},
{
"code": "// Java code to find the largest subarray// with 0 sumclass GFG { // Returns length of the largest subarray // with 0 sum static int maxLen(int arr[], int n) { int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize curr_sum for every // starting point int curr_sum = 0; // try all subarrays starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, then update // max_len if (curr_sum == 0) max_len = Math.max(max_len, j - i + 1); } } return max_len; } public static void main(String args[]) { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = arr.length; System.out.println(\"Length of the longest 0 sum \" + \"subarray is \" + maxLen(arr, n)); }}// This code is contributed by Kamal Rawal",
"e": 3162,
"s": 2150,
"text": null
},
{
"code": "# Python program to find the length of largest subarray with 0 sum # returns the lengthdef maxLen(arr): # initialize result max_len = 0 # pick a starting point for i in range(len(arr)): # initialize sum for every starting point curr_sum = 0 # try all subarrays starting with 'i' for j in range(i, len(arr)): curr_sum += arr[j] # if curr_sum becomes 0, then update max_len if curr_sum == 0: max_len = max(max_len, j-i + 1) return max_len # test arrayarr = [15, -2, 2, -8, 1, 7, 10, 13] print (\"Length of the longest 0 sum subarray is % d\" % maxLen(arr))",
"e": 3842,
"s": 3162,
"text": null
},
{
"code": "// C# code to find the largest// subarray with 0 sumusing System; class GFG { // Returns length of the // largest subarray with 0 sum static int maxLen(int[] arr, int n) { int max_len = 0; // Pick a starting point for (int i = 0; i < n; i++) { // Initialize curr_sum // for every starting point int curr_sum = 0; // try all subarrays // starting with 'i' for (int j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len if (curr_sum == 0) max_len = Math.Max(max_len, j - i + 1); } } return max_len; } // Driver code static public void Main() { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = arr.Length; Console.WriteLine(\"Length of the longest 0 sum \" + \"subarray is \" + maxLen(arr, n)); }} // This code is contributed by ajit",
"e": 4936,
"s": 3842,
"text": null
},
{
"code": "<?php// A simple PHP program to find// largest subarray with 0 sum // Returns length of the// largest subarray with 0 sumfunction maxLen($arr, $n){ $max_len = 0; // Initialize result // Pick a starting point for ($i = 0; $i < $n; $i++) { // Initialize currr_sum // for every starting point $curr_sum = 0; // try all subarrays // starting with 'i' for ($j = $i; $j < $n; $j++) { $curr_sum += $arr[$j]; // If curr_sum becomes 0, // then update max_len // if required if ($curr_sum == 0) $max_len = max($max_len, $j - $i + 1); } } return $max_len;} // Driver Code$arr = array(15, -2, 2, -8, 1, 7, 10, 23);$n = sizeof($arr);echo \"Length of the longest 0 \" . \"sum subarray is \", maxLen($arr, $n); // This code is contributed by aj_36?>",
"e": 5881,
"s": 4936,
"text": null
},
{
"code": "<script> // Javascript code to find the largest // subarray with 0 sum // Returns length of the // largest subarray with 0 sum function maxLen(arr, n) { let max_len = 0; // Pick a starting point for (let i = 0; i < n; i++) { // Initialize curr_sum // for every starting point let curr_sum = 0; // try all subarrays // starting with 'i' for (let j = i; j < n; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len if (curr_sum == 0) max_len = Math.max(max_len, j - i + 1); } } return max_len; } let arr = [ 15, -2, 2, -8, 1, 7, 10, 23 ]; let n = arr.length; document.write(\"Length of the longest 0 sum \" + \"subarray is \" + maxLen(arr, n)); </script>",
"e": 6796,
"s": 5881,
"text": null
},
{
"code": null,
"e": 6838,
"s": 6796,
"text": "Length of the longest 0 sum subarray is 5"
},
{
"code": null,
"e": 6861,
"s": 6838,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 6917,
"s": 6861,
"text": "Time Complexity: O(n^2) due to the use of nested loops."
},
{
"code": null,
"e": 6967,
"s": 6917,
"text": "Space complexity: O(1) as no extra space is used."
},
{
"code": null,
"e": 7570,
"s": 6967,
"text": "Efficient Approach: The brute force solution is calculating the sum of each and every sub-array and checking whether the sum is zero or not. Let’s now try to improve the time complexity by taking an extra space of ‘n’ length. The new array will store the sum of all the elements up to that index. The sum-index pair will be stored in a hash-map. A Hash map allows insertion and deletion of key-value pair in constant time. Therefore, the time complexity remains unaffected. So, if the same value appears twice in the array, it will be guaranteed that the particular array will be a zero-sum sub-array. "
},
{
"code": null,
"e": 7592,
"s": 7570,
"text": "Mathematical Proof: "
},
{
"code": null,
"e": 7848,
"s": 7592,
"text": "prefix(i) = arr[0] + arr[1] +...+ arr[i] prefix(j) = arr[0] + arr[1] +...+ arr[j], j>i ifprefix(i) == prefix(j) then prefix(j) – prefix(i) = 0 that means arr[i+1] + .. + arr[j] = 0, So a sub-array has zero sum , and the length of that sub-array is j-i+1 "
},
{
"code": null,
"e": 7861,
"s": 7848,
"text": "Algorithm: "
},
{
"code": null,
"e": 8449,
"s": 7861,
"text": "Create an extra space, an array of length n (prefix), a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair.Move along the input array from the start to the end.For every index, update the value of sum = sum + array[i].Check every index, if the current sum is present in the hash map or not.If present, update the value of max_len to a maximum difference of two indices (current index and index in the hash-map) and max_len.Else, put the value (sum) in the hash map, with the index as a key-value pair.Print the maximum length (max_len)."
},
{
"code": null,
"e": 8608,
"s": 8449,
"text": "Create an extra space, an array of length n (prefix), a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair."
},
{
"code": null,
"e": 8662,
"s": 8608,
"text": "Move along the input array from the start to the end."
},
{
"code": null,
"e": 8721,
"s": 8662,
"text": "For every index, update the value of sum = sum + array[i]."
},
{
"code": null,
"e": 8794,
"s": 8721,
"text": "Check every index, if the current sum is present in the hash map or not."
},
{
"code": null,
"e": 8928,
"s": 8794,
"text": "If present, update the value of max_len to a maximum difference of two indices (current index and index in the hash-map) and max_len."
},
{
"code": null,
"e": 9007,
"s": 8928,
"text": "Else, put the value (sum) in the hash map, with the index as a key-value pair."
},
{
"code": null,
"e": 9043,
"s": 9007,
"text": "Print the maximum length (max_len)."
},
{
"code": null,
"e": 9086,
"s": 9043,
"text": "Below is a dry run of the above approach: "
},
{
"code": null,
"e": 9103,
"s": 9086,
"text": "Implementation: "
},
{
"code": null,
"e": 9107,
"s": 9103,
"text": "C++"
},
{
"code": null,
"e": 9112,
"s": 9107,
"text": "Java"
},
{
"code": null,
"e": 9120,
"s": 9112,
"text": "Python3"
},
{
"code": null,
"e": 9123,
"s": 9120,
"text": "C#"
},
{
"code": null,
"e": 9134,
"s": 9123,
"text": "Javascript"
},
{
"code": "// C++ program to find the length of largest subarray// with 0 sum#include <bits/stdc++.h>using namespace std; // Returns Length of the required subarrayint maxLen(int arr[], int n){ // Map to store the previous sums unordered_map<int, int> presum; int sum = 0; // Initialize the sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look for this sum in Hash table if (presum.find(sum) != presum.end()) { // If this sum is seen before, then update max_len max_len = max(max_len, i - presum[sum]); } else { // Else insert this sum with index in hash table presum[sum] = i; } } return max_len;} // Driver Codeint main(){ int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Length of the longest 0 sum subarray is \" << maxLen(arr, n); return 0;}",
"e": 10288,
"s": 9134,
"text": null
},
{
"code": "// A Java program to find maximum length subarray with 0 sumimport java.util.HashMap; class MaxLenZeroSumSub { // Returns length of the maximum length subarray with 0 sum static int maxLen(int arr[]) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < arr.length; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table Integer prev_i = hM.get(sum); // If this sum is seen before, then update max_len // if required if (prev_i != null) max_len = Math.max(max_len, i - prev_i); else // Else put this sum in hash table hM.put(sum, i); } return max_len; } // Drive method public static void main(String arg[]) { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; System.out.println(\"Length of the longest 0 sum subarray is \" + maxLen(arr)); }}",
"e": 11608,
"s": 10288,
"text": null
},
{
"code": "# A python program to find maximum length subarray# with 0 sum in o(n) time # Returns the maximum lengthdef maxLen(arr): # NOTE: Dictionary in python in implemented as Hash Maps # Create an empty hash map (dictionary) hash_map = {} # Initialize result max_len = 0 # Initialize sum of elements curr_sum = 0 # Traverse through the given array for i in range(len(arr)): # Add the current element to the sum curr_sum += arr[i] if arr[i] is 0 and max_len is 0: max_len = 1 if curr_sum is 0: max_len = i + 1 # NOTE: 'in' operation in dictionary to search # key takes O(1). Look if current sum is seen # before if curr_sum in hash_map: max_len = max(max_len, i - hash_map[curr_sum] ) else: # else put this sum in dictionary hash_map[curr_sum] = i return max_len # test arrayarr = [15, -2, 2, -8, 1, 7, 10, 13] print (\"Length of the longest 0 sum subarray is % d\" % maxLen(arr))",
"e": 12651,
"s": 11608,
"text": null
},
{
"code": "// C# program to find maximum// length subarray with 0 sumusing System;using System.Collections.Generic; public class MaxLenZeroSumSub { // Returns length of the maximum // length subarray with 0 sum static int maxLen(int[] arr) { // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < arr.GetLength(0); i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table int prev_i = 0; if (hM.ContainsKey(sum)) { prev_i = hM[sum]; } // If this sum is seen before, then update max_len // if required if (hM.ContainsKey(sum)) max_len = Math.Max(max_len, i - prev_i); else { // Else put this sum in hash table if (hM.ContainsKey(sum)) hM.Remove(sum); hM.Add(sum, i); } } return max_len; } // Driver code public static void Main() { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; Console.WriteLine(\"Length of the longest 0 sum subarray is \" + maxLen(arr)); }} /* This code contributed by PrinciRaj1992 */",
"e": 14210,
"s": 12651,
"text": null
},
{
"code": "<script> // Javascript program to find maximum length subarray with 0 sum // Returns length of the maximum length subarray with 0 sum function maxLen(arr) { // Creates an empty hashMap hM let hM = new Map(); let sum = 0; // Initialize sum of elements let max_len = 0; // Initialize result // Traverse through the given array for (let i = 0; i < arr.length; i++) { // Add current element to sum sum += arr[i]; if (arr[i] == 0 && max_len == 0) max_len = 1; if (sum == 0) max_len = i + 1; // Look this sum in hash table let prev_i = hM.get(sum); // If this sum is seen before, then update max_len // if required if (prev_i != null) max_len = Math.max(max_len, i - prev_i); else // Else put this sum in hash table hM.set(sum, i); } return max_len; } // Driver program let arr = [ 15, -2, 2, -8, 1, 7, 10, 23 ]; document.write(\"Length of the longest 0 sum subarray is \" + maxLen(arr)); </script>",
"e": 15396,
"s": 14210,
"text": null
},
{
"code": null,
"e": 15438,
"s": 15396,
"text": "Length of the longest 0 sum subarray is 5"
},
{
"code": null,
"e": 15460,
"s": 15438,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 15580,
"s": 15460,
"text": "Time Complexity: O(n), as use of the good hashing function, will allow insertion and retrieval operations in O(1) time."
},
{
"code": null,
"e": 15670,
"s": 15580,
"text": "Space Complexity: O(n), for the use of extra space to store the prefix array and hashmap."
},
{
"code": null,
"e": 15707,
"s": 15670,
"text": " Alternative and efficient approach:"
},
{
"code": null,
"e": 15800,
"s": 15707,
"text": "The above efficient approach can be tweaked a little bit to handle all if conditions in one."
},
{
"code": null,
"e": 15811,
"s": 15800,
"text": "Algorithm:"
},
{
"code": null,
"e": 16338,
"s": 15811,
"text": "In this approach, the Hash Map will store (Cumulative Sum, index+1).It starts with inserting (0,0) to the Hash Map at the beginning and initializing cumSum = 0 and length = -1;Traverse throughout the array.Find cumulative sum till that point by Cumulative sum = Cumulative sum + current value of array;if the cumulative sum is already present in the Hash Map as a key then update length as maximum of (length, index+1 – value corresponding to cumulative sum in Hash Map)else insert (cumulative sum, index + 1) to the Hash Map."
},
{
"code": null,
"e": 16407,
"s": 16338,
"text": "In this approach, the Hash Map will store (Cumulative Sum, index+1)."
},
{
"code": null,
"e": 16516,
"s": 16407,
"text": "It starts with inserting (0,0) to the Hash Map at the beginning and initializing cumSum = 0 and length = -1;"
},
{
"code": null,
"e": 16547,
"s": 16516,
"text": "Traverse throughout the array."
},
{
"code": null,
"e": 16644,
"s": 16547,
"text": "Find cumulative sum till that point by Cumulative sum = Cumulative sum + current value of array;"
},
{
"code": null,
"e": 16813,
"s": 16644,
"text": "if the cumulative sum is already present in the Hash Map as a key then update length as maximum of (length, index+1 – value corresponding to cumulative sum in Hash Map)"
},
{
"code": null,
"e": 16870,
"s": 16813,
"text": "else insert (cumulative sum, index + 1) to the Hash Map."
},
{
"code": null,
"e": 16883,
"s": 16870,
"text": "Explanation:"
},
{
"code": null,
"e": 17044,
"s": 16883,
"text": "Let’s consider array [ 0, -2, 2, 2, -2].initial Hash Map {0, 0}, cumSum = 0, length = -1.Iterating over the array with index ranging from 0 to array length – 1."
},
{
"code": null,
"e": 17085,
"s": 17044,
"text": "Let’s consider array [ 0, -2, 2, 2, -2]."
},
{
"code": null,
"e": 17135,
"s": 17085,
"text": "initial Hash Map {0, 0}, cumSum = 0, length = -1."
},
{
"code": null,
"e": 17207,
"s": 17135,
"text": "Iterating over the array with index ranging from 0 to array length – 1."
},
{
"code": null,
"e": 17345,
"s": 17207,
"text": "index = 0, cumSum = 0, cumSum is present in Hash Map as a key. length = Max(length, index+1 – hm.get(cumSum)) => length = max(-1 , 1) = 1"
},
{
"code": null,
"e": 17478,
"s": 17345,
"text": "index = 1, cumSum = -2, cumSum is not present in Hash Map as a key. Inserting (cumSum, index + 1). Hash Map becomes { 0 = 0, -2 = 2}"
},
{
"code": null,
"e": 17590,
"s": 17478,
"text": "index = 2, cumSum = 0, cumSum is present in Hash Map as a key. So, length = Max(1 , 2+1-0). Hence, length = 3."
},
{
"code": null,
"e": 17687,
"s": 17590,
"text": "index = 3, cumSum = 2, cumSum is not present in Hash Map key. Hash Map = { 0 = 0, -2 = 2, 2 = 4}"
},
{
"code": null,
"e": 17766,
"s": 17687,
"text": "index = 4, cumSum = 0, cumSum is present as a key, length = max(3 , 4+1-0) = 5"
},
{
"code": null,
"e": 17770,
"s": 17766,
"text": "C++"
},
{
"code": null,
"e": 17775,
"s": 17770,
"text": "Java"
},
{
"code": null,
"e": 17783,
"s": 17775,
"text": "Python3"
},
{
"code": null,
"e": 17786,
"s": 17783,
"text": "C#"
},
{
"code": null,
"e": 17797,
"s": 17786,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // to find maximum length of sub array having sum 0int maxSubArrayLen(vector<int>arr){ map<int,int>hm; hm[0] = 0; int length = -1; int cumSum = 0; for (int i = 0; i < arr.size(); i++) { cumSum = cumSum + arr[i]; if (hm.find(cumSum) != hm.end()) { length = max(length, i + 1 - hm[cumSum]); } else { hm[cumSum] = i + 1; } } return length;} // Driver Codeint main(){ vector<int>arr = {15, -2, 2, -8, 1, 7, 10, 23};cout<<maxSubArrayLen(arr)<<endl; } // This code is contributed by shinjanpatra",
"e": 18476,
"s": 17797,
"text": null
},
{
"code": "// to find maximum length of sub array having sum 0import java.io.*;import java.util.HashMap; class GFG { public static int maxSubArrayLen(int[] arr) { HashMap<Integer, Integer> hm = new HashMap<>(); hm.put(0, 0); int length = -1; int cumSum = 0; for (int i = 0; i < arr.length; i++) { cumSum = cumSum + arr[i]; if (hm.containsKey(cumSum)) { length = Math.max(length, i + 1 - hm.get(cumSum)); } else { hm.put(cumSum, i + 1); } } return length; } public static void main(String[] args) { int[] arr = new int[] { 15, -2, 2, -8, 1, 7, 10, 23 }; System.out.println(maxSubArrayLen(arr)); }}// Contributed by Bibhu Parambrahma Patra (bibhup)",
"e": 19324,
"s": 18476,
"text": null
},
{
"code": "# to find maximum length of sub array having sum 0def maxSubArrayLen(arr): hm = {} hm[0] = 0 length = -1 cumSum = 0 for i in range(len(arr)): cumSum = cumSum + arr[i] if (cumSum in hm): length = max(length,i + 1 - hm[cumSum]) else: hm[cumSum] = i + 1 return length # driver codearr = [15, -2, 2, -8, 1, 7, 10, 23]print(maxSubArrayLen(arr)) # This code is contributed by shinjanpatra",
"e": 19774,
"s": 19324,
"text": null
},
{
"code": "// C# program to find maximum length of sub array having sum// 0using System;using System.Collections.Generic; public class GFG{ // function to find the length of the longest // of the sub array with its sum equal to 0 static int maxSubArrayLen(int[] arr) { // declaring a dictionary to maintain the length and // sum of each subarray IDictionary<int, int> hm = new Dictionary<int, int>(); hm[0] = 0; int length = -1; int cumSum = 0; // iterating over the array and building the // dictionary for (int i = 0; i < arr.Length; i++) { cumSum = cumSum + arr[i]; if (hm.ContainsKey(cumSum)) { length = Math.Max(length, i + 1 - hm[cumSum]); } else { hm[cumSum] = i + 1; } } return length; } // driver call public static void Main(string[] args) { int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 }; // function call Console.WriteLine(maxSubArrayLen(arr)); }} // This code is contributed by phasing17",
"e": 20771,
"s": 19774,
"text": null
},
{
"code": "<script> // to find maximum length of sub array having sum 0function maxSubArrayLen(arr){ let hm = new Map(); hm.set(0,0); let length = -1; let cumSum = 0; for (let i = 0; i < arr.length; i++) { cumSum = cumSum + arr[i]; if (hm.has(cumSum)) { length = Math.max(length, i + 1 - hm.get(cumSum)); } else { hm.set(cumSum, i + 1); } } return length;} // driver codelet arr = [15, -2, 2, -8, 1, 7, 10, 23];document.write(maxSubArrayLen(arr),\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 21376,
"s": 20771,
"text": null
},
{
"code": null,
"e": 21378,
"s": 21376,
"text": "5"
},
{
"code": null,
"e": 21399,
"s": 21378,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 21462,
"s": 21399,
"text": "Time Complexity: O(n).Space Complexity: O(n), for the Hash Map"
},
{
"code": null,
"e": 21468,
"s": 21462,
"text": "jit_t"
},
{
"code": null,
"e": 21478,
"s": 21468,
"text": "Mahin_251"
},
{
"code": null,
"e": 21492,
"s": 21478,
"text": "princiraj1992"
},
{
"code": null,
"e": 21503,
"s": 21492,
"text": "andrew1234"
},
{
"code": null,
"e": 21513,
"s": 21503,
"text": "ankitdoot"
},
{
"code": null,
"e": 21524,
"s": 21513,
"text": "decode2207"
},
{
"code": null,
"e": 21533,
"s": 21524,
"text": "target_2"
},
{
"code": null,
"e": 21549,
"s": 21533,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 21562,
"s": 21549,
"text": "simmytarika5"
},
{
"code": null,
"e": 21569,
"s": 21562,
"text": "bibhup"
},
{
"code": null,
"e": 21582,
"s": 21569,
"text": "shinjanpatra"
},
{
"code": null,
"e": 21592,
"s": 21582,
"text": "phasing17"
},
{
"code": null,
"e": 21609,
"s": 21592,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21616,
"s": 21609,
"text": "Amazon"
},
{
"code": null,
"e": 21627,
"s": 21616,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 21636,
"s": 21627,
"text": "subarray"
},
{
"code": null,
"e": 21649,
"s": 21636,
"text": "subarray-sum"
},
{
"code": null,
"e": 21656,
"s": 21649,
"text": "Arrays"
},
{
"code": null,
"e": 21661,
"s": 21656,
"text": "Hash"
},
{
"code": null,
"e": 21668,
"s": 21661,
"text": "Amazon"
},
{
"code": null,
"e": 21679,
"s": 21668,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 21686,
"s": 21679,
"text": "Arrays"
},
{
"code": null,
"e": 21691,
"s": 21686,
"text": "Hash"
}
] |
How to Display/Hide functions using aria-hidden attribute in jQuery ?
|
20 Sep, 2021
The ‘aria-hidden’ attribute plays an important role in context of web-accessibility. It is a simple way to make web content/applications more accessible to people with disabilities. This attribute is used to indicate that the element and all of its descendants are not visible or perceivable to any user as per the implementation. Now in your mind may a question arrived that what is the difference between ‘hidden’ and ‘aria-hidden’ attributes?The main aspect of making this solution is to make content readable only when content is visible on screen otherwise should remain inaccessible. Here, we’ll be using attr() method to do the same which is used for setting/getting an element’s attribute.Syntax:
Getter: $([selector]).attr('attribute');
Setter: $([selector]).attr('attribute', 'value');
Below example illustrate the above approach:Example:
html
<!DOCTYPE html><html> <head> <title> aria-hidden attribute on JQuery Show/Hide functions </title> <!-- Added support for BS3 and jQuery using CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <style> .access { margin-left: 90px; } </style></head> <body> <br><br> <div class="row"> <div class="col-sm-4"> <!-- button to toggle attribute --> <center> <button class="btn btn-success"> Toggle </button> </center> </div> <div class="col-sm-8"> <!-- Attribute's value --> <p><i>aria-hidden</i> attribute's value : <b> <span id="answer">false</span> </b> </p> </div> </div> <br> <br> <div class="container-fluid"> <div class="access" aria-hidden="false"> <!-- For Content accessibility --> <h1 class="text-success"> GeeksforGeeks </h1> <b> A Computer Science portal for Geeks </b> </div> </div> <script> $(document).ready(function() { $('button').click(function() { /*Check and alternate attribute's value, then show/hide accordingly using chaining. */ if ($('.access') .attr('aria-hidden') == 'true') $('.access') .attr('aria-hidden', 'false') .show('fast'); else $('.access') .attr('aria-hidden', 'true') .hide('slow'); // Display changed attribute's value $('#answer') .text($('.access') .attr('aria-hidden')); }); }); </script></body> </html>
Output:
kalrap615
jQuery-Misc
Picked
JQuery
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Sep, 2021"
},
{
"code": null,
"e": 735,
"s": 28,
"text": "The ‘aria-hidden’ attribute plays an important role in context of web-accessibility. It is a simple way to make web content/applications more accessible to people with disabilities. This attribute is used to indicate that the element and all of its descendants are not visible or perceivable to any user as per the implementation. Now in your mind may a question arrived that what is the difference between ‘hidden’ and ‘aria-hidden’ attributes?The main aspect of making this solution is to make content readable only when content is visible on screen otherwise should remain inaccessible. Here, we’ll be using attr() method to do the same which is used for setting/getting an element’s attribute.Syntax: "
},
{
"code": null,
"e": 826,
"s": 735,
"text": "Getter: $([selector]).attr('attribute');\nSetter: $([selector]).attr('attribute', 'value');"
},
{
"code": null,
"e": 881,
"s": 826,
"text": "Below example illustrate the above approach:Example: "
},
{
"code": null,
"e": 886,
"s": 881,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> aria-hidden attribute on JQuery Show/Hide functions </title> <!-- Added support for BS3 and jQuery using CDN --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://code.jquery.com/jquery-3.4.1.slim.min.js\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <style> .access { margin-left: 90px; } </style></head> <body> <br><br> <div class=\"row\"> <div class=\"col-sm-4\"> <!-- button to toggle attribute --> <center> <button class=\"btn btn-success\"> Toggle </button> </center> </div> <div class=\"col-sm-8\"> <!-- Attribute's value --> <p><i>aria-hidden</i> attribute's value : <b> <span id=\"answer\">false</span> </b> </p> </div> </div> <br> <br> <div class=\"container-fluid\"> <div class=\"access\" aria-hidden=\"false\"> <!-- For Content accessibility --> <h1 class=\"text-success\"> GeeksforGeeks </h1> <b> A Computer Science portal for Geeks </b> </div> </div> <script> $(document).ready(function() { $('button').click(function() { /*Check and alternate attribute's value, then show/hide accordingly using chaining. */ if ($('.access') .attr('aria-hidden') == 'true') $('.access') .attr('aria-hidden', 'false') .show('fast'); else $('.access') .attr('aria-hidden', 'true') .hide('slow'); // Display changed attribute's value $('#answer') .text($('.access') .attr('aria-hidden')); }); }); </script></body> </html>",
"e": 3136,
"s": 886,
"text": null
},
{
"code": null,
"e": 3146,
"s": 3136,
"text": "Output: "
},
{
"code": null,
"e": 3158,
"s": 3148,
"text": "kalrap615"
},
{
"code": null,
"e": 3170,
"s": 3158,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 3177,
"s": 3170,
"text": "Picked"
},
{
"code": null,
"e": 3184,
"s": 3177,
"text": "JQuery"
},
{
"code": null,
"e": 3203,
"s": 3184,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3220,
"s": 3203,
"text": "Web Technologies"
},
{
"code": null,
"e": 3247,
"s": 3220,
"text": "Web technologies Questions"
}
] |
Shellphish Tool in Kali Linux - GeeksforGeeks
|
15 Mar, 2021
Shellphish is a powerful open-source tool Phishing Tool. It became very popular nowadays that is used to do phishing attacks on Target. Shellphish is easier than Social Engineering Toolkit. It contains some templates generated by another tool called SocialFish and offers phishing templates webpages for 18 popular sites such as Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, LinkedIn, WordPress, Origin, Steam, Microsoft, etc. It also provides an option to use a custom template if someone wants. This tool makes it easy to perform a phishing attack. Using this tool you can perform phishing in (wide area network). This tool can be used to get credentials such as id, password.
Uses of Shellphish:
Shellphish tool can create phishing pages of most popular social networking sites like
Facebook
Instagram
Yahoo
Twitter
Netflix
Step 1: Open your Terminal on Kali Linux and move to Desktop
cd Desktop
Step 2: Create a new Directory i.e shellphish
mkdir shellphish
Step 3: On Terminal itself download and install shellphish in the above directory by the following command
git clone https://github.com/suljot/shellphish.git
Step 4: Finally to execute shellphish tool-type following command
./shellphish.sh
Congratulations you have installed shellphish tool in your Kali Linux machine. You can see you are getting multiple options here, for Instagram you are getting [01], for Facebook you are getting [02], and for multiple other sites you are getting other options.
For example, let’s type 1 and press enter .now you can see shellphish has created the URL https://8b992b4bc918.ngrok.io. Send this link to the target person through any medium (email, WhatsApp, text message). Once your target open this link and fill the respective phishing form and I’d and password will be shown below {waiting IPs and Credentials}
Once the victim opens the link, they will be able to see a page that will look exactly like the Instagram login page, and this will earn their trust. Once they have entered the credentials, HACKED! You will be able to see their username and password on your Kali Linux terminal. The victim will be now redirected to the original Instagram page.
Kali-Linux
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 26222,
"s": 26194,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 26940,
"s": 26222,
"text": "Shellphish is a powerful open-source tool Phishing Tool. It became very popular nowadays that is used to do phishing attacks on Target. Shellphish is easier than Social Engineering Toolkit. It contains some templates generated by another tool called SocialFish and offers phishing templates webpages for 18 popular sites such as Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, LinkedIn, WordPress, Origin, Steam, Microsoft, etc. It also provides an option to use a custom template if someone wants. This tool makes it easy to perform a phishing attack. Using this tool you can perform phishing in (wide area network). This tool can be used to get credentials such as id, password."
},
{
"code": null,
"e": 26960,
"s": 26940,
"text": "Uses of Shellphish:"
},
{
"code": null,
"e": 27047,
"s": 26960,
"text": "Shellphish tool can create phishing pages of most popular social networking sites like"
},
{
"code": null,
"e": 27056,
"s": 27047,
"text": "Facebook"
},
{
"code": null,
"e": 27066,
"s": 27056,
"text": "Instagram"
},
{
"code": null,
"e": 27072,
"s": 27066,
"text": "Yahoo"
},
{
"code": null,
"e": 27080,
"s": 27072,
"text": "Twitter"
},
{
"code": null,
"e": 27088,
"s": 27080,
"text": "Netflix"
},
{
"code": null,
"e": 27149,
"s": 27088,
"text": "Step 1: Open your Terminal on Kali Linux and move to Desktop"
},
{
"code": null,
"e": 27161,
"s": 27149,
"text": "cd Desktop "
},
{
"code": null,
"e": 27207,
"s": 27161,
"text": "Step 2: Create a new Directory i.e shellphish"
},
{
"code": null,
"e": 27224,
"s": 27207,
"text": "mkdir shellphish"
},
{
"code": null,
"e": 27331,
"s": 27224,
"text": "Step 3: On Terminal itself download and install shellphish in the above directory by the following command"
},
{
"code": null,
"e": 27382,
"s": 27331,
"text": "git clone https://github.com/suljot/shellphish.git"
},
{
"code": null,
"e": 27448,
"s": 27382,
"text": "Step 4: Finally to execute shellphish tool-type following command"
},
{
"code": null,
"e": 27464,
"s": 27448,
"text": "./shellphish.sh"
},
{
"code": null,
"e": 27725,
"s": 27464,
"text": "Congratulations you have installed shellphish tool in your Kali Linux machine. You can see you are getting multiple options here, for Instagram you are getting [01], for Facebook you are getting [02], and for multiple other sites you are getting other options."
},
{
"code": null,
"e": 28075,
"s": 27725,
"text": "For example, let’s type 1 and press enter .now you can see shellphish has created the URL https://8b992b4bc918.ngrok.io. Send this link to the target person through any medium (email, WhatsApp, text message). Once your target open this link and fill the respective phishing form and I’d and password will be shown below {waiting IPs and Credentials}"
},
{
"code": null,
"e": 28420,
"s": 28075,
"text": "Once the victim opens the link, they will be able to see a page that will look exactly like the Instagram login page, and this will earn their trust. Once they have entered the credentials, HACKED! You will be able to see their username and password on your Kali Linux terminal. The victim will be now redirected to the original Instagram page."
},
{
"code": null,
"e": 28431,
"s": 28420,
"text": "Kali-Linux"
},
{
"code": null,
"e": 28438,
"s": 28431,
"text": "How To"
},
{
"code": null,
"e": 28449,
"s": 28438,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28547,
"s": 28449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28581,
"s": 28547,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28639,
"s": 28581,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28688,
"s": 28639,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28730,
"s": 28688,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28790,
"s": 28730,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 28830,
"s": 28790,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 28870,
"s": 28830,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 28897,
"s": 28870,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 28932,
"s": 28897,
"text": "cut command in Linux with examples"
}
] |
Bitwise AND of all unordered pairs from a given array - GeeksforGeeks
|
26 Jul, 2021
Given an array arr[] of size N, the task is to find the bitwise AND of all possible unordered pairs present in the given array.
Examples:
Input: arr[] = {1, 5, 3, 7}Output: 1 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7). Bitwise AND of all possible pairs = ( 1 & 5 ) & ( 1 & 3 ) & ( 1 & 7 ) & ( 5 & 3 ) & ( 5 & 7 ) & ( 3 & 7 ) = 1 & 1 & 1 & 1 & 5 & 3 = 1 Therefore, the required output is 1.
Input: arr[] = {4, 5, 12, 15}Output: 4
Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print Bitwise AND of each element present in these pairs of the given array. Follow the steps below to solve the problem:
Initialize a variable, say totalAND, to store Bitwise AND of each element from these pairs.
Iterate over the array and generate all possible pairs (arr[i], arr[j]) from the given array.
For each pair (arr[i], arr[j]), update the value of totalAND = (totalAND & arr[i] & arr[j]).
Finally, print the value of totalAND.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate bitwise AND// of all pairs from the given arrayint TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codeint main(){ int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N);}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N));}} // This code is contributed by shikhasingrajput
# Python3 program to implement# the above approach # Function to calculate bitwise AND# of all pairs from the given arraydef TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1 # Generate all possible pairs for i in range(N): for j in range(i + 1, N): # Calculate bitwise AND # of each pair totalAND &= (arr[i] & arr[j]) return totalAND # Driver Codeif __name__ == '__main__': arr=[4, 5, 12, 15] N = len(arr) print(TotalAndPair(arr, N)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approach using System; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int[] arr, int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codepublic static void Main(){ int[] arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N));}} // This code is contributed by sanjoy_62
<script> // JavaScript program to implement// the above approach // Function to calculate bitwise AND// of all pairs from the given arrayfunction TotalAndPair(arr, N){ // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Generate all possible pairs for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi </script>
4
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
Considering an array of 4 elements, required Bitwise AND is as follows:
(arr[0] & arr[1]) & (arr[0] & arr[2]) & (arr[0] & arr[3]) & (arr[1] & arr[2]) & (arr[1] & arr[3]) & (arr[2] & arr[3])
Since Bitwise AND follows Associative property, the above expression can be rearranged as:
(arr[0] & arr[0] & arr[0]) & (arr[1] & arr[1] & arr[1]) & (arr[2] & arr[2] & arr[2]) & (arr[3] & arr[3] & arr[3])
It can be observed that each array element occurs exactly (N – 1) times in all possible pairs.
Based on the X & X = X property of Bitwise AND operators, the above expression can be rearranged to arr[0] & arr[1] & arr[2] & arr[3], which is equal to the Bitwise AND of all elements of original array.
Follow the steps below to solve the problem:
Initialize a variable totalAND to store the result.
Traverse the given array.
Calculate Bitwise AND of all unordered pairs by updating totalAND = totalAND & arr[i].
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate bitwise AND// of all pairs from the given arrayint TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codeint main(){ int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N);}
// Java program to implement// the above approach import java.util.*; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N));}} // This code is contributed by 29AjayKumar
# Python program to implement# the above approach # Function to calculate bitwise AND# of all pairs from the given arraydef TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1; # Iterate over the array arr for i in range(N): # Calculate bitwise AND # of each array element totalAND &= arr[i]; return totalAND; # Driver Codeif __name__ == '__main__': arr = [4, 5, 12, 15]; N = len(arr); print(TotalAndPair(arr, N)); # This code is contributed by 29AjayKumar
// C# program to implement// the above approachusing System; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int []arr, int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for(int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N));}} // This code is contributed by AnkThon
<script>// JavaScript program to implement// the above approach // Function to calculate bitwise AND// of all pairs from the given arrayfunction TotalAndPair(arr, N){ // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (let i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi.</script>
4
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
shikhasingrajput
sanjoy_62
29AjayKumar
ankthon
surbhityagi15
adnanirshad158
Bitwise-AND
Arrays
Bit Magic
C++ Programs
Mathematical
Arrays
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 26917,
"s": 26889,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 27045,
"s": 26917,
"text": "Given an array arr[] of size N, the task is to find the bitwise AND of all possible unordered pairs present in the given array."
},
{
"code": null,
"e": 27055,
"s": 27045,
"text": "Examples:"
},
{
"code": null,
"e": 27472,
"s": 27055,
"text": "Input: arr[] = {1, 5, 3, 7}Output: 1 Explanation: All possible unordered pairs are (1, 5), (1, 3), (1, 7), (5, 3), (5, 7), (3, 7). Bitwise AND of all possible pairs = ( 1 & 5 ) & ( 1 & 3 ) & ( 1 & 7 ) & ( 5 & 3 ) & ( 5 & 7 ) & ( 3 & 7 ) = 1 & 1 & 1 & 1 & 5 & 3 = 1 Therefore, the required output is 1."
},
{
"code": null,
"e": 27511,
"s": 27472,
"text": "Input: arr[] = {4, 5, 12, 15}Output: 4"
},
{
"code": null,
"e": 27744,
"s": 27511,
"text": "Naive approach: The idea is to traverse the array and generate all possible pairs of the given array. Finally, print Bitwise AND of each element present in these pairs of the given array. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27836,
"s": 27744,
"text": "Initialize a variable, say totalAND, to store Bitwise AND of each element from these pairs."
},
{
"code": null,
"e": 27930,
"s": 27836,
"text": "Iterate over the array and generate all possible pairs (arr[i], arr[j]) from the given array."
},
{
"code": null,
"e": 28023,
"s": 27930,
"text": "For each pair (arr[i], arr[j]), update the value of totalAND = (totalAND & arr[i] & arr[j])."
},
{
"code": null,
"e": 28061,
"s": 28023,
"text": "Finally, print the value of totalAND."
},
{
"code": null,
"e": 28112,
"s": 28061,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28116,
"s": 28112,
"text": "C++"
},
{
"code": null,
"e": 28121,
"s": 28116,
"text": "Java"
},
{
"code": null,
"e": 28129,
"s": 28121,
"text": "Python3"
},
{
"code": null,
"e": 28132,
"s": 28129,
"text": "C#"
},
{
"code": null,
"e": 28143,
"s": 28132,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate bitwise AND// of all pairs from the given arrayint TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codeint main(){ int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N);}",
"e": 28848,
"s": 28143,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N));}} // This code is contributed by shikhasingrajput",
"e": 29625,
"s": 28848,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to calculate bitwise AND# of all pairs from the given arraydef TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1 # Generate all possible pairs for i in range(N): for j in range(i + 1, N): # Calculate bitwise AND # of each pair totalAND &= (arr[i] & arr[j]) return totalAND # Driver Codeif __name__ == '__main__': arr=[4, 5, 12, 15] N = len(arr) print(TotalAndPair(arr, N)) # This code is contributed by mohit kumar 29",
"e": 30213,
"s": 29625,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int[] arr, int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Generate all possible pairs for(int i = 0; i < N; i++) { for(int j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Codepublic static void Main(){ int[] arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N));}} // This code is contributed by sanjoy_62",
"e": 30949,
"s": 30213,
"text": null
},
{
"code": "<script> // JavaScript program to implement// the above approach // Function to calculate bitwise AND// of all pairs from the given arrayfunction TotalAndPair(arr, N){ // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Generate all possible pairs for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { // Calculate bitwise AND // of each pair totalAND &= arr[i] & arr[j]; } } return totalAND;} // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi </script>",
"e": 31650,
"s": 30949,
"text": null
},
{
"code": null,
"e": 31652,
"s": 31650,
"text": "4"
},
{
"code": null,
"e": 31698,
"s": 31654,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31791,
"s": 31698,
"text": "Efficient Approach: The above approach can be optimized based on the following observations:"
},
{
"code": null,
"e": 31863,
"s": 31791,
"text": "Considering an array of 4 elements, required Bitwise AND is as follows:"
},
{
"code": null,
"e": 31983,
"s": 31863,
"text": "(arr[0] & arr[1]) & (arr[0] & arr[2]) & (arr[0] & arr[3]) & (arr[1] & arr[2]) & (arr[1] & arr[3]) & (arr[2] & arr[3]) "
},
{
"code": null,
"e": 32074,
"s": 31983,
"text": "Since Bitwise AND follows Associative property, the above expression can be rearranged as:"
},
{
"code": null,
"e": 32190,
"s": 32074,
"text": "(arr[0] & arr[0] & arr[0]) & (arr[1] & arr[1] & arr[1]) & (arr[2] & arr[2] & arr[2]) & (arr[3] & arr[3] & arr[3]) "
},
{
"code": null,
"e": 32285,
"s": 32190,
"text": "It can be observed that each array element occurs exactly (N – 1) times in all possible pairs."
},
{
"code": null,
"e": 32489,
"s": 32285,
"text": "Based on the X & X = X property of Bitwise AND operators, the above expression can be rearranged to arr[0] & arr[1] & arr[2] & arr[3], which is equal to the Bitwise AND of all elements of original array."
},
{
"code": null,
"e": 32535,
"s": 32489,
"text": "Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 32587,
"s": 32535,
"text": "Initialize a variable totalAND to store the result."
},
{
"code": null,
"e": 32613,
"s": 32587,
"text": "Traverse the given array."
},
{
"code": null,
"e": 32700,
"s": 32613,
"text": "Calculate Bitwise AND of all unordered pairs by updating totalAND = totalAND & arr[i]."
},
{
"code": null,
"e": 32750,
"s": 32700,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 32754,
"s": 32750,
"text": "C++"
},
{
"code": null,
"e": 32759,
"s": 32754,
"text": "Java"
},
{
"code": null,
"e": 32767,
"s": 32759,
"text": "Python3"
},
{
"code": null,
"e": 32770,
"s": 32767,
"text": "C#"
},
{
"code": null,
"e": 32781,
"s": 32770,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate bitwise AND// of all pairs from the given arrayint TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codeint main(){ int arr[] = { 4, 5, 12, 15 }; int N = sizeof(arr) / sizeof(arr[0]); cout << TotalAndPair(arr, N);}",
"e": 33390,
"s": 32781,
"text": null
},
{
"code": "// Java program to implement// the above approach import java.util.*; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int arr[], int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codepublic static void main(String[] args){ int arr[] = { 4, 5, 12, 15 }; int N = arr.length; System.out.print(TotalAndPair(arr, N));}} // This code is contributed by 29AjayKumar",
"e": 34057,
"s": 33390,
"text": null
},
{
"code": "# Python program to implement# the above approach # Function to calculate bitwise AND# of all pairs from the given arraydef TotalAndPair(arr, N): # Stores bitwise AND # of all possible pairs totalAND = (1 << 30) - 1; # Iterate over the array arr for i in range(N): # Calculate bitwise AND # of each array element totalAND &= arr[i]; return totalAND; # Driver Codeif __name__ == '__main__': arr = [4, 5, 12, 15]; N = len(arr); print(TotalAndPair(arr, N)); # This code is contributed by 29AjayKumar",
"e": 34622,
"s": 34057,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to calculate bitwise AND// of all pairs from the given arraystatic int TotalAndPair(int []arr, int N){ // Stores bitwise AND // of all possible pairs int totalAND = (1 << 30) - 1; // Iterate over the array arr[] for(int i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Codepublic static void Main(String[] args){ int []arr = { 4, 5, 12, 15 }; int N = arr.Length; Console.Write(TotalAndPair(arr, N));}} // This code is contributed by AnkThon",
"e": 35297,
"s": 34622,
"text": null
},
{
"code": "<script>// JavaScript program to implement// the above approach // Function to calculate bitwise AND// of all pairs from the given arrayfunction TotalAndPair(arr, N){ // Stores bitwise AND // of all possible pairs let totalAND = (1 << 30) - 1; // Iterate over the array arr[] for (let i = 0; i < N; i++) { // Calculate bitwise AND // of each array element totalAND &= arr[i]; } return totalAND;} // Driver Code let arr = [ 4, 5, 12, 15 ]; let N = arr.length; document.write(TotalAndPair(arr, N)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 35903,
"s": 35297,
"text": null
},
{
"code": null,
"e": 35905,
"s": 35903,
"text": "4"
},
{
"code": null,
"e": 35950,
"s": 35907,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 35967,
"s": 35952,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35984,
"s": 35967,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 35994,
"s": 35984,
"text": "sanjoy_62"
},
{
"code": null,
"e": 36006,
"s": 35994,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36014,
"s": 36006,
"text": "ankthon"
},
{
"code": null,
"e": 36028,
"s": 36014,
"text": "surbhityagi15"
},
{
"code": null,
"e": 36043,
"s": 36028,
"text": "adnanirshad158"
},
{
"code": null,
"e": 36055,
"s": 36043,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 36062,
"s": 36055,
"text": "Arrays"
},
{
"code": null,
"e": 36072,
"s": 36062,
"text": "Bit Magic"
},
{
"code": null,
"e": 36085,
"s": 36072,
"text": "C++ Programs"
},
{
"code": null,
"e": 36098,
"s": 36085,
"text": "Mathematical"
},
{
"code": null,
"e": 36105,
"s": 36098,
"text": "Arrays"
},
{
"code": null,
"e": 36118,
"s": 36105,
"text": "Mathematical"
},
{
"code": null,
"e": 36128,
"s": 36118,
"text": "Bit Magic"
},
{
"code": null,
"e": 36226,
"s": 36128,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36294,
"s": 36226,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36338,
"s": 36294,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36361,
"s": 36338,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36393,
"s": 36361,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36407,
"s": 36393,
"text": "Linear Search"
},
{
"code": null,
"e": 36434,
"s": 36407,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 36480,
"s": 36434,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 36548,
"s": 36480,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 36577,
"s": 36548,
"text": "Count set bits in an integer"
}
] |
Node.js Stream writable.destroy() Method - GeeksforGeeks
|
12 Oct, 2021
The writable.destroy() method is an inbuilt application programming interface of Stream module which is used to destroy the created stream and you cannot call the write() method to write data again after you have already destroyed the created stream.
Syntax:
writable.destroy()
Parameters: This method does not accept any parameters.
Return Value: It returns all the properties of the Writable in which destroyed property is set to true.
Below examples illustrate the use of writable.cork() method in Node.js:
Example 1:
// Node.js program to demonstrate the // writable.uncork() method const stream = require('stream'); // Creating a stream and creating // a write functionconst writable = new stream.Writable({ // Write function with its // parameters write: function(chunk, encoding, next) { // Converting the chunk of // data to string console.log(chunk.toString()); next(); }}); // Writing datawritable.write('hi'); // Again writing some datawritable.write('hello'); // Calling destroy functionwritable.destroy();
Output:
hi
hello
Writable { _writableState:
WritableState {
objectMode: false, highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 2,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree:
{ next: null,
entry: null,
finish: [Function: bound onCorkedFinish] } },
writable: true,
_write: [Function: write],
domain: null,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined }
So, the created stream is destroyed.
Example 2:
// Node.js program to demonstrate the // writable.uncork() method const stream = require('stream'); // Creating a stream and creating // a write functionconst writable = new stream.Writable({ // Write function with its // parameters write: function(chunk, encoding, next) { // Converting the chunk of // data to string console.log(chunk.toString()); next(); }}); // Writing datawritable.write('hi'); // Again writing some datawritable.write('hello'); // Calling destroy functionwritable.destroy(); writable.write('');
Output:
hi
hello
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destro
yed
at doWrite (_stream_writable.js:411:19)
at writeOrBuffer (_stream_writable.js:399:5)
at Writable.write (_stream_writable.js:299:11)
at /home/runner/QuizzicalFluffyOperation/index.js:29:10
at Script.runInContext (vm.js:133:20)
at Object. (/run_dir/interp.js:156:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:
10)
at Module.load (internal/modules/cjs/loader.js:653:32)
In the above example, an error occurs because the write() method was called after the stream was destroyed.
Reference: https://nodejs.org/api/stream.html#stream_writable_destroy_error
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 38501,
"s": 38473,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 38752,
"s": 38501,
"text": "The writable.destroy() method is an inbuilt application programming interface of Stream module which is used to destroy the created stream and you cannot call the write() method to write data again after you have already destroyed the created stream."
},
{
"code": null,
"e": 38760,
"s": 38752,
"text": "Syntax:"
},
{
"code": null,
"e": 38779,
"s": 38760,
"text": "writable.destroy()"
},
{
"code": null,
"e": 38835,
"s": 38779,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 38939,
"s": 38835,
"text": "Return Value: It returns all the properties of the Writable in which destroyed property is set to true."
},
{
"code": null,
"e": 39011,
"s": 38939,
"text": "Below examples illustrate the use of writable.cork() method in Node.js:"
},
{
"code": null,
"e": 39022,
"s": 39011,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // writable.uncork() method const stream = require('stream'); // Creating a stream and creating // a write functionconst writable = new stream.Writable({ // Write function with its // parameters write: function(chunk, encoding, next) { // Converting the chunk of // data to string console.log(chunk.toString()); next(); }}); // Writing datawritable.write('hi'); // Again writing some datawritable.write('hello'); // Calling destroy functionwritable.destroy();",
"e": 39550,
"s": 39022,
"text": null
},
{
"code": null,
"e": 39558,
"s": 39550,
"text": "Output:"
},
{
"code": null,
"e": 40510,
"s": 39558,
"text": "hi\nhello\nWritable { _writableState:\n WritableState {\n objectMode: false, highWaterMark: 16384,\n finalCalled: false,\n needDrain: false,\n ending: false,\n ended: false,\n finished: false,\n destroyed: true,\n decodeStrings: true,\n defaultEncoding: 'utf8',\n length: 0,\n writing: false,\n corked: 0,\n sync: false,\n bufferProcessing: false,\n onwrite: [Function: bound onwrite],\n writecb: null,\n writelen: 0,\n bufferedRequest: null,\n lastBufferedRequest: null,\n pendingcb: 2,\n prefinished: false,\n errorEmitted: false,\n emitClose: true,\n autoDestroy: false,\n bufferedRequestCount: 0,\n corkedRequestsFree:\n { next: null,\n entry: null,\n finish: [Function: bound onCorkedFinish] } },\n writable: true,\n _write: [Function: write],\n domain: null,\n _events: [Object: null prototype] {},\n _eventsCount: 0,\n _maxListeners: undefined }\n"
},
{
"code": null,
"e": 40547,
"s": 40510,
"text": "So, the created stream is destroyed."
},
{
"code": null,
"e": 40558,
"s": 40547,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // writable.uncork() method const stream = require('stream'); // Creating a stream and creating // a write functionconst writable = new stream.Writable({ // Write function with its // parameters write: function(chunk, encoding, next) { // Converting the chunk of // data to string console.log(chunk.toString()); next(); }}); // Writing datawritable.write('hi'); // Again writing some datawritable.write('hello'); // Calling destroy functionwritable.destroy(); writable.write('');",
"e": 41107,
"s": 40558,
"text": null
},
{
"code": null,
"e": 41115,
"s": 41107,
"text": "Output:"
},
{
"code": null,
"e": 41692,
"s": 41115,
"text": "hi\nhello\nError [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destro\nyed\n at doWrite (_stream_writable.js:411:19)\n at writeOrBuffer (_stream_writable.js:399:5)\n at Writable.write (_stream_writable.js:299:11)\n at /home/runner/QuizzicalFluffyOperation/index.js:29:10\n at Script.runInContext (vm.js:133:20)\n at Object. (/run_dir/interp.js:156:20)\n at Module._compile (internal/modules/cjs/loader.js:778:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:\n10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n"
},
{
"code": null,
"e": 41800,
"s": 41692,
"text": "In the above example, an error occurs because the write() method was called after the stream was destroyed."
},
{
"code": null,
"e": 41876,
"s": 41800,
"text": "Reference: https://nodejs.org/api/stream.html#stream_writable_destroy_error"
},
{
"code": null,
"e": 41898,
"s": 41876,
"text": "Node.js-Stream-module"
},
{
"code": null,
"e": 41906,
"s": 41898,
"text": "Node.js"
},
{
"code": null,
"e": 41923,
"s": 41906,
"text": "Web Technologies"
},
{
"code": null,
"e": 42021,
"s": 41923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42069,
"s": 42021,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 42102,
"s": 42069,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 42132,
"s": 42102,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 42152,
"s": 42132,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 42206,
"s": 42152,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 42246,
"s": 42206,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42291,
"s": 42246,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42334,
"s": 42291,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 42384,
"s": 42334,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python-Quizzes | Python List Quiz | Question 4 - GeeksforGeeks
|
17 Sep, 2020
Question 4: Find the output of the following program:
def addToList(listcontainer): listcontainer += [10] mylistContainer = [10, 20, 30, 40] addToList(mylistContainer) print len(mylistContainer)
(A) 4(B) 5(C) 6(D) 10Answer: (B)Explanation: In Python, everything is a reference, and references are passed by value. Parameter passing in Python is the same as reference passing in Java. As a consequence, the function can modify the value referred by passed argument, i.e. the value of the variable in the caller’s scope can be changed. Here the task of the function “addToList” is to add an element 10 in the list, So this will increase the length of the list by 1. So the output of the program is 5.Quiz of this Question
Python-Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python Dictionary Quiz | Question 25
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Miscellaneous | Question 1
Python-Quizzes | Miscellaneous | Question 7
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Miscellaneous | Question 9
Why do people prefer Selenium with Python?
Output of Python Program - Dictionary (set 25)
Python-Quizzes | Miscellaneous | Question 10
Python-Quizzes | Miscellaneous | Question 8
|
[
{
"code": null,
"e": 25415,
"s": 25387,
"text": "\n17 Sep, 2020"
},
{
"code": null,
"e": 25469,
"s": 25415,
"text": "Question 4: Find the output of the following program:"
},
{
"code": "def addToList(listcontainer): listcontainer += [10] mylistContainer = [10, 20, 30, 40] addToList(mylistContainer) print len(mylistContainer) ",
"e": 25617,
"s": 25469,
"text": null
},
{
"code": null,
"e": 26142,
"s": 25617,
"text": "(A) 4(B) 5(C) 6(D) 10Answer: (B)Explanation: In Python, everything is a reference, and references are passed by value. Parameter passing in Python is the same as reference passing in Java. As a consequence, the function can modify the value referred by passed argument, i.e. the value of the variable in the caller’s scope can be changed. Here the task of the function “addToList” is to add an element 10 in the list, So this will increase the length of the list by 1. So the output of the program is 5.Quiz of this Question"
},
{
"code": null,
"e": 26157,
"s": 26142,
"text": "Python-Quizzes"
},
{
"code": null,
"e": 26255,
"s": 26157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26309,
"s": 26255,
"text": "Python-Quizzes | Python Dictionary Quiz | Question 25"
},
{
"code": null,
"e": 26363,
"s": 26309,
"text": "Python-Quizzes | Python Dictionary Quiz | Question 23"
},
{
"code": null,
"e": 26399,
"s": 26363,
"text": "Python | Miscellaneous | Question 1"
},
{
"code": null,
"e": 26443,
"s": 26399,
"text": "Python-Quizzes | Miscellaneous | Question 7"
},
{
"code": null,
"e": 26492,
"s": 26443,
"text": "Python | Animated Banner showing 'GeeksForGeeks'"
},
{
"code": null,
"e": 26536,
"s": 26492,
"text": "Python-Quizzes | Miscellaneous | Question 9"
},
{
"code": null,
"e": 26579,
"s": 26536,
"text": "Why do people prefer Selenium with Python?"
},
{
"code": null,
"e": 26626,
"s": 26579,
"text": "Output of Python Program - Dictionary (set 25)"
},
{
"code": null,
"e": 26671,
"s": 26626,
"text": "Python-Quizzes | Miscellaneous | Question 10"
}
] |
File delete() method in Java with Examples - GeeksforGeeks
|
28 Jan, 2019
The delete() function is a part of File class in Java . This function deletes an existing file or directory. If the file is deleted then the function returns true else returns false
Function signature:
public boolean delete()
Syntax:
boolean var = file.delete();
Parameters: This method does not accept any parameter.
Return Type: The function returns boolean data type representing whether the new file is deleted or not.
Exception: This method throws Security Exception: if the write access to the file is denied.
Below programs illustrates the use of delete() function:
Example 1: The file “F:\\program.txt” is a existing file in F: Directory.
// Java program to demonstrate// delete() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // Get the file File f = new File("F:\\program.txt"); // delete file if (f.delete()) System.out.println("File deleted"); else System.out.println("File was not deleted"); } catch (Exception e) { System.err.println(e); } }}
Output:
File deleted
Example 2: The file “F:\\program1.txt” does not exist
// Java program to demonstrate// delete() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // Get the file File f = new File("F:\\program1.txt"); // delete file if (f.delete()) System.out.println("File deleted"); else System.out.println("File was not deleted"); } catch (Exception e) { System.err.println(e); } }}
Output:
File was not deleted
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
How to Write Data into Excel Sheet using Java?
Removing last element from ArrayList in Java
Tic-Tac-Toe Game in Java
Java Program to Write an Array of Strings to the Output Console
|
[
{
"code": null,
"e": 26107,
"s": 26079,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 26289,
"s": 26107,
"text": "The delete() function is a part of File class in Java . This function deletes an existing file or directory. If the file is deleted then the function returns true else returns false"
},
{
"code": null,
"e": 26309,
"s": 26289,
"text": "Function signature:"
},
{
"code": null,
"e": 26333,
"s": 26309,
"text": "public boolean delete()"
},
{
"code": null,
"e": 26341,
"s": 26333,
"text": "Syntax:"
},
{
"code": null,
"e": 26370,
"s": 26341,
"text": "boolean var = file.delete();"
},
{
"code": null,
"e": 26425,
"s": 26370,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 26530,
"s": 26425,
"text": "Return Type: The function returns boolean data type representing whether the new file is deleted or not."
},
{
"code": null,
"e": 26623,
"s": 26530,
"text": "Exception: This method throws Security Exception: if the write access to the file is denied."
},
{
"code": null,
"e": 26680,
"s": 26623,
"text": "Below programs illustrates the use of delete() function:"
},
{
"code": null,
"e": 26754,
"s": 26680,
"text": "Example 1: The file “F:\\\\program.txt” is a existing file in F: Directory."
},
{
"code": "// Java program to demonstrate// delete() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // Get the file File f = new File(\"F:\\\\program.txt\"); // delete file if (f.delete()) System.out.println(\"File deleted\"); else System.out.println(\"File was not deleted\"); } catch (Exception e) { System.err.println(e); } }}",
"e": 27269,
"s": 26754,
"text": null
},
{
"code": null,
"e": 27277,
"s": 27269,
"text": "Output:"
},
{
"code": null,
"e": 27290,
"s": 27277,
"text": "File deleted"
},
{
"code": null,
"e": 27344,
"s": 27290,
"text": "Example 2: The file “F:\\\\program1.txt” does not exist"
},
{
"code": "// Java program to demonstrate// delete() method of File Class import java.io.*; public class solution { public static void main(String args[]) { try { // Get the file File f = new File(\"F:\\\\program1.txt\"); // delete file if (f.delete()) System.out.println(\"File deleted\"); else System.out.println(\"File was not deleted\"); } catch (Exception e) { System.err.println(e); } }}",
"e": 27860,
"s": 27344,
"text": null
},
{
"code": null,
"e": 27868,
"s": 27860,
"text": "Output:"
},
{
"code": null,
"e": 27889,
"s": 27868,
"text": "File was not deleted"
},
{
"code": null,
"e": 27996,
"s": 27889,
"text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file."
},
{
"code": null,
"e": 28012,
"s": 27996,
"text": "Java-File Class"
},
{
"code": null,
"e": 28031,
"s": 28012,
"text": "java-file-handling"
},
{
"code": null,
"e": 28046,
"s": 28031,
"text": "Java-Functions"
},
{
"code": null,
"e": 28062,
"s": 28046,
"text": "Java-IO package"
},
{
"code": null,
"e": 28076,
"s": 28062,
"text": "Java Programs"
},
{
"code": null,
"e": 28174,
"s": 28076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28222,
"s": 28174,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28273,
"s": 28222,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 28307,
"s": 28273,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 28345,
"s": 28307,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 28389,
"s": 28345,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 28432,
"s": 28389,
"text": "Java Program to Find Sum of Array Elements"
},
{
"code": null,
"e": 28479,
"s": 28432,
"text": "How to Write Data into Excel Sheet using Java?"
},
{
"code": null,
"e": 28524,
"s": 28479,
"text": "Removing last element from ArrayList in Java"
},
{
"code": null,
"e": 28549,
"s": 28524,
"text": "Tic-Tac-Toe Game in Java"
}
] |
C# | Removing the specified node from the LinkedList<T> - GeeksforGeeks
|
01 Feb, 2019
Remove(LinkedListNode<T>) method is used to remove the specified node from the LinkedList<T>.
Syntax:
public void Remove (System.Collections.Generic.LinkedListNode<T> node);
Here, node is the LinkedListNode<T> to remove from the LinkedList<T>.
Exceptions:
ArgumentNullException : If the node is null.
InvalidOperationException : If the node is not in the current LinkedList<T>.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Removing the first node from the LinkedList myList.Remove(myList.First); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Output:
Total nodes in myList are : 4
2
4
6
8
Total nodes in myList are : 3
4
6
8
Example 2:
// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("A"); myList.AddLast("B"); myList.AddLast("C"); myList.AddLast("D"); myList.AddLast("E"); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(string str in myList) { Console.WriteLine(str); } // Removing the specified node from the LinkedList myList.Remove("D"); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(string str in myList) { Console.WriteLine(str); } }}
Output:
Total nodes in myList are : 5
A
B
C
D
E
Total nodes in myList are : 4
A
B
C
E
Note: This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.remove?view=netframework-4.7.2#System_Collections_Generic_LinkedList_1_Remove_System_Collections_Generic_LinkedListNode__0__
CSharp-Generic-Namespace
CSharp-LinkedList
CSharp-LinkedList-Methods
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
HashSet in C# with Examples
|
[
{
"code": null,
"e": 25759,
"s": 25731,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25853,
"s": 25759,
"text": "Remove(LinkedListNode<T>) method is used to remove the specified node from the LinkedList<T>."
},
{
"code": null,
"e": 25861,
"s": 25853,
"text": "Syntax:"
},
{
"code": null,
"e": 25934,
"s": 25861,
"text": "public void Remove (System.Collections.Generic.LinkedListNode<T> node);\n"
},
{
"code": null,
"e": 26004,
"s": 25934,
"text": "Here, node is the LinkedListNode<T> to remove from the LinkedList<T>."
},
{
"code": null,
"e": 26016,
"s": 26004,
"text": "Exceptions:"
},
{
"code": null,
"e": 26061,
"s": 26016,
"text": "ArgumentNullException : If the node is null."
},
{
"code": null,
"e": 26138,
"s": 26061,
"text": "InvalidOperationException : If the node is not in the current LinkedList<T>."
},
{
"code": null,
"e": 26218,
"s": 26138,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 26229,
"s": 26218,
"text": "Example 1:"
},
{
"code": "// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Removing the first node from the LinkedList myList.Remove(myList.First); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 27358,
"s": 26229,
"text": null
},
{
"code": null,
"e": 27366,
"s": 27358,
"text": "Output:"
},
{
"code": null,
"e": 27441,
"s": 27366,
"text": "Total nodes in myList are : 4\n2\n4\n6\n8\nTotal nodes in myList are : 3\n4\n6\n8\n"
},
{
"code": null,
"e": 27452,
"s": 27441,
"text": "Example 2:"
},
{
"code": "// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"A\"); myList.AddLast(\"B\"); myList.AddLast(\"C\"); myList.AddLast(\"D\"); myList.AddLast(\"E\"); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(string str in myList) { Console.WriteLine(str); } // Removing the specified node from the LinkedList myList.Remove(\"D\"); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(string str in myList) { Console.WriteLine(str); } }}",
"e": 28631,
"s": 27452,
"text": null
},
{
"code": null,
"e": 28639,
"s": 28631,
"text": "Output:"
},
{
"code": null,
"e": 28718,
"s": 28639,
"text": "Total nodes in myList are : 5\nA\nB\nC\nD\nE\nTotal nodes in myList are : 4\nA\nB\nC\nE\n"
},
{
"code": null,
"e": 28758,
"s": 28718,
"text": "Note: This method is an O(1) operation."
},
{
"code": null,
"e": 28769,
"s": 28758,
"text": "Reference:"
},
{
"code": null,
"e": 28978,
"s": 28769,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.remove?view=netframework-4.7.2#System_Collections_Generic_LinkedList_1_Remove_System_Collections_Generic_LinkedListNode__0__"
},
{
"code": null,
"e": 29003,
"s": 28978,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 29021,
"s": 29003,
"text": "CSharp-LinkedList"
},
{
"code": null,
"e": 29047,
"s": 29021,
"text": "CSharp-LinkedList-Methods"
},
{
"code": null,
"e": 29050,
"s": 29047,
"text": "C#"
},
{
"code": null,
"e": 29148,
"s": 29050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29163,
"s": 29148,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29185,
"s": 29163,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29231,
"s": 29185,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29254,
"s": 29231,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29276,
"s": 29254,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 29294,
"s": 29276,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29316,
"s": 29294,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29347,
"s": 29316,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29363,
"s": 29347,
"text": "C# | Data Types"
}
] |
Writing a CSV file in Java using OpenCSV - GeeksforGeeks
|
07 Dec, 2021
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”).
OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java.
How to add OpenCSV in your Project?
For maven project, you can include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>
For Gradle Project, you can include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
compile group: 'com.opencsv', name: 'opencsv', version: '4.1'
You can Download OpenCSV Jar and include in your project class path.Writing a CSV FileWriting a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { "Name", "Class", "Marks" }; writer.writeNext(header); // add data to csv String[] data1 = { "Aman", "10", "620" }; writer.writeNext(data1); String[] data2 = { "Suraj", "10", "630" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Writing CSV File with different separatorBy default, the separator for CSV will be a comma(, ). If you want to make another character as a separator so it can be passed as an argument to CSVWriter class.Syntax :
CSVWriter(Writer writer, char separator, char quotechar,
char escapechar, String lineEnd)
Description : Constructs CSVWriter with supplied separator,
quote char, escape char and line ending.
Code:public static void writeDataForCustomSeparatorCSV(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with '|' as separator CSVWriter writer = new CSVWriter(outputfile, '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following DataName|Class|Marks
Aman|10|620
Suraj|10|630
Example:Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input.Input:
Enter no of rows
9
Enter Data
Name Class Marks
Aman 10 543
Amar 10 541
Sanjeet 10 555
Luv 10 580
Ranjeet 10 512
Rabi 10 540
Dev 10 333
Sunny 10 198
Code:// Java program to illustrate// for Writing Data in CSV fileimport java.io.*;import java.util.*;import com.opencsv.CSVWriter; public class ResultGenerator { private static final String CSV_FILE_PATH = "./result.csv"; public static void main(String[] args) { addDataToCSV(CSV_FILE_PATH); } public static void addDataToCSV(String output) { // first create file object for file placed at location // specified by filepath File file = new File(output); Scanner sc = new Scanner(System.in); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with ';' as separator CSVWriter writer = new CSVWriter(outputfile, ';', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains Data List<String[]> data = new ArrayList<String[]>(); System.out.println("Enter no of rows"); int noOfRow = Integer.parseInt(sc.nextLine()); System.out.println("Enter Data"); for (int i = 0; i < noOfRow; i++) { String row = sc.nextLine(); String[] rowdata = row.split(" "); data.add(rowdata); } writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}Output: result.csv file with following DataName;Class;Marks
Aman;10;543
Amar;10;541
Sanjeet;10;555
Luv;10;580
Ranjeet;10;512
Rabi;10;540
Dev;10;333
Sunny;10;198
In future articles, we will include more Operations on CSV file using OpenCSV.Reference:OpenCSV Documentation, CSVWriter class documentationMy Personal Notes
arrow_drop_upSave
Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { "Name", "Class", "Marks" }; writer.writeNext(header); // add data to csv String[] data1 = { "Aman", "10", "620" }; writer.writeNext(data1); String[] data2 = { "Suraj", "10", "630" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { "Name", "Class", "Marks" }; writer.writeNext(header); // add data to csv String[] data1 = { "Aman", "10", "620" }; writer.writeNext(data1); String[] data2 = { "Suraj", "10", "630" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { "Name", "Class", "Marks" }; writer.writeNext(header); // add data to csv String[] data1 = { "Aman", "10", "620" }; writer.writeNext(data1); String[] data2 = { "Suraj", "10", "630" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
Output: result.csv file with following Data
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
Output: result.csv file with following Data
"Name", "Class", "Marks"
"Aman", "10", "620"
"Suraj", "10", "630"
Syntax :
CSVWriter(Writer writer, char separator, char quotechar,
char escapechar, String lineEnd)
Description : Constructs CSVWriter with supplied separator,
quote char, escape char and line ending.
Code:
public static void writeDataForCustomSeparatorCSV(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with '|' as separator CSVWriter writer = new CSVWriter(outputfile, '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { "Name", "Class", "Marks" }); data.add(new String[] { "Aman", "10", "620" }); data.add(new String[] { "Suraj", "10", "630" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
Output: result.csv file with following Data
Name|Class|Marks
Aman|10|620
Suraj|10|630
Example:Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input.
Input:
Enter no of rows
9
Enter Data
Name Class Marks
Aman 10 543
Amar 10 541
Sanjeet 10 555
Luv 10 580
Ranjeet 10 512
Rabi 10 540
Dev 10 333
Sunny 10 198
Code:
// Java program to illustrate// for Writing Data in CSV fileimport java.io.*;import java.util.*;import com.opencsv.CSVWriter; public class ResultGenerator { private static final String CSV_FILE_PATH = "./result.csv"; public static void main(String[] args) { addDataToCSV(CSV_FILE_PATH); } public static void addDataToCSV(String output) { // first create file object for file placed at location // specified by filepath File file = new File(output); Scanner sc = new Scanner(System.in); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with ';' as separator CSVWriter writer = new CSVWriter(outputfile, ';', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains Data List<String[]> data = new ArrayList<String[]>(); System.out.println("Enter no of rows"); int noOfRow = Integer.parseInt(sc.nextLine()); System.out.println("Enter Data"); for (int i = 0; i < noOfRow; i++) { String row = sc.nextLine(); String[] rowdata = row.split(" "); data.add(rowdata); } writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
Output: result.csv file with following Data
Name;Class;Marks
Aman;10;543
Amar;10;541
Sanjeet;10;555
Luv;10;580
Ranjeet;10;512
Rabi;10;540
Dev;10;333
Sunny;10;198
In future articles, we will include more Operations on CSV file using OpenCSV.Reference:OpenCSV Documentation, CSVWriter class documentation
adnanirshad158
CSV
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 25831,
"s": 25803,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 25998,
"s": 25831,
"text": "A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”)."
},
{
"code": null,
"e": 26315,
"s": 25998,
"text": "OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java language does not provide any native support for effectively handling CSV files so we are using OpenCSV for handling CSV files in Java."
},
{
"code": null,
"e": 26351,
"s": 26315,
"text": "How to add OpenCSV in your Project?"
},
{
"code": null,
"e": 26553,
"s": 26351,
"text": "For maven project, you can include the OpenCSV maven dependency in pom.xml file.<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>"
},
{
"code": "<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.1</version></dependency>",
"e": 26675,
"s": 26553,
"text": null
},
{
"code": null,
"e": 26796,
"s": 26675,
"text": "For Gradle Project, you can include the OpenCSV dependency.compile group: 'com.opencsv', name: 'opencsv', version: '4.1'"
},
{
"code": null,
"e": 26858,
"s": 26796,
"text": "compile group: 'com.opencsv', name: 'opencsv', version: '4.1'"
},
{
"code": null,
"e": 33584,
"s": 26858,
"text": "You can Download OpenCSV Jar and include in your project class path.Writing a CSV FileWriting a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { \"Name\", \"Class\", \"Marks\" }; writer.writeNext(header); // add data to csv String[] data1 = { \"Aman\", \"10\", \"620\" }; writer.writeNext(data1); String[] data2 = { \"Suraj\", \"10\", \"630\" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\nWrite all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\nWriting CSV File with different separatorBy default, the separator for CSV will be a comma(, ). If you want to make another character as a separator so it can be passed as an argument to CSVWriter class.Syntax :\nCSVWriter(Writer writer, char separator, char quotechar,\n char escapechar, String lineEnd)\nDescription : Constructs CSVWriter with supplied separator,\nquote char, escape char and line ending.\nCode:public static void writeDataForCustomSeparatorCSV(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with '|' as separator CSVWriter writer = new CSVWriter(outputfile, '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following DataName|Class|Marks\nAman|10|620\nSuraj|10|630\nExample:Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input.Input:\nEnter no of rows\n9\nEnter Data\nName Class Marks\nAman 10 543\nAmar 10 541\nSanjeet 10 555\nLuv 10 580\nRanjeet 10 512\nRabi 10 540\nDev 10 333\nSunny 10 198\nCode:// Java program to illustrate// for Writing Data in CSV fileimport java.io.*;import java.util.*;import com.opencsv.CSVWriter; public class ResultGenerator { private static final String CSV_FILE_PATH = \"./result.csv\"; public static void main(String[] args) { addDataToCSV(CSV_FILE_PATH); } public static void addDataToCSV(String output) { // first create file object for file placed at location // specified by filepath File file = new File(output); Scanner sc = new Scanner(System.in); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with ';' as separator CSVWriter writer = new CSVWriter(outputfile, ';', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains Data List<String[]> data = new ArrayList<String[]>(); System.out.println(\"Enter no of rows\"); int noOfRow = Integer.parseInt(sc.nextLine()); System.out.println(\"Enter Data\"); for (int i = 0; i < noOfRow; i++) { String row = sc.nextLine(); String[] rowdata = row.split(\" \"); data.add(rowdata); } writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}Output: result.csv file with following DataName;Class;Marks\nAman;10;543\nAmar;10;541\nSanjeet;10;555\nLuv;10;580\nRanjeet;10;512\nRabi;10;540\nDev;10;333\nSunny;10;198\n\nIn future articles, we will include more Operations on CSV file using OpenCSV.Reference:OpenCSV Documentation, CSVWriter class documentationMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 36255,
"s": 33584,
"text": "Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { \"Name\", \"Class\", \"Marks\" }; writer.writeNext(header); // add data to csv String[] data1 = { \"Aman\", \"10\", \"620\" }; writer.writeNext(data1); String[] data2 = { \"Suraj\", \"10\", \"630\" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\nWrite all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\n"
},
{
"code": null,
"e": 37438,
"s": 36255,
"text": "Write Data Line by line – CSVWriter can write line by line using writeNext() method where a string array is passed with each comma-separated element as a separate entry.CODE:public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { \"Name\", \"Class\", \"Marks\" }; writer.writeNext(header); // add data to csv String[] data1 = { \"Aman\", \"10\", \"620\" }; writer.writeNext(data1); String[] data2 = { \"Suraj\", \"10\", \"630\" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\n"
},
{
"code": "public static void writeDataLineByLine(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // adding header to csv String[] header = { \"Name\", \"Class\", \"Marks\" }; writer.writeNext(header); // add data to csv String[] data1 = { \"Aman\", \"10\", \"620\" }; writer.writeNext(data1); String[] data2 = { \"Suraj\", \"10\", \"630\" }; writer.writeNext(data2); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}",
"e": 38338,
"s": 37438,
"text": null
},
{
"code": null,
"e": 38382,
"s": 38338,
"text": "Output: result.csv file with following Data"
},
{
"code": null,
"e": 38449,
"s": 38382,
"text": "\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\n"
},
{
"code": null,
"e": 39649,
"s": 38449,
"text": "Write all Data at once- For witting data at once call writeAll() method of CSVWriter class and pass A List of String[] as the parameter with each String[] representing a line of the file.CODE:public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Output: result.csv file with following Data\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\n"
},
{
"code": "public static void writeDataAtOnce(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter object filewriter object as parameter CSVWriter writer = new CSVWriter(outputfile); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}",
"e": 40548,
"s": 39649,
"text": null
},
{
"code": null,
"e": 40592,
"s": 40548,
"text": "Output: result.csv file with following Data"
},
{
"code": null,
"e": 40659,
"s": 40592,
"text": "\"Name\", \"Class\", \"Marks\"\n\"Aman\", \"10\", \"620\"\n\"Suraj\", \"10\", \"630\"\n"
},
{
"code": null,
"e": 40890,
"s": 40659,
"text": "Syntax :\nCSVWriter(Writer writer, char separator, char quotechar,\n char escapechar, String lineEnd)\nDescription : Constructs CSVWriter with supplied separator,\nquote char, escape char and line ending.\n"
},
{
"code": null,
"e": 40896,
"s": 40890,
"text": "Code:"
},
{
"code": "public static void writeDataForCustomSeparatorCSV(String filePath){ // first create file object for file placed at location // specified by filepath File file = new File(filePath); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with '|' as separator CSVWriter writer = new CSVWriter(outputfile, '|', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains String array List<String[]> data = new ArrayList<String[]>(); data.add(new String[] { \"Name\", \"Class\", \"Marks\" }); data.add(new String[] { \"Aman\", \"10\", \"620\" }); data.add(new String[] { \"Suraj\", \"10\", \"630\" }); writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}",
"e": 42013,
"s": 40896,
"text": null
},
{
"code": null,
"e": 42057,
"s": 42013,
"text": "Output: result.csv file with following Data"
},
{
"code": null,
"e": 42100,
"s": 42057,
"text": "Name|Class|Marks\nAman|10|620\nSuraj|10|630\n"
},
{
"code": null,
"e": 42222,
"s": 42100,
"text": "Example:Let’s create java program which generate a semi-colon separated csv file and contains the data provided as input."
},
{
"code": null,
"e": 42378,
"s": 42222,
"text": "Input:\nEnter no of rows\n9\nEnter Data\nName Class Marks\nAman 10 543\nAmar 10 541\nSanjeet 10 555\nLuv 10 580\nRanjeet 10 512\nRabi 10 540\nDev 10 333\nSunny 10 198\n"
},
{
"code": null,
"e": 42384,
"s": 42378,
"text": "Code:"
},
{
"code": "// Java program to illustrate// for Writing Data in CSV fileimport java.io.*;import java.util.*;import com.opencsv.CSVWriter; public class ResultGenerator { private static final String CSV_FILE_PATH = \"./result.csv\"; public static void main(String[] args) { addDataToCSV(CSV_FILE_PATH); } public static void addDataToCSV(String output) { // first create file object for file placed at location // specified by filepath File file = new File(output); Scanner sc = new Scanner(System.in); try { // create FileWriter object with file as parameter FileWriter outputfile = new FileWriter(file); // create CSVWriter with ';' as separator CSVWriter writer = new CSVWriter(outputfile, ';', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); // create a List which contains Data List<String[]> data = new ArrayList<String[]>(); System.out.println(\"Enter no of rows\"); int noOfRow = Integer.parseInt(sc.nextLine()); System.out.println(\"Enter Data\"); for (int i = 0; i < noOfRow; i++) { String row = sc.nextLine(); String[] rowdata = row.split(\" \"); data.add(rowdata); } writer.writeAll(data); // closing writer connection writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}",
"e": 44097,
"s": 42384,
"text": null
},
{
"code": null,
"e": 44141,
"s": 44097,
"text": "Output: result.csv file with following Data"
},
{
"code": null,
"e": 44261,
"s": 44141,
"text": "Name;Class;Marks\nAman;10;543\nAmar;10;541\nSanjeet;10;555\nLuv;10;580\nRanjeet;10;512\nRabi;10;540\nDev;10;333\nSunny;10;198\n\n"
},
{
"code": null,
"e": 44402,
"s": 44261,
"text": "In future articles, we will include more Operations on CSV file using OpenCSV.Reference:OpenCSV Documentation, CSVWriter class documentation"
},
{
"code": null,
"e": 44417,
"s": 44402,
"text": "adnanirshad158"
},
{
"code": null,
"e": 44421,
"s": 44417,
"text": "CSV"
},
{
"code": null,
"e": 44426,
"s": 44421,
"text": "Java"
},
{
"code": null,
"e": 44431,
"s": 44426,
"text": "Java"
},
{
"code": null,
"e": 44529,
"s": 44431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44580,
"s": 44529,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 44610,
"s": 44580,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 44625,
"s": 44610,
"text": "Stream In Java"
},
{
"code": null,
"e": 44644,
"s": 44625,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 44675,
"s": 44644,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 44693,
"s": 44675,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 44725,
"s": 44693,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 44745,
"s": 44725,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 44769,
"s": 44745,
"text": "Singleton Class in Java"
}
] |
Inorder predecessor and successor for a given key in BST - GeeksforGeeks
|
18 Mar, 2022
I recently encountered with a question in an interview at e-commerce company. The interviewer asked the following question:There is BST given with root node with key part as integer only. The structure of each node is as follows:
C++
Java
Python3
C#
Javascript
struct Node{ int key; struct Node *left, *right ;};
static class Node{ int key; Node left, right ;}; // This code is contributed by gauravrajput1
class Node: def __init__(self, key): self.key = key self.left = None self.right = None # This code is contributed by harshitkap00r
public class Node{ public int key; public Node left, right ;}; // This code is contributed by gauravrajput1
<script> class Node { constructor() { this.key = 0; this.left = null; this.right = null; } } </script>
You need to find the inorder successor and predecessor of a given key. In case the given key is not found in BST, then return the two values within which this key will lie.
Following is the algorithm to reach the desired result. Its a recursive method:
Input: root node, key
output: predecessor node, successor node
1. If root is NULL
then return
2. if key is found then
a. If its left subtree is not null
Then predecessor will be the right most
child of left subtree or left child itself.
b. If its right subtree is not null
The successor will be the left most child
of right subtree or right child itself.
return
3. If key is smaller then root node
set the successor as root
search recursively into left subtree
else
set the predecessor as root
search recursively into right subtree
Following is the implementation of the above algorithm:
C++
Java
Python
C#
Javascript
// C++ program to find predecessor and successor in a BST#include <iostream>using namespace std; // BST Nodestruct Node{ int key; struct Node *left, *right;}; // This function finds predecessor and successor of key in BST.// It sets pre and suc as predecessor and successor respectivelyvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key){ // Base case if (root == NULL) return ; // If key is present at root if (root->key == key) { // the maximum value in left subtree is predecessor if (root->left != NULL) { Node* tmp = root->left; while (tmp->right) tmp = tmp->right; pre = tmp ; } // the minimum value in right subtree is successor if (root->right != NULL) { Node* tmp = root->right ; while (tmp->left) tmp = tmp->left ; suc = tmp ; } return ; } // If key is smaller than root's key, go to left subtree if (root->key > key) { suc = root ; findPreSuc(root->left, pre, suc, key) ; } else // go to right subtree { pre = root ; findPreSuc(root->right, pre, suc, key) ; }} // A utility function to create a new BST nodeNode *newNode(int item){ Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node;} // Driver program to test above functionint main(){ int key = 65; //Key to be searched in BST /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node* pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << "Predecessor is " << pre->key << endl; else cout << "No Predecessor"; if (suc != NULL) cout << "Successor is " << suc->key; else cout << "No Successor"; return 0;}
// Java program to find predecessor// and successor in a BSTclass GFG{ // BST Nodestatic class Node{ int key; Node left, right; public Node() {} public Node(int key) { this.key = key; this.left = this.right = null; }}; static Node pre = new Node(), suc = new Node(); // This function finds predecessor and// successor of key in BST. It sets pre// and suc as predecessor and successor// respectivelystatic void findPreSuc(Node root, int key){ // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { Node tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { Node tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); }} // A utility function to insert a// new node with given key in BSTstatic Node insert(Node node, int key){ if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node;} // Driver codepublic static void main(String[] args){ // Key to be searched in BST int key = 65; /* * Let us create following BST * 50 * / \ * 30 70 * / \ / \ * 20 40 60 80 */ Node root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) System.out.println("Predecessor is " + pre.key); else System.out.println("No Predecessor"); if (suc != null) System.out.println("Successor is " + suc.key); else System.out.println("No Successor");}} // This code is contributed by sanjeev2552
# Python program to find predecessor and successor in a BST # A BST nodeclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function finds predecessor and successor of key in BST# It sets pre and suc as predecessor and successor respectivelydef findPreSuc(root, key): # Base Case if root is None: return # If key is present at root if root.key == key: # the maximum value in left subtree is predecessor if root.left is not None: tmp = root.left while(tmp.right): tmp = tmp.right findPreSuc.pre = tmp # the minimum value in right subtree is successor if root.right is not None: tmp = root.right while(temp.left): tmp = tmp.left findPreSuc.suc = tmp return # If key is smaller than root's key, go to left subtree if root.key > key : findPreSuc.suc = root findPreSuc(root.left, key) else: # go to right subtree findPreSuc.pre = root findPreSuc(root.right, key) # A utility function to insert a new node in with given key in BSTdef insert(node , key): if node is None: return Node(key) if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) return node # Driver program to test above functionkey = 65 #Key to be searched in BST """ Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80"""root = Noneroot = insert(root, 50)insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80); # Static variables of the function findPreSucfindPreSuc.pre = NonefindPreSuc.suc = None findPreSuc(root, key) if findPreSuc.pre is not None: print "Predecessor is", findPreSuc.pre.key else: print "No Predecessor" if findPreSuc.suc is not None: print "Successor is", findPreSuc.suc.keyelse: print "No Successor" # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to find predecessor// and successor in a BSTusing System;public class GFG{ // BST Node public class Node { public int key; public Node left, right; public Node() {} public Node(int key) { this.key = key; this.left = this.right = null; } }; static Node pre = new Node(), suc = new Node(); // This function finds predecessor and // successor of key in BST. It sets pre // and suc as predecessor and successor // respectively static void findPreSuc(Node root, int key) { // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { Node tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { Node tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); } } // A utility function to insert a // new node with given key in BST static Node insert(Node node, int key) { if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node; } // Driver code public static void Main(String[] args) { // Key to be searched in BST int key = 65; /* * Let us create following BST * 50 * / \ * 30 70 * / \ / \ * 20 40 60 80 */ Node root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) Console.WriteLine("Predecessor is " + pre.key); else Console.WriteLine("No Predecessor"); if (suc != null) Console.WriteLine("Successor is " + suc.key); else Console.WriteLine("No Successor"); }} // This code is contributed by aashish1995
<script> // JavaScript program to find predecessor// and successor in a BST// BST Node class Node{ constructor(key) { this.key = key; this.left = this.right = null; }} var pre = new Node(), suc = new Node(); // This function finds predecessor and// successor of key in BST. It sets pre// and suc as predecessor and successor// respectivelyfunction findPreSuc(root , key){ // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { var tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { var tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); }} // A utility function to insert a// new node with given key in BSTfunction insert(node , key){ if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node;} // Driver code // Key to be searched in BST var key = 65; /* * Let us create following BST * 50 * / \ * 30 70 * / \ / \ * 20 40 60 80 */ var root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) document.write("Predecessor is " + pre.key); else document.write("No Predecessor"); if (suc != null) document.write("<br/>Successor is " + suc.key); else document.write("<br/>No Successor"); // This code contributed by gauravrajput1 </script>
Output:
Predecessor is 60
Successor is 70
Complexity Analysis:
Time Complexity: O(h), where h is the height of the tree. In the worst case as explained above we travel the whole height of the tree.Auxiliary Space: O(h)
Another Approach : We can also find the inorder successor and inorder predecessor using inorder traversal . Check if the current node is smaller than the given key for predecessor and for successor, check if it is greater than the given key. If it is greater than the given key then, check if it is smaller than the already stored value in successor then, update it. At last, get the predecessor and successor stored in q(successor) and p(predecessor).
C++
Java
Python3
C#
Javascript
// CPP code for inorder successor// and predecessor of tree#include<iostream>#include<stdlib.h> using namespace std; struct Node{ int data; Node* left,*right;}; // Function to return dataNode* getnode(int info){ Node* p = (Node*)malloc(sizeof(Node)); p->data = info; p->right = NULL; p->left = NULL; return p;} /*since inorder traversal results inascending order visit to node , wecan store the values of the largestno which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal*/void find_p_s(Node* root,int a, Node** p, Node** q){ // If root is null return if(!root) return ; // traverse the left subtree find_p_s(root->left, a, p, q); // root data is greater than a if(root&&root->data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((!*q) || (*q) && (*q)->data > root->data) *q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root && root->data < a) { *p = root; } // traverse the right subtree find_p_s(root->right, a, p, q);} // Driver codeint main(){ Node* root1 = getnode(50); root1->left = getnode(20); root1->right = getnode(60); root1->left->left = getnode(10); root1->left->right = getnode(30); root1->right->left = getnode(55); root1->right->right = getnode(70); Node* p = NULL, *q = NULL; find_p_s(root1, 55, &p, &q); if(p) cout << p->data; if(q) cout << " " << q->data; return 0;}
// JAVA code for inorder successor// and predecessor of tree import java.util.*; class GFG{ static class Node{ int data; Node left,right;}; // Function to return datastatic Node getnode(int info){ Node p = new Node(); p.data = info; p.right = null; p.left = null; return p;} /*since inorder traversal results inascending order visit to node , wecan store the values of the largestno which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal*/static Node p,q;static void find_p_s(Node root,int a){ // If root is null return if(root == null) return ; // traverse the left subtree find_p_s(root.left, a); // root data is greater than a if(root != null && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((q == null) || (q != null) && q.data > root.data) q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root != null && root.data < a) { p = root; } // traverse the right subtree find_p_s(root.right, a);} // Driver codepublic static void main(String[] args){ Node root1 = getnode(50); root1.left = getnode(20); root1.right = getnode(60); root1.left.left = getnode(10); root1.left.right = getnode(30); root1.right.left = getnode(55); root1.right.right = getnode(70); p = null; q = null; find_p_s(root1, 55); if(p != null) System.out.print(p.data); if(q != null) System.out.print(" " + q.data);}} // This code is contributed by Rajput-Ji
""" Python3 code for inorder successorand predecessor of tree """ # A Binary Tree Node# Utility function to create a new tree nodeclass getnode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None """since inorder traversal results inascendingorder visit to node , wecan store the values of the largesto which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal"""def find_p_s(root, a, p, q): # If root is None return if(not root): return # traverse the left subtree find_p_s(root.left, a, p, q) # root data is greater than a if(root and root.data > a): # q stores the node whose data is greater # than a and is smaller than the previously # stored data in *q which is successor if((not q[0]) or q[0] and q[0].data > root.data): q[0] = root # if the root data is smaller than # store it in p which is predecessor elif(root and root.data < a): p[0]= root # traverse the right subtree find_p_s(root.right, a, p, q) # Driver Codeif __name__ == '__main__': root1 = getnode(50) root1.left = getnode(20) root1.right = getnode(60) root1.left.left = getnode(10) root1.left.right = getnode(30) root1.right.left = getnode(55) root1.right.right = getnode(70) p = [None] q = [None] find_p_s(root1, 55, p, q) if(p[0]) : print(p[0].data, end = "") if(q[0]) : print("", q[0].data) # This code is contributed by# SHUBHAMSINGH10
// C# code for inorder successor// and predecessor of treeusing System; public class GFG { public class Node { public int data; public Node left, right; }; // Function to return data static Node getnode(int info) { Node p = new Node(); p.data = info; p.right = null; p.left = null; return p; } /* * since inorder traversal results in ascending order visit to node , we can * store the values of the largest no which is smaller than a (predecessor) and * smallest no which is large than a (successor) using inorder traversal */ static Node p, q; static void find_p_s(Node root, int a) { // If root is null return if (root == null) return; // traverse the left subtree find_p_s(root.left, a); // root data is greater than a if (root != null && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if ((q == null) || (q != null) && q.data > root.data) q = root; } // if the root data is smaller than // store it in p which is predecessor else if (root != null && root.data < a) { p = root; } // traverse the right subtree find_p_s(root.right, a); } // Driver code public static void Main(String[] args) { Node root1 = getnode(50); root1.left = getnode(20); root1.right = getnode(60); root1.left.left = getnode(10); root1.left.right = getnode(30); root1.right.left = getnode(55); root1.right.right = getnode(70); p = null; q = null; find_p_s(root1, 55); if (p != null) Console.Write(p.data); if (q != null) Console.Write(" " + q.data); }} // This code is contributed by Rajput-Ji
<script> class Node{ constructor(data) { this.data = data; this.left = this.right = null; }} function find_p_s(root, a, p, q){ // If root is None return if(root == null) return // traverse the left subtree find_p_s(root.left, a, p, q) // root data is greater than a if(root && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((q[0] == null) || q[0] != null && q[0].data > root.data) q[0] = root } // if the root data is smaller than // store it in p which is predecessor else if(root && root.data < a) { p[0] = root } // traverse the right subtree find_p_s(root.right, a, p, q)} // Driver Codelet root1 = new Node(50)root1.left = new Node(20)root1.right = new Node(60)root1.left.left = new Node(10)root1.left.right = new Node(30)root1.right.left = new Node(55)root1.right.right = new Node(70)p = [null]q = [null] find_p_s(root1, 55, p, q) if(p[0] != null) document.write(p[0].data, end = " ")if(q[0] != null) document.write(" ", q[0].data) // This code is contributed by patel2127</script>
Output :
50 60
Complexity Analysis:
Time Complexity: O(n), where n is the total number of nodes in the tree. In the worst case as explained above we travel the whole tree.Auxiliary Space: O(n).Thanks Shweta for suggesting this method.
YouTubeGeeksforGeeks507K subscribersInorder predecessor and successor for a given key in BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1FSDhZRZ7bw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
This article is contributed by algoLover. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHUBHAMSINGH10
sanjeev2552
aashish1995
GauravRajput1
surinderdawra388
itwasme
patel2127
harshitkap00r
Rajput-Ji
kapilag
Ola Cabs
Binary Search Tree
Tree
Ola Cabs
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorted Array to Balanced BST
Red-Black Tree | Set 2 (Insert)
Optimal Binary Search Tree | DP-24
Inorder Successor in Binary Search Tree
Find the node with minimum value in a Binary Search Tree
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 26397,
"s": 26369,
"text": "\n18 Mar, 2022"
},
{
"code": null,
"e": 26627,
"s": 26397,
"text": "I recently encountered with a question in an interview at e-commerce company. The interviewer asked the following question:There is BST given with root node with key part as integer only. The structure of each node is as follows:"
},
{
"code": null,
"e": 26631,
"s": 26627,
"text": "C++"
},
{
"code": null,
"e": 26636,
"s": 26631,
"text": "Java"
},
{
"code": null,
"e": 26644,
"s": 26636,
"text": "Python3"
},
{
"code": null,
"e": 26647,
"s": 26644,
"text": "C#"
},
{
"code": null,
"e": 26658,
"s": 26647,
"text": "Javascript"
},
{
"code": "struct Node{ int key; struct Node *left, *right ;};",
"e": 26716,
"s": 26658,
"text": null
},
{
"code": "static class Node{ int key; Node left, right ;}; // This code is contributed by gauravrajput1",
"e": 26816,
"s": 26716,
"text": null
},
{
"code": "class Node: def __init__(self, key): self.key = key self.left = None self.right = None # This code is contributed by harshitkap00r",
"e": 26981,
"s": 26816,
"text": null
},
{
"code": "public class Node{ public int key; public Node left, right ;}; // This code is contributed by gauravrajput1",
"e": 27095,
"s": 26981,
"text": null
},
{
"code": "<script> class Node { constructor() { this.key = 0; this.left = null; this.right = null; } } </script>",
"e": 27257,
"s": 27095,
"text": null
},
{
"code": null,
"e": 27430,
"s": 27257,
"text": "You need to find the inorder successor and predecessor of a given key. In case the given key is not found in BST, then return the two values within which this key will lie."
},
{
"code": null,
"e": 27511,
"s": 27430,
"text": "Following is the algorithm to reach the desired result. Its a recursive method: "
},
{
"code": null,
"e": 28132,
"s": 27511,
"text": "Input: root node, key\noutput: predecessor node, successor node\n\n1. If root is NULL\n then return\n2. if key is found then\n a. If its left subtree is not null\n Then predecessor will be the right most \n child of left subtree or left child itself.\n b. If its right subtree is not null\n The successor will be the left most child \n of right subtree or right child itself.\n return\n3. If key is smaller then root node\n set the successor as root\n search recursively into left subtree\n else\n set the predecessor as root\n search recursively into right subtree"
},
{
"code": null,
"e": 28189,
"s": 28132,
"text": "Following is the implementation of the above algorithm: "
},
{
"code": null,
"e": 28193,
"s": 28189,
"text": "C++"
},
{
"code": null,
"e": 28198,
"s": 28193,
"text": "Java"
},
{
"code": null,
"e": 28205,
"s": 28198,
"text": "Python"
},
{
"code": null,
"e": 28208,
"s": 28205,
"text": "C#"
},
{
"code": null,
"e": 28219,
"s": 28208,
"text": "Javascript"
},
{
"code": "// C++ program to find predecessor and successor in a BST#include <iostream>using namespace std; // BST Nodestruct Node{ int key; struct Node *left, *right;}; // This function finds predecessor and successor of key in BST.// It sets pre and suc as predecessor and successor respectivelyvoid findPreSuc(Node* root, Node*& pre, Node*& suc, int key){ // Base case if (root == NULL) return ; // If key is present at root if (root->key == key) { // the maximum value in left subtree is predecessor if (root->left != NULL) { Node* tmp = root->left; while (tmp->right) tmp = tmp->right; pre = tmp ; } // the minimum value in right subtree is successor if (root->right != NULL) { Node* tmp = root->right ; while (tmp->left) tmp = tmp->left ; suc = tmp ; } return ; } // If key is smaller than root's key, go to left subtree if (root->key > key) { suc = root ; findPreSuc(root->left, pre, suc, key) ; } else // go to right subtree { pre = root ; findPreSuc(root->right, pre, suc, key) ; }} // A utility function to create a new BST nodeNode *newNode(int item){ Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node;} // Driver program to test above functionint main(){ int key = 65; //Key to be searched in BST /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node* pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << \"Predecessor is \" << pre->key << endl; else cout << \"No Predecessor\"; if (suc != NULL) cout << \"Successor is \" << suc->key; else cout << \"No Successor\"; return 0;}",
"e": 30603,
"s": 28219,
"text": null
},
{
"code": "// Java program to find predecessor// and successor in a BSTclass GFG{ // BST Nodestatic class Node{ int key; Node left, right; public Node() {} public Node(int key) { this.key = key; this.left = this.right = null; }}; static Node pre = new Node(), suc = new Node(); // This function finds predecessor and// successor of key in BST. It sets pre// and suc as predecessor and successor// respectivelystatic void findPreSuc(Node root, int key){ // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { Node tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { Node tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); }} // A utility function to insert a// new node with given key in BSTstatic Node insert(Node node, int key){ if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node;} // Driver codepublic static void main(String[] args){ // Key to be searched in BST int key = 65; /* * Let us create following BST * 50 * / \\ * 30 70 * / \\ / \\ * 20 40 60 80 */ Node root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) System.out.println(\"Predecessor is \" + pre.key); else System.out.println(\"No Predecessor\"); if (suc != null) System.out.println(\"Successor is \" + suc.key); else System.out.println(\"No Successor\");}} // This code is contributed by sanjeev2552",
"e": 33088,
"s": 30603,
"text": null
},
{
"code": "# Python program to find predecessor and successor in a BST # A BST nodeclass Node: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # This function finds predecessor and successor of key in BST# It sets pre and suc as predecessor and successor respectivelydef findPreSuc(root, key): # Base Case if root is None: return # If key is present at root if root.key == key: # the maximum value in left subtree is predecessor if root.left is not None: tmp = root.left while(tmp.right): tmp = tmp.right findPreSuc.pre = tmp # the minimum value in right subtree is successor if root.right is not None: tmp = root.right while(temp.left): tmp = tmp.left findPreSuc.suc = tmp return # If key is smaller than root's key, go to left subtree if root.key > key : findPreSuc.suc = root findPreSuc(root.left, key) else: # go to right subtree findPreSuc.pre = root findPreSuc(root.right, key) # A utility function to insert a new node in with given key in BSTdef insert(node , key): if node is None: return Node(key) if key < node.key: node.left = insert(node.left, key) else: node.right = insert(node.right, key) return node # Driver program to test above functionkey = 65 #Key to be searched in BST \"\"\" Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80\"\"\"root = Noneroot = insert(root, 50)insert(root, 30);insert(root, 20);insert(root, 40);insert(root, 70);insert(root, 60);insert(root, 80); # Static variables of the function findPreSucfindPreSuc.pre = NonefindPreSuc.suc = None findPreSuc(root, key) if findPreSuc.pre is not None: print \"Predecessor is\", findPreSuc.pre.key else: print \"No Predecessor\" if findPreSuc.suc is not None: print \"Successor is\", findPreSuc.suc.keyelse: print \"No Successor\" # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 35248,
"s": 33088,
"text": null
},
{
"code": "// C# program to find predecessor// and successor in a BSTusing System;public class GFG{ // BST Node public class Node { public int key; public Node left, right; public Node() {} public Node(int key) { this.key = key; this.left = this.right = null; } }; static Node pre = new Node(), suc = new Node(); // This function finds predecessor and // successor of key in BST. It sets pre // and suc as predecessor and successor // respectively static void findPreSuc(Node root, int key) { // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { Node tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { Node tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); } } // A utility function to insert a // new node with given key in BST static Node insert(Node node, int key) { if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node; } // Driver code public static void Main(String[] args) { // Key to be searched in BST int key = 65; /* * Let us create following BST * 50 * / \\ * 30 70 * / \\ / \\ * 20 40 60 80 */ Node root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) Console.WriteLine(\"Predecessor is \" + pre.key); else Console.WriteLine(\"No Predecessor\"); if (suc != null) Console.WriteLine(\"Successor is \" + suc.key); else Console.WriteLine(\"No Successor\"); }} // This code is contributed by aashish1995",
"e": 37684,
"s": 35248,
"text": null
},
{
"code": "<script> // JavaScript program to find predecessor// and successor in a BST// BST Node class Node{ constructor(key) { this.key = key; this.left = this.right = null; }} var pre = new Node(), suc = new Node(); // This function finds predecessor and// successor of key in BST. It sets pre// and suc as predecessor and successor// respectivelyfunction findPreSuc(root , key){ // Base case if (root == null) return; // If key is present at root if (root.key == key) { // The maximum value in left // subtree is predecessor if (root.left != null) { var tmp = root.left; while (tmp.right != null) tmp = tmp.right; pre = tmp; } // The minimum value in // right subtree is successor if (root.right != null) { var tmp = root.right; while (tmp.left != null) tmp = tmp.left; suc = tmp; } return; } // If key is smaller than // root's key, go to left subtree if (root.key > key) { suc = root; findPreSuc(root.left, key); } // Go to right subtree else { pre = root; findPreSuc(root.right, key); }} // A utility function to insert a// new node with given key in BSTfunction insert(node , key){ if (node == null) return new Node(key); if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); return node;} // Driver code // Key to be searched in BST var key = 65; /* * Let us create following BST * 50 * / \\ * 30 70 * / \\ / \\ * 20 40 60 80 */ var root = new Node(); root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); findPreSuc(root, key); if (pre != null) document.write(\"Predecessor is \" + pre.key); else document.write(\"No Predecessor\"); if (suc != null) document.write(\"<br/>Successor is \" + suc.key); else document.write(\"<br/>No Successor\"); // This code contributed by gauravrajput1 </script>",
"e": 40032,
"s": 37684,
"text": null
},
{
"code": null,
"e": 40041,
"s": 40032,
"text": "Output: "
},
{
"code": null,
"e": 40075,
"s": 40041,
"text": "Predecessor is 60\nSuccessor is 70"
},
{
"code": null,
"e": 40096,
"s": 40075,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 40252,
"s": 40096,
"text": "Time Complexity: O(h), where h is the height of the tree. In the worst case as explained above we travel the whole height of the tree.Auxiliary Space: O(h)"
},
{
"code": null,
"e": 40706,
"s": 40252,
"text": "Another Approach : We can also find the inorder successor and inorder predecessor using inorder traversal . Check if the current node is smaller than the given key for predecessor and for successor, check if it is greater than the given key. If it is greater than the given key then, check if it is smaller than the already stored value in successor then, update it. At last, get the predecessor and successor stored in q(successor) and p(predecessor). "
},
{
"code": null,
"e": 40710,
"s": 40706,
"text": "C++"
},
{
"code": null,
"e": 40715,
"s": 40710,
"text": "Java"
},
{
"code": null,
"e": 40723,
"s": 40715,
"text": "Python3"
},
{
"code": null,
"e": 40726,
"s": 40723,
"text": "C#"
},
{
"code": null,
"e": 40737,
"s": 40726,
"text": "Javascript"
},
{
"code": "// CPP code for inorder successor// and predecessor of tree#include<iostream>#include<stdlib.h> using namespace std; struct Node{ int data; Node* left,*right;}; // Function to return dataNode* getnode(int info){ Node* p = (Node*)malloc(sizeof(Node)); p->data = info; p->right = NULL; p->left = NULL; return p;} /*since inorder traversal results inascending order visit to node , wecan store the values of the largestno which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal*/void find_p_s(Node* root,int a, Node** p, Node** q){ // If root is null return if(!root) return ; // traverse the left subtree find_p_s(root->left, a, p, q); // root data is greater than a if(root&&root->data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((!*q) || (*q) && (*q)->data > root->data) *q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root && root->data < a) { *p = root; } // traverse the right subtree find_p_s(root->right, a, p, q);} // Driver codeint main(){ Node* root1 = getnode(50); root1->left = getnode(20); root1->right = getnode(60); root1->left->left = getnode(10); root1->left->right = getnode(30); root1->right->left = getnode(55); root1->right->right = getnode(70); Node* p = NULL, *q = NULL; find_p_s(root1, 55, &p, &q); if(p) cout << p->data; if(q) cout << \" \" << q->data; return 0;}",
"e": 42447,
"s": 40737,
"text": null
},
{
"code": "// JAVA code for inorder successor// and predecessor of tree import java.util.*; class GFG{ static class Node{ int data; Node left,right;}; // Function to return datastatic Node getnode(int info){ Node p = new Node(); p.data = info; p.right = null; p.left = null; return p;} /*since inorder traversal results inascending order visit to node , wecan store the values of the largestno which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal*/static Node p,q;static void find_p_s(Node root,int a){ // If root is null return if(root == null) return ; // traverse the left subtree find_p_s(root.left, a); // root data is greater than a if(root != null && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((q == null) || (q != null) && q.data > root.data) q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root != null && root.data < a) { p = root; } // traverse the right subtree find_p_s(root.right, a);} // Driver codepublic static void main(String[] args){ Node root1 = getnode(50); root1.left = getnode(20); root1.right = getnode(60); root1.left.left = getnode(10); root1.left.right = getnode(30); root1.right.left = getnode(55); root1.right.right = getnode(70); p = null; q = null; find_p_s(root1, 55); if(p != null) System.out.print(p.data); if(q != null) System.out.print(\" \" + q.data);}} // This code is contributed by Rajput-Ji",
"e": 44195,
"s": 42447,
"text": null
},
{
"code": "\"\"\" Python3 code for inorder successorand predecessor of tree \"\"\" # A Binary Tree Node# Utility function to create a new tree nodeclass getnode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None \"\"\"since inorder traversal results inascendingorder visit to node , wecan store the values of the largesto which is smaller than a (predecessor)and smallest no which is large thana (successor) using inorder traversal\"\"\"def find_p_s(root, a, p, q): # If root is None return if(not root): return # traverse the left subtree find_p_s(root.left, a, p, q) # root data is greater than a if(root and root.data > a): # q stores the node whose data is greater # than a and is smaller than the previously # stored data in *q which is successor if((not q[0]) or q[0] and q[0].data > root.data): q[0] = root # if the root data is smaller than # store it in p which is predecessor elif(root and root.data < a): p[0]= root # traverse the right subtree find_p_s(root.right, a, p, q) # Driver Codeif __name__ == '__main__': root1 = getnode(50) root1.left = getnode(20) root1.right = getnode(60) root1.left.left = getnode(10) root1.left.right = getnode(30) root1.right.left = getnode(55) root1.right.right = getnode(70) p = [None] q = [None] find_p_s(root1, 55, p, q) if(p[0]) : print(p[0].data, end = \"\") if(q[0]) : print(\"\", q[0].data) # This code is contributed by# SHUBHAMSINGH10",
"e": 45856,
"s": 44195,
"text": null
},
{
"code": "// C# code for inorder successor// and predecessor of treeusing System; public class GFG { public class Node { public int data; public Node left, right; }; // Function to return data static Node getnode(int info) { Node p = new Node(); p.data = info; p.right = null; p.left = null; return p; } /* * since inorder traversal results in ascending order visit to node , we can * store the values of the largest no which is smaller than a (predecessor) and * smallest no which is large than a (successor) using inorder traversal */ static Node p, q; static void find_p_s(Node root, int a) { // If root is null return if (root == null) return; // traverse the left subtree find_p_s(root.left, a); // root data is greater than a if (root != null && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if ((q == null) || (q != null) && q.data > root.data) q = root; } // if the root data is smaller than // store it in p which is predecessor else if (root != null && root.data < a) { p = root; } // traverse the right subtree find_p_s(root.right, a); } // Driver code public static void Main(String[] args) { Node root1 = getnode(50); root1.left = getnode(20); root1.right = getnode(60); root1.left.left = getnode(10); root1.left.right = getnode(30); root1.right.left = getnode(55); root1.right.right = getnode(70); p = null; q = null; find_p_s(root1, 55); if (p != null) Console.Write(p.data); if (q != null) Console.Write(\" \" + q.data); }} // This code is contributed by Rajput-Ji",
"e": 47613,
"s": 45856,
"text": null
},
{
"code": "<script> class Node{ constructor(data) { this.data = data; this.left = this.right = null; }} function find_p_s(root, a, p, q){ // If root is None return if(root == null) return // traverse the left subtree find_p_s(root.left, a, p, q) // root data is greater than a if(root && root.data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((q[0] == null) || q[0] != null && q[0].data > root.data) q[0] = root } // if the root data is smaller than // store it in p which is predecessor else if(root && root.data < a) { p[0] = root } // traverse the right subtree find_p_s(root.right, a, p, q)} // Driver Codelet root1 = new Node(50)root1.left = new Node(20)root1.right = new Node(60)root1.left.left = new Node(10)root1.left.right = new Node(30)root1.right.left = new Node(55)root1.right.right = new Node(70)p = [null]q = [null] find_p_s(root1, 55, p, q) if(p[0] != null) document.write(p[0].data, end = \" \")if(q[0] != null) document.write(\" \", q[0].data) // This code is contributed by patel2127</script>",
"e": 48892,
"s": 47613,
"text": null
},
{
"code": null,
"e": 48903,
"s": 48892,
"text": "Output : "
},
{
"code": null,
"e": 48909,
"s": 48903,
"text": "50 60"
},
{
"code": null,
"e": 48930,
"s": 48909,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 49129,
"s": 48930,
"text": "Time Complexity: O(n), where n is the total number of nodes in the tree. In the worst case as explained above we travel the whole tree.Auxiliary Space: O(n).Thanks Shweta for suggesting this method."
},
{
"code": null,
"e": 49984,
"s": 49129,
"text": "YouTubeGeeksforGeeks507K subscribersInorder predecessor and successor for a given key in BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=1FSDhZRZ7bw\" 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": 50026,
"s": 49984,
"text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk "
},
{
"code": null,
"e": 50194,
"s": 50026,
"text": "This article is contributed by algoLover. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 50211,
"s": 50196,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 50223,
"s": 50211,
"text": "sanjeev2552"
},
{
"code": null,
"e": 50235,
"s": 50223,
"text": "aashish1995"
},
{
"code": null,
"e": 50249,
"s": 50235,
"text": "GauravRajput1"
},
{
"code": null,
"e": 50266,
"s": 50249,
"text": "surinderdawra388"
},
{
"code": null,
"e": 50274,
"s": 50266,
"text": "itwasme"
},
{
"code": null,
"e": 50284,
"s": 50274,
"text": "patel2127"
},
{
"code": null,
"e": 50298,
"s": 50284,
"text": "harshitkap00r"
},
{
"code": null,
"e": 50308,
"s": 50298,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 50316,
"s": 50308,
"text": "kapilag"
},
{
"code": null,
"e": 50325,
"s": 50316,
"text": "Ola Cabs"
},
{
"code": null,
"e": 50344,
"s": 50325,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 50349,
"s": 50344,
"text": "Tree"
},
{
"code": null,
"e": 50358,
"s": 50349,
"text": "Ola Cabs"
},
{
"code": null,
"e": 50377,
"s": 50358,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 50382,
"s": 50377,
"text": "Tree"
},
{
"code": null,
"e": 50480,
"s": 50382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 50509,
"s": 50480,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 50541,
"s": 50509,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 50576,
"s": 50541,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 50616,
"s": 50576,
"text": "Inorder Successor in Binary Search Tree"
},
{
"code": null,
"e": 50673,
"s": 50616,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 50723,
"s": 50673,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 50758,
"s": 50723,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 50792,
"s": 50758,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 50835,
"s": 50792,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
How to Take Input From User Separated By Space in Java ? - GeeksforGeeks
|
15 Sep, 2021
There are 2 methods to take input from the user which are separated by space which are as follows:
Using BufferedReader Class and then splitting and parsing each valueUsing nextInt( ) method of Scanner class
Using BufferedReader Class and then splitting and parsing each value
Using nextInt( ) method of Scanner class
Let us discuss both the methods one by one in order to get a better understanding by implementing the same clean java programs.
Method 1:
Using BufferedReader Class and then splitting and parsing each value.
Procedure:
Using readline() method of BufferedReader and Scan the whole string.Split this String for str.split(” “)Iterate over the above array and parse each integer value using Integer.parseInt( ).
Using readline() method of BufferedReader and Scan the whole string.
Split this String for str.split(” “)
Iterate over the above array and parse each integer value using Integer.parseInt( ).
Example
Java
// Java Program to Take Input from User Separated by Space// Using BufferedReader class // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; // Main class// BufferedReaderTestclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating an object of BufferedReader class BufferedReader bi = new BufferedReader( new InputStreamReader(System.in)); // Custom integer array of size 10 int num[] = new int[10]; // Array of string type to store input String[] strNums; // Display message System.out.println("enter string of numbers"); // Reading input a string strNums = bi.readLine().split(" "); for (int i = 0; i < strNums.length; i++) { num[i] = Integer.parseInt(strNums[i]); } // Display message System.out.println("printing stored numbers "); // Printing the stored numbers using for loop for (int i = 0; i < strNums.length; i++) { System.out.println(num[i]); } }}
Output:
FIG = OUTPUT OF METHOD 1
Method 2: Using nextInt() method of Scanner class.
Procedure:
Using the nextInt() method of Scanner class and scan to scan the input.Using for loop to store input in an array.Iterate through the above array and parse each integer using sc.nextInt()
Using the nextInt() method of Scanner class and scan to scan the input.
Using for loop to store input in an array.
Iterate through the above array and parse each integer using sc.nextInt()
Example
Java
// Java Program to Take Input from User Separated by Space// Using Scanner class // Importing required classesimport java.io.IOException;import java.util.Scanner; // Main class// Scanner classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Display message for better readability System.out.println("enter input "); // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Declaring and initializing an array of size 10 int[] nums = new int[10]; int i; // Loop to store input values in nums array for (i = 0; i < nums.length; i++) { nums[i] = sc.nextInt(); } // Display message System.out.println("printing stored values"); // Printing stored values for (i = 0; i < nums.length; i++) { System.out.println(nums[i] + " "); } }}
Output:
FIG = OUTPUT OF METHOD 2
Note: The first method using Bufferedreader class and then splitting and parsing each value is much faster than using nixing() method of Scanner class. It is nearly 2 times faster than the second one. Bel;ow we do provide in order how to calculate the time consume by both methods by using nanotime method
// Initializing variables
long startTime, endTime;
// Start time
startTime = System.nanoTime(); {
// Insert code here
// Method 1 or method 2 code
}
// End time
endTime = System.nanoTime();
arorakashish0911
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
|
[
{
"code": null,
"e": 25250,
"s": 25222,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 25349,
"s": 25250,
"text": "There are 2 methods to take input from the user which are separated by space which are as follows:"
},
{
"code": null,
"e": 25458,
"s": 25349,
"text": "Using BufferedReader Class and then splitting and parsing each valueUsing nextInt( ) method of Scanner class"
},
{
"code": null,
"e": 25527,
"s": 25458,
"text": "Using BufferedReader Class and then splitting and parsing each value"
},
{
"code": null,
"e": 25568,
"s": 25527,
"text": "Using nextInt( ) method of Scanner class"
},
{
"code": null,
"e": 25697,
"s": 25568,
"text": "Let us discuss both the methods one by one in order to get a better understanding by implementing the same clean java programs. "
},
{
"code": null,
"e": 25708,
"s": 25697,
"text": "Method 1: "
},
{
"code": null,
"e": 25778,
"s": 25708,
"text": "Using BufferedReader Class and then splitting and parsing each value."
},
{
"code": null,
"e": 25789,
"s": 25778,
"text": "Procedure:"
},
{
"code": null,
"e": 25978,
"s": 25789,
"text": "Using readline() method of BufferedReader and Scan the whole string.Split this String for str.split(” “)Iterate over the above array and parse each integer value using Integer.parseInt( )."
},
{
"code": null,
"e": 26047,
"s": 25978,
"text": "Using readline() method of BufferedReader and Scan the whole string."
},
{
"code": null,
"e": 26084,
"s": 26047,
"text": "Split this String for str.split(” “)"
},
{
"code": null,
"e": 26169,
"s": 26084,
"text": "Iterate over the above array and parse each integer value using Integer.parseInt( )."
},
{
"code": null,
"e": 26178,
"s": 26169,
"text": "Example "
},
{
"code": null,
"e": 26183,
"s": 26178,
"text": "Java"
},
{
"code": "// Java Program to Take Input from User Separated by Space// Using BufferedReader class // Importing required classesimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; // Main class// BufferedReaderTestclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating an object of BufferedReader class BufferedReader bi = new BufferedReader( new InputStreamReader(System.in)); // Custom integer array of size 10 int num[] = new int[10]; // Array of string type to store input String[] strNums; // Display message System.out.println(\"enter string of numbers\"); // Reading input a string strNums = bi.readLine().split(\" \"); for (int i = 0; i < strNums.length; i++) { num[i] = Integer.parseInt(strNums[i]); } // Display message System.out.println(\"printing stored numbers \"); // Printing the stored numbers using for loop for (int i = 0; i < strNums.length; i++) { System.out.println(num[i]); } }}",
"e": 27337,
"s": 26183,
"text": null
},
{
"code": null,
"e": 27345,
"s": 27337,
"text": "Output:"
},
{
"code": null,
"e": 27371,
"s": 27345,
"text": "FIG = OUTPUT OF METHOD 1 "
},
{
"code": null,
"e": 27422,
"s": 27371,
"text": "Method 2: Using nextInt() method of Scanner class."
},
{
"code": null,
"e": 27434,
"s": 27422,
"text": "Procedure: "
},
{
"code": null,
"e": 27621,
"s": 27434,
"text": "Using the nextInt() method of Scanner class and scan to scan the input.Using for loop to store input in an array.Iterate through the above array and parse each integer using sc.nextInt()"
},
{
"code": null,
"e": 27693,
"s": 27621,
"text": "Using the nextInt() method of Scanner class and scan to scan the input."
},
{
"code": null,
"e": 27736,
"s": 27693,
"text": "Using for loop to store input in an array."
},
{
"code": null,
"e": 27810,
"s": 27736,
"text": "Iterate through the above array and parse each integer using sc.nextInt()"
},
{
"code": null,
"e": 27819,
"s": 27810,
"text": "Example "
},
{
"code": null,
"e": 27824,
"s": 27819,
"text": "Java"
},
{
"code": "// Java Program to Take Input from User Separated by Space// Using Scanner class // Importing required classesimport java.io.IOException;import java.util.Scanner; // Main class// Scanner classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Display message for better readability System.out.println(\"enter input \"); // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Declaring and initializing an array of size 10 int[] nums = new int[10]; int i; // Loop to store input values in nums array for (i = 0; i < nums.length; i++) { nums[i] = sc.nextInt(); } // Display message System.out.println(\"printing stored values\"); // Printing stored values for (i = 0; i < nums.length; i++) { System.out.println(nums[i] + \" \"); } }}",
"e": 28774,
"s": 27824,
"text": null
},
{
"code": null,
"e": 28782,
"s": 28774,
"text": "Output:"
},
{
"code": null,
"e": 28807,
"s": 28782,
"text": "FIG = OUTPUT OF METHOD 2"
},
{
"code": null,
"e": 29115,
"s": 28807,
"text": "Note: The first method using Bufferedreader class and then splitting and parsing each value is much faster than using nixing() method of Scanner class. It is nearly 2 times faster than the second one. Bel;ow we do provide in order how to calculate the time consume by both methods by using nanotime method "
},
{
"code": null,
"e": 29308,
"s": 29115,
"text": "// Initializing variables\nlong startTime, endTime;\n\n// Start time\nstartTime = System.nanoTime(); {\n\n// Insert code here\n// Method 1 or method 2 code\n}\n\n// End time\nendTime = System.nanoTime();"
},
{
"code": null,
"e": 29327,
"s": 29310,
"text": "arorakashish0911"
},
{
"code": null,
"e": 29332,
"s": 29327,
"text": "Java"
},
{
"code": null,
"e": 29346,
"s": 29332,
"text": "Java Programs"
},
{
"code": null,
"e": 29351,
"s": 29346,
"text": "Java"
},
{
"code": null,
"e": 29449,
"s": 29351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29464,
"s": 29449,
"text": "Stream In Java"
},
{
"code": null,
"e": 29485,
"s": 29464,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29504,
"s": 29485,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29534,
"s": 29504,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29551,
"s": 29534,
"text": "Generics in Java"
},
{
"code": null,
"e": 29577,
"s": 29551,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29611,
"s": 29577,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29658,
"s": 29611,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29690,
"s": 29658,
"text": "How to Iterate HashMap in Java?"
}
] |
Compute nCr % p | Set 2 (Lucas Theorem) - GeeksforGeeks
|
22 Mar, 2021
Given three numbers n, r and p, compute value of nCr mod p.Examples:
Input: n = 10, r = 2, p = 13
Output: 6
Explanation: 10C2 is 45 and 45 % 13 is 6.
Input: n = 1000, r = 900, p = 13
Output: 8
We strongly recommend to refer below post as a prerequisite of this.Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)We have introduced overflow problem and discussed Dynamic Programming based solution in above set 1. The time complexity of the DP based solution is O(n*r) and it required O(n) space. The time taken and extra space become very high for large values of n, especially values close to 109.In this post, Lucas Theorem based solution is discussed. Time complexity of this solution is O(p2 * Logp n) and it requires only O(p) space.Lucas Theorem: For non negative integers n and r and a prime p, the following congruence relation holds: where and Using Lucas Theorem for nCr % p: Lucas theorem basically suggests that the value of nCr can be computed by multiplying results of niCri where ni and ri are individual same-positioned digits in base p representations of n and r respectively..The idea is to one by one compute niCri for individual digits ni and ri in base p. We can compute these values DP based solution discussed in previous post. Since these digits are in base p, we would never need more than O(p) space and time complexity of these individual computations would be bounded by O(p2).Below is implementation of above idea
C++
Java
Python3
C#
PHP
Javascript
// A Lucas Theorem based solution to compute nCr % p#include<bits/stdc++.h>using namespace std; // Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.int nCrModpDP(int n, int r, int p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r+1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsint nCrModpLucas(int n, int r, int p){ // Base case if (r==0) return 1; // Compute last digits of n and r in base p int ni = n%p, ri = r%p; // Compute result for last digits computed above, and // for remaining digits. Multiply the two results and // compute the result of multiplication in modulo p. return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programint main(){ int n = 1000, r = 900, p = 13; cout << "Value of nCr % p is " << nCrModpLucas(n, r, p); return 0;}
// A Lucas Theorem based solution to compute nCr % p class GFG{// Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.static int nCrModpDP(int n, int r, int p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int[] C=new int[r+1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r==0) return 1; // Compute last digits of n and r in base pint ni = n%p;int ri = r%p; // Compute result for last digits computed above, and// for remaining digits. Multiply the two results and// compute the result of multiplication in modulo p.return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programpublic static void main(String[] args){ int n = 1000, r = 900, p = 13; System.out.println("Value of nCr % p is "+nCrModpLucas(n, r, p));}}// This code is contributed by mits
# A Lucas Theorem based solution# to compute nCr % p # Returns nCr % p. In this Lucas# Theorem based program, this# function is only called for# n < p and r < p.def nCrModpDP(n, r, p): # The array C is going to store # last row of pascal triangle # at the end. And last entry # of last row is nCr C = [0] * (n + 1); # Top row of Pascal Triangle C[0] = 1; # One by constructs remaining # rows of Pascal Triangle from # top to bottom for i in range(1, (n + 1)): # Fill entries of current # row using previous row # values j = min(i, r); while(j > 0): C[j] = (C[j] + C[j - 1]) % p; j -= 1; return C[r]; # Lucas Theorem based function that # returns nCr % p. This function# works like decimal to binary# conversion recursive function.# First we compute last digits of# n and r in base p, then recur# for remaining digitsdef nCrModpLucas(n, r, p): # Base case if (r == 0): return 1; # Compute last digits of n # and r in base p ni = int(n % p); ri = int(r % p); # Compute result for last digits # computed above, and for remaining # digits. Multiply the two results # and compute the result of # multiplication in modulo p. # Last digits of n and r return (nCrModpLucas(int(n / p), int(r / p), p) * nCrModpDP(ni, ri, p)) % p; # Remaining digits # Driver Coden = 1000;r = 900;p = 13;print("Value of nCr % p is", nCrModpLucas(n, r, p)); # This code is contributed by mits
// A Lucas Theorem based solution// to compute nCr % pusing System; class GFG{// Returns nCr % p. In this Lucas// Theorem based program, this// function is only called for// n < p and r < p.static int nCrModpDP(int n, int r, int p){ // The array C is going to store // last row of pascal triangle // at the end. And last entry // of last row is nCr int[] C = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining // rows of Pascal Triangle // from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row // using previous row values for (int j = Math.Min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Lucas Theorem based function that// returns nCr % p. This function works// like decimal to binary conversion// recursive function. First we compute// last digits of n and r in base p,// then recur for remaining digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r == 0) return 1; // Compute last digits of n// and r in base pint ni = n % p;int ri = r % p; // Compute result for last digits// computed above, and for remaining// digits. Multiply the two results// and compute the result of// multiplication in modulo p.return (nCrModpLucas(n / p, r / p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver Codepublic static void Main(){ int n = 1000, r = 900, p = 13; Console.Write("Value of nCr % p is " + nCrModpLucas(n, r, p));}} // This code is contributed// by ChitraNayal
<?php// A Lucas Theorem based// solution to compute// nCr % p // Returns nCr % p. In this// Lucas Theorem based program,// this function is only called// for n < p and r < p.function nCrModpDP($n, $r, $p){ // The array C is going to // store last row of pascal // triangle at the end. And // last entry of last row is nCr $C = array_fill(0, $n + 1, false); // Top row of // Pascal Triangle $C[0] = 1; // One by constructs remaining // rows of Pascal Triangle from // top to bottom for ($i = 1; $i <= $n; $i++) { // Fill entries of current // row using previous row // values for ($j = min($i, $r); $j > 0; $j--) $C[$j] = ($C[$j] + $C[$j - 1]) % $p; } return $C[$r];} // Lucas Theorem based function// that returns nCr % p. This// function works like decimal// to binary conversion recursive// function. First we compute last// digits of n and r in base p,// then recur for remaining digitsfunction nCrModpLucas($n, $r, $p){ // Base caseif ($r == 0) return 1; // Compute last digits// of n and r in base p$ni = $n % $p;$ri = $r % $p; // Compute result for last// digits computed above,// and for remaining digits.// Multiply the two results// and compute the result of// multiplication in modulo p.return (nCrModpLucas($n / $p, $r / $p, $p) * // Last digits of n and r nCrModpDP($ni, $ri, $p)) % $p; // Remaining digits} // Driver Code$n = 1000; $r = 900; $p = 13;echo "Value of nCr % p is " , nCrModpLucas($n, $r, $p); // This code is contributed by ajit?>
<script> // A Lucas Theorem based solution to compute nCr % p // Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.function nCrModpDP(n, r, p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr C = Array(r+1).fill(0); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (var i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (var j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsfunction nCrModpLucas(n, r, p){// Base caseif (r==0) return 1; // Compute last digits of n and r in base pvar ni = n%p, ri = r%p; // Compute result for last digits computed above, and// for remaining digits. Multiply the two results and// compute the result of multiplication in modulo p.return (nCrModpLucas(parseInt(n/p), parseInt(r/p), p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programvar n = 1000, r = 900, p = 13;document.write("Value of nCr % p is " + nCrModpLucas(n, r, p)); </script>
Output:
Value of nCr % p is 8
Time Complexity: Time complexity of this solution is O(p2 * Logp n). There are O(Logp n) digits in base p representation of n. Each of these digits is smaller than p, therefore, computations for individual digits take O(p2). Note that these computations are done using DP method which takes O(n*r) time.Alternate Implementation with O(p2 + Logp n) time and O(p2) space: The idea is to precompute Pascal triangle for size p x p and store it in 2D array. All values needed would now take O(1) time. Therefore overall time complexity becomes O(p2 + Logp n).This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
Mithun Kumar
ukasp
rutvik_56
large-numbers
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 25939,
"s": 25911,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 26010,
"s": 25939,
"text": "Given three numbers n, r and p, compute value of nCr mod p.Examples: "
},
{
"code": null,
"e": 26137,
"s": 26010,
"text": "Input: n = 10, r = 2, p = 13\nOutput: 6\nExplanation: 10C2 is 45 and 45 % 13 is 6.\n\nInput: n = 1000, r = 900, p = 13\nOutput: 8"
},
{
"code": null,
"e": 27408,
"s": 26137,
"text": "We strongly recommend to refer below post as a prerequisite of this.Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)We have introduced overflow problem and discussed Dynamic Programming based solution in above set 1. The time complexity of the DP based solution is O(n*r) and it required O(n) space. The time taken and extra space become very high for large values of n, especially values close to 109.In this post, Lucas Theorem based solution is discussed. Time complexity of this solution is O(p2 * Logp n) and it requires only O(p) space.Lucas Theorem: For non negative integers n and r and a prime p, the following congruence relation holds: where and Using Lucas Theorem for nCr % p: Lucas theorem basically suggests that the value of nCr can be computed by multiplying results of niCri where ni and ri are individual same-positioned digits in base p representations of n and r respectively..The idea is to one by one compute niCri for individual digits ni and ri in base p. We can compute these values DP based solution discussed in previous post. Since these digits are in base p, we would never need more than O(p) space and time complexity of these individual computations would be bounded by O(p2).Below is implementation of above idea "
},
{
"code": null,
"e": 27412,
"s": 27408,
"text": "C++"
},
{
"code": null,
"e": 27417,
"s": 27412,
"text": "Java"
},
{
"code": null,
"e": 27425,
"s": 27417,
"text": "Python3"
},
{
"code": null,
"e": 27428,
"s": 27425,
"text": "C#"
},
{
"code": null,
"e": 27432,
"s": 27428,
"text": "PHP"
},
{
"code": null,
"e": 27443,
"s": 27432,
"text": "Javascript"
},
{
"code": "// A Lucas Theorem based solution to compute nCr % p#include<bits/stdc++.h>using namespace std; // Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.int nCrModpDP(int n, int r, int p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int C[r+1]; memset(C, 0, sizeof(C)); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsint nCrModpLucas(int n, int r, int p){ // Base case if (r==0) return 1; // Compute last digits of n and r in base p int ni = n%p, ri = r%p; // Compute result for last digits computed above, and // for remaining digits. Multiply the two results and // compute the result of multiplication in modulo p. return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programint main(){ int n = 1000, r = 900, p = 13; cout << \"Value of nCr % p is \" << nCrModpLucas(n, r, p); return 0;}",
"e": 29033,
"s": 27443,
"text": null
},
{
"code": "// A Lucas Theorem based solution to compute nCr % p class GFG{// Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.static int nCrModpDP(int n, int r, int p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr int[] C=new int[r+1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (int j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r==0) return 1; // Compute last digits of n and r in base pint ni = n%p;int ri = r%p; // Compute result for last digits computed above, and// for remaining digits. Multiply the two results and// compute the result of multiplication in modulo p.return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programpublic static void main(String[] args){ int n = 1000, r = 900, p = 13; System.out.println(\"Value of nCr % p is \"+nCrModpLucas(n, r, p));}}// This code is contributed by mits",
"e": 30621,
"s": 29033,
"text": null
},
{
"code": "# A Lucas Theorem based solution# to compute nCr % p # Returns nCr % p. In this Lucas# Theorem based program, this# function is only called for# n < p and r < p.def nCrModpDP(n, r, p): # The array C is going to store # last row of pascal triangle # at the end. And last entry # of last row is nCr C = [0] * (n + 1); # Top row of Pascal Triangle C[0] = 1; # One by constructs remaining # rows of Pascal Triangle from # top to bottom for i in range(1, (n + 1)): # Fill entries of current # row using previous row # values j = min(i, r); while(j > 0): C[j] = (C[j] + C[j - 1]) % p; j -= 1; return C[r]; # Lucas Theorem based function that # returns nCr % p. This function# works like decimal to binary# conversion recursive function.# First we compute last digits of# n and r in base p, then recur# for remaining digitsdef nCrModpLucas(n, r, p): # Base case if (r == 0): return 1; # Compute last digits of n # and r in base p ni = int(n % p); ri = int(r % p); # Compute result for last digits # computed above, and for remaining # digits. Multiply the two results # and compute the result of # multiplication in modulo p. # Last digits of n and r return (nCrModpLucas(int(n / p), int(r / p), p) * nCrModpDP(ni, ri, p)) % p; # Remaining digits # Driver Coden = 1000;r = 900;p = 13;print(\"Value of nCr % p is\", nCrModpLucas(n, r, p)); # This code is contributed by mits",
"e": 32181,
"s": 30621,
"text": null
},
{
"code": "// A Lucas Theorem based solution// to compute nCr % pusing System; class GFG{// Returns nCr % p. In this Lucas// Theorem based program, this// function is only called for// n < p and r < p.static int nCrModpDP(int n, int r, int p){ // The array C is going to store // last row of pascal triangle // at the end. And last entry // of last row is nCr int[] C = new int[r + 1]; C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining // rows of Pascal Triangle // from top to bottom for (int i = 1; i <= n; i++) { // Fill entries of current row // using previous row values for (int j = Math.Min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j - 1]) % p; } return C[r];} // Lucas Theorem based function that// returns nCr % p. This function works// like decimal to binary conversion// recursive function. First we compute// last digits of n and r in base p,// then recur for remaining digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r == 0) return 1; // Compute last digits of n// and r in base pint ni = n % p;int ri = r % p; // Compute result for last digits// computed above, and for remaining// digits. Multiply the two results// and compute the result of// multiplication in modulo p.return (nCrModpLucas(n / p, r / p, p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver Codepublic static void Main(){ int n = 1000, r = 900, p = 13; Console.Write(\"Value of nCr % p is \" + nCrModpLucas(n, r, p));}} // This code is contributed// by ChitraNayal",
"e": 33838,
"s": 32181,
"text": null
},
{
"code": "<?php// A Lucas Theorem based// solution to compute// nCr % p // Returns nCr % p. In this// Lucas Theorem based program,// this function is only called// for n < p and r < p.function nCrModpDP($n, $r, $p){ // The array C is going to // store last row of pascal // triangle at the end. And // last entry of last row is nCr $C = array_fill(0, $n + 1, false); // Top row of // Pascal Triangle $C[0] = 1; // One by constructs remaining // rows of Pascal Triangle from // top to bottom for ($i = 1; $i <= $n; $i++) { // Fill entries of current // row using previous row // values for ($j = min($i, $r); $j > 0; $j--) $C[$j] = ($C[$j] + $C[$j - 1]) % $p; } return $C[$r];} // Lucas Theorem based function// that returns nCr % p. This// function works like decimal// to binary conversion recursive// function. First we compute last// digits of n and r in base p,// then recur for remaining digitsfunction nCrModpLucas($n, $r, $p){ // Base caseif ($r == 0) return 1; // Compute last digits// of n and r in base p$ni = $n % $p;$ri = $r % $p; // Compute result for last// digits computed above,// and for remaining digits.// Multiply the two results// and compute the result of// multiplication in modulo p.return (nCrModpLucas($n / $p, $r / $p, $p) * // Last digits of n and r nCrModpDP($ni, $ri, $p)) % $p; // Remaining digits} // Driver Code$n = 1000; $r = 900; $p = 13;echo \"Value of nCr % p is \" , nCrModpLucas($n, $r, $p); // This code is contributed by ajit?>",
"e": 35474,
"s": 33838,
"text": null
},
{
"code": "<script> // A Lucas Theorem based solution to compute nCr % p // Returns nCr % p. In this Lucas Theorem based program,// this function is only called for n < p and r < p.function nCrModpDP(n, r, p){ // The array C is going to store last row of // pascal triangle at the end. And last entry // of last row is nCr C = Array(r+1).fill(0); C[0] = 1; // Top row of Pascal Triangle // One by constructs remaining rows of Pascal // Triangle from top to bottom for (var i = 1; i <= n; i++) { // Fill entries of current row using previous // row values for (var j = Math.min(i, r); j > 0; j--) // nCj = (n-1)Cj + (n-1)C(j-1); C[j] = (C[j] + C[j-1])%p; } return C[r];} // Lucas Theorem based function that returns nCr % p// This function works like decimal to binary conversion// recursive function. First we compute last digits of// n and r in base p, then recur for remaining digitsfunction nCrModpLucas(n, r, p){// Base caseif (r==0) return 1; // Compute last digits of n and r in base pvar ni = n%p, ri = r%p; // Compute result for last digits computed above, and// for remaining digits. Multiply the two results and// compute the result of multiplication in modulo p.return (nCrModpLucas(parseInt(n/p), parseInt(r/p), p) * // Last digits of n and r nCrModpDP(ni, ri, p)) % p; // Remaining digits} // Driver programvar n = 1000, r = 900, p = 13;document.write(\"Value of nCr % p is \" + nCrModpLucas(n, r, p)); </script>",
"e": 36982,
"s": 35474,
"text": null
},
{
"code": null,
"e": 36991,
"s": 36982,
"text": "Output: "
},
{
"code": null,
"e": 37013,
"s": 36991,
"text": "Value of nCr % p is 8"
},
{
"code": null,
"e": 37736,
"s": 37013,
"text": "Time Complexity: Time complexity of this solution is O(p2 * Logp n). There are O(Logp n) digits in base p representation of n. Each of these digits is smaller than p, therefore, computations for individual digits take O(p2). Note that these computations are done using DP method which takes O(n*r) time.Alternate Implementation with O(p2 + Logp n) time and O(p2) space: The idea is to precompute Pascal triangle for size p x p and store it in 2D array. All values needed would now take O(1) time. Therefore overall time complexity becomes O(p2 + Logp n).This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 37742,
"s": 37736,
"text": "jit_t"
},
{
"code": null,
"e": 37755,
"s": 37742,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 37761,
"s": 37755,
"text": "ukasp"
},
{
"code": null,
"e": 37771,
"s": 37761,
"text": "rutvik_56"
},
{
"code": null,
"e": 37785,
"s": 37771,
"text": "large-numbers"
},
{
"code": null,
"e": 37804,
"s": 37785,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37817,
"s": 37804,
"text": "Mathematical"
},
{
"code": null,
"e": 37830,
"s": 37817,
"text": "Mathematical"
},
{
"code": null,
"e": 37849,
"s": 37830,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37947,
"s": 37849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37971,
"s": 37947,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 38014,
"s": 37971,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 38028,
"s": 38014,
"text": "Prime Numbers"
},
{
"code": null,
"e": 38070,
"s": 38028,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 38092,
"s": 38070,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 38165,
"s": 38092,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 38186,
"s": 38165,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 38229,
"s": 38186,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 38263,
"s": 38229,
"text": "Program for factorial of a number"
}
] |
How to Merge Two Pandas DataFrames on Index? - GeeksforGeeks
|
13 Jan, 2022
In this article, we will discuss how to merge two Pandas Dataframes on Index.
This method is used to join the dataframe based on index.
Syntax:
dataframe1.join(dataframe2)
Example:
Python3
# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframesprint(data1.join(data2))
Output:
This will merge the two dataframes with matching indexes
Syntax:
pandas.merge(dataframe1, dataframe2, left_index=True, right_index=True)
where,
dataframe1 is the first dataframe
dataframe2 is the second dataframe
left_index specifies the first dataframe index set to be true
right_index specifies the second dataframe index set to be true
Example:
Python3
# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with mergeprint(pd.merge(data1, data2, left_index=True, right_index=True))
Output:
We can concatenate two dataframes by using concat() method by setting axis=1.
Syntax:
pandas.concat([daatframe1,dataframe2], axis=1)
Example:
Python3
# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with concatprint(pd.concat([data1, data2], axis=1))
Output:
adnanirshad158
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 25615,
"s": 25537,
"text": "In this article, we will discuss how to merge two Pandas Dataframes on Index."
},
{
"code": null,
"e": 25673,
"s": 25615,
"text": "This method is used to join the dataframe based on index."
},
{
"code": null,
"e": 25681,
"s": 25673,
"text": "Syntax:"
},
{
"code": null,
"e": 25709,
"s": 25681,
"text": "dataframe1.join(dataframe2)"
},
{
"code": null,
"e": 25718,
"s": 25709,
"text": "Example:"
},
{
"code": null,
"e": 25726,
"s": 25718,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframesprint(data1.join(data2))",
"e": 26205,
"s": 25726,
"text": null
},
{
"code": null,
"e": 26213,
"s": 26205,
"text": "Output:"
},
{
"code": null,
"e": 26271,
"s": 26213,
"text": "This will merge the two dataframes with matching indexes "
},
{
"code": null,
"e": 26279,
"s": 26271,
"text": "Syntax:"
},
{
"code": null,
"e": 26351,
"s": 26279,
"text": "pandas.merge(dataframe1, dataframe2, left_index=True, right_index=True)"
},
{
"code": null,
"e": 26358,
"s": 26351,
"text": "where,"
},
{
"code": null,
"e": 26392,
"s": 26358,
"text": "dataframe1 is the first dataframe"
},
{
"code": null,
"e": 26427,
"s": 26392,
"text": "dataframe2 is the second dataframe"
},
{
"code": null,
"e": 26489,
"s": 26427,
"text": "left_index specifies the first dataframe index set to be true"
},
{
"code": null,
"e": 26553,
"s": 26489,
"text": "right_index specifies the second dataframe index set to be true"
},
{
"code": null,
"e": 26562,
"s": 26553,
"text": "Example:"
},
{
"code": null,
"e": 26570,
"s": 26562,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with mergeprint(pd.merge(data1, data2, left_index=True, right_index=True))",
"e": 27100,
"s": 26570,
"text": null
},
{
"code": null,
"e": 27108,
"s": 27100,
"text": "Output:"
},
{
"code": null,
"e": 27186,
"s": 27108,
"text": "We can concatenate two dataframes by using concat() method by setting axis=1."
},
{
"code": null,
"e": 27194,
"s": 27186,
"text": "Syntax:"
},
{
"code": null,
"e": 27241,
"s": 27194,
"text": "pandas.concat([daatframe1,dataframe2], axis=1)"
},
{
"code": null,
"e": 27250,
"s": 27241,
"text": "Example:"
},
{
"code": null,
"e": 27258,
"s": 27250,
"text": "Python3"
},
{
"code": "# import pandas moduleimport pandas as pd # create student dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4], 'name': ['manoj', 'manoja', 'manoji', 'manij']}, index=['one', 'two', 'three', 'four']) # create marks dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7], 'marks': [98, 90, 78, 86, 78]}, index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with concatprint(pd.concat([data1, data2], axis=1))",
"e": 27765,
"s": 27258,
"text": null
},
{
"code": null,
"e": 27773,
"s": 27765,
"text": "Output:"
},
{
"code": null,
"e": 27788,
"s": 27773,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27795,
"s": 27788,
"text": "Picked"
},
{
"code": null,
"e": 27819,
"s": 27795,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27833,
"s": 27819,
"text": "Python-pandas"
},
{
"code": null,
"e": 27840,
"s": 27833,
"text": "Python"
},
{
"code": null,
"e": 27938,
"s": 27840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27970,
"s": 27938,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28012,
"s": 27970,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28054,
"s": 28012,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28081,
"s": 28054,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28137,
"s": 28081,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28159,
"s": 28137,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28198,
"s": 28159,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28229,
"s": 28198,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28258,
"s": 28229,
"text": "Create a directory in Python"
}
] |
JavaScript | ArrayBuffer Object - GeeksforGeeks
|
26 Jun, 2018
An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. The contents of an ArrayBuffer cannot be directly manipulated and can only be accessed through a DataView Object or one of the typed array objects. These Objects are used to read and write the contents of the buffer. More than one DataView or typed array objects can be added to one ArrayBuffer and any changes to one object can be easily seen by the other objects view.The following are the typed arrays:Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array.Syntax:
new ArrayBuffer(byteLength)
Parameters: It accepts one parameter i.e. bytelength which denotes the size, in bytes, of the array buffer to be created.Return value: It returns a new ArrayBuffer object of the specified size and the content is initialized to 0.
<script> //Create a 16byte buffer var buffer = new ArrayBuffer(16); //Create a DataView referring to the buffer var view1 = new DataView(buffer); //Create a Int8Array view referring to the buffer var view2 = new Int8Array(buffer); //Put value of 32bits view1.setInt32(0, 0x76543210); //prints the 32bit value document.write(view1.getInt32(0).toString(16) + "<br>"); //prints only 8bit value document.write(view1.getInt8(0).toString(16) + "<br>"); document.write(view2[0].toString(16)); </script>
Output:
76543210
76
76
Properties :
ArrayBuffer.byteLength: The byteLength property returns the length of the buffer in bytes.
ArrayBuffer.prototype: This property allows to add properties to all ArrayBuffer objects.
Methods:
ArrayBuffer.isView(arg): If arg is one of the ArrayBuffer views (typed array objects or a DataView) then true is returned otherwise, false is returned.
ArrayBuffer.transfer(oldBuffer [, newByteLength]): The contents from the oldbuffer specified is either truncated or zero-extended by the specified newByteLength and is returned as a new ArrayBuffer.
Instance Methods:
ArrayBuffer.slice() and ArrayBuffer.prototype.slice(): A new ArrayBuffer is returned whose contents are a copy of this ArrayBuffer’s bytes from begin, inclusive, up to end, exclusive.
javascript-array
javascript-object
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
|
[
{
"code": null,
"e": 26129,
"s": 26101,
"text": "\n26 Jun, 2018"
},
{
"code": null,
"e": 26752,
"s": 26129,
"text": "An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. The contents of an ArrayBuffer cannot be directly manipulated and can only be accessed through a DataView Object or one of the typed array objects. These Objects are used to read and write the contents of the buffer. More than one DataView or typed array objects can be added to one ArrayBuffer and any changes to one object can be easily seen by the other objects view.The following are the typed arrays:Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array.Syntax:"
},
{
"code": null,
"e": 26780,
"s": 26752,
"text": "new ArrayBuffer(byteLength)"
},
{
"code": null,
"e": 27010,
"s": 26780,
"text": "Parameters: It accepts one parameter i.e. bytelength which denotes the size, in bytes, of the array buffer to be created.Return value: It returns a new ArrayBuffer object of the specified size and the content is initialized to 0."
},
{
"code": "<script> //Create a 16byte buffer var buffer = new ArrayBuffer(16); //Create a DataView referring to the buffer var view1 = new DataView(buffer); //Create a Int8Array view referring to the buffer var view2 = new Int8Array(buffer); //Put value of 32bits view1.setInt32(0, 0x76543210); //prints the 32bit value document.write(view1.getInt32(0).toString(16) + \"<br>\"); //prints only 8bit value document.write(view1.getInt8(0).toString(16) + \"<br>\"); document.write(view2[0].toString(16)); </script> ",
"e": 27604,
"s": 27010,
"text": null
},
{
"code": null,
"e": 27612,
"s": 27604,
"text": "Output:"
},
{
"code": null,
"e": 27627,
"s": 27612,
"text": "76543210\n76\n76"
},
{
"code": null,
"e": 27640,
"s": 27627,
"text": "Properties :"
},
{
"code": null,
"e": 27731,
"s": 27640,
"text": "ArrayBuffer.byteLength: The byteLength property returns the length of the buffer in bytes."
},
{
"code": null,
"e": 27821,
"s": 27731,
"text": "ArrayBuffer.prototype: This property allows to add properties to all ArrayBuffer objects."
},
{
"code": null,
"e": 27830,
"s": 27821,
"text": "Methods:"
},
{
"code": null,
"e": 27982,
"s": 27830,
"text": "ArrayBuffer.isView(arg): If arg is one of the ArrayBuffer views (typed array objects or a DataView) then true is returned otherwise, false is returned."
},
{
"code": null,
"e": 28181,
"s": 27982,
"text": "ArrayBuffer.transfer(oldBuffer [, newByteLength]): The contents from the oldbuffer specified is either truncated or zero-extended by the specified newByteLength and is returned as a new ArrayBuffer."
},
{
"code": null,
"e": 28199,
"s": 28181,
"text": "Instance Methods:"
},
{
"code": null,
"e": 28383,
"s": 28199,
"text": "ArrayBuffer.slice() and ArrayBuffer.prototype.slice(): A new ArrayBuffer is returned whose contents are a copy of this ArrayBuffer’s bytes from begin, inclusive, up to end, exclusive."
},
{
"code": null,
"e": 28400,
"s": 28383,
"text": "javascript-array"
},
{
"code": null,
"e": 28418,
"s": 28400,
"text": "javascript-object"
},
{
"code": null,
"e": 28429,
"s": 28418,
"text": "JavaScript"
},
{
"code": null,
"e": 28527,
"s": 28429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28567,
"s": 28527,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28612,
"s": 28567,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28673,
"s": 28612,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28745,
"s": 28673,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28797,
"s": 28745,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28838,
"s": 28797,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28879,
"s": 28838,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 28927,
"s": 28879,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 28963,
"s": 28927,
"text": "Node.js | fs.writeFileSync() Method"
}
] |
Lexicographically minimum string rotation | Set 1 - GeeksforGeeks
|
11 Jun, 2021
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples:
Input: GEEKSQUIZ
Output: EEKSQUIZG
Input: GFG
Output: FGG
Input: GEEKSFORGEEKS
Output: EEKSFORGEEKSG
Following is a simple solution. Let the given string be ‘str’ 1) Concatenate ‘str’ with itself and store in a temporary string say ‘concat’. 2) Create an array of strings to store all rotations of ‘str’. Let the array be ‘arr’. 3) Find all rotations of ‘str’ by taking substrings of ‘concat’ at index 0, 1, 2..n-1. Store these rotations in arr[] 4) Sort arr[] and return arr[0].
Following is the implementation of above solution.
C++
Java
Python3
C#
Javascript
// A simple C++ program to find lexicographically minimum rotation// of a given string#include <iostream>#include <algorithm>using namespace std; // This functionr return lexicographically minimum// rotation of strstring minLexRotation(string str){ // Find length of given string int n = str.length(); // Create an array of strings to store all rotations string arr[n]; // Create a concatenation of string with itself string concat = str + str; // One by one store all rotations of str in array. // A rotation is obtained by getting a substring of concat for (int i = 0; i < n; i++) arr[i] = concat.substr(i, n); // Sort all rotations sort(arr, arr+n); // Return the first rotation from the sorted array return arr[0];} // Driver program to test above functionint main(){ cout << minLexRotation("GEEKSFORGEEKS") << endl; cout << minLexRotation("GEEKSQUIZ") << endl; cout << minLexRotation("BCABDADAB") << endl;}
// A simple Java program to find// lexicographically minimum rotation// of a given Stringimport java.util.*; class GFG{ // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.length(); // Create an array of strings // to store all rotations String arr[] = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations Arrays.sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void main(String[] args) { System.out.println(minLexRotation("GEEKSFORGEEKS")); System.out.println(minLexRotation("GEEKSQUIZ")); System.out.println(minLexRotation("BCABDADAB")); }} // This code is contributed by 29AjayKumar
# A simple Python3 program to find lexicographically# minimum rotation of a given string # This function return lexicographically minimum# rotation of strdef minLexRotation(str_) : # Find length of given string n = len(str_) # Create an array of strings to store all rotations arr = [0] * n # Create a concatenation of string with itself concat = str_ + str_ # One by one store all rotations of str in array. # A rotation is obtained by getting a substring of concat for i in range(n) : arr[i] = concat[i : n + i] # Sort all rotations arr.sort() # Return the first rotation from the sorted array return arr[0] # Driver Codeprint(minLexRotation("GEEKSFORGEEKS"))print(minLexRotation("GEEKSQUIZ"))print(minLexRotation("BCABDADAB")) # This code is contributed by divyamohan123
// A simple C# program to find// lexicographically minimum rotation// of a given Stringusing System; class GFG{ // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.Length; // Create an array of strings // to store all rotations String []arr = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.Substring(i, n); } // Sort all rotations Array.Sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void Main(String[] args) { Console.WriteLine(minLexRotation("GEEKSFORGEEKS")); Console.WriteLine(minLexRotation("GEEKSQUIZ")); Console.WriteLine(minLexRotation("BCABDADAB")); }} // This code is contributed by Rajput-Ji
<script> // A simple Javascript program to find// lexicographically minimum rotation// of a given String // This functionr return lexicographically// minimum rotation of strfunction minLexRotation(str){ // Find length of given String let n = str.length; // Create an array of strings // to store all rotations let arr = new Array(n); // Create a concatenation of // String with itself let concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for(let i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations arr.sort(); // Return the first rotation // from the sorted array return arr[0];} // Driver codedocument.write(minLexRotation("GEEKSFORGEEKS") + "</br>");document.write(minLexRotation("GEEKSQUIZ") + "</br>");document.write(minLexRotation("BCABDADAB") + "</br>"); // This code is contributed by divyeshrabadiya07 </script>
Output:
EEKSFORGEEKSG
EEKSQUIZG
ABBCABDAD
Lexicographically smallest rotated sequence | Set 2Time complexity of the above solution is O(n2Logn) under the assumption that we have used a O(nLogn) sorting algorithm. This problem can be solved using more efficient methods like Booth’s Algorithm which solves the problem in O(n) time. We will soon be covering these methods as separate posts.This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
Rajput-Ji
divyamohan123
divyeshrabadiya07
lexicographic-ordering
rotation
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 26553,
"s": 26525,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 26727,
"s": 26553,
"text": "Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples: "
},
{
"code": null,
"e": 26833,
"s": 26727,
"text": "Input: GEEKSQUIZ\nOutput: EEKSQUIZG\n\nInput: GFG\nOutput: FGG\n\nInput: GEEKSFORGEEKS\nOutput: EEKSFORGEEKSG"
},
{
"code": null,
"e": 27212,
"s": 26833,
"text": "Following is a simple solution. Let the given string be ‘str’ 1) Concatenate ‘str’ with itself and store in a temporary string say ‘concat’. 2) Create an array of strings to store all rotations of ‘str’. Let the array be ‘arr’. 3) Find all rotations of ‘str’ by taking substrings of ‘concat’ at index 0, 1, 2..n-1. Store these rotations in arr[] 4) Sort arr[] and return arr[0]."
},
{
"code": null,
"e": 27264,
"s": 27212,
"text": "Following is the implementation of above solution. "
},
{
"code": null,
"e": 27268,
"s": 27264,
"text": "C++"
},
{
"code": null,
"e": 27273,
"s": 27268,
"text": "Java"
},
{
"code": null,
"e": 27281,
"s": 27273,
"text": "Python3"
},
{
"code": null,
"e": 27284,
"s": 27281,
"text": "C#"
},
{
"code": null,
"e": 27295,
"s": 27284,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find lexicographically minimum rotation// of a given string#include <iostream>#include <algorithm>using namespace std; // This functionr return lexicographically minimum// rotation of strstring minLexRotation(string str){ // Find length of given string int n = str.length(); // Create an array of strings to store all rotations string arr[n]; // Create a concatenation of string with itself string concat = str + str; // One by one store all rotations of str in array. // A rotation is obtained by getting a substring of concat for (int i = 0; i < n; i++) arr[i] = concat.substr(i, n); // Sort all rotations sort(arr, arr+n); // Return the first rotation from the sorted array return arr[0];} // Driver program to test above functionint main(){ cout << minLexRotation(\"GEEKSFORGEEKS\") << endl; cout << minLexRotation(\"GEEKSQUIZ\") << endl; cout << minLexRotation(\"BCABDADAB\") << endl;}",
"e": 28267,
"s": 27295,
"text": null
},
{
"code": "// A simple Java program to find// lexicographically minimum rotation// of a given Stringimport java.util.*; class GFG{ // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.length(); // Create an array of strings // to store all rotations String arr[] = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations Arrays.sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void main(String[] args) { System.out.println(minLexRotation(\"GEEKSFORGEEKS\")); System.out.println(minLexRotation(\"GEEKSQUIZ\")); System.out.println(minLexRotation(\"BCABDADAB\")); }} // This code is contributed by 29AjayKumar",
"e": 29462,
"s": 28267,
"text": null
},
{
"code": "# A simple Python3 program to find lexicographically# minimum rotation of a given string # This function return lexicographically minimum# rotation of strdef minLexRotation(str_) : # Find length of given string n = len(str_) # Create an array of strings to store all rotations arr = [0] * n # Create a concatenation of string with itself concat = str_ + str_ # One by one store all rotations of str in array. # A rotation is obtained by getting a substring of concat for i in range(n) : arr[i] = concat[i : n + i] # Sort all rotations arr.sort() # Return the first rotation from the sorted array return arr[0] # Driver Codeprint(minLexRotation(\"GEEKSFORGEEKS\"))print(minLexRotation(\"GEEKSQUIZ\"))print(minLexRotation(\"BCABDADAB\")) # This code is contributed by divyamohan123",
"e": 30288,
"s": 29462,
"text": null
},
{
"code": "// A simple C# program to find// lexicographically minimum rotation// of a given Stringusing System; class GFG{ // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.Length; // Create an array of strings // to store all rotations String []arr = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.Substring(i, n); } // Sort all rotations Array.Sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void Main(String[] args) { Console.WriteLine(minLexRotation(\"GEEKSFORGEEKS\")); Console.WriteLine(minLexRotation(\"GEEKSQUIZ\")); Console.WriteLine(minLexRotation(\"BCABDADAB\")); }} // This code is contributed by Rajput-Ji",
"e": 31463,
"s": 30288,
"text": null
},
{
"code": "<script> // A simple Javascript program to find// lexicographically minimum rotation// of a given String // This functionr return lexicographically// minimum rotation of strfunction minLexRotation(str){ // Find length of given String let n = str.length; // Create an array of strings // to store all rotations let arr = new Array(n); // Create a concatenation of // String with itself let concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for(let i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations arr.sort(); // Return the first rotation // from the sorted array return arr[0];} // Driver codedocument.write(minLexRotation(\"GEEKSFORGEEKS\") + \"</br>\");document.write(minLexRotation(\"GEEKSQUIZ\") + \"</br>\");document.write(minLexRotation(\"BCABDADAB\") + \"</br>\"); // This code is contributed by divyeshrabadiya07 </script>",
"e": 32471,
"s": 31463,
"text": null
},
{
"code": null,
"e": 32480,
"s": 32471,
"text": "Output: "
},
{
"code": null,
"e": 32514,
"s": 32480,
"text": "EEKSFORGEEKSG\nEEKSQUIZG\nABBCABDAD"
},
{
"code": null,
"e": 33027,
"s": 32514,
"text": "Lexicographically smallest rotated sequence | Set 2Time complexity of the above solution is O(n2Logn) under the assumption that we have used a O(nLogn) sorting algorithm. This problem can be solved using more efficient methods like Booth’s Algorithm which solves the problem in O(n) time. We will soon be covering these methods as separate posts.This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33039,
"s": 33027,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33049,
"s": 33039,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 33063,
"s": 33049,
"text": "divyamohan123"
},
{
"code": null,
"e": 33081,
"s": 33063,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33104,
"s": 33081,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 33113,
"s": 33104,
"text": "rotation"
},
{
"code": null,
"e": 33121,
"s": 33113,
"text": "Strings"
},
{
"code": null,
"e": 33129,
"s": 33121,
"text": "Strings"
},
{
"code": null,
"e": 33227,
"s": 33129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33302,
"s": 33227,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 33359,
"s": 33302,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 33395,
"s": 33359,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33442,
"s": 33395,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 33495,
"s": 33442,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33531,
"s": 33495,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 33569,
"s": 33531,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 33599,
"s": 33569,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 33651,
"s": 33599,
"text": "Check whether two strings are anagram of each other"
}
] |
Getting Synchronized Map from Java HashMap - GeeksforGeeks
|
13 Jan, 2021
HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map.
// Get synchronized map using Collections.synchronizedMap()
Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);
To iterate the synchronized map we use a synchronized block:
// Synchronized block
synchronized (synchrMap) {
// Iterate synchronized map
for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) {
// Print key : value
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
Implementation:
Java
// Java Program to demonstrate how // to get synchronized map from HashMap import java.util.*; class GFG { public static void main(String[] args) { // New HashMap HashMap<Integer, String> hmap = new HashMap<>(); // Add element to map hmap.put(1, "Akshay"); hmap.put(2, "Bina"); hmap.put(3, "Chintu"); // Get synchronized map using // Collections.synchronizedMap() Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap); System.out.println("Synchronized Map : "); // Synchronized block synchronized (synchrMap) { // Iterate synchronized map for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) { // Print key : value System.out.println(entry.getKey() + " : " + entry.getValue()); } } }}
Synchronized Map :
1 : Akshay
2 : Bina
3 : Chintu
Java-Collections
Java-HashMap
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25801,
"s": 25773,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 26126,
"s": 25801,
"text": "HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map."
},
{
"code": null,
"e": 26255,
"s": 26126,
"text": "// Get synchronized map using Collections.synchronizedMap()\n\nMap<Integer, String> synchrMap = Collections.synchronizedMap(hmap);"
},
{
"code": null,
"e": 26316,
"s": 26255,
"text": "To iterate the synchronized map we use a synchronized block:"
},
{
"code": null,
"e": 26590,
"s": 26316,
"text": "// Synchronized block\nsynchronized (synchrMap) {\n\n // Iterate synchronized map\n for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) {\n\n // Print key : value\n System.out.println(entry.getKey() + \" : \" + entry.getValue());\n \n }\n}"
},
{
"code": null,
"e": 26606,
"s": 26590,
"text": "Implementation:"
},
{
"code": null,
"e": 26611,
"s": 26606,
"text": "Java"
},
{
"code": "// Java Program to demonstrate how // to get synchronized map from HashMap import java.util.*; class GFG { public static void main(String[] args) { // New HashMap HashMap<Integer, String> hmap = new HashMap<>(); // Add element to map hmap.put(1, \"Akshay\"); hmap.put(2, \"Bina\"); hmap.put(3, \"Chintu\"); // Get synchronized map using // Collections.synchronizedMap() Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap); System.out.println(\"Synchronized Map : \"); // Synchronized block synchronized (synchrMap) { // Iterate synchronized map for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) { // Print key : value System.out.println(entry.getKey() + \" : \" + entry.getValue()); } } }}",
"e": 27554,
"s": 26611,
"text": null
},
{
"code": null,
"e": 27605,
"s": 27554,
"text": "Synchronized Map : \n1 : Akshay\n2 : Bina\n3 : Chintu"
},
{
"code": null,
"e": 27622,
"s": 27605,
"text": "Java-Collections"
},
{
"code": null,
"e": 27635,
"s": 27622,
"text": "Java-HashMap"
},
{
"code": null,
"e": 27642,
"s": 27635,
"text": "Picked"
},
{
"code": null,
"e": 27647,
"s": 27642,
"text": "Java"
},
{
"code": null,
"e": 27661,
"s": 27647,
"text": "Java Programs"
},
{
"code": null,
"e": 27666,
"s": 27661,
"text": "Java"
},
{
"code": null,
"e": 27683,
"s": 27666,
"text": "Java-Collections"
},
{
"code": null,
"e": 27781,
"s": 27683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27832,
"s": 27781,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27862,
"s": 27832,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27881,
"s": 27862,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27896,
"s": 27881,
"text": "Stream In Java"
},
{
"code": null,
"e": 27927,
"s": 27896,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27955,
"s": 27927,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 27999,
"s": 27955,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 28025,
"s": 27999,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28059,
"s": 28025,
"text": "Convert Double to Integer in Java"
}
] |
Maximize matrix as per given condition - GeeksforGeeks
|
21 May, 2021
You are given a N*N matrix, where each element of matrix lies in the range 0 to M. You can apply the below operation on matrix any number of times:
Choose any two consecutive elements
Increment one of them by 1 and decrease other by 1
Note: The elements should remain within the range 0 to M after applying above operations. The task is to find the maximum value of the expression shown below that can be obtained after performing the above operation on matrix if required:
res += (i+j)*A[i][j]
for 0 <= i, j <= N
Examples:
Input : A[][] = {1, 2,
5, 1}
M = 5
Output : RESULT = 27
Matrix : 0 0
4 5
Input : A[][] = {3, 4,
5, 4}
M = 6
Output : RESULT = 43
Matrix : 0 4
6 6
Algorithm : Below is the step by step algorithm to do this:
First of all, calculate the sum of all elements of given matrix as SUM.Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n).....Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero.Finally you can calculate RESULT as per above mentioned formula.
First of all, calculate the sum of all elements of given matrix as SUM.
Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n).....
Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero.
Finally you can calculate RESULT as per above mentioned formula.
Example : Input Matrix:
Solution Matrix after applying above algorithm :
Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// CPP to maximize matrix result#include<bits/stdc++.h>using namespace std;#define n 4 // utility function for maximize matrix resultint maxMatrix(int A[][n], int M){ int sum = 0, res = 0; for ( int i=0; i<n ; i++) for ( int j=0; j<n; j++) sum += A[i][j]; // diagonals below longest diagonal // starting from last element of matrix for (int j=n-1; j>0; j--) { for (int i=0; i<n-j; i++) { if (sum > M) { A[n-1-i][j+i] = M; sum -= M; } else { A[n-1-i][j+i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i=n-1; i>=0; i--) { for (int j=0; j<=i; j++) { if (sum > M) { A[i-j][j] = M; sum -= M; } else { A[i-j][j] = sum; sum -= sum; } } } // calculating result for (int i=0; i<n; i++) { for (int j=0; j<n;j++) res += (i+j+2) * A[i][j]; } return res;} // driver program int main(){ int A[n][n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 2, 3, 4, 5, 6}; int m = 9; cout << maxMatrix(A, m); return 0;}
// Java to maximize matrix result class GFG { static final int n = 4; // utility function for maximize matrix result static int maxMatrix(int A[][], int M) { int sum = 0, res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += A[i][j]; } } // diagonals below longest diagonal // starting from last element of matrix for (int j = n - 1; j > 0; j--) { for (int i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i][j + i] = M; sum -= M; } else { A[n - 1 - i][j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (sum > M) { A[i - j][j] = M; sum -= M; } else { A[i - j][j] = sum; sum -= sum; } } } // calculating result for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res += (i + j + 2) * A[i][j]; } } return res; } // driver program static public void main(String[] args) { int A[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 1, 1, 2}, {3, 4, 5, 6}}; int m = 9; System.out.println(maxMatrix(A, m)); }} // This code is contributed by Rajput-Ji
# Python to maximize matrix resultn = 4 # utility function for maximize# matrix resultdef maxMatrix(A, M): sum, res = 0, 0 for i in range(n): for j in range(n): sum += A[i][j] # diagonals below longest diagonal # starting from last element of matrix for j in range(n - 1, 0, -1): for i in range(n - j): if (sum > M): A[n - 1 - i][j + i] = M sum -= M else: A[n - 1 - i][j + i] = sum sum -= sum # diagonals above longest diagonal for i in range(n - 1, -1, -1): for j in range(i + 1): if (sum > M): A[i - j][j] = M sum -= M else: A[i - j][j] = sum sum -= sum # calculating result for i in range(n): for j in range(n): res += (i + j + 2) * A[i][j] return res # Driver Codeif __name__ == '__main__': A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 1, 2], [3, 4, 5, 6]] m = 9 print(maxMatrix(A, m)) # This code is contributed by 29AjayKumar
// C# to maximize matrix resultusing System;public class GFG { static readonly int n = 4; // utility function for maximize matrix result static int maxMatrix(int [,]A, int M) { int sum = 0, res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += A[i,j]; } } // diagonals below longest diagonal // starting from last element of matrix for (int j = n - 1; j > 0; j--) { for (int i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i,j + i] = M; sum -= M; } else { A[n - 1 - i,j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (sum > M) { A[i - j,j] = M; sum -= M; } else { A[i - j,j] = sum; sum -= sum; } } } // calculating result for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res += (i + j + 2) * A[i,j]; } } return res; } // driver program static public void Main() { int [,]A= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 1, 1, 2}, {3, 4, 5, 6}}; int m = 9; Console.Write(maxMatrix(A, m)); }} // This code is contributed by Rajput-Ji
<?php// PHP to maximize matrix result $n = 4; // function for maximize// matrix resultfunction maxMatrix($A, $M){ global $n; $sum = 0; $res = 0; for ($i = 0; $i < $n ; $i++) for ($j = 0; $j < $n; $j++) $sum += $A[$i][$j]; // diagonals below longest diagonal // starting from last element of matrix for ($j = $n - 1; $j > 0; $j--) { for ($i = 0; $i < $n - $j; $i++) { if ($sum > $M) { $A[$n - 1 - $i][$j + $i] = $M; $sum -= $M; } else { $A[$n - 1 - $i][$j + i] = $sum; $sum -= $sum; } } } // diagonals above longest diagonal for ($i = $n - 1; $i >= 0; $i--) { for ($j = 0; $j <= $i; $j++) { if ($sum > $M) { $A[$i - $j][$j] = $M; $sum -= $M; } else { $A[$i - $j][$j] = $sum; $sum -= $sum; } } } // calculating result for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) $res += ($i + $j + 2) * $A[$i][$j]; } return $res;} // Driver Code $A = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 1, 1, 2), array(3, 4, 5, 6)); $m = 9; echo maxMatrix($A, $m); // This code is contributed by anuj_67.?>
<script> // Javascript to maximize matrix result let n = 4; // utility function for maximize matrix result function maxMatrix(A, M) { let sum = 0, res = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { sum += A[i][j]; } } // diagonals below longest diagonal // starting from last element of matrix for (let j = n - 1; j > 0; j--) { for (let i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i][j + i] = M; sum -= M; } else { A[n - 1 - i][j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (let i = n - 1; i >= 0; i--) { for (let j = 0; j <= i; j++) { if (sum > M) { A[i - j][j] = M; sum -= M; } else { A[i - j][j] = sum; sum -= sum; } } } // calculating result for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { res += (i + j + 2) * A[i][j]; } } return res; } let A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 1, 2], [3, 4, 5, 6]]; let m = 9; document.write(maxMatrix(A, m)); // This code is contributed by divyesh072019.</script>
Output:
425
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Rajput-Ji
29AjayKumar
divyesh072019
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Check for possible path in 2D matrix
Flood fill Algorithm - how to implement fill() in paint?
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices
Unique paths in a Grid with Obstacles
A Boolean Matrix Question
Shortest distance between two cells in a matrix or grid
Breadth First Traversal ( BFS ) on a 2D array
|
[
{
"code": null,
"e": 26165,
"s": 26137,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26315,
"s": 26165,
"text": "You are given a N*N matrix, where each element of matrix lies in the range 0 to M. You can apply the below operation on matrix any number of times: "
},
{
"code": null,
"e": 26351,
"s": 26315,
"text": "Choose any two consecutive elements"
},
{
"code": null,
"e": 26402,
"s": 26351,
"text": "Increment one of them by 1 and decrease other by 1"
},
{
"code": null,
"e": 26643,
"s": 26402,
"text": "Note: The elements should remain within the range 0 to M after applying above operations. The task is to find the maximum value of the expression shown below that can be obtained after performing the above operation on matrix if required: "
},
{
"code": null,
"e": 26684,
"s": 26643,
"text": "res += (i+j)*A[i][j]\n\nfor 0 <= i, j <= N"
},
{
"code": null,
"e": 26696,
"s": 26684,
"text": "Examples: "
},
{
"code": null,
"e": 26911,
"s": 26696,
"text": "Input : A[][] = {1, 2,\n 5, 1}\n M = 5\nOutput : RESULT = 27\nMatrix : 0 0\n 4 5\n\nInput : A[][] = {3, 4,\n 5, 4}\n M = 6\nOutput : RESULT = 43\nMatrix : 0 4\n 6 6"
},
{
"code": null,
"e": 26975,
"s": 26913,
"text": "Algorithm : Below is the step by step algorithm to do this: "
},
{
"code": null,
"e": 27476,
"s": 26975,
"text": "First of all, calculate the sum of all elements of given matrix as SUM.Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n).....Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero.Finally you can calculate RESULT as per above mentioned formula."
},
{
"code": null,
"e": 27548,
"s": 27476,
"text": "First of all, calculate the sum of all elements of given matrix as SUM."
},
{
"code": null,
"e": 27712,
"s": 27548,
"text": "Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n)....."
},
{
"code": null,
"e": 27915,
"s": 27712,
"text": "Fill up each cell of matrix with M and update SUM = SUM- M for each element till SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero and all other remaining place as zero."
},
{
"code": null,
"e": 27980,
"s": 27915,
"text": "Finally you can calculate RESULT as per above mentioned formula."
},
{
"code": null,
"e": 28006,
"s": 27980,
"text": "Example : Input Matrix: "
},
{
"code": null,
"e": 28057,
"s": 28006,
"text": "Solution Matrix after applying above algorithm : "
},
{
"code": null,
"e": 28103,
"s": 28057,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 28107,
"s": 28103,
"text": "C++"
},
{
"code": null,
"e": 28112,
"s": 28107,
"text": "Java"
},
{
"code": null,
"e": 28120,
"s": 28112,
"text": "Python3"
},
{
"code": null,
"e": 28123,
"s": 28120,
"text": "C#"
},
{
"code": null,
"e": 28127,
"s": 28123,
"text": "PHP"
},
{
"code": null,
"e": 28138,
"s": 28127,
"text": "Javascript"
},
{
"code": "// CPP to maximize matrix result#include<bits/stdc++.h>using namespace std;#define n 4 // utility function for maximize matrix resultint maxMatrix(int A[][n], int M){ int sum = 0, res = 0; for ( int i=0; i<n ; i++) for ( int j=0; j<n; j++) sum += A[i][j]; // diagonals below longest diagonal // starting from last element of matrix for (int j=n-1; j>0; j--) { for (int i=0; i<n-j; i++) { if (sum > M) { A[n-1-i][j+i] = M; sum -= M; } else { A[n-1-i][j+i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i=n-1; i>=0; i--) { for (int j=0; j<=i; j++) { if (sum > M) { A[i-j][j] = M; sum -= M; } else { A[i-j][j] = sum; sum -= sum; } } } // calculating result for (int i=0; i<n; i++) { for (int j=0; j<n;j++) res += (i+j+2) * A[i][j]; } return res;} // driver program int main(){ int A[n][n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 2, 3, 4, 5, 6}; int m = 9; cout << maxMatrix(A, m); return 0;}",
"e": 29502,
"s": 28138,
"text": null
},
{
"code": "// Java to maximize matrix result class GFG { static final int n = 4; // utility function for maximize matrix result static int maxMatrix(int A[][], int M) { int sum = 0, res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += A[i][j]; } } // diagonals below longest diagonal // starting from last element of matrix for (int j = n - 1; j > 0; j--) { for (int i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i][j + i] = M; sum -= M; } else { A[n - 1 - i][j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (sum > M) { A[i - j][j] = M; sum -= M; } else { A[i - j][j] = sum; sum -= sum; } } } // calculating result for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res += (i + j + 2) * A[i][j]; } } return res; } // driver program static public void main(String[] args) { int A[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 1, 1, 2}, {3, 4, 5, 6}}; int m = 9; System.out.println(maxMatrix(A, m)); }} // This code is contributed by Rajput-Ji",
"e": 31070,
"s": 29502,
"text": null
},
{
"code": "# Python to maximize matrix resultn = 4 # utility function for maximize# matrix resultdef maxMatrix(A, M): sum, res = 0, 0 for i in range(n): for j in range(n): sum += A[i][j] # diagonals below longest diagonal # starting from last element of matrix for j in range(n - 1, 0, -1): for i in range(n - j): if (sum > M): A[n - 1 - i][j + i] = M sum -= M else: A[n - 1 - i][j + i] = sum sum -= sum # diagonals above longest diagonal for i in range(n - 1, -1, -1): for j in range(i + 1): if (sum > M): A[i - j][j] = M sum -= M else: A[i - j][j] = sum sum -= sum # calculating result for i in range(n): for j in range(n): res += (i + j + 2) * A[i][j] return res # Driver Codeif __name__ == '__main__': A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 1, 2], [3, 4, 5, 6]] m = 9 print(maxMatrix(A, m)) # This code is contributed by 29AjayKumar",
"e": 32209,
"s": 31070,
"text": null
},
{
"code": " // C# to maximize matrix resultusing System;public class GFG { static readonly int n = 4; // utility function for maximize matrix result static int maxMatrix(int [,]A, int M) { int sum = 0, res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += A[i,j]; } } // diagonals below longest diagonal // starting from last element of matrix for (int j = n - 1; j > 0; j--) { for (int i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i,j + i] = M; sum -= M; } else { A[n - 1 - i,j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (int i = n - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { if (sum > M) { A[i - j,j] = M; sum -= M; } else { A[i - j,j] = sum; sum -= sum; } } } // calculating result for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { res += (i + j + 2) * A[i,j]; } } return res; } // driver program static public void Main() { int [,]A= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 1, 1, 2}, {3, 4, 5, 6}}; int m = 9; Console.Write(maxMatrix(A, m)); }} // This code is contributed by Rajput-Ji",
"e": 33782,
"s": 32209,
"text": null
},
{
"code": "<?php// PHP to maximize matrix result $n = 4; // function for maximize// matrix resultfunction maxMatrix($A, $M){ global $n; $sum = 0; $res = 0; for ($i = 0; $i < $n ; $i++) for ($j = 0; $j < $n; $j++) $sum += $A[$i][$j]; // diagonals below longest diagonal // starting from last element of matrix for ($j = $n - 1; $j > 0; $j--) { for ($i = 0; $i < $n - $j; $i++) { if ($sum > $M) { $A[$n - 1 - $i][$j + $i] = $M; $sum -= $M; } else { $A[$n - 1 - $i][$j + i] = $sum; $sum -= $sum; } } } // diagonals above longest diagonal for ($i = $n - 1; $i >= 0; $i--) { for ($j = 0; $j <= $i; $j++) { if ($sum > $M) { $A[$i - $j][$j] = $M; $sum -= $M; } else { $A[$i - $j][$j] = $sum; $sum -= $sum; } } } // calculating result for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) $res += ($i + $j + 2) * $A[$i][$j]; } return $res;} // Driver Code $A = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 1, 1, 2), array(3, 4, 5, 6)); $m = 9; echo maxMatrix($A, $m); // This code is contributed by anuj_67.?>",
"e": 35248,
"s": 33782,
"text": null
},
{
"code": "<script> // Javascript to maximize matrix result let n = 4; // utility function for maximize matrix result function maxMatrix(A, M) { let sum = 0, res = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { sum += A[i][j]; } } // diagonals below longest diagonal // starting from last element of matrix for (let j = n - 1; j > 0; j--) { for (let i = 0; i < n - j; i++) { if (sum > M) { A[n - 1 - i][j + i] = M; sum -= M; } else { A[n - 1 - i][j + i] = sum; sum -= sum; } } } // diagonals above longest diagonal for (let i = n - 1; i >= 0; i--) { for (let j = 0; j <= i; j++) { if (sum > M) { A[i - j][j] = M; sum -= M; } else { A[i - j][j] = sum; sum -= sum; } } } // calculating result for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { res += (i + j + 2) * A[i][j]; } } return res; } let A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 1, 2], [3, 4, 5, 6]]; let m = 9; document.write(maxMatrix(A, m)); // This code is contributed by divyesh072019.</script>",
"e": 36757,
"s": 35248,
"text": null
},
{
"code": null,
"e": 36767,
"s": 36757,
"text": "Output: "
},
{
"code": null,
"e": 36771,
"s": 36767,
"text": "425"
},
{
"code": null,
"e": 37206,
"s": 36771,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37211,
"s": 37206,
"text": "vt_m"
},
{
"code": null,
"e": 37221,
"s": 37211,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37233,
"s": 37221,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37247,
"s": 37233,
"text": "divyesh072019"
},
{
"code": null,
"e": 37254,
"s": 37247,
"text": "Matrix"
},
{
"code": null,
"e": 37261,
"s": 37254,
"text": "Matrix"
},
{
"code": null,
"e": 37359,
"s": 37261,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37409,
"s": 37359,
"text": "Efficiently compute sums of diagonals of a matrix"
},
{
"code": null,
"e": 37446,
"s": 37409,
"text": "Check for possible path in 2D matrix"
},
{
"code": null,
"e": 37503,
"s": 37446,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 37544,
"s": 37503,
"text": "Zigzag (or diagonal) traversal of Matrix"
},
{
"code": null,
"e": 37608,
"s": 37544,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
},
{
"code": null,
"e": 37643,
"s": 37608,
"text": "Python program to add two Matrices"
},
{
"code": null,
"e": 37681,
"s": 37643,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 37707,
"s": 37681,
"text": "A Boolean Matrix Question"
},
{
"code": null,
"e": 37763,
"s": 37707,
"text": "Shortest distance between two cells in a matrix or grid"
}
] |
PyQt5 QCalendarWidget - Setting date Range - GeeksforGeeks
|
18 Aug, 2021
In this article we will see how we can set the date range to the QCalendarWidget. The date range of QCalendarWidget restricts the user selection, i.e. the user can only select dates within the specified date range. Rest of the dates get disabled.
In order to do this we will use setDateRange method with the QCalendarWidget object.Syntax : calendar.setDateRange(lower_date, upper_date)Argument : It takes two QDate object as argumentReturn : It return None
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # lower bound date l_date = QDate(2020, 6, 5) # upper bound date u_date = QDate(2020, 6, 15) # setting date range calendar.setDateRange(l_date, u_date) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
|
[
{
"code": null,
"e": 26437,
"s": 26409,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 26685,
"s": 26437,
"text": "In this article we will see how we can set the date range to the QCalendarWidget. The date range of QCalendarWidget restricts the user selection, i.e. the user can only select dates within the specified date range. Rest of the dates get disabled. "
},
{
"code": null,
"e": 26897,
"s": 26685,
"text": "In order to do this we will use setDateRange method with the QCalendarWidget object.Syntax : calendar.setDateRange(lower_date, upper_date)Argument : It takes two QDate object as argumentReturn : It return None "
},
{
"code": null,
"e": 26927,
"s": 26897,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26935,
"s": 26927,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # lower bound date l_date = QDate(2020, 6, 5) # upper bound date u_date = QDate(2020, 6, 15) # setting date range calendar.setDateRange(l_date, u_date) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27957,
"s": 26935,
"text": null
},
{
"code": null,
"e": 27968,
"s": 27957,
"text": "Output : "
},
{
"code": null,
"e": 27978,
"s": 27970,
"text": "clintra"
},
{
"code": null,
"e": 28006,
"s": 27978,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 28017,
"s": 28006,
"text": "Python-gui"
},
{
"code": null,
"e": 28029,
"s": 28017,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28036,
"s": 28029,
"text": "Python"
},
{
"code": null,
"e": 28134,
"s": 28036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28152,
"s": 28134,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28174,
"s": 28152,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28196,
"s": 28174,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28221,
"s": 28196,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28247,
"s": 28221,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28282,
"s": 28247,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28314,
"s": 28282,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28330,
"s": 28314,
"text": "Deque in Python"
},
{
"code": null,
"e": 28372,
"s": 28330,
"text": "Different ways to create Pandas Dataframe"
}
] |
Python File flush() Method
|
Python file method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
Python automatically flushes the files when closing them. But you may want to flush the data before closing any file.
Following is the syntax for flush() method −
fileObject.flush();
NA
NA
This method does not return any value.
The following example shows the usage of flush() method.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Here it does nothing, but you can call it with read operation.
fo.flush()
# Close opend file
fo.close()
When we run above program, it produces following result −
Name of the file: foo.txt
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2368,
"s": 2244,
"text": "Python file method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects."
},
{
"code": null,
"e": 2486,
"s": 2368,
"text": "Python automatically flushes the files when closing them. But you may want to flush the data before closing any file."
},
{
"code": null,
"e": 2531,
"s": 2486,
"text": "Following is the syntax for flush() method −"
},
{
"code": null,
"e": 2553,
"s": 2531,
"text": "fileObject.flush(); \n"
},
{
"code": null,
"e": 2556,
"s": 2553,
"text": "NA"
},
{
"code": null,
"e": 2559,
"s": 2556,
"text": "NA"
},
{
"code": null,
"e": 2598,
"s": 2559,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2655,
"s": 2598,
"text": "The following example shows the usage of flush() method."
},
{
"code": null,
"e": 2859,
"s": 2655,
"text": "#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nprint \"Name of the file: \", fo.name\n\n# Here it does nothing, but you can call it with read operation.\nfo.flush()\n\n# Close opend file\nfo.close()"
},
{
"code": null,
"e": 2917,
"s": 2859,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2945,
"s": 2917,
"text": "Name of the file: foo.txt\n"
},
{
"code": null,
"e": 2982,
"s": 2945,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2998,
"s": 2982,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3031,
"s": 2998,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3050,
"s": 3031,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3085,
"s": 3050,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3107,
"s": 3085,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3141,
"s": 3107,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3169,
"s": 3141,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3204,
"s": 3169,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3218,
"s": 3204,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3251,
"s": 3218,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3268,
"s": 3251,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3275,
"s": 3268,
"text": " Print"
},
{
"code": null,
"e": 3286,
"s": 3275,
"text": " Add Notes"
}
] |
JavaScript Number.MAX_VALUE & Number.MIN_VALUE with Examples
|
The JavaScript Number.MAX_VALUE & Number.MIN_VALUE property represents the maximum and minimum numeric value representation possible in JavaScript respectively.
Following is the code for the JavaScript Number.MAX_VALUE & Number.MIN_VALUE property −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample{
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JavaScript Number.MAX_VALUE & Number.MIN_VALUE</h1>
<div class="sample"></div>
<div style="font-weight: bold; color: black;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above to get the maximum and minimum number value possible in JavaScript
</h3>
<script>
let sampleEle = document.querySelector(".sample");
document.querySelector(".Btn").addEventListener("click", () => {
sampleEle.innerHTML = 'Number.MAX_VALUE = ' + Number.MAX_VALUE + '<br>';
sampleEle.innerHTML += 'Number.MIN_VALUE = ' + Number.MIN_VALUE + '<br>';
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
|
[
{
"code": null,
"e": 1223,
"s": 1062,
"text": "The JavaScript Number.MAX_VALUE & Number.MIN_VALUE property represents the maximum and minimum numeric value representation possible in JavaScript respectively."
},
{
"code": null,
"e": 1311,
"s": 1223,
"text": "Following is the code for the JavaScript Number.MAX_VALUE & Number.MIN_VALUE property −"
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": " Live Demo"
},
{
"code": null,
"e": 2292,
"s": 1322,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample{\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Number.MAX_VALUE & Number.MIN_VALUE</h1>\n<div class=\"sample\"></div>\n<div style=\"font-weight: bold; color: black;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above to get the maximum and minimum number value possible in JavaScript\n</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n sampleEle.innerHTML = 'Number.MAX_VALUE = ' + Number.MAX_VALUE + '<br>';\n sampleEle.innerHTML += 'Number.MIN_VALUE = ' + Number.MIN_VALUE + '<br>';\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2330,
"s": 2292,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
PHP - Local Variables
|
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −
Local variables
Function parameters
Global variables
Static variables.
A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function −
<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. <br />";
}
assignx();
print "\$x outside of function is $x. <br />";
?>
This will produce the following result −
$x inside function is 0.
$x outside of function is 4.
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2909,
"s": 2757,
"text": "Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −"
},
{
"code": null,
"e": 2925,
"s": 2909,
"text": "Local variables"
},
{
"code": null,
"e": 2945,
"s": 2925,
"text": "Function parameters"
},
{
"code": null,
"e": 2962,
"s": 2945,
"text": "Global variables"
},
{
"code": null,
"e": 2980,
"s": 2962,
"text": "Static variables."
},
{
"code": null,
"e": 3227,
"s": 2980,
"text": "A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function −"
},
{
"code": null,
"e": 3413,
"s": 3227,
"text": "<?php\n $x = 4;\n \n function assignx () { \n $x = 0;\n print \"\\$x inside function is $x. <br />\";\n }\n \n assignx();\n print \"\\$x outside of function is $x. <br />\";\n?>"
},
{
"code": null,
"e": 3454,
"s": 3413,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3511,
"s": 3454,
"text": "$x inside function is 0. \n$x outside of function is 4. \n"
},
{
"code": null,
"e": 3544,
"s": 3511,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3560,
"s": 3544,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3593,
"s": 3560,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3604,
"s": 3593,
"text": " Syed Raza"
},
{
"code": null,
"e": 3639,
"s": 3604,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3656,
"s": 3639,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3689,
"s": 3656,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3704,
"s": 3689,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3739,
"s": 3704,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3751,
"s": 3739,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3786,
"s": 3751,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3814,
"s": 3786,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3821,
"s": 3814,
"text": " Print"
},
{
"code": null,
"e": 3832,
"s": 3821,
"text": " Add Notes"
}
] |
Prediction task with Multivariate Time Series and VAR model. | by Alena Nazarava | Towards Data Science
|
Time Series data can be confusing, but very interesting to explore. The reason this sort of data grabbed my attention is that it can be found in almost every business (sales, deliveries, weather conditions etc.). For instance: using Google BigQuery how to explore weather effects on NYC link.
The main steps in the task:
Problem definitionGathering informationExploratory AnalysisChoosing and fitting modelsUsing and evaluating a forecast model
Problem definition
Gathering information
Exploratory Analysis
Choosing and fitting models
Using and evaluating a forecast model
We want to predict the future values of the series using current information from the dataset. This information contains current and past values of the series. There are lots of projects with univariate dataset, to make it a bit more complicated and closer to a real life problem, I chose a multivariate dataset. Multivariate time series analysis considers simultaneous multiple time series that deals with dependent data. (The dataset contains more than one time-dependent variable.)
I want to make a weather forecast. The task of predicting the state of the atmosphere at a future time and a specified location using a statistical model.
I will be using data from the following sources:
NOAA. Climate Data Online (CDO) offers web services that provide access to available data through API. linkGoogleCloud BigQuery public data. linkKaggle. link You can download from this page and run in your env or use kaggle account and use it in your notebook, that kaggle provide.
NOAA. Climate Data Online (CDO) offers web services that provide access to available data through API. link
GoogleCloud BigQuery public data. link
Kaggle. link You can download from this page and run in your env or use kaggle account and use it in your notebook, that kaggle provide.
Getting Data from NOAA
In order to access the CDO web services a token must be first obtained from the token request page. Documentation is straight-forward and should not take a lot time to understand.
Example: To find information about weather in Portland, Maine you need to know: State_id and coordinates of Portland. At first I will get the list of all states.
def get_states_list(self): url = conf.noaa['host']+'locations?locationcategoryid=ST&limit=50' headers = dict(token=conf.noaa['token']) r = requests.get(url, headers=headers) data = json.loads(r.content) states_list = json_normalize(data['results']) return states_list
Then, using parameter ‘name’: ‘Maine’ find information about the particular state:
def state_info(self, state): dataset = NoaaApi() states_info = dataset.get_states_list() df_states = pd.DataFrame(states_info) id = df_states[(df_states.name == state)].id return id
Results: Where id of state Maine is: ‘FIPS:23’
dataset.state_info('Maine')State id: FIPS:23
The next step is to get Stations near Portland, Portland’s coordinates could be found easily in google map ( 43.6591 N, 70.2568 W Portland).
The list of Stations in the Maine state could be found with the following GET request.
def get_stations_list(self): url = conf.noaa['host']+'stations?locationid=FIPS:23&limit=687' headers = dict(token=conf.noaa['token']) r = requests.get(url, headers=headers) data = json.loads(r.content) stations_list = json_normalize(data['results']) return stations_list
I do not need all stations in the state, I would like to find Stations just near Portland. To do this I will specify coordinates.
def station_info(self): dataset = NoaaApi() stations_list = dataset.get_stations_list() df_stations = pd.DataFrame(stations_list) portland_st = df_stations[(df_stations.latitude > 43.5) & (df_stations.latitude < 43.7) & (df_stations.longitude > -70.3) & (df_stations.longitude < -70.1)] return portland_st
Conclusion: We got list of Stations near Portland, that can be used in the feature to get weather data in that region.
Getting Data from Kaggle
There are bunch of datasets that provide opportunities to learn and improve your skills as well as participate in competitions where you can earn money and show off your skills. I found Daily Global Historical Climatology Network (BigQuery Dataset) The whole description could be found in the overview page: link . A perfect chance to practice your BigQuery skills.
import numpy as np import pandas as pd import osimport bq_helperfrom bq_helper import BigQueryHelpernoaa = bq_helper.BigQueryHelper(active_project="bigquery-public-data", dataset_name="ghcn_d")
Create a query and estimate size:
#43.6591° N, 70.2568° W Portland/Coordinates Maine 45.2538° N, 69.4455° WqueryStations = """SELECT id, name, state, latitude, longitudeFROM `bigquery-public-data.ghcn_d.ghcnd_stations`WHERE latitude > 43.5 AND latitude < 44 AND longitude > -70.4 AND longitude < -69.4; """ noaa.estimate_query_size(queryStations)
Kaggle BigQuery.helper provides estimation for query to avoid exceed limit.
0.0065232375636696815
Now run the query:
stations_portland = noaa.query_to_pandas_safe(queryStations)stations_portland.head(20)
As we can see, we got almost the same list of Stations.
Getting Data from GoogleCloud
Google provides 30GB of public weather data. There is the possibility to have a free account and practice to improve your skills in Bigquery. Also there is the possibility to select data that you need and download the dataset for further investigation. Super useful for private use as well as for companies. I will not try to find list of Stations, but will request daily temperature from the Station that was found.
SELECT TIMESTAMP(CONCAT(year,"-",mo,"-",da)) AS date, AVG(IF (temp=9999.9, 0, temp)) AS temperature, MIN(IF (temp=9999.9, 0, min)) AS temperature_min, MAX(IF (temp=9999.9, 0, max)) AS temperature_max, AVG(IF (visib=999.9, 0, visib)) AS visibility, AVG(IF (gust=999.9, 0, gust)) AS wind_gust, AVG(IF (wdsp="999.9", 0, CAST(wdsp AS Float64))) AS wind_speed, AVG(IF (prcp=99.99, 0, prcp)) AS precipitation, AVG(IF (sndp=999.9, 0, sndp)) AS snow_depthFROM `bigquery-public-data.noaa_gsod.gsod20*`WHERE CAST(YEAR AS INT64) > 2008 AND (stn="726060") GROUP BY dateORDER BY date
This query will process 5.19 GB when run.
This query will return daily weather from one station in city Portland, Maine for the last 10 years.
At first I would like to visualise important information, to make it clear what kind of data we have.
I will use data from the city of Portland, Maine to plot the locations of weather Stations, using GeoPandas library. The first step is to find and download a shape-file(.shp file). I already showed how to get Stations near Portland using NOAA API(portland_st)
highway_map = gpd.read_file('./maine_highway/maine_highway.shp')crs = {'init': 'epsg:4326'}point = [Point(xy) for xy in zip(portland_st['longitude'], portland_st['latitude'])]geo_stations = gpd.GeoDataFrame(portland_st, crs=crs, geometry=point)fig, ax = plt.subplots(figsize=(5, 5))highway_map.plot(ax=ax, alpha=0.4, color='grey')geo_stations.plot(ax=ax, color='red', marker='o')plt.legend(prop={'size': 5})plt.show()
I found the shape-file (‘maine_highway.shp’) that shows main roads in Portland and combine it with the Stations location. Red dots are the locations of the weather stations. Now it’s obvious which station is needed for the feature model. It is an easy way to visualise geospatial data.
The goal of time series analysis is to find patterns in the data and use the data for predictions.
It is also useful to explore relationships between time series. Let’s look at subplots with all features for the year 2017:
For sure we want to look at the series that is going to be forecast. I did it using iplot library.
df[['temperature', 'temperature_min']].iplot( mode='lines+markers', opacity=0.8, size=8, symbol=1, xTitle='Time', yTitle='Temperature', title='Temperature over last 10 years')
Just for curiosity’s sake I can illustrate line plot that shows avg/min/max temperature at New Year’s for the last 10 years:
sns.set(rc={'figure.figsize': (14.7, 8.27)})g = sns.lineplot(data=newyear.temperature_max, palette="tab10", linewidth=2.5, label="max")g = sns.lineplot(data=newyear.temperature_min, palette="tab10", linewidth=2.5, label="min")g = sns.lineplot(data=newyear.temperature, palette="tab10", linewidth=2.5, label="avg")g.tick_params(labelsize=10)plt.xticks(rotation=45)plt.show()
Temperature during the period from 27.12 till 03.01 for 10 years. In case someone would need historical statistics from the past years only for a defined period, let say New Year’s week.
If the main purpose is only to prepare data and select a model. The right solution would be to plot four graphs when looking at particular series.
As well as looking at the time plot of the data, the ACF plot is also useful for identifying non-stationary time series. For a stationary time series, the ACF will drop to zero relatively quickly, while the ACF of non-stationary data decreases slowly.
def tsplot(y, title, lags=None, figsize=(10, 6)): fig = plt.figure(figsize=figsize) layout = (2, 2) ts_ax = plt.subplot2grid(layout, (0, 0)) hist_ax = plt.subplot2grid(layout, (0, 1)) acf_ax = plt.subplot2grid(layout, (1, 0)) pacf_ax = plt.subplot2grid(layout, (1, 1)) y.plot(ax=ts_ax) ts_ax.set_title(title, fontsize=12, fontweight='bold') y.plot(ax=hist_ax, kind='hist', bins=25) hist_ax.set_title('Histogram') sm.tsa.graphics.plot_acf(y, lags=lags, ax=acf_ax) sm.tsa.graphics.plot_pacf(y, lags=lags, ax=pacf_ax) sns.despine() plt.tight_layout() plt.show() return ts_ax, acf_ax, pacf_ax
In a series of daily temperatures, the mean temperature is not constant, since it varies by day, but for the same month in different years we can expect a constant average value.
The seasonal period, s, defines the number of observations that make up a seasonal cycle. For example, s = 12 for monthly series, s = 4 for quarterly series, s = 365 for daily series.
However, this may not be precisely true: for example, if we have daily data and the seasonal period is the length of the month, s will be approximately 30, but it will vary from month to month. And the trickiest thing is, there may be more than one type of seasonality. For example, with daily data we can have monthly seasonality, with s = 30 and yearly, with s = 365.
Daily data are challenging for a different reason — they often involve multiple seasonal patterns, and so we need to use a method that handles such complex seasonality.
Time Series data might also have other patterns, such as trends or cyclic. And all of this shows that the data is not stationary.
To use statistical model such as the VAR model we should take care of these patterns before the data can be fit into the model. For the VAR model you need stationary condition to be performed. Put enough structure into the model to identify some of the parameters in a model.
Applying seasonal differencing to the log of the series should make the above series stationary. It is quite challenging to define parameters for climate data, that are a lot of publications about this topic. I will not dig deep inside and choose just simple parameters lag=365 and diff=1. More information about parameters you can find in Trend analysis of climate time series publication.
A stationary time series is one whose properties do not depend on the time at which the series is observed. Time series with seasonality, are not stationary, because seasonality will affect the value of the time series at different times.
transformed = df.copy()transformed['temperature'] = np.log(df.iloc[:, 0]).diff(1)transformed['wind_speed'] = np.log(df.iloc[:, 1]).diff(1)
The purpose of transformation is make the series stationary.
The next step is to split the data.
Split the samples into training/testing and validation set. It needs to be split carefully regarding the dependency structure. The approach that can mostly fit to this case is a rolling window. But in this particular example I will just leave a few observations at the end to validate my model. I want to forecast 7 days. Later to check the performance of the model I will use these 7 true values.
This kind of model required the series to be stationary, if the series are not stationary, the individual series have to be transformed to be stationary.
A VAR(p) in two variables can be written in matrix form (where p=1) as
model = sm.tsa.VARMAX(y_train, order=(5, 0), trend='c')model_result = model.fit(maxiter=1000, disp=False)model_result.summary()
The way to select an order is to use information criteria AIC, BIC, HQIC. Estimate a range of models and choose the best one. The most common approach for model order selection involves minimizing one or more information criteria evaluated over a range of model orders.
for i in range(5): i += 1 model = sm.tsa.VARMAX(y_train, order=(i,0)) model_result = model.fit(maxiter=1000, disp=False) print('Order = ', i) print('AIC: ', model_result.aic) print('BIC: ', model_result.bic) print('HQIC: ', model_result.hqic)
more details about how to choose right order you can find in the book New Introduction to Multiple Time Series Analysis by Lütkepohl, Helmut (chapter 4). In this particular example I will use p = 5, where AIC criteria reach their minimum.
The next step is the model diagnostic and checking that underlying assumption is true. The VARMAX class in Statsmodels allows estimation of VAR, VMA, and VARMA models (through the order argument) The VARMAX procedure is a well-established and powerful tool for analysing multivariate time series.
model = sm.tsa.VARMAX(y_train, order=(5, 0))model_result = model.fit(maxiter=1000, disp=False)model_result.plot_diagnostics()plt.show()
A common overall diagnostic is the plot of the residuals and to see whether the residuals obey the models assumptions.
It can be possible to apply tests:
tests to confirm normalityabsence of serial correlationabsence of heteroscedasticity
tests to confirm normality
absence of serial correlation
absence of heteroscedasticity
The two series do not exhibit trends or regular seasonal patterns. Therefore we assume that they are the realisation of a stationary VAR(p) process.
To recap: We transformed temperature and wind speed with the following equation, where yt is an original series:
This means that it should be transformed back to define and estimate real results with predicted. For this purpose we calculate the equation and apply to predicted values:
z = model_result.forecast(steps=7)
Transform values and print a result:
pd.concat([df['temperature'][-7:], forecast], axis=1)
Calculate Mean Squared Error:
rmse = sqrt(mean_squared_error(df['temperature'][-7:], forecast))RMSE: 4.200
Conclusion: Time Series data can be very tricky to deal with correctly. You need to properly explore your data to understand it, be aware of any seasonality or other patterns. It is not always possible to use the same approach. In general is best to start with simple models and build your analysis from there.
AM207: Pavlos Protopapas, Harvard UniversityForecasting: Principles and Practice, Rob J Hyndman and George AthanasopoulosJeffrey Yau, PyData Conference 2017New Introduction to Multiple Time Series Analysis by Lütkepohl, HelmutGoogle BigQuery to explore weather effects
AM207: Pavlos Protopapas, Harvard University
Forecasting: Principles and Practice, Rob J Hyndman and George Athanasopoulos
Jeffrey Yau, PyData Conference 2017
New Introduction to Multiple Time Series Analysis by Lütkepohl, Helmut
Google BigQuery to explore weather effects
|
[
{
"code": null,
"e": 465,
"s": 172,
"text": "Time Series data can be confusing, but very interesting to explore. The reason this sort of data grabbed my attention is that it can be found in almost every business (sales, deliveries, weather conditions etc.). For instance: using Google BigQuery how to explore weather effects on NYC link."
},
{
"code": null,
"e": 493,
"s": 465,
"text": "The main steps in the task:"
},
{
"code": null,
"e": 617,
"s": 493,
"text": "Problem definitionGathering informationExploratory AnalysisChoosing and fitting modelsUsing and evaluating a forecast model"
},
{
"code": null,
"e": 636,
"s": 617,
"text": "Problem definition"
},
{
"code": null,
"e": 658,
"s": 636,
"text": "Gathering information"
},
{
"code": null,
"e": 679,
"s": 658,
"text": "Exploratory Analysis"
},
{
"code": null,
"e": 707,
"s": 679,
"text": "Choosing and fitting models"
},
{
"code": null,
"e": 745,
"s": 707,
"text": "Using and evaluating a forecast model"
},
{
"code": null,
"e": 1230,
"s": 745,
"text": "We want to predict the future values of the series using current information from the dataset. This information contains current and past values of the series. There are lots of projects with univariate dataset, to make it a bit more complicated and closer to a real life problem, I chose a multivariate dataset. Multivariate time series analysis considers simultaneous multiple time series that deals with dependent data. (The dataset contains more than one time-dependent variable.)"
},
{
"code": null,
"e": 1385,
"s": 1230,
"text": "I want to make a weather forecast. The task of predicting the state of the atmosphere at a future time and a specified location using a statistical model."
},
{
"code": null,
"e": 1434,
"s": 1385,
"text": "I will be using data from the following sources:"
},
{
"code": null,
"e": 1716,
"s": 1434,
"text": "NOAA. Climate Data Online (CDO) offers web services that provide access to available data through API. linkGoogleCloud BigQuery public data. linkKaggle. link You can download from this page and run in your env or use kaggle account and use it in your notebook, that kaggle provide."
},
{
"code": null,
"e": 1824,
"s": 1716,
"text": "NOAA. Climate Data Online (CDO) offers web services that provide access to available data through API. link"
},
{
"code": null,
"e": 1863,
"s": 1824,
"text": "GoogleCloud BigQuery public data. link"
},
{
"code": null,
"e": 2000,
"s": 1863,
"text": "Kaggle. link You can download from this page and run in your env or use kaggle account and use it in your notebook, that kaggle provide."
},
{
"code": null,
"e": 2023,
"s": 2000,
"text": "Getting Data from NOAA"
},
{
"code": null,
"e": 2203,
"s": 2023,
"text": "In order to access the CDO web services a token must be first obtained from the token request page. Documentation is straight-forward and should not take a lot time to understand."
},
{
"code": null,
"e": 2365,
"s": 2203,
"text": "Example: To find information about weather in Portland, Maine you need to know: State_id and coordinates of Portland. At first I will get the list of all states."
},
{
"code": null,
"e": 2651,
"s": 2365,
"text": "def get_states_list(self): url = conf.noaa['host']+'locations?locationcategoryid=ST&limit=50' headers = dict(token=conf.noaa['token']) r = requests.get(url, headers=headers) data = json.loads(r.content) states_list = json_normalize(data['results']) return states_list"
},
{
"code": null,
"e": 2734,
"s": 2651,
"text": "Then, using parameter ‘name’: ‘Maine’ find information about the particular state:"
},
{
"code": null,
"e": 2931,
"s": 2734,
"text": "def state_info(self, state): dataset = NoaaApi() states_info = dataset.get_states_list() df_states = pd.DataFrame(states_info) id = df_states[(df_states.name == state)].id return id"
},
{
"code": null,
"e": 2978,
"s": 2931,
"text": "Results: Where id of state Maine is: ‘FIPS:23’"
},
{
"code": null,
"e": 3023,
"s": 2978,
"text": "dataset.state_info('Maine')State id: FIPS:23"
},
{
"code": null,
"e": 3164,
"s": 3023,
"text": "The next step is to get Stations near Portland, Portland’s coordinates could be found easily in google map ( 43.6591 N, 70.2568 W Portland)."
},
{
"code": null,
"e": 3251,
"s": 3164,
"text": "The list of Stations in the Maine state could be found with the following GET request."
},
{
"code": null,
"e": 3540,
"s": 3251,
"text": "def get_stations_list(self): url = conf.noaa['host']+'stations?locationid=FIPS:23&limit=687' headers = dict(token=conf.noaa['token']) r = requests.get(url, headers=headers) data = json.loads(r.content) stations_list = json_normalize(data['results']) return stations_list"
},
{
"code": null,
"e": 3670,
"s": 3540,
"text": "I do not need all stations in the state, I would like to find Stations just near Portland. To do this I will specify coordinates."
},
{
"code": null,
"e": 4069,
"s": 3670,
"text": "def station_info(self): dataset = NoaaApi() stations_list = dataset.get_stations_list() df_stations = pd.DataFrame(stations_list) portland_st = df_stations[(df_stations.latitude > 43.5) & (df_stations.latitude < 43.7) & (df_stations.longitude > -70.3) & (df_stations.longitude < -70.1)] return portland_st"
},
{
"code": null,
"e": 4188,
"s": 4069,
"text": "Conclusion: We got list of Stations near Portland, that can be used in the feature to get weather data in that region."
},
{
"code": null,
"e": 4213,
"s": 4188,
"text": "Getting Data from Kaggle"
},
{
"code": null,
"e": 4579,
"s": 4213,
"text": "There are bunch of datasets that provide opportunities to learn and improve your skills as well as participate in competitions where you can earn money and show off your skills. I found Daily Global Historical Climatology Network (BigQuery Dataset) The whole description could be found in the overview page: link . A perfect chance to practice your BigQuery skills."
},
{
"code": null,
"e": 4773,
"s": 4579,
"text": "import numpy as np import pandas as pd import osimport bq_helperfrom bq_helper import BigQueryHelpernoaa = bq_helper.BigQueryHelper(active_project=\"bigquery-public-data\", dataset_name=\"ghcn_d\")"
},
{
"code": null,
"e": 4807,
"s": 4773,
"text": "Create a query and estimate size:"
},
{
"code": null,
"e": 5134,
"s": 4807,
"text": "#43.6591° N, 70.2568° W Portland/Coordinates Maine 45.2538° N, 69.4455° WqueryStations = \"\"\"SELECT id, name, state, latitude, longitudeFROM `bigquery-public-data.ghcn_d.ghcnd_stations`WHERE latitude > 43.5 AND latitude < 44 AND longitude > -70.4 AND longitude < -69.4; \"\"\" noaa.estimate_query_size(queryStations)"
},
{
"code": null,
"e": 5210,
"s": 5134,
"text": "Kaggle BigQuery.helper provides estimation for query to avoid exceed limit."
},
{
"code": null,
"e": 5232,
"s": 5210,
"text": "0.0065232375636696815"
},
{
"code": null,
"e": 5251,
"s": 5232,
"text": "Now run the query:"
},
{
"code": null,
"e": 5338,
"s": 5251,
"text": "stations_portland = noaa.query_to_pandas_safe(queryStations)stations_portland.head(20)"
},
{
"code": null,
"e": 5394,
"s": 5338,
"text": "As we can see, we got almost the same list of Stations."
},
{
"code": null,
"e": 5424,
"s": 5394,
"text": "Getting Data from GoogleCloud"
},
{
"code": null,
"e": 5841,
"s": 5424,
"text": "Google provides 30GB of public weather data. There is the possibility to have a free account and practice to improve your skills in Bigquery. Also there is the possibility to select data that you need and download the dataset for further investigation. Super useful for private use as well as for companies. I will not try to find list of Stations, but will request daily temperature from the Station that was found."
},
{
"code": null,
"e": 6426,
"s": 5841,
"text": "SELECT TIMESTAMP(CONCAT(year,\"-\",mo,\"-\",da)) AS date, AVG(IF (temp=9999.9, 0, temp)) AS temperature, MIN(IF (temp=9999.9, 0, min)) AS temperature_min, MAX(IF (temp=9999.9, 0, max)) AS temperature_max, AVG(IF (visib=999.9, 0, visib)) AS visibility, AVG(IF (gust=999.9, 0, gust)) AS wind_gust, AVG(IF (wdsp=\"999.9\", 0, CAST(wdsp AS Float64))) AS wind_speed, AVG(IF (prcp=99.99, 0, prcp)) AS precipitation, AVG(IF (sndp=999.9, 0, sndp)) AS snow_depthFROM `bigquery-public-data.noaa_gsod.gsod20*`WHERE CAST(YEAR AS INT64) > 2008 AND (stn=\"726060\") GROUP BY dateORDER BY date"
},
{
"code": null,
"e": 6468,
"s": 6426,
"text": "This query will process 5.19 GB when run."
},
{
"code": null,
"e": 6569,
"s": 6468,
"text": "This query will return daily weather from one station in city Portland, Maine for the last 10 years."
},
{
"code": null,
"e": 6671,
"s": 6569,
"text": "At first I would like to visualise important information, to make it clear what kind of data we have."
},
{
"code": null,
"e": 6931,
"s": 6671,
"text": "I will use data from the city of Portland, Maine to plot the locations of weather Stations, using GeoPandas library. The first step is to find and download a shape-file(.shp file). I already showed how to get Stations near Portland using NOAA API(portland_st)"
},
{
"code": null,
"e": 7349,
"s": 6931,
"text": "highway_map = gpd.read_file('./maine_highway/maine_highway.shp')crs = {'init': 'epsg:4326'}point = [Point(xy) for xy in zip(portland_st['longitude'], portland_st['latitude'])]geo_stations = gpd.GeoDataFrame(portland_st, crs=crs, geometry=point)fig, ax = plt.subplots(figsize=(5, 5))highway_map.plot(ax=ax, alpha=0.4, color='grey')geo_stations.plot(ax=ax, color='red', marker='o')plt.legend(prop={'size': 5})plt.show()"
},
{
"code": null,
"e": 7635,
"s": 7349,
"text": "I found the shape-file (‘maine_highway.shp’) that shows main roads in Portland and combine it with the Stations location. Red dots are the locations of the weather stations. Now it’s obvious which station is needed for the feature model. It is an easy way to visualise geospatial data."
},
{
"code": null,
"e": 7734,
"s": 7635,
"text": "The goal of time series analysis is to find patterns in the data and use the data for predictions."
},
{
"code": null,
"e": 7858,
"s": 7734,
"text": "It is also useful to explore relationships between time series. Let’s look at subplots with all features for the year 2017:"
},
{
"code": null,
"e": 7957,
"s": 7858,
"text": "For sure we want to look at the series that is going to be forecast. I did it using iplot library."
},
{
"code": null,
"e": 8154,
"s": 7957,
"text": "df[['temperature', 'temperature_min']].iplot( mode='lines+markers', opacity=0.8, size=8, symbol=1, xTitle='Time', yTitle='Temperature', title='Temperature over last 10 years')"
},
{
"code": null,
"e": 8279,
"s": 8154,
"text": "Just for curiosity’s sake I can illustrate line plot that shows avg/min/max temperature at New Year’s for the last 10 years:"
},
{
"code": null,
"e": 8653,
"s": 8279,
"text": "sns.set(rc={'figure.figsize': (14.7, 8.27)})g = sns.lineplot(data=newyear.temperature_max, palette=\"tab10\", linewidth=2.5, label=\"max\")g = sns.lineplot(data=newyear.temperature_min, palette=\"tab10\", linewidth=2.5, label=\"min\")g = sns.lineplot(data=newyear.temperature, palette=\"tab10\", linewidth=2.5, label=\"avg\")g.tick_params(labelsize=10)plt.xticks(rotation=45)plt.show()"
},
{
"code": null,
"e": 8840,
"s": 8653,
"text": "Temperature during the period from 27.12 till 03.01 for 10 years. In case someone would need historical statistics from the past years only for a defined period, let say New Year’s week."
},
{
"code": null,
"e": 8987,
"s": 8840,
"text": "If the main purpose is only to prepare data and select a model. The right solution would be to plot four graphs when looking at particular series."
},
{
"code": null,
"e": 9239,
"s": 8987,
"text": "As well as looking at the time plot of the data, the ACF plot is also useful for identifying non-stationary time series. For a stationary time series, the ACF will drop to zero relatively quickly, while the ACF of non-stationary data decreases slowly."
},
{
"code": null,
"e": 9876,
"s": 9239,
"text": "def tsplot(y, title, lags=None, figsize=(10, 6)): fig = plt.figure(figsize=figsize) layout = (2, 2) ts_ax = plt.subplot2grid(layout, (0, 0)) hist_ax = plt.subplot2grid(layout, (0, 1)) acf_ax = plt.subplot2grid(layout, (1, 0)) pacf_ax = plt.subplot2grid(layout, (1, 1)) y.plot(ax=ts_ax) ts_ax.set_title(title, fontsize=12, fontweight='bold') y.plot(ax=hist_ax, kind='hist', bins=25) hist_ax.set_title('Histogram') sm.tsa.graphics.plot_acf(y, lags=lags, ax=acf_ax) sm.tsa.graphics.plot_pacf(y, lags=lags, ax=pacf_ax) sns.despine() plt.tight_layout() plt.show() return ts_ax, acf_ax, pacf_ax"
},
{
"code": null,
"e": 10055,
"s": 9876,
"text": "In a series of daily temperatures, the mean temperature is not constant, since it varies by day, but for the same month in different years we can expect a constant average value."
},
{
"code": null,
"e": 10239,
"s": 10055,
"text": "The seasonal period, s, defines the number of observations that make up a seasonal cycle. For example, s = 12 for monthly series, s = 4 for quarterly series, s = 365 for daily series."
},
{
"code": null,
"e": 10609,
"s": 10239,
"text": "However, this may not be precisely true: for example, if we have daily data and the seasonal period is the length of the month, s will be approximately 30, but it will vary from month to month. And the trickiest thing is, there may be more than one type of seasonality. For example, with daily data we can have monthly seasonality, with s = 30 and yearly, with s = 365."
},
{
"code": null,
"e": 10778,
"s": 10609,
"text": "Daily data are challenging for a different reason — they often involve multiple seasonal patterns, and so we need to use a method that handles such complex seasonality."
},
{
"code": null,
"e": 10908,
"s": 10778,
"text": "Time Series data might also have other patterns, such as trends or cyclic. And all of this shows that the data is not stationary."
},
{
"code": null,
"e": 11184,
"s": 10908,
"text": "To use statistical model such as the VAR model we should take care of these patterns before the data can be fit into the model. For the VAR model you need stationary condition to be performed. Put enough structure into the model to identify some of the parameters in a model."
},
{
"code": null,
"e": 11575,
"s": 11184,
"text": "Applying seasonal differencing to the log of the series should make the above series stationary. It is quite challenging to define parameters for climate data, that are a lot of publications about this topic. I will not dig deep inside and choose just simple parameters lag=365 and diff=1. More information about parameters you can find in Trend analysis of climate time series publication."
},
{
"code": null,
"e": 11814,
"s": 11575,
"text": "A stationary time series is one whose properties do not depend on the time at which the series is observed. Time series with seasonality, are not stationary, because seasonality will affect the value of the time series at different times."
},
{
"code": null,
"e": 11953,
"s": 11814,
"text": "transformed = df.copy()transformed['temperature'] = np.log(df.iloc[:, 0]).diff(1)transformed['wind_speed'] = np.log(df.iloc[:, 1]).diff(1)"
},
{
"code": null,
"e": 12014,
"s": 11953,
"text": "The purpose of transformation is make the series stationary."
},
{
"code": null,
"e": 12050,
"s": 12014,
"text": "The next step is to split the data."
},
{
"code": null,
"e": 12448,
"s": 12050,
"text": "Split the samples into training/testing and validation set. It needs to be split carefully regarding the dependency structure. The approach that can mostly fit to this case is a rolling window. But in this particular example I will just leave a few observations at the end to validate my model. I want to forecast 7 days. Later to check the performance of the model I will use these 7 true values."
},
{
"code": null,
"e": 12602,
"s": 12448,
"text": "This kind of model required the series to be stationary, if the series are not stationary, the individual series have to be transformed to be stationary."
},
{
"code": null,
"e": 12673,
"s": 12602,
"text": "A VAR(p) in two variables can be written in matrix form (where p=1) as"
},
{
"code": null,
"e": 12801,
"s": 12673,
"text": "model = sm.tsa.VARMAX(y_train, order=(5, 0), trend='c')model_result = model.fit(maxiter=1000, disp=False)model_result.summary()"
},
{
"code": null,
"e": 13071,
"s": 12801,
"text": "The way to select an order is to use information criteria AIC, BIC, HQIC. Estimate a range of models and choose the best one. The most common approach for model order selection involves minimizing one or more information criteria evaluated over a range of model orders."
},
{
"code": null,
"e": 13335,
"s": 13071,
"text": "for i in range(5): i += 1 model = sm.tsa.VARMAX(y_train, order=(i,0)) model_result = model.fit(maxiter=1000, disp=False) print('Order = ', i) print('AIC: ', model_result.aic) print('BIC: ', model_result.bic) print('HQIC: ', model_result.hqic)"
},
{
"code": null,
"e": 13575,
"s": 13335,
"text": "more details about how to choose right order you can find in the book New Introduction to Multiple Time Series Analysis by Lütkepohl, Helmut (chapter 4). In this particular example I will use p = 5, where AIC criteria reach their minimum."
},
{
"code": null,
"e": 13872,
"s": 13575,
"text": "The next step is the model diagnostic and checking that underlying assumption is true. The VARMAX class in Statsmodels allows estimation of VAR, VMA, and VARMA models (through the order argument) The VARMAX procedure is a well-established and powerful tool for analysing multivariate time series."
},
{
"code": null,
"e": 14008,
"s": 13872,
"text": "model = sm.tsa.VARMAX(y_train, order=(5, 0))model_result = model.fit(maxiter=1000, disp=False)model_result.plot_diagnostics()plt.show()"
},
{
"code": null,
"e": 14127,
"s": 14008,
"text": "A common overall diagnostic is the plot of the residuals and to see whether the residuals obey the models assumptions."
},
{
"code": null,
"e": 14162,
"s": 14127,
"text": "It can be possible to apply tests:"
},
{
"code": null,
"e": 14247,
"s": 14162,
"text": "tests to confirm normalityabsence of serial correlationabsence of heteroscedasticity"
},
{
"code": null,
"e": 14274,
"s": 14247,
"text": "tests to confirm normality"
},
{
"code": null,
"e": 14304,
"s": 14274,
"text": "absence of serial correlation"
},
{
"code": null,
"e": 14334,
"s": 14304,
"text": "absence of heteroscedasticity"
},
{
"code": null,
"e": 14483,
"s": 14334,
"text": "The two series do not exhibit trends or regular seasonal patterns. Therefore we assume that they are the realisation of a stationary VAR(p) process."
},
{
"code": null,
"e": 14596,
"s": 14483,
"text": "To recap: We transformed temperature and wind speed with the following equation, where yt is an original series:"
},
{
"code": null,
"e": 14768,
"s": 14596,
"text": "This means that it should be transformed back to define and estimate real results with predicted. For this purpose we calculate the equation and apply to predicted values:"
},
{
"code": null,
"e": 14803,
"s": 14768,
"text": "z = model_result.forecast(steps=7)"
},
{
"code": null,
"e": 14840,
"s": 14803,
"text": "Transform values and print a result:"
},
{
"code": null,
"e": 14894,
"s": 14840,
"text": "pd.concat([df['temperature'][-7:], forecast], axis=1)"
},
{
"code": null,
"e": 14924,
"s": 14894,
"text": "Calculate Mean Squared Error:"
},
{
"code": null,
"e": 15001,
"s": 14924,
"text": "rmse = sqrt(mean_squared_error(df['temperature'][-7:], forecast))RMSE: 4.200"
},
{
"code": null,
"e": 15312,
"s": 15001,
"text": "Conclusion: Time Series data can be very tricky to deal with correctly. You need to properly explore your data to understand it, be aware of any seasonality or other patterns. It is not always possible to use the same approach. In general is best to start with simple models and build your analysis from there."
},
{
"code": null,
"e": 15582,
"s": 15312,
"text": "AM207: Pavlos Protopapas, Harvard UniversityForecasting: Principles and Practice, Rob J Hyndman and George AthanasopoulosJeffrey Yau, PyData Conference 2017New Introduction to Multiple Time Series Analysis by Lütkepohl, HelmutGoogle BigQuery to explore weather effects"
},
{
"code": null,
"e": 15627,
"s": 15582,
"text": "AM207: Pavlos Protopapas, Harvard University"
},
{
"code": null,
"e": 15705,
"s": 15627,
"text": "Forecasting: Principles and Practice, Rob J Hyndman and George Athanasopoulos"
},
{
"code": null,
"e": 15741,
"s": 15705,
"text": "Jeffrey Yau, PyData Conference 2017"
},
{
"code": null,
"e": 15813,
"s": 15741,
"text": "New Introduction to Multiple Time Series Analysis by Lütkepohl, Helmut"
}
] |
HDF5 files in Python - GeeksforGeeks
|
28 Jun, 2021
HDF5 file stands for Hierarchical Data Format 5. It is an open-source file which comes in handy to store large amount of data. As the name suggests, it stores data in a hierarchical structure within a single file. So if we want to quickly access a particular part of the file rather than the whole file, we can easily do that using HDF5. This functionality is not seen in normal text files hence HDF5 is becoming seemingly popular in fact of being a new concept. To use HDF5, numpy needs to be imported. One important feature is that it can attach metaset to every data in the file thus provides powerful searching and accessing. Let’s get started with installing HDF5 to the computer.To install HDF5, type this in your terminal:
pip install h5py
We will use a special tool called HDF5 Viewer to view these files graphically and to work on them. To install HDF5 Viewer, type this code :
pip install h5pyViewer
As HDF5 works on numpy, we would need numpy installed in our machine too.
python -m pip install numpy
After all the installations are done, let’s see how can we write into an HDF5 file.Note: Working with HDF5 requires basic understanding of numpy and its attributes, so one must be familiar with numpy in order to understand the codes following in this article. To know more about numpy click here.We will create a file and save a random array of numpy in it:
Python3
# Python program to demonstrate# HDF5 file import numpy as npimport h5py # initializing a random numpy arrayarr = np.random.randn(1000) # creating a filewith h5py.File('test.hdf5', 'w') as f: dset = f.create_dataset("default", data = arr)
Output:
In the above code, we first import the modules which were installed previously. Then we initialize the variable arr to a random array of numpy ranging till 1000. Hence, we can say that this array consists of a large number of data. Next, we open the file as “write only” attribute. This means that if there isn’t any file with the name test.hdf5 then it will create one otherwise it will delete (overwrite) the content of the existing file. While opening the file, we used with instead of open as it has an upper-hand when compared to open() method. We don’t need to close a file if we open it using with Finally, we use the .create_dataset() to set the variable dset to the array which was created earlier.We will now read the file which we wrote above:
Python3
# open the file as 'f'with h5py.File('test.hdf5', 'r') as f: data = f['default'] # get the minimum value print(min(data)) # get the maximum value print(max(data)) # get the values ranging from index 0 to 15 print(data[:15])
Output:
Here, we open the file again but this time we open it by “read-only” attribute so that no changes can be made to the file. We set the variable data to the data we stored in the previous file. Let’s look at the output:It may seem that there’s nothing new. It is just an array and we are printing out the numbers just as in an array. But, the variable data is not an array. It’s actually very different than array. It’s a dataset. Rather than storing data in the RAM, it saves it in hard-drive of the computer, thus maintaining a hierarchy of structures just like directories:
When the below line is used
data = f['default']
in the previous code, we did not access the content of the file directly but created a pointer to point at our content. Let’s look at an advantage of this:
Python3
import numpy as npimport h5py arr1 = np.random.randn(10000)arr2 = np.random.randn(10000) with h5py.File('test_read.hdf5', 'w') as f: f.create_dataset('array_1', data = arr1) f.create_dataset('array_2', data = arr2)
We created two datasets but the whole procedure is same as before. A file named “test_read.hdf5” is created using the “w” attribute and it contains two datasets (array1 and array2) of random numbers. Now suppose we want to read only a selective portion of array2. For example, we want to read that part of array2 corresponding to where values of array1 are greater than 1. If we were using the conventional text files instead of HDF5 files, it would be nearly impossible to achieve this. That’s exactly were we see the power of HDF5 files:
Python3
with h5py.File('test_read.hdf5', 'r') as f: d1 = f['array_1'] d2 = f['array_2'] data = d2[d1[:]>1]
We use the [:] to create a copy of the dataset d1 into the RAM. We did this because a dataset (the data in hard-drive) cannot be compared to the integers. Output:
So, we conclude that HDF5 files are our best tools when we are dealing with large files as it allows us selective reading and writing of files which otherwise would have consumed a lot of memory and time.
adnanirshad158
python-file-handling
python-modules
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
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25023,
"s": 24292,
"text": "HDF5 file stands for Hierarchical Data Format 5. It is an open-source file which comes in handy to store large amount of data. As the name suggests, it stores data in a hierarchical structure within a single file. So if we want to quickly access a particular part of the file rather than the whole file, we can easily do that using HDF5. This functionality is not seen in normal text files hence HDF5 is becoming seemingly popular in fact of being a new concept. To use HDF5, numpy needs to be imported. One important feature is that it can attach metaset to every data in the file thus provides powerful searching and accessing. Let’s get started with installing HDF5 to the computer.To install HDF5, type this in your terminal: "
},
{
"code": null,
"e": 25040,
"s": 25023,
"text": "pip install h5py"
},
{
"code": null,
"e": 25181,
"s": 25040,
"text": "We will use a special tool called HDF5 Viewer to view these files graphically and to work on them. To install HDF5 Viewer, type this code : "
},
{
"code": null,
"e": 25204,
"s": 25181,
"text": "pip install h5pyViewer"
},
{
"code": null,
"e": 25279,
"s": 25204,
"text": "As HDF5 works on numpy, we would need numpy installed in our machine too. "
},
{
"code": null,
"e": 25307,
"s": 25279,
"text": "python -m pip install numpy"
},
{
"code": null,
"e": 25667,
"s": 25307,
"text": "After all the installations are done, let’s see how can we write into an HDF5 file.Note: Working with HDF5 requires basic understanding of numpy and its attributes, so one must be familiar with numpy in order to understand the codes following in this article. To know more about numpy click here.We will create a file and save a random array of numpy in it: "
},
{
"code": null,
"e": 25675,
"s": 25667,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# HDF5 file import numpy as npimport h5py # initializing a random numpy arrayarr = np.random.randn(1000) # creating a filewith h5py.File('test.hdf5', 'w') as f: dset = f.create_dataset(\"default\", data = arr)",
"e": 25917,
"s": 25675,
"text": null
},
{
"code": null,
"e": 25926,
"s": 25917,
"text": "Output: "
},
{
"code": null,
"e": 26682,
"s": 25926,
"text": "In the above code, we first import the modules which were installed previously. Then we initialize the variable arr to a random array of numpy ranging till 1000. Hence, we can say that this array consists of a large number of data. Next, we open the file as “write only” attribute. This means that if there isn’t any file with the name test.hdf5 then it will create one otherwise it will delete (overwrite) the content of the existing file. While opening the file, we used with instead of open as it has an upper-hand when compared to open() method. We don’t need to close a file if we open it using with Finally, we use the .create_dataset() to set the variable dset to the array which was created earlier.We will now read the file which we wrote above: "
},
{
"code": null,
"e": 26690,
"s": 26682,
"text": "Python3"
},
{
"code": "# open the file as 'f'with h5py.File('test.hdf5', 'r') as f: data = f['default'] # get the minimum value print(min(data)) # get the maximum value print(max(data)) # get the values ranging from index 0 to 15 print(data[:15]) ",
"e": 26954,
"s": 26690,
"text": null
},
{
"code": null,
"e": 26963,
"s": 26954,
"text": "Output: "
},
{
"code": null,
"e": 27539,
"s": 26963,
"text": "Here, we open the file again but this time we open it by “read-only” attribute so that no changes can be made to the file. We set the variable data to the data we stored in the previous file. Let’s look at the output:It may seem that there’s nothing new. It is just an array and we are printing out the numbers just as in an array. But, the variable data is not an array. It’s actually very different than array. It’s a dataset. Rather than storing data in the RAM, it saves it in hard-drive of the computer, thus maintaining a hierarchy of structures just like directories: "
},
{
"code": null,
"e": 27569,
"s": 27539,
"text": "When the below line is used "
},
{
"code": null,
"e": 27589,
"s": 27569,
"text": "data = f['default']"
},
{
"code": null,
"e": 27746,
"s": 27589,
"text": "in the previous code, we did not access the content of the file directly but created a pointer to point at our content. Let’s look at an advantage of this: "
},
{
"code": null,
"e": 27754,
"s": 27746,
"text": "Python3"
},
{
"code": "import numpy as npimport h5py arr1 = np.random.randn(10000)arr2 = np.random.randn(10000) with h5py.File('test_read.hdf5', 'w') as f: f.create_dataset('array_1', data = arr1) f.create_dataset('array_2', data = arr2)",
"e": 27976,
"s": 27754,
"text": null
},
{
"code": null,
"e": 28517,
"s": 27976,
"text": "We created two datasets but the whole procedure is same as before. A file named “test_read.hdf5” is created using the “w” attribute and it contains two datasets (array1 and array2) of random numbers. Now suppose we want to read only a selective portion of array2. For example, we want to read that part of array2 corresponding to where values of array1 are greater than 1. If we were using the conventional text files instead of HDF5 files, it would be nearly impossible to achieve this. That’s exactly were we see the power of HDF5 files: "
},
{
"code": null,
"e": 28525,
"s": 28517,
"text": "Python3"
},
{
"code": "with h5py.File('test_read.hdf5', 'r') as f: d1 = f['array_1'] d2 = f['array_2'] data = d2[d1[:]>1]",
"e": 28634,
"s": 28525,
"text": null
},
{
"code": null,
"e": 28798,
"s": 28634,
"text": "We use the [:] to create a copy of the dataset d1 into the RAM. We did this because a dataset (the data in hard-drive) cannot be compared to the integers. Output: "
},
{
"code": null,
"e": 29004,
"s": 28798,
"text": "So, we conclude that HDF5 files are our best tools when we are dealing with large files as it allows us selective reading and writing of files which otherwise would have consumed a lot of memory and time. "
},
{
"code": null,
"e": 29021,
"s": 29006,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29042,
"s": 29021,
"text": "python-file-handling"
},
{
"code": null,
"e": 29057,
"s": 29042,
"text": "python-modules"
},
{
"code": null,
"e": 29064,
"s": 29057,
"text": "Python"
},
{
"code": null,
"e": 29162,
"s": 29064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29171,
"s": 29162,
"text": "Comments"
},
{
"code": null,
"e": 29184,
"s": 29171,
"text": "Old Comments"
},
{
"code": null,
"e": 29216,
"s": 29184,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29272,
"s": 29216,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29327,
"s": 29272,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29369,
"s": 29327,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29411,
"s": 29369,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29442,
"s": 29411,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29481,
"s": 29442,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29510,
"s": 29481,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29532,
"s": 29510,
"text": "Defaultdict in Python"
}
] |
Add Legend to Plot in R - GeeksforGeeks
|
16 May, 2021
Legends are useful to add more information to the plots and enhance the user readability. It involves the creation of titles, indexes, placement of plot boxes in order to create a better understanding of the graphs plotted. The in-built R function legend() can be used to add legend to plot.
Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
Parameters:
x and y: These are co-ordinates to be used to position the legend
legend: Text of the legend
fill: Colors to use for filling the boxes of legend text
col: Colors of lines
bg: It defines background color for the legend box.
title: Legend title (optional)
text.font: An integer specifying the font style of the legend (optional)
Returns: Legend plot
After normally visualizing our plot, to add legend to it only appropriate arguments with required values are to be given to the legend() function.
Example:
R
# declaring the data to plotx<-1:10y=x^1/2z= x^2 # plotting x and y coordinate # line plot(x, y, col="blue") # adding another line on the# coordinates involving y and zlines(z, y ,col="red") # Adding a legend to the graph# defining the lines legend(2, 4, legend=c("Equation 1", "Equation 2"), fill = c("blue","red"))
Output
The legend box in the graph can be customized to suit the requirements in order to convey more information and add aesthetics to the graph at the same time. Given below are properties of legends basing which they can be customized:
title: The title of the legend box that can be declared to understand what the index of the indicates
position : Indicator of the placement of the legend box ; which can have the possible options : “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”
bty (Default : o) : The type of box to enclose the legend . Different types of letters can be used, where the box shape is equivalent to the letter shape. For instance, “n” can be used for no box.
bg: A background colour can be assigned to the legend box
box.lwd : Indicator of the line width of the legend box
box.lty : Indicator of the line type of the legend box
box.col : Indicator of the line color of the legend box
When appropriate values are applied to these properties, and they are then passed to the legend() function the required customization is achieved.
Example:
R
# declaring the data to plotx<-1:10y=x^1/2z= x^2 # plotting x and y coordinate line plot(x, y, col="blue") # adding another line on the # coordinates involving y and zlines(z, y ,col="red") # Adding a legend to the graph# defining the lines legend(x = "topleft", box.col = "brown", bg ="yellow", box.lwd = 2 , title="EQUATIONS", legend=c("Equation 1", "Equation 2"), fill = c("blue","red"))
Output
The text of the legend function can also be customized for better styling using the following properties:
text.font: A numerical value which is an indicator of the font style of the legend text. It has the following values :(1 – normal 2- bold, 3 – italic, 4 – bold and italic)
text.col : Which is used to indicate the color of the text used to write legend text
border (Default : black) : Indicator of the border color of the boxes inside the legend box
fill_color : colors used for filling boxes
Example:
R
# declaring the data to plotx<-20:1y=xz= x*(1/4) # plotting x and y coordinate line plot(x, y, lty = 4,col="blue") # adding another line on the # coordinates involving y and zlines(y, z ,lty = 6,col="orange") # Adding a legend to the graph# defining the lines legend(x = "topleft", lty = c(4,6), text.font = 4, col= c("blue","orange"),text.col = "blue", legend=c("Equation 1", "Equation 2"))
Output
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
|
[
{
"code": null,
"e": 25046,
"s": 25018,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 25339,
"s": 25046,
"text": "Legends are useful to add more information to the plots and enhance the user readability. It involves the creation of titles, indexes, placement of plot boxes in order to create a better understanding of the graphs plotted. The in-built R function legend() can be used to add legend to plot. "
},
{
"code": null,
"e": 25415,
"s": 25339,
"text": "Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)"
},
{
"code": null,
"e": 25427,
"s": 25415,
"text": "Parameters:"
},
{
"code": null,
"e": 25493,
"s": 25427,
"text": "x and y: These are co-ordinates to be used to position the legend"
},
{
"code": null,
"e": 25520,
"s": 25493,
"text": "legend: Text of the legend"
},
{
"code": null,
"e": 25577,
"s": 25520,
"text": "fill: Colors to use for filling the boxes of legend text"
},
{
"code": null,
"e": 25598,
"s": 25577,
"text": "col: Colors of lines"
},
{
"code": null,
"e": 25650,
"s": 25598,
"text": "bg: It defines background color for the legend box."
},
{
"code": null,
"e": 25688,
"s": 25650,
"text": "title: Legend title (optional)"
},
{
"code": null,
"e": 25761,
"s": 25688,
"text": "text.font: An integer specifying the font style of the legend (optional)"
},
{
"code": null,
"e": 25782,
"s": 25761,
"text": "Returns: Legend plot"
},
{
"code": null,
"e": 25930,
"s": 25782,
"text": "After normally visualizing our plot, to add legend to it only appropriate arguments with required values are to be given to the legend() function. "
},
{
"code": null,
"e": 25939,
"s": 25930,
"text": "Example:"
},
{
"code": null,
"e": 25941,
"s": 25939,
"text": "R"
},
{
"code": "# declaring the data to plotx<-1:10y=x^1/2z= x^2 # plotting x and y coordinate # line plot(x, y, col=\"blue\") # adding another line on the# coordinates involving y and zlines(z, y ,col=\"red\") # Adding a legend to the graph# defining the lines legend(2, 4, legend=c(\"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"))",
"e": 26268,
"s": 25941,
"text": null
},
{
"code": null,
"e": 26275,
"s": 26268,
"text": "Output"
},
{
"code": null,
"e": 26507,
"s": 26275,
"text": "The legend box in the graph can be customized to suit the requirements in order to convey more information and add aesthetics to the graph at the same time. Given below are properties of legends basing which they can be customized:"
},
{
"code": null,
"e": 26609,
"s": 26507,
"text": "title: The title of the legend box that can be declared to understand what the index of the indicates"
},
{
"code": null,
"e": 26804,
"s": 26609,
"text": "position : Indicator of the placement of the legend box ; which can have the possible options : “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”"
},
{
"code": null,
"e": 27001,
"s": 26804,
"text": "bty (Default : o) : The type of box to enclose the legend . Different types of letters can be used, where the box shape is equivalent to the letter shape. For instance, “n” can be used for no box."
},
{
"code": null,
"e": 27059,
"s": 27001,
"text": "bg: A background colour can be assigned to the legend box"
},
{
"code": null,
"e": 27115,
"s": 27059,
"text": "box.lwd : Indicator of the line width of the legend box"
},
{
"code": null,
"e": 27170,
"s": 27115,
"text": "box.lty : Indicator of the line type of the legend box"
},
{
"code": null,
"e": 27226,
"s": 27170,
"text": "box.col : Indicator of the line color of the legend box"
},
{
"code": null,
"e": 27373,
"s": 27226,
"text": "When appropriate values are applied to these properties, and they are then passed to the legend() function the required customization is achieved."
},
{
"code": null,
"e": 27382,
"s": 27373,
"text": "Example:"
},
{
"code": null,
"e": 27384,
"s": 27382,
"text": "R"
},
{
"code": "# declaring the data to plotx<-1:10y=x^1/2z= x^2 # plotting x and y coordinate line plot(x, y, col=\"blue\") # adding another line on the # coordinates involving y and zlines(z, y ,col=\"red\") # Adding a legend to the graph# defining the lines legend(x = \"topleft\", box.col = \"brown\", bg =\"yellow\", box.lwd = 2 , title=\"EQUATIONS\", legend=c(\"Equation 1\", \"Equation 2\"), fill = c(\"blue\",\"red\"))",
"e": 27798,
"s": 27384,
"text": null
},
{
"code": null,
"e": 27805,
"s": 27798,
"text": "Output"
},
{
"code": null,
"e": 27911,
"s": 27805,
"text": "The text of the legend function can also be customized for better styling using the following properties:"
},
{
"code": null,
"e": 28083,
"s": 27911,
"text": "text.font: A numerical value which is an indicator of the font style of the legend text. It has the following values :(1 – normal 2- bold, 3 – italic, 4 – bold and italic)"
},
{
"code": null,
"e": 28168,
"s": 28083,
"text": "text.col : Which is used to indicate the color of the text used to write legend text"
},
{
"code": null,
"e": 28260,
"s": 28168,
"text": "border (Default : black) : Indicator of the border color of the boxes inside the legend box"
},
{
"code": null,
"e": 28303,
"s": 28260,
"text": "fill_color : colors used for filling boxes"
},
{
"code": null,
"e": 28312,
"s": 28303,
"text": "Example:"
},
{
"code": null,
"e": 28314,
"s": 28312,
"text": "R"
},
{
"code": "# declaring the data to plotx<-20:1y=xz= x*(1/4) # plotting x and y coordinate line plot(x, y, lty = 4,col=\"blue\") # adding another line on the # coordinates involving y and zlines(y, z ,lty = 6,col=\"orange\") # Adding a legend to the graph# defining the lines legend(x = \"topleft\", lty = c(4,6), text.font = 4, col= c(\"blue\",\"orange\"),text.col = \"blue\", legend=c(\"Equation 1\", \"Equation 2\"))",
"e": 28723,
"s": 28314,
"text": null
},
{
"code": null,
"e": 28730,
"s": 28723,
"text": "Output"
},
{
"code": null,
"e": 28737,
"s": 28730,
"text": "Picked"
},
{
"code": null,
"e": 28746,
"s": 28737,
"text": "R-Charts"
},
{
"code": null,
"e": 28755,
"s": 28746,
"text": "R-Graphs"
},
{
"code": null,
"e": 28763,
"s": 28755,
"text": "R-plots"
},
{
"code": null,
"e": 28774,
"s": 28763,
"text": "R Language"
},
{
"code": null,
"e": 28872,
"s": 28774,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28924,
"s": 28872,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28962,
"s": 28924,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28997,
"s": 28962,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29033,
"s": 28997,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 29091,
"s": 29033,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29140,
"s": 29091,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29177,
"s": 29140,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29203,
"s": 29177,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29253,
"s": 29203,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
MongoDB aggregation group and remove duplicate array values?
|
Use MongoDB aggregate for this and within that, use $group. Let us create a collection with documents −
> db.demo649.insertOne(
... { "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo649.insertOne({ "_id" :102, "Names" : [ "John", "Robert" ], "CountryName" : "UK"});
{ "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo649.find();
This will produce the following output −
{ "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" }
{ "_id" : 102, "Names" : [ "John", "Robert" ], "CountryName" : "UK" }
Following is the query for aggregation group −
> db.demo649.aggregate(
... { $unwind : "$Names"},
... { $group : { _id : "$_id" , Names : { $addToSet : "$Names" } ,
... CountryName : { $first : "$CountryName" }}}
... )
This will produce the following output −
{ "_id" : 102, "Names" : [ "Robert", "John" ], "CountryName" : "UK" }
{ "_id" : 101, "Names" : [ "Robert", "Bob", "John" ], "CountryName" : "US" }
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Use MongoDB aggregate for this and within that, use $group. Let us create a collection with documents −"
},
{
"code": null,
"e": 1475,
"s": 1166,
"text": "> db.demo649.insertOne(\n... { \"_id\" : 101, \"Names\" : [ \"John\", \"Bob\", \"Bob\", \"Robert\" ], \"CountryName\" : \"US\" }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 101 }\n>\n> db.demo649.insertOne({ \"_id\" :102, \"Names\" : [ \"John\", \"Robert\" ], \"CountryName\" : \"UK\"});\n{ \"acknowledged\" : true, \"insertedId\" : 102 }"
},
{
"code": null,
"e": 1548,
"s": 1475,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1569,
"s": 1548,
"text": "> db.demo649.find();"
},
{
"code": null,
"e": 1610,
"s": 1569,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1764,
"s": 1610,
"text": "{ \"_id\" : 101, \"Names\" : [ \"John\", \"Bob\", \"Bob\", \"Robert\" ], \"CountryName\" : \"US\" }\n{ \"_id\" : 102, \"Names\" : [ \"John\", \"Robert\" ], \"CountryName\" : \"UK\" }"
},
{
"code": null,
"e": 1811,
"s": 1764,
"text": "Following is the query for aggregation group −"
},
{
"code": null,
"e": 1992,
"s": 1811,
"text": "> db.demo649.aggregate(\n... { $unwind : \"$Names\"},\n... { $group : { _id : \"$_id\" , Names : { $addToSet : \"$Names\" } ,\n... CountryName : { $first : \"$CountryName\" }}}\n... )"
},
{
"code": null,
"e": 2033,
"s": 1992,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2180,
"s": 2033,
"text": "{ \"_id\" : 102, \"Names\" : [ \"Robert\", \"John\" ], \"CountryName\" : \"UK\" }\n{ \"_id\" : 101, \"Names\" : [ \"Robert\", \"Bob\", \"John\" ], \"CountryName\" : \"US\" }"
}
] |
Select specific rows in a range with MySQL?
|
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(20)
);
Query OK, 0 rows affected (1.23 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Adam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+-------------+
| Id | StudentName |
+----+-------------+
| 1 | John |
| 2 | Carol |
| 3 | David |
| 4 | Bob |
| 5 | Chris |
| 6 | Robert |
| 7 | Adam |
| 8 | Mike |
| 9 | Sam |
+----+-------------+
9 rows in set (0.00 sec)
Here is the query to select specific rows MySQL −
mysql> select *from DemoTable ORDER BY Id DESC LIMIT 4 OFFSET 2;
+----+-------------+
| Id | StudentName |
+----+-------------+
| 7 | Adam |
| 6 | Robert |
| 5 | Chris |
| 4 | Bob |
+----+-------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1244,
"s": 1092,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(20)\n );\nQuery OK, 0 rows affected (1.23 sec)"
},
{
"code": null,
"e": 1300,
"s": 1244,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2149,
"s": 1300,
"text": "mysql> insert into DemoTable(StudentName) values('John');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable(StudentName) values('Carol');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(StudentName) values('David');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable(StudentName) values('Bob');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentName) values('Chris');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentName) values('Robert');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentName) values('Adam');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable(StudentName) values('Mike');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(StudentName) values('Sam');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2209,
"s": 2149,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2240,
"s": 2209,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2538,
"s": 2240,
"text": "+----+-------------+\n| Id | StudentName |\n+----+-------------+\n| 1 | John |\n| 2 | Carol |\n| 3 | David |\n| 4 | Bob |\n| 5 | Chris |\n| 6 | Robert |\n| 7 | Adam |\n| 8 | Mike |\n| 9 | Sam |\n+----+-------------+\n9 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2588,
"s": 2538,
"text": "Here is the query to select specific rows MySQL −"
},
{
"code": null,
"e": 2653,
"s": 2588,
"text": "mysql> select *from DemoTable ORDER BY Id DESC LIMIT 4 OFFSET 2;"
},
{
"code": null,
"e": 2846,
"s": 2653,
"text": "+----+-------------+\n| Id | StudentName |\n+----+-------------+\n| 7 | Adam |\n| 6 | Robert |\n| 5 | Chris |\n| 4 | Bob |\n+----+-------------+\n4 rows in set (0.00 sec)"
}
] |
How to create a command-line progress bar in C/C++ - GeeksforGeeks
|
19 Jul, 2020
The task is to write a C/C++ program to draw a command-line progress bar.
Approach: To create a progress bar the idea is to use system() function which will give colored output. Below is the illustration of how to use system() function.
The system function accepts the following parameters for colouring the output screen:
keyword: colorBackground colorForeground color
keyword: color
Background color
Foreground color
Color Codes:
Syntax:
system(“color 9F”); The above code will give White Color output with Bright Blue color on Background.
Below is the program to draw the progress bar in the command line in C/C++:
C
C++
// C program to create loading bar#include <stdio.h>#include <windows.h> // Function to creating loading barvoid loadingBar(){ // 0 - black background, // A - Green Foreground system("color 0A"); // Initialize char for printing // loading bar char a = 177, b = 219; printf("\n\n\n\n"); printf("\n\n\n\n\t\t\t\t\t" + "Loading...\n\n"); printf("\t\t\t\t\t"); // Print initial loading bar for (int i = 0; i < 26; i++) printf("%c", a); // Set the cursor again starting // point of loading bar printf("\r"); printf("\t\t\t\t\t"); // Print loading bar progress for (int i = 0; i < 26; i++) { printf("%c", b); // Sleep for 1 second Sleep(1000); }} // Driver Codeint main(){ // Function Call loadingBar(); return 0;}
// C++ program to create loading bar#include <iostream>#include <windows.h>using namespace std; // Function to creating loading barvoid loadingBar(){ // 0 - black background, // A - Green Foreground system("color 0A"); // Initialize char for printing // loading bar char a = 177, b = 219; printf("\n\n\n\n"); printf("\n\n\n\n\t\t\t\t\t" + "Loading...\n\n"); printf("\t\t\t\t\t"); // Print initial loading bar for (int i = 0; i < 26; i++) printf("%c", a); // Set the cursor again starting // point of loading bar printf("\r"); printf("\t\t\t\t\t"); // Print loading bar progress for (int i = 0; i < 26; i++) { printf("%c", b); // Sleep for 1 second Sleep(1000); }} // Driver Codeint main(){ // Function Call loadingBar(); return 0;}
Output:Below is the output of the above program:
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
C++ Program for QuickSort
CSV file management using C++
delete keyword in C++
cin in C++
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 24930,
"s": 24902,
"text": "\n19 Jul, 2020"
},
{
"code": null,
"e": 25004,
"s": 24930,
"text": "The task is to write a C/C++ program to draw a command-line progress bar."
},
{
"code": null,
"e": 25167,
"s": 25004,
"text": "Approach: To create a progress bar the idea is to use system() function which will give colored output. Below is the illustration of how to use system() function."
},
{
"code": null,
"e": 25253,
"s": 25167,
"text": "The system function accepts the following parameters for colouring the output screen:"
},
{
"code": null,
"e": 25300,
"s": 25253,
"text": "keyword: colorBackground colorForeground color"
},
{
"code": null,
"e": 25315,
"s": 25300,
"text": "keyword: color"
},
{
"code": null,
"e": 25332,
"s": 25315,
"text": "Background color"
},
{
"code": null,
"e": 25349,
"s": 25332,
"text": "Foreground color"
},
{
"code": null,
"e": 25363,
"s": 25349,
"text": "Color Codes: "
},
{
"code": null,
"e": 25380,
"s": 25363,
"text": "Syntax: "
},
{
"code": null,
"e": 25483,
"s": 25380,
"text": "system(“color 9F”); The above code will give White Color output with Bright Blue color on Background. "
},
{
"code": null,
"e": 25560,
"s": 25483,
"text": "Below is the program to draw the progress bar in the command line in C/C++: "
},
{
"code": null,
"e": 25562,
"s": 25560,
"text": "C"
},
{
"code": null,
"e": 25566,
"s": 25562,
"text": "C++"
},
{
"code": "// C program to create loading bar#include <stdio.h>#include <windows.h> // Function to creating loading barvoid loadingBar(){ // 0 - black background, // A - Green Foreground system(\"color 0A\"); // Initialize char for printing // loading bar char a = 177, b = 219; printf(\"\\n\\n\\n\\n\"); printf(\"\\n\\n\\n\\n\\t\\t\\t\\t\\t\" + \"Loading...\\n\\n\"); printf(\"\\t\\t\\t\\t\\t\"); // Print initial loading bar for (int i = 0; i < 26; i++) printf(\"%c\", a); // Set the cursor again starting // point of loading bar printf(\"\\r\"); printf(\"\\t\\t\\t\\t\\t\"); // Print loading bar progress for (int i = 0; i < 26; i++) { printf(\"%c\", b); // Sleep for 1 second Sleep(1000); }} // Driver Codeint main(){ // Function Call loadingBar(); return 0;}",
"e": 26390,
"s": 25566,
"text": null
},
{
"code": "// C++ program to create loading bar#include <iostream>#include <windows.h>using namespace std; // Function to creating loading barvoid loadingBar(){ // 0 - black background, // A - Green Foreground system(\"color 0A\"); // Initialize char for printing // loading bar char a = 177, b = 219; printf(\"\\n\\n\\n\\n\"); printf(\"\\n\\n\\n\\n\\t\\t\\t\\t\\t\" + \"Loading...\\n\\n\"); printf(\"\\t\\t\\t\\t\\t\"); // Print initial loading bar for (int i = 0; i < 26; i++) printf(\"%c\", a); // Set the cursor again starting // point of loading bar printf(\"\\r\"); printf(\"\\t\\t\\t\\t\\t\"); // Print loading bar progress for (int i = 0; i < 26; i++) { printf(\"%c\", b); // Sleep for 1 second Sleep(1000); }} // Driver Codeint main(){ // Function Call loadingBar(); return 0;}",
"e": 27237,
"s": 26390,
"text": null
},
{
"code": null,
"e": 27286,
"s": 27237,
"text": "Output:Below is the output of the above program:"
},
{
"code": null,
"e": 27297,
"s": 27286,
"text": "C Programs"
},
{
"code": null,
"e": 27310,
"s": 27297,
"text": "C++ Programs"
},
{
"code": null,
"e": 27408,
"s": 27310,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27417,
"s": 27408,
"text": "Comments"
},
{
"code": null,
"e": 27430,
"s": 27417,
"text": "Old Comments"
},
{
"code": null,
"e": 27471,
"s": 27430,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27502,
"s": 27471,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27543,
"s": 27502,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27614,
"s": 27543,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 27639,
"s": 27614,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 27665,
"s": 27639,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27695,
"s": 27665,
"text": "CSV file management using C++"
},
{
"code": null,
"e": 27717,
"s": 27695,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 27728,
"s": 27717,
"text": "cin in C++"
}
] |
Smallest Subsequence of Distinct Characters in Python
|
Suppose we have a text, we have to find the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once. So if the input is like “cdadabcc”, then the output will be “adbc”.
To solve this, we will follow these steps −
Define a stack st, two maps last_o and considered, they are initially blank
for i in range length of text – 1 down to 0if text[i] is not present in last_o −last_o[text[i]] := iconsidered[text[i]] := falsei := 0while i < length of textif stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise increase i by 1
if text[i] is not present in last_o −last_o[text[i]] := iconsidered[text[i]] := false
last_o[text[i]] := i
considered[text[i]] := false
i := 0
while i < length of textif stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise increase i by 1
if stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1
push text[i] into stack
considered[text[i]] := true
increase i by 1
otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1
if last_o[stack top] > iconsidered[stack top element] := falsepop from stack
considered[stack top element] := false
pop from stack
Otherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1
considered[tex[i]] = true
insert text[i] into stack
increase i by 1
otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1
insert text[i] into stack
considered[text[i]] := true
increase i by 1
otherwise increase i by 1
return all of the elements of stack as string in reverse order
Let us see the following implementation to get better understanding −
class Solution(object):
def smallestSubsequence(self, text):
"""
:type text: str
:rtype: str
"""
stack = []
last_o = {}
considered = {}
for i in range(len(text)-1,-1,-1):
if text[i] not in last_o:
last_o[text[i]] = i
considered[text[i]] = False
print(last_o)
i = 0
while i < len(text):
print(stack,i,text[i])
if len(stack) == 0:
stack.append(text[i])
considered[text[i]] = True
i+=1
elif stack[-1]>text[i] and considered[text[i]] == False:
if last_o[stack[-1]]>i:
considered[stack[-1]]=False
stack.pop()
else:
considered[text[i]] = True
stack.append(text[i])
i+=1
elif stack[-1]<text[i] and considered[text[i]] == False:
stack.append(text[i])
considered[text[i]] = True
i+=1
else:
i+=1
return "".join(i for i in stack)
"cdadabcc"
"adbc"
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "Suppose we have a text, we have to find the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once. So if the input is like “cdadabcc”, then the output will be “adbc”."
},
{
"code": null,
"e": 1329,
"s": 1285,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1405,
"s": 1329,
"text": "Define a stack st, two maps last_o and considered, they are initially blank"
},
{
"code": null,
"e": 2031,
"s": 1405,
"text": "for i in range length of text – 1 down to 0if text[i] is not present in last_o −last_o[text[i]] := iconsidered[text[i]] := falsei := 0while i < length of textif stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise increase i by 1"
},
{
"code": null,
"e": 2117,
"s": 2031,
"text": "if text[i] is not present in last_o −last_o[text[i]] := iconsidered[text[i]] := false"
},
{
"code": null,
"e": 2138,
"s": 2117,
"text": "last_o[text[i]] := i"
},
{
"code": null,
"e": 2167,
"s": 2138,
"text": "considered[text[i]] := false"
},
{
"code": null,
"e": 2174,
"s": 2167,
"text": "i := 0"
},
{
"code": null,
"e": 2666,
"s": 2174,
"text": "while i < length of textif stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1otherwise increase i by 1"
},
{
"code": null,
"e": 2756,
"s": 2666,
"text": "if stack has no elementspush text[i] into stackconsidered[text[i]] := trueincrease i by 1"
},
{
"code": null,
"e": 2780,
"s": 2756,
"text": "push text[i] into stack"
},
{
"code": null,
"e": 2808,
"s": 2780,
"text": "considered[text[i]] := true"
},
{
"code": null,
"e": 2824,
"s": 2808,
"text": "increase i by 1"
},
{
"code": null,
"e": 3037,
"s": 2824,
"text": "otherwise stack top > text[i] and considered[text[i]] is falseif last_o[stack top] > iconsidered[stack top element] := falsepop from stackOtherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1"
},
{
"code": null,
"e": 3114,
"s": 3037,
"text": "if last_o[stack top] > iconsidered[stack top element] := falsepop from stack"
},
{
"code": null,
"e": 3153,
"s": 3114,
"text": "considered[stack top element] := false"
},
{
"code": null,
"e": 3168,
"s": 3153,
"text": "pop from stack"
},
{
"code": null,
"e": 3243,
"s": 3168,
"text": "Otherwiseconsidered[tex[i]] = trueinsert text[i] into stackincrease i by 1"
},
{
"code": null,
"e": 3269,
"s": 3243,
"text": "considered[tex[i]] = true"
},
{
"code": null,
"e": 3295,
"s": 3269,
"text": "insert text[i] into stack"
},
{
"code": null,
"e": 3311,
"s": 3295,
"text": "increase i by 1"
},
{
"code": null,
"e": 3453,
"s": 3311,
"text": "otherwise when stack top element < temp[i] and considered[text[i]] = falseinsert text[i] into stackconsidered[text[i]] := trueincrease i by 1"
},
{
"code": null,
"e": 3479,
"s": 3453,
"text": "insert text[i] into stack"
},
{
"code": null,
"e": 3507,
"s": 3479,
"text": "considered[text[i]] := true"
},
{
"code": null,
"e": 3523,
"s": 3507,
"text": "increase i by 1"
},
{
"code": null,
"e": 3549,
"s": 3523,
"text": "otherwise increase i by 1"
},
{
"code": null,
"e": 3612,
"s": 3549,
"text": "return all of the elements of stack as string in reverse order"
},
{
"code": null,
"e": 3682,
"s": 3612,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 4737,
"s": 3682,
"text": "class Solution(object):\n def smallestSubsequence(self, text):\n \"\"\"\n :type text: str\n :rtype: str\n \"\"\"\n stack = []\n last_o = {}\n considered = {}\n for i in range(len(text)-1,-1,-1):\n if text[i] not in last_o:\n last_o[text[i]] = i\n considered[text[i]] = False\n print(last_o)\n i = 0\n while i < len(text):\n print(stack,i,text[i])\n if len(stack) == 0:\n stack.append(text[i])\n considered[text[i]] = True\n i+=1\n elif stack[-1]>text[i] and considered[text[i]] == False:\n if last_o[stack[-1]]>i:\n considered[stack[-1]]=False\n stack.pop()\n else:\n considered[text[i]] = True\n stack.append(text[i])\n i+=1\n elif stack[-1]<text[i] and considered[text[i]] == False:\n stack.append(text[i])\n considered[text[i]] = True\n i+=1\n else:\n i+=1\n return \"\".join(i for i in stack)"
},
{
"code": null,
"e": 4748,
"s": 4737,
"text": "\"cdadabcc\""
},
{
"code": null,
"e": 4755,
"s": 4748,
"text": "\"adbc\""
}
] |
Isolation Forest is the best Anomaly Detection Algorithm for Big Data Right Now | by Andrew Young | Towards Data Science
|
Isolation forest or “iForest” is an astoundingly beautiful and elegantly simple algorithm that identifies anomalies with few parameters. The original paper is accessible to a broad audience and contains minimal math. In this article, I will explain why iForest is the best anomaly detection algorithm for big data right now, provide a summary of the algorithm, history of the algorithm and share a code implementation.
Best-in-class performance that generalizes. iForest performs better than most other outlier detection (OD) algorithms across a variety of datasets, based on ROC performance and Precision. I took benchmark data from the authors of the Python Outlier Detection package (PyOD; original paper) and applied row-wise green-red gradient conditional formatting in Excel. Dark green indicates the best performing algorithm for a dataset and dark red indicates the worst performing:
We see that iForest leads across most datasets and in aggregate, as shown by colors for the mean, median and standard deviation rows that I calculated. The same pattern of superior results for iForest holds true for precision @ N performances:
Scalability. iForest is the fastest performing algorithm for its performance. PCA and Histogram-based Outlier Score (HBOS; paper, poster) are expectedly faster across all datasets. k-nearest-neighbors (KNN) is much slower and scales terribly with more observations, N.
I’ve successfully constructed isolation forests with datasets containing 100M observations with 36 columns on the order of minutes in a cluster environment. I cannot say the same for sk-learn’s KNN().
I will provide a grossly simplified summary of the 10 page paper with the following overview:
Most other outlier detection (OD) algorithms seek to build a profile of “normal” instances then flag instances that don’t fit that profile of normality. iForest explicitly isolates anomalous records by taking advantage of inherent properties of anomalies: they have unusual values for the set of covariates.Existing methods are constrained to low dimensional data and small data size due to computational expense. Case in point: ever try sklearn.neighbor.KNeighborsClassifier on big data? :)Additionally, iForest has “a low constant and low memory requirement” i.e. low overhead. Specifics: the number of external nodes is n since each observation, n, is isolated by itself. The total number of internal nodes is clearly n-1, and the total number nodes is 2n-1. Hence, we see why the memory requirement is bounded and grows linearly with n.Isolation tree node definition: T is either a childless external node or an internal node with one test and exactly two daughter nodes (Tl, Tr). To build an iTree, we recursively divide X by randomly selecting an attribute q and a split value p until either: (i) the tree reaches a height limit, (ii) all observations are isolated at their own external node, or (iii) all data have the same values for all attributes.Path length. The path length h(x) of an observation x is measured by the number of edges x traverses an iTree from the root node until transversal is terminated at an external node. E(h(x)) is the average of h(x) from a collection of isolation trees. An anomaly score, s(x, n), can be derived from the average path length, E(h(x)): s(x, n) = 2^[− E(h(x)) / c(n)]. Basically, there is a monotonic relationship between s and E(h(x)) (see appendix at end for details and a helpful figure illustrating their relationship). I won’t get into the term c(n) so I can keep this brief but it is a constant for any given, static data set.Only requires user to set two variables: the number of trees to build and the sub-sampling size. The authors present experiments with generated Gaussian distribution data that show how convergence for mean path length is achieved relatively quickly with few trees and small subsamples.Small subsampling (sample of a sample) size addresses swamping and masking issues. Swamping and masking are caused by input data that is too large for the purposes of anomaly detection. Swamping is when an “normal” observation is mistaken for an “anomalous” one because it is surrounded by anomalies and masking is the opposite. In other words, when a tree is fed a sample consisting of a majority of anomalies, a normal data point might look anomalous. The authors present examples of this phenomenon with mammography data.Small subsamples allows each isolation tree to be specialized,as each sub-sample includes a different set of anomalies oreven no anomalyiForest doesn’t depend on any distance or density-based measures to identify anomalies so it is fast and computationally inexpensive, which leads to the next pointLinear time complexity, O(n). Informally, this means that the running time increases at most linearly with the size of the input. This is pretty good:
Most other outlier detection (OD) algorithms seek to build a profile of “normal” instances then flag instances that don’t fit that profile of normality. iForest explicitly isolates anomalous records by taking advantage of inherent properties of anomalies: they have unusual values for the set of covariates.
Existing methods are constrained to low dimensional data and small data size due to computational expense. Case in point: ever try sklearn.neighbor.KNeighborsClassifier on big data? :)
Additionally, iForest has “a low constant and low memory requirement” i.e. low overhead. Specifics: the number of external nodes is n since each observation, n, is isolated by itself. The total number of internal nodes is clearly n-1, and the total number nodes is 2n-1. Hence, we see why the memory requirement is bounded and grows linearly with n.
Isolation tree node definition: T is either a childless external node or an internal node with one test and exactly two daughter nodes (Tl, Tr). To build an iTree, we recursively divide X by randomly selecting an attribute q and a split value p until either: (i) the tree reaches a height limit, (ii) all observations are isolated at their own external node, or (iii) all data have the same values for all attributes.
Path length. The path length h(x) of an observation x is measured by the number of edges x traverses an iTree from the root node until transversal is terminated at an external node. E(h(x)) is the average of h(x) from a collection of isolation trees. An anomaly score, s(x, n), can be derived from the average path length, E(h(x)): s(x, n) = 2^[− E(h(x)) / c(n)]. Basically, there is a monotonic relationship between s and E(h(x)) (see appendix at end for details and a helpful figure illustrating their relationship). I won’t get into the term c(n) so I can keep this brief but it is a constant for any given, static data set.
Only requires user to set two variables: the number of trees to build and the sub-sampling size. The authors present experiments with generated Gaussian distribution data that show how convergence for mean path length is achieved relatively quickly with few trees and small subsamples.
Small subsampling (sample of a sample) size addresses swamping and masking issues. Swamping and masking are caused by input data that is too large for the purposes of anomaly detection. Swamping is when an “normal” observation is mistaken for an “anomalous” one because it is surrounded by anomalies and masking is the opposite. In other words, when a tree is fed a sample consisting of a majority of anomalies, a normal data point might look anomalous. The authors present examples of this phenomenon with mammography data.
Small subsamples allows each isolation tree to be specialized,as each sub-sample includes a different set of anomalies oreven no anomaly
iForest doesn’t depend on any distance or density-based measures to identify anomalies so it is fast and computationally inexpensive, which leads to the next point
Linear time complexity, O(n). Informally, this means that the running time increases at most linearly with the size of the input. This is pretty good:
11. For the reader with relevant background, the following diagrams from the paper make it explicitly clear how the algorithm works:
The well-read reader knows that the lag time between a great new idea and wider adoption can be decades long. For example, the logistic function was discovered in 1845, re-discovered in 1922 (read more) and is now regularly used by modern-day data scientists for logistic regression. The lag time between a new idea and its broader adoption has decreased in recent decades, but it is still arguably a long period of time. iForest was first shared in 2008 and commercially viable applications weren’t released until late 2018! Timeline below:
12/2008 — Original paper for iForest released (paper)07/2009 — iForest authors last modify their code implementation (code)10/2018 — h2o team makes iForest available to R and Python users (code)01/2019 — PyOD releases outlier detection (OD) toolkit for Python users (code, paper)08/2019 — LinkedIn engineering team releases Spark/Scala implementation of iForest (code, press release)
Since this article is about big data, I assume a cluster environment. My implementation below works with data stored in AWS S3 but can be minimally modified to be used elsewhere. Code scaffolding (code to QA objects, debug, etc.) mostly omitted. Need help installing packages for an AWS cluster environment? See my Medium article: How to Set-up a cost-effective AWS EMR cluster and Jupyter Notebooks for SparkSQL
I have found iForest to easily and quickly work with 7.5M rows and 36 features, finishing calculations on the order of minutes.
Python (h2o):
The following histogram is produced by the code above. For the observations in my DataFrame predictions_fullX , most observations are not anomalous as evidenced by the frequency of larger mean path lengths.
If your data has labels you’d like to corroborate with iForest, you can compare the distributions of the sets of normal instances with anomalous instances and with the original dataset for further inference. For example, you can look at counts by different combinations of features in the original data set, like so:
N = df.count()df[['v1', 'v2', 'id']].groupby(['v1', 'v2']).count() / Ndf[['v1', 'v3', 'id']].groupby(['v1', 'v3']).count() / N...
and compare with normal/anomalous sets of instances as determined by iForest as shown below:
I did all of that and also exported my data to Excel to quickly produce some cumulative distribution functions like so:
Python (pyod) (I’ll add code if requested in the comments!)
Update (15 Dec 2020), PyOD code:
There are plenty of great examples on the PyOD github (link) so I don’t see much need for me to make one up. If you have a specific request for PyOD code that isn’t available on the GitHub repo, please let me know in the comments. Github doesn’t show you what the results should look like, so my value-add can be showing you what the code should output, in case you’re having trouble getting even that far.
The output for https://github.com/yzhao062/pyod/blob/master/examples/ocsvm_example.py should look like:
Scala (forthcoming)
I used the LinkedIn Team’s implementation of iForest (github) for Scala since PyOD and h2o are for Python. Presently not able to get it to work but will update when I can.
F. T. Liu, K. M. Ting, and Z.-H. Zhou. Isolation forest. In: Proceedings of the 8th IEEE International Conference on Data Mining (ICDM’08), Pisa, Italy, 2008, pp.413–422. [code] This paper won the Theoretical/Algorithms Runner-Up Best Paper Award at IEEE ICDM’08
Zhao, Y., Nasrullah, Z. and Li, Z., 2019. PyOD: A Python Toolbox for Scalable Outlier Detection. Journal of machine learning research (JMLR), 20(96), pp.1–7.
Andrew Young is an R&D Data Scientist Manager at Neustar. For context, Neustar is an information services company that ingests structured and unstructured text and picture data from hundreds of companies in the domains of aviation, banking, government, marketing, social media and telecommunications to name several. Neustar combines these data ingredients then sells a finished dish with added value to enterprise clients for purposes like consulting, cyber security, fraud detection and marketing. In this context, Mr. Young is a hands-on lead architect on a small R&D data science team responsible for building, optimizing and maintaining a system feeding all products and services responsible for $1+ billion in annual revenue for Neustar. Follow Andrew on LinkedIn to stay up-to-date on the latest trends in data science!
Every Data Scientist Should Know: The Bias-Variance Trade-off Generalization is Wrong
Must-Know Presentation Tools for the Effective Data Scientist
Algorithm main points/summary, point #5 details:
when E(h(x)) → c(n), s → 0.5 (the observation is not an obvious anomaly)
when E(h(x)) → 0, s → 1 (anomaly)
when E(h(x)) → n − 1, s → 0 (not an anomaly)
so to summarize the above in the words of the paper:
(a) if instances return s very close to 1, then they are definitely anomalies,
(b) if instances have s much smaller than 0.5, then they are quite safe to be regarded as normal instances, and
© if all the instances return s ≈ 0.5, then the entire sample does not really have any distinct anomaly.
Helpful figure that illustrates the relationship between anomaly score, s, and average path length E(h(x))
|
[
{
"code": null,
"e": 591,
"s": 172,
"text": "Isolation forest or “iForest” is an astoundingly beautiful and elegantly simple algorithm that identifies anomalies with few parameters. The original paper is accessible to a broad audience and contains minimal math. In this article, I will explain why iForest is the best anomaly detection algorithm for big data right now, provide a summary of the algorithm, history of the algorithm and share a code implementation."
},
{
"code": null,
"e": 1064,
"s": 591,
"text": "Best-in-class performance that generalizes. iForest performs better than most other outlier detection (OD) algorithms across a variety of datasets, based on ROC performance and Precision. I took benchmark data from the authors of the Python Outlier Detection package (PyOD; original paper) and applied row-wise green-red gradient conditional formatting in Excel. Dark green indicates the best performing algorithm for a dataset and dark red indicates the worst performing:"
},
{
"code": null,
"e": 1308,
"s": 1064,
"text": "We see that iForest leads across most datasets and in aggregate, as shown by colors for the mean, median and standard deviation rows that I calculated. The same pattern of superior results for iForest holds true for precision @ N performances:"
},
{
"code": null,
"e": 1577,
"s": 1308,
"text": "Scalability. iForest is the fastest performing algorithm for its performance. PCA and Histogram-based Outlier Score (HBOS; paper, poster) are expectedly faster across all datasets. k-nearest-neighbors (KNN) is much slower and scales terribly with more observations, N."
},
{
"code": null,
"e": 1778,
"s": 1577,
"text": "I’ve successfully constructed isolation forests with datasets containing 100M observations with 36 columns on the order of minutes in a cluster environment. I cannot say the same for sk-learn’s KNN()."
},
{
"code": null,
"e": 1872,
"s": 1778,
"text": "I will provide a grossly simplified summary of the 10 page paper with the following overview:"
},
{
"code": null,
"e": 5015,
"s": 1872,
"text": "Most other outlier detection (OD) algorithms seek to build a profile of “normal” instances then flag instances that don’t fit that profile of normality. iForest explicitly isolates anomalous records by taking advantage of inherent properties of anomalies: they have unusual values for the set of covariates.Existing methods are constrained to low dimensional data and small data size due to computational expense. Case in point: ever try sklearn.neighbor.KNeighborsClassifier on big data? :)Additionally, iForest has “a low constant and low memory requirement” i.e. low overhead. Specifics: the number of external nodes is n since each observation, n, is isolated by itself. The total number of internal nodes is clearly n-1, and the total number nodes is 2n-1. Hence, we see why the memory requirement is bounded and grows linearly with n.Isolation tree node definition: T is either a childless external node or an internal node with one test and exactly two daughter nodes (Tl, Tr). To build an iTree, we recursively divide X by randomly selecting an attribute q and a split value p until either: (i) the tree reaches a height limit, (ii) all observations are isolated at their own external node, or (iii) all data have the same values for all attributes.Path length. The path length h(x) of an observation x is measured by the number of edges x traverses an iTree from the root node until transversal is terminated at an external node. E(h(x)) is the average of h(x) from a collection of isolation trees. An anomaly score, s(x, n), can be derived from the average path length, E(h(x)): s(x, n) = 2^[− E(h(x)) / c(n)]. Basically, there is a monotonic relationship between s and E(h(x)) (see appendix at end for details and a helpful figure illustrating their relationship). I won’t get into the term c(n) so I can keep this brief but it is a constant for any given, static data set.Only requires user to set two variables: the number of trees to build and the sub-sampling size. The authors present experiments with generated Gaussian distribution data that show how convergence for mean path length is achieved relatively quickly with few trees and small subsamples.Small subsampling (sample of a sample) size addresses swamping and masking issues. Swamping and masking are caused by input data that is too large for the purposes of anomaly detection. Swamping is when an “normal” observation is mistaken for an “anomalous” one because it is surrounded by anomalies and masking is the opposite. In other words, when a tree is fed a sample consisting of a majority of anomalies, a normal data point might look anomalous. The authors present examples of this phenomenon with mammography data.Small subsamples allows each isolation tree to be specialized,as each sub-sample includes a different set of anomalies oreven no anomalyiForest doesn’t depend on any distance or density-based measures to identify anomalies so it is fast and computationally inexpensive, which leads to the next pointLinear time complexity, O(n). Informally, this means that the running time increases at most linearly with the size of the input. This is pretty good:"
},
{
"code": null,
"e": 5323,
"s": 5015,
"text": "Most other outlier detection (OD) algorithms seek to build a profile of “normal” instances then flag instances that don’t fit that profile of normality. iForest explicitly isolates anomalous records by taking advantage of inherent properties of anomalies: they have unusual values for the set of covariates."
},
{
"code": null,
"e": 5508,
"s": 5323,
"text": "Existing methods are constrained to low dimensional data and small data size due to computational expense. Case in point: ever try sklearn.neighbor.KNeighborsClassifier on big data? :)"
},
{
"code": null,
"e": 5858,
"s": 5508,
"text": "Additionally, iForest has “a low constant and low memory requirement” i.e. low overhead. Specifics: the number of external nodes is n since each observation, n, is isolated by itself. The total number of internal nodes is clearly n-1, and the total number nodes is 2n-1. Hence, we see why the memory requirement is bounded and grows linearly with n."
},
{
"code": null,
"e": 6276,
"s": 5858,
"text": "Isolation tree node definition: T is either a childless external node or an internal node with one test and exactly two daughter nodes (Tl, Tr). To build an iTree, we recursively divide X by randomly selecting an attribute q and a split value p until either: (i) the tree reaches a height limit, (ii) all observations are isolated at their own external node, or (iii) all data have the same values for all attributes."
},
{
"code": null,
"e": 6904,
"s": 6276,
"text": "Path length. The path length h(x) of an observation x is measured by the number of edges x traverses an iTree from the root node until transversal is terminated at an external node. E(h(x)) is the average of h(x) from a collection of isolation trees. An anomaly score, s(x, n), can be derived from the average path length, E(h(x)): s(x, n) = 2^[− E(h(x)) / c(n)]. Basically, there is a monotonic relationship between s and E(h(x)) (see appendix at end for details and a helpful figure illustrating their relationship). I won’t get into the term c(n) so I can keep this brief but it is a constant for any given, static data set."
},
{
"code": null,
"e": 7190,
"s": 6904,
"text": "Only requires user to set two variables: the number of trees to build and the sub-sampling size. The authors present experiments with generated Gaussian distribution data that show how convergence for mean path length is achieved relatively quickly with few trees and small subsamples."
},
{
"code": null,
"e": 7715,
"s": 7190,
"text": "Small subsampling (sample of a sample) size addresses swamping and masking issues. Swamping and masking are caused by input data that is too large for the purposes of anomaly detection. Swamping is when an “normal” observation is mistaken for an “anomalous” one because it is surrounded by anomalies and masking is the opposite. In other words, when a tree is fed a sample consisting of a majority of anomalies, a normal data point might look anomalous. The authors present examples of this phenomenon with mammography data."
},
{
"code": null,
"e": 7852,
"s": 7715,
"text": "Small subsamples allows each isolation tree to be specialized,as each sub-sample includes a different set of anomalies oreven no anomaly"
},
{
"code": null,
"e": 8016,
"s": 7852,
"text": "iForest doesn’t depend on any distance or density-based measures to identify anomalies so it is fast and computationally inexpensive, which leads to the next point"
},
{
"code": null,
"e": 8167,
"s": 8016,
"text": "Linear time complexity, O(n). Informally, this means that the running time increases at most linearly with the size of the input. This is pretty good:"
},
{
"code": null,
"e": 8300,
"s": 8167,
"text": "11. For the reader with relevant background, the following diagrams from the paper make it explicitly clear how the algorithm works:"
},
{
"code": null,
"e": 8842,
"s": 8300,
"text": "The well-read reader knows that the lag time between a great new idea and wider adoption can be decades long. For example, the logistic function was discovered in 1845, re-discovered in 1922 (read more) and is now regularly used by modern-day data scientists for logistic regression. The lag time between a new idea and its broader adoption has decreased in recent decades, but it is still arguably a long period of time. iForest was first shared in 2008 and commercially viable applications weren’t released until late 2018! Timeline below:"
},
{
"code": null,
"e": 9226,
"s": 8842,
"text": "12/2008 — Original paper for iForest released (paper)07/2009 — iForest authors last modify their code implementation (code)10/2018 — h2o team makes iForest available to R and Python users (code)01/2019 — PyOD releases outlier detection (OD) toolkit for Python users (code, paper)08/2019 — LinkedIn engineering team releases Spark/Scala implementation of iForest (code, press release)"
},
{
"code": null,
"e": 9639,
"s": 9226,
"text": "Since this article is about big data, I assume a cluster environment. My implementation below works with data stored in AWS S3 but can be minimally modified to be used elsewhere. Code scaffolding (code to QA objects, debug, etc.) mostly omitted. Need help installing packages for an AWS cluster environment? See my Medium article: How to Set-up a cost-effective AWS EMR cluster and Jupyter Notebooks for SparkSQL"
},
{
"code": null,
"e": 9767,
"s": 9639,
"text": "I have found iForest to easily and quickly work with 7.5M rows and 36 features, finishing calculations on the order of minutes."
},
{
"code": null,
"e": 9781,
"s": 9767,
"text": "Python (h2o):"
},
{
"code": null,
"e": 9988,
"s": 9781,
"text": "The following histogram is produced by the code above. For the observations in my DataFrame predictions_fullX , most observations are not anomalous as evidenced by the frequency of larger mean path lengths."
},
{
"code": null,
"e": 10305,
"s": 9988,
"text": "If your data has labels you’d like to corroborate with iForest, you can compare the distributions of the sets of normal instances with anomalous instances and with the original dataset for further inference. For example, you can look at counts by different combinations of features in the original data set, like so:"
},
{
"code": null,
"e": 10435,
"s": 10305,
"text": "N = df.count()df[['v1', 'v2', 'id']].groupby(['v1', 'v2']).count() / Ndf[['v1', 'v3', 'id']].groupby(['v1', 'v3']).count() / N..."
},
{
"code": null,
"e": 10528,
"s": 10435,
"text": "and compare with normal/anomalous sets of instances as determined by iForest as shown below:"
},
{
"code": null,
"e": 10648,
"s": 10528,
"text": "I did all of that and also exported my data to Excel to quickly produce some cumulative distribution functions like so:"
},
{
"code": null,
"e": 10708,
"s": 10648,
"text": "Python (pyod) (I’ll add code if requested in the comments!)"
},
{
"code": null,
"e": 10741,
"s": 10708,
"text": "Update (15 Dec 2020), PyOD code:"
},
{
"code": null,
"e": 11148,
"s": 10741,
"text": "There are plenty of great examples on the PyOD github (link) so I don’t see much need for me to make one up. If you have a specific request for PyOD code that isn’t available on the GitHub repo, please let me know in the comments. Github doesn’t show you what the results should look like, so my value-add can be showing you what the code should output, in case you’re having trouble getting even that far."
},
{
"code": null,
"e": 11252,
"s": 11148,
"text": "The output for https://github.com/yzhao062/pyod/blob/master/examples/ocsvm_example.py should look like:"
},
{
"code": null,
"e": 11272,
"s": 11252,
"text": "Scala (forthcoming)"
},
{
"code": null,
"e": 11444,
"s": 11272,
"text": "I used the LinkedIn Team’s implementation of iForest (github) for Scala since PyOD and h2o are for Python. Presently not able to get it to work but will update when I can."
},
{
"code": null,
"e": 11707,
"s": 11444,
"text": "F. T. Liu, K. M. Ting, and Z.-H. Zhou. Isolation forest. In: Proceedings of the 8th IEEE International Conference on Data Mining (ICDM’08), Pisa, Italy, 2008, pp.413–422. [code] This paper won the Theoretical/Algorithms Runner-Up Best Paper Award at IEEE ICDM’08"
},
{
"code": null,
"e": 11865,
"s": 11707,
"text": "Zhao, Y., Nasrullah, Z. and Li, Z., 2019. PyOD: A Python Toolbox for Scalable Outlier Detection. Journal of machine learning research (JMLR), 20(96), pp.1–7."
},
{
"code": null,
"e": 12692,
"s": 11865,
"text": "Andrew Young is an R&D Data Scientist Manager at Neustar. For context, Neustar is an information services company that ingests structured and unstructured text and picture data from hundreds of companies in the domains of aviation, banking, government, marketing, social media and telecommunications to name several. Neustar combines these data ingredients then sells a finished dish with added value to enterprise clients for purposes like consulting, cyber security, fraud detection and marketing. In this context, Mr. Young is a hands-on lead architect on a small R&D data science team responsible for building, optimizing and maintaining a system feeding all products and services responsible for $1+ billion in annual revenue for Neustar. Follow Andrew on LinkedIn to stay up-to-date on the latest trends in data science!"
},
{
"code": null,
"e": 12778,
"s": 12692,
"text": "Every Data Scientist Should Know: The Bias-Variance Trade-off Generalization is Wrong"
},
{
"code": null,
"e": 12840,
"s": 12778,
"text": "Must-Know Presentation Tools for the Effective Data Scientist"
},
{
"code": null,
"e": 12889,
"s": 12840,
"text": "Algorithm main points/summary, point #5 details:"
},
{
"code": null,
"e": 12962,
"s": 12889,
"text": "when E(h(x)) → c(n), s → 0.5 (the observation is not an obvious anomaly)"
},
{
"code": null,
"e": 12996,
"s": 12962,
"text": "when E(h(x)) → 0, s → 1 (anomaly)"
},
{
"code": null,
"e": 13041,
"s": 12996,
"text": "when E(h(x)) → n − 1, s → 0 (not an anomaly)"
},
{
"code": null,
"e": 13094,
"s": 13041,
"text": "so to summarize the above in the words of the paper:"
},
{
"code": null,
"e": 13173,
"s": 13094,
"text": "(a) if instances return s very close to 1, then they are definitely anomalies,"
},
{
"code": null,
"e": 13285,
"s": 13173,
"text": "(b) if instances have s much smaller than 0.5, then they are quite safe to be regarded as normal instances, and"
},
{
"code": null,
"e": 13390,
"s": 13285,
"text": "© if all the instances return s ≈ 0.5, then the entire sample does not really have any distinct anomaly."
}
] |
Python | Ways to Convert a 3D list into a 2D list
|
02 Aug, 2019
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development.Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source.Below are some ways to achieve the above task.
Input:
[[[3], [4]], [[5], [6]], [[7], [8]]]
Output:
[[3], [4], [5], [6], [7], [8]]
Method #1: Using simple iteration to convert a 3D list into a 2D list.
# Python code to convert a 3D list into a 2D list # Input list initializationInput = [[[3], [4]], [[5], [6]], [[7], [8]]] # Output list initializationOutput = [] # Using iterationfor temp in Input: for elem in temp: Output.append(elem) # printing outputprint("Initial 3d list is")print(Input)print("Converted 2d list is")print(Output)
Output:
Initial 3d list is
[[[3], [4]], [[5], [6]], [[7], [8]]]
Converted 2d list is
[[3], [4], [5], [6], [7], [8]]
Method #2: Using List Comprehension to convert a 3D list into a 2D list
# Python code to convert a 3D list into a 2D list # Input list initializationInput = [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]] # Using list comprehensionOutput = [elem for twod in Input for elem in twod] # printing outputprint("Initial 3d list is")print(Input)print("Converted 2d list is")print(Output)
Output:
Initial 3d list is
[[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]]
Converted 2d list is
[[1, 1], [2, 7], [3], [4], [6, 5], [6]]
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 407,
"s": 28,
"text": "List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development.Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source.Below are some ways to achieve the above task."
},
{
"code": null,
"e": 491,
"s": 407,
"text": "Input:\n[[[3], [4]], [[5], [6]], [[7], [8]]]\nOutput:\n[[3], [4], [5], [6], [7], [8]]\n"
},
{
"code": null,
"e": 562,
"s": 491,
"text": "Method #1: Using simple iteration to convert a 3D list into a 2D list."
},
{
"code": "# Python code to convert a 3D list into a 2D list # Input list initializationInput = [[[3], [4]], [[5], [6]], [[7], [8]]] # Output list initializationOutput = [] # Using iterationfor temp in Input: for elem in temp: Output.append(elem) # printing outputprint(\"Initial 3d list is\")print(Input)print(\"Converted 2d list is\")print(Output)",
"e": 911,
"s": 562,
"text": null
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Output:"
},
{
"code": null,
"e": 1028,
"s": 919,
"text": "Initial 3d list is\n[[[3], [4]], [[5], [6]], [[7], [8]]]\nConverted 2d list is\n[[3], [4], [5], [6], [7], [8]]\n"
},
{
"code": null,
"e": 1100,
"s": 1028,
"text": "Method #2: Using List Comprehension to convert a 3D list into a 2D list"
},
{
"code": "# Python code to convert a 3D list into a 2D list # Input list initializationInput = [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]] # Using list comprehensionOutput = [elem for twod in Input for elem in twod] # printing outputprint(\"Initial 3d list is\")print(Input)print(\"Converted 2d list is\")print(Output)",
"e": 1410,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Output:"
},
{
"code": null,
"e": 1545,
"s": 1418,
"text": "Initial 3d list is\n[[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]]\nConverted 2d list is\n[[1, 1], [2, 7], [3], [4], [6, 5], [6]]\n"
},
{
"code": null,
"e": 1552,
"s": 1545,
"text": "Python"
}
] |
Weighted K-NN
|
07 Apr, 2020
Weighted kNN is a modified version of k nearest neighbors. One of the many issues that affect the performance of the kNN algorithm is the choice of the hyperparameter k. If k is too small, the algorithm would be more sensitive to outliers. If k is too large, then the neighborhood may include too many points from other classes.Another issue is the approach to combining the class labels. The simplest method is to take the majority vote, but this can be a problem if the nearest neighbors vary widely in their distance and the closest neighbors more reliably indicate the class of the object.
Intuition:Consider the following training setThe red labels indicate the class 0 points and the green labels indicate class 1 points.Consider the white point as the query point( the point whose class label has to be predicted)If we give the above dataset to a kNN based classifier, then the classifier would declare the query point to belong to the class 0. But in the plot, it is clear that the point is more closer to the class 1 points compared to the class 0 points. To overcome this disadvantage, weighted kNN is used. In weighted kNN, the nearest k points are given a weight using a function called as the kernel function. The intuition behind weighted kNN, is to give more weight to the points which are nearby and less weight to the points which are farther away. Any function can be used as a kernel function for the weighted knn classifier whose value decreases as the distance increases. The simple function which is used is the inverse distance function.
Algorithm:
Let L = { ( xi , yi ) , i = 1, . . . ,n } be a training set of observations xi with given class yi and let x be a new observation(query point), whose class label y has to be predicted.
Compute d(xi, x) for i = 1, . . . ,n , the distance between the query point and every other point in the training set.
Select D’ ⊆ D, the set of k nearest training data points to the query points
Predict the class of the query point, using distance-weighted voting. The v represents the class labels. Use the following formula
Implementation:Consider 0 as the label for class 0 and 1 as the label for class 1. Below is the implementation of weighted-kNN algorithm.
C/C++
Python3
// C++ program to implement the // weighted K nearest neighbour algorithm. #include <bits/stdc++.h> using namespace std; struct Point { int val; // Class of point double x, y; // Co-ordinate of point double distance; // Distance from test point }; // Used to sort an array of points by increasing // order of weighted distance bool comparison(Point a, Point b) { return (a.distance < b.distance); } // This function finds classification of point p using // weighted k nearest neighbour algorithm. It assumes only // two groups and returns 0 if p belongs to class 0, else // 1 (belongs to class 1). int weightedkNN(Point arr[], int n, int k, Point p) { // Fill weighted distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = (sqrt((arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y))); // Sort the Points by weighted distance from p sort(arr, arr+n, comparison); // Now consider the first k elements and only // two groups double freq1 = 0; // weighted sum of group 0 double freq2 = 0; // weighted sum of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1 += double(1/arr[i].distance); else if (arr[i].val == 1) freq2 += double(1/arr[i].distance); } return (freq1 > freq2 ? 0 : 1); } // Driver code int main() { int n = 13; // Number of data points Point arr[n]; arr[0].x = 0; arr[0].y = 4; arr[0].val = 0; arr[1].x = 1; arr[1].y = 4.9; arr[1].val = 0; arr[2].x = 1.6; arr[2].y = 5.4; arr[2].val = 0; arr[3].x = 2.2; arr[3].y = 6; arr[3].val = 0; arr[4].x = 2.8; arr[4].y = 7; arr[4].val = 0; arr[5].x = 3.2; arr[5].y = 8; arr[5].val = 0; arr[6].x = 3.4; arr[6].y = 9; arr[6].val = 0; arr[7].x = 1.8; arr[7].y = 1; arr[7].val = 1; arr[8].x = 2.2; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 4; arr[9].val = 1; arr[10].x = 4; arr[10].y = 4.5; arr[10].val = 1; arr[11].x = 5; arr[11].y = 5; arr[11].val = 1; arr[12].x = 6; arr[12].y = 5.5; arr[12].val = 1; /*Testing Point*/ Point p; p.x = 2; p.y = 4; // Parameter to decide the class of the query point int k = 5; printf ("The value classified to query point" " is: %d.\n", weightedkNN(arr, n, k, p)); return 0; }
# Python3 program to implement the# weighted K nearest neighbour algorithm. import math def weightedkNN(points,p,k=3): ''' This function finds classification of p using weighted k nearest neighbour algorithm. It assumes only two two classes and returns 0 if p belongs to class 0, else 1 (belongs to class 1). Parameters - points : Dictionary of training points having two keys - 0 and 1 Each key have a list of training data points belong to that p : A tuple ,test data point of form (x,y) k : number of nearest neighbour to consider, default is 3 ''' distance=[] for group in points: for feature in points[group]: #calculate the euclidean distance of p from training points euclidean_distance = math.sqrt((feature[0]-p[0])**2 +(feature[1]-p[1])**2) # Add a tuple of form (distance,group) in the distance list distance.append((euclidean_distance,group)) # sort the distance list in ascending order # and select first k distances distance = sorted(distance)[:k] freq1 = 0 # weighted sum of group 0 freq2 = 0 # weighted sum of group 1 for d in distance: if d[1] == 0: freq1 += (1 / d[0]) elif d[1] == 1: freq2 += (1 /d[0]) return 0 if freq1>freq2 else 1 # Driver function def main(): # Dictionary of training points having two keys - 0 and 1 # key 0 have points belong to class 0 # key 1 have points belong to class 1 points = {0:[(0, 4),(1, 4.9),(1.6, 5.4),(2.2, 6),(2.8, 7),(3.2, 8),(3.4, 9)], 1:[(1.8, 1),(2.2, 3),(3, 4),(4, 4.5),(5, 5),(6, 5.5)]} # query point p(x,y) p = (2, 4) # Number of neighbours k = 5 print("The value classified to query point is: {}".format(weightedkNN(points,p,k))) if __name__ == '__main__': main()
The value classified to query point is: 1
kanakalathav99
C++
Machine Learning
Python
Machine Learning
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Apr, 2020"
},
{
"code": null,
"e": 646,
"s": 52,
"text": "Weighted kNN is a modified version of k nearest neighbors. One of the many issues that affect the performance of the kNN algorithm is the choice of the hyperparameter k. If k is too small, the algorithm would be more sensitive to outliers. If k is too large, then the neighborhood may include too many points from other classes.Another issue is the approach to combining the class labels. The simplest method is to take the majority vote, but this can be a problem if the nearest neighbors vary widely in their distance and the closest neighbors more reliably indicate the class of the object."
},
{
"code": null,
"e": 1613,
"s": 646,
"text": "Intuition:Consider the following training setThe red labels indicate the class 0 points and the green labels indicate class 1 points.Consider the white point as the query point( the point whose class label has to be predicted)If we give the above dataset to a kNN based classifier, then the classifier would declare the query point to belong to the class 0. But in the plot, it is clear that the point is more closer to the class 1 points compared to the class 0 points. To overcome this disadvantage, weighted kNN is used. In weighted kNN, the nearest k points are given a weight using a function called as the kernel function. The intuition behind weighted kNN, is to give more weight to the points which are nearby and less weight to the points which are farther away. Any function can be used as a kernel function for the weighted knn classifier whose value decreases as the distance increases. The simple function which is used is the inverse distance function."
},
{
"code": null,
"e": 1624,
"s": 1613,
"text": "Algorithm:"
},
{
"code": null,
"e": 1809,
"s": 1624,
"text": "Let L = { ( xi , yi ) , i = 1, . . . ,n } be a training set of observations xi with given class yi and let x be a new observation(query point), whose class label y has to be predicted."
},
{
"code": null,
"e": 1928,
"s": 1809,
"text": "Compute d(xi, x) for i = 1, . . . ,n , the distance between the query point and every other point in the training set."
},
{
"code": null,
"e": 2005,
"s": 1928,
"text": "Select D’ ⊆ D, the set of k nearest training data points to the query points"
},
{
"code": null,
"e": 2136,
"s": 2005,
"text": "Predict the class of the query point, using distance-weighted voting. The v represents the class labels. Use the following formula"
},
{
"code": null,
"e": 2274,
"s": 2136,
"text": "Implementation:Consider 0 as the label for class 0 and 1 as the label for class 1. Below is the implementation of weighted-kNN algorithm."
},
{
"code": null,
"e": 2280,
"s": 2274,
"text": "C/C++"
},
{
"code": null,
"e": 2288,
"s": 2280,
"text": "Python3"
},
{
"code": "// C++ program to implement the // weighted K nearest neighbour algorithm. #include <bits/stdc++.h> using namespace std; struct Point { int val; // Class of point double x, y; // Co-ordinate of point double distance; // Distance from test point }; // Used to sort an array of points by increasing // order of weighted distance bool comparison(Point a, Point b) { return (a.distance < b.distance); } // This function finds classification of point p using // weighted k nearest neighbour algorithm. It assumes only // two groups and returns 0 if p belongs to class 0, else // 1 (belongs to class 1). int weightedkNN(Point arr[], int n, int k, Point p) { // Fill weighted distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = (sqrt((arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y))); // Sort the Points by weighted distance from p sort(arr, arr+n, comparison); // Now consider the first k elements and only // two groups double freq1 = 0; // weighted sum of group 0 double freq2 = 0; // weighted sum of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1 += double(1/arr[i].distance); else if (arr[i].val == 1) freq2 += double(1/arr[i].distance); } return (freq1 > freq2 ? 0 : 1); } // Driver code int main() { int n = 13; // Number of data points Point arr[n]; arr[0].x = 0; arr[0].y = 4; arr[0].val = 0; arr[1].x = 1; arr[1].y = 4.9; arr[1].val = 0; arr[2].x = 1.6; arr[2].y = 5.4; arr[2].val = 0; arr[3].x = 2.2; arr[3].y = 6; arr[3].val = 0; arr[4].x = 2.8; arr[4].y = 7; arr[4].val = 0; arr[5].x = 3.2; arr[5].y = 8; arr[5].val = 0; arr[6].x = 3.4; arr[6].y = 9; arr[6].val = 0; arr[7].x = 1.8; arr[7].y = 1; arr[7].val = 1; arr[8].x = 2.2; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 4; arr[9].val = 1; arr[10].x = 4; arr[10].y = 4.5; arr[10].val = 1; arr[11].x = 5; arr[11].y = 5; arr[11].val = 1; arr[12].x = 6; arr[12].y = 5.5; arr[12].val = 1; /*Testing Point*/ Point p; p.x = 2; p.y = 4; // Parameter to decide the class of the query point int k = 5; printf (\"The value classified to query point\" \" is: %d.\\n\", weightedkNN(arr, n, k, p)); return 0; } ",
"e": 4825,
"s": 2288,
"text": null
},
{
"code": "# Python3 program to implement the# weighted K nearest neighbour algorithm. import math def weightedkNN(points,p,k=3): ''' This function finds classification of p using weighted k nearest neighbour algorithm. It assumes only two two classes and returns 0 if p belongs to class 0, else 1 (belongs to class 1). Parameters - points : Dictionary of training points having two keys - 0 and 1 Each key have a list of training data points belong to that p : A tuple ,test data point of form (x,y) k : number of nearest neighbour to consider, default is 3 ''' distance=[] for group in points: for feature in points[group]: #calculate the euclidean distance of p from training points euclidean_distance = math.sqrt((feature[0]-p[0])**2 +(feature[1]-p[1])**2) # Add a tuple of form (distance,group) in the distance list distance.append((euclidean_distance,group)) # sort the distance list in ascending order # and select first k distances distance = sorted(distance)[:k] freq1 = 0 # weighted sum of group 0 freq2 = 0 # weighted sum of group 1 for d in distance: if d[1] == 0: freq1 += (1 / d[0]) elif d[1] == 1: freq2 += (1 /d[0]) return 0 if freq1>freq2 else 1 # Driver function def main(): # Dictionary of training points having two keys - 0 and 1 # key 0 have points belong to class 0 # key 1 have points belong to class 1 points = {0:[(0, 4),(1, 4.9),(1.6, 5.4),(2.2, 6),(2.8, 7),(3.2, 8),(3.4, 9)], 1:[(1.8, 1),(2.2, 3),(3, 4),(4, 4.5),(5, 5),(6, 5.5)]} # query point p(x,y) p = (2, 4) # Number of neighbours k = 5 print(\"The value classified to query point is: {}\".format(weightedkNN(points,p,k))) if __name__ == '__main__': main() ",
"e": 6761,
"s": 4825,
"text": null
},
{
"code": null,
"e": 6804,
"s": 6761,
"text": "The value classified to query point is: 1\n"
},
{
"code": null,
"e": 6819,
"s": 6804,
"text": "kanakalathav99"
},
{
"code": null,
"e": 6823,
"s": 6819,
"text": "C++"
},
{
"code": null,
"e": 6840,
"s": 6823,
"text": "Machine Learning"
},
{
"code": null,
"e": 6847,
"s": 6840,
"text": "Python"
},
{
"code": null,
"e": 6864,
"s": 6847,
"text": "Machine Learning"
},
{
"code": null,
"e": 6868,
"s": 6864,
"text": "CPP"
}
] |
File.SetAttributes() Method in C# with Examples
|
26 Feb, 2021
File.SetAttributes(String, FileAttributes) is an inbuilt File class method that is used to set the specified file attributes of the file on the specified path. File attributes are those certain rights that are either granted or denied. These rights are for a user or for an operating system that accesses the file. These attributes are such as Read-only, Archive, System, Hidden, etc.
Syntax:
public static void SetAttributes (string path, System.IO.FileAttributes fileAttributes);
Parameter: This function accepts two parameters which are illustrated below:
path: This is the specified file path.
fileAttributes: This is the bitwise combination of the enumeration values.
Exceptions:
ArgumentException: The path is empty, contains only white spaces, invalid characters, or the file attribute is invalid.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
NotSupportedException: The path is in an invalid format.
DirectoryNotFoundException: The specified path is invalid.
FileNotFoundException: The file cannot be found.
UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
Below are the programs to illustrate the File.SetAttributes(String, FileAttributes) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below:
CSharp
// C# program to illustrate the usage// of File.SetAttributes(String) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Getting the file attributes FileAttributes attributes = File.GetAttributes(path); // Checking if the file is having whether hidden attributes // If the file is having hidden attribute then // that attribute will be removed if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { // Removing the file's hidden attribute attributes = RemoveAttribute(attributes, FileAttributes.Hidden); // Calling the SetAttributes() function File.SetAttributes(path, attributes); Console.WriteLine("The {0} file is no longer hidden.", path); } else { // Calling the SetAttributes() function to // set hidden attribute File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine("The {0} file is now hidden.", path); } } private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; }}
Output:
The file.txt file is now hidden.
Program 2: Initially, no file was created. Below code, itself creates a file gfg.txt.
CSharp
// C# program to illustrate the usage// of File.SetAttributes(String) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"gfg.txt"; // Create the file if it does not exist. if (!File.Exists(path)) { File.Create(path); } // Getting the file attributes FileAttributes attributes = File.GetAttributes(path); // Checking if the file is having whether hidden attributes // If the file is having hidden attribute then // that attribute will be removed if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { // Removing the file's hidden attribute attributes = RemoveAttribute(attributes, FileAttributes.Hidden); // Calling the SetAttributes() function File.SetAttributes(path, attributes); Console.WriteLine("The {0} file is no longer hidden.", path); } else { // Calling the SetAttributes() function to // set hidden attribute File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine("The {0} file is now hidden.", path); } } private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; }}
Output:
The gfg.txt file is now hidden.
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 414,
"s": 28,
"text": "File.SetAttributes(String, FileAttributes) is an inbuilt File class method that is used to set the specified file attributes of the file on the specified path. File attributes are those certain rights that are either granted or denied. These rights are for a user or for an operating system that accesses the file. These attributes are such as Read-only, Archive, System, Hidden, etc. "
},
{
"code": null,
"e": 424,
"s": 414,
"text": "Syntax: "
},
{
"code": null,
"e": 513,
"s": 424,
"text": "public static void SetAttributes (string path, System.IO.FileAttributes fileAttributes);"
},
{
"code": null,
"e": 592,
"s": 513,
"text": "Parameter: This function accepts two parameters which are illustrated below: "
},
{
"code": null,
"e": 631,
"s": 592,
"text": "path: This is the specified file path."
},
{
"code": null,
"e": 706,
"s": 631,
"text": "fileAttributes: This is the bitwise combination of the enumeration values."
},
{
"code": null,
"e": 719,
"s": 706,
"text": "Exceptions: "
},
{
"code": null,
"e": 839,
"s": 719,
"text": "ArgumentException: The path is empty, contains only white spaces, invalid characters, or the file attribute is invalid."
},
{
"code": null,
"e": 942,
"s": 839,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 999,
"s": 942,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 1058,
"s": 999,
"text": "DirectoryNotFoundException: The specified path is invalid."
},
{
"code": null,
"e": 1107,
"s": 1058,
"text": "FileNotFoundException: The file cannot be found."
},
{
"code": null,
"e": 1329,
"s": 1107,
"text": "UnauthorizedAccessException: The path specified a file that is read-only. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission."
},
{
"code": null,
"e": 1522,
"s": 1329,
"text": "Below are the programs to illustrate the File.SetAttributes(String, FileAttributes) method.Program 1: Before running the below code, a file file.txt is created with some contents shown below: "
},
{
"code": null,
"e": 1531,
"s": 1524,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.SetAttributes(String) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Getting the file attributes FileAttributes attributes = File.GetAttributes(path); // Checking if the file is having whether hidden attributes // If the file is having hidden attribute then // that attribute will be removed if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { // Removing the file's hidden attribute attributes = RemoveAttribute(attributes, FileAttributes.Hidden); // Calling the SetAttributes() function File.SetAttributes(path, attributes); Console.WriteLine(\"The {0} file is no longer hidden.\", path); } else { // Calling the SetAttributes() function to // set hidden attribute File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine(\"The {0} file is now hidden.\", path); } } private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; }}",
"e": 2953,
"s": 1531,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2953,
"text": "Output: "
},
{
"code": null,
"e": 2996,
"s": 2963,
"text": "The file.txt file is now hidden."
},
{
"code": null,
"e": 3083,
"s": 2996,
"text": "Program 2: Initially, no file was created. Below code, itself creates a file gfg.txt. "
},
{
"code": null,
"e": 3090,
"s": 3083,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.SetAttributes(String) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"gfg.txt\"; // Create the file if it does not exist. if (!File.Exists(path)) { File.Create(path); } // Getting the file attributes FileAttributes attributes = File.GetAttributes(path); // Checking if the file is having whether hidden attributes // If the file is having hidden attribute then // that attribute will be removed if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { // Removing the file's hidden attribute attributes = RemoveAttribute(attributes, FileAttributes.Hidden); // Calling the SetAttributes() function File.SetAttributes(path, attributes); Console.WriteLine(\"The {0} file is no longer hidden.\", path); } else { // Calling the SetAttributes() function to // set hidden attribute File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine(\"The {0} file is now hidden.\", path); } } private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; }}",
"e": 4633,
"s": 3090,
"text": null
},
{
"code": null,
"e": 4643,
"s": 4633,
"text": "Output: "
},
{
"code": null,
"e": 4675,
"s": 4643,
"text": "The gfg.txt file is now hidden."
},
{
"code": null,
"e": 4694,
"s": 4677,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4715,
"s": 4694,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 4718,
"s": 4715,
"text": "C#"
}
] |
Find whether there is path between two cells in matrix
|
12 May, 2022
Given N X N matrix filled with 1, 0, 2, 3. Find whether there is a path possible from source to destination, traversing through blank cells only. You can traverse up, down, right, and left.
A value of cell 1 means Source.
A value of cell 2 means Destination.
A value of cell 3 means Blank cell.
A value of cell 0 means Blank Wall.
Note: there are an only a single source and single destination(sink).
Examples:
Input: M[3][3] = {{ 0, 3, 2 }, { 3, 3, 0 }, { 1, 3, 0 }}; Output : Yes Explanation:
Input: M[4][4] = {{ 0, 3, 1, 0 }, { 3, 0, 3, 3 }, { 2, 3, 0, 3 }, { 0, 3, 3, 3 }}; Output: Yes Explanation:
Asked in: Adobe Interview
Simple Solution: Recursion.Approach: Find the source index of the cell in each matrix and then recursively find a path from source index to destination in the matrix. The algorithm involves recursively finding all the paths until a final path is found to the destination.
Algorithm :
Traverse the matrix and find the starting index of the matrix.Create a recursive function that takes the index and visited matrix.Mark the current cell and check if the current cell is a destination or not. If the current cell is destination return true.Call the recursion function for all adjacent empty and unvisited cells.If any of the recursive functions returns true then unmark the cell and return true else unmark the cell and return false.
Traverse the matrix and find the starting index of the matrix.
Create a recursive function that takes the index and visited matrix.
Mark the current cell and check if the current cell is a destination or not. If the current cell is destination return true.
Call the recursion function for all adjacent empty and unvisited cells.
If any of the recursive functions returns true then unmark the cell and return true else unmark the cell and return false.
C++
Java
Python3
C#
Javascript
// C++ program to find path between two// cell in matrix#include <iostream>using namespace std;#define N 4 // Method for checking boundariesbool isSafe(int i, int j, int matrix[][N]){ if (i >= 0 && i < N && j >= 0 && j < N) return true; return false;} // Returns true if there is a// path from a source (a// cell with value 1) to a// destination (a cell with// value 2)bool isPath(int matrix[][N], int i, int j, bool visited[][N]){ // Checking the boundaries, walls and // whether the cell is unvisited if (isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up bool up = isPath(matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left bool left = isPath(matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down bool down = isPath(matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right bool right = isPath(matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false;} // Method for finding and printing// whether the path exists or notvoid isPath(int matrix[][N]){ // Defining visited array to keep // track of already visited indexes bool visited[N][N]; // Flag to indicate whether the // path exists or not bool flag = false; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // if matrix[i][j] is source // and it is not visited if (matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (isPath(matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) cout << "YES"; else cout << "NO";} // Driver program to// check above functionint main(){ int matrix[N][N] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // calling isPath method isPath(matrix); return 0;} // This code is contributed by sudhanshugupta2019a.
// Java program to find path between two// cell in matrixclass Path { // Method for finding and printing // whether the path exists or not public static void isPath( int matrix[][], int n) { // Defining visited array to keep // track of already visited indexes boolean visited[][] = new boolean[n][n]; // Flag to indicate whether the // path exists or not boolean flag = false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // if matrix[i][j] is source // and it is not visited if ( matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (isPath( matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) System.out.println("YES"); else System.out.println("NO"); } // Method for checking boundaries public static boolean isSafe( int i, int j, int matrix[][]) { if ( i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length) return true; return false; } // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2) public static boolean isPath( int matrix[][], int i, int j, boolean visited[][]) { // Checking the boundaries, walls and // whether the cell is unvisited if ( isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up boolean up = isPath( matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left boolean left = isPath( matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down boolean down = isPath( matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right boolean right = isPath( matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false; } // driver program to // check above function public static void main(String[] args) { int matrix[][] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // calling isPath method isPath(matrix, 4); }} /* This code is contributed by Madhu Priya */
# Python3 program to find# path between two cell in matrix # Method for finding and printing# whether the path exists or notdef isPath(matrix, n): # Defining visited array to keep # track of already visited indexes visited = [[False for x in range (n)] for y in range (n)] # Flag to indicate whether the # path exists or not flag = False for i in range (n): for j in range (n): # If matrix[i][j] is source # and it is not visited if (matrix[i][j] == 1 and not visited[i][j]): # Starting from i, j and # then finding the path if (checkPath(matrix, i, j, visited)): # If path exists flag = True break if (flag): print("YES") else: print("NO") # Method for checking boundariesdef isSafe(i, j, matrix): if (i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix[0])): return True return False # Returns true if there is a# path from a source(a# cell with value 1) to a# destination(a cell with# value 2)def checkPath(matrix, i, j, visited): # Checking the boundaries, walls and # whether the cell is unvisited if (isSafe(i, j, matrix) and matrix[i][j] != 0 and not visited[i][j]): # Make the cell visited visited[i][j] = True # If the cell is the required # destination then return true if (matrix[i][j] == 2): return True # traverse up up = checkPath(matrix, i - 1, j, visited) # If path is found in up # direction return true if (up): return True # Traverse left left = checkPath(matrix, i, j - 1, visited) # If path is found in left # direction return true if (left): return True # Traverse down down = checkPath(matrix, i + 1, j, visited) # If path is found in down # direction return true if (down): return True # Traverse right right = checkPath(matrix, i, j + 1, visited) # If path is found in right # direction return true if (right): return True # No path has been found return False # Driver codeif __name__ == "__main__": matrix = [[0, 3, 0, 1], [3, 0, 3, 3], [2, 3, 3, 3], [0, 3, 3, 3]] # calling isPath method isPath(matrix, 4) # This code is contributed by Chitranayal
// C# program to find path between two// cell in matrixusing System; class GFG{ // Method for finding and printing// whether the path exists or notstatic void isPath(int[,] matrix, int n){ // Defining visited array to keep // track of already visited indexes bool[,] visited = new bool[n, n]; // Flag to indicate whether the // path exists or not bool flag = false; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If matrix[i][j] is source // and it is not visited if (matrix[i, j] == 1 && !visited[i, j]) // Starting from i, j and // then finding the path if (isPath(matrix, i, j, visited)) { // If path exists flag = true; break; } } } if (flag) Console.WriteLine("YES"); else Console.WriteLine("NO");} // Method for checking boundariespublic static bool isSafe(int i, int j, int[,] matrix){ if (i >= 0 && i < matrix.GetLength(0) && j >= 0 && j < matrix.GetLength(1)) return true; return false;} // Returns true if there is a path from// a source (a cell with value 1) to a// destination (a cell with value 2)public static bool isPath(int[,] matrix, int i, int j, bool[,] visited){ // Checking the boundaries, walls and // whether the cell is unvisited if (isSafe(i, j, matrix) && matrix[i, j] != 0 && !visited[i, j]) { // Make the cell visited visited[i, j] = true; // If the cell is the required // destination then return true if (matrix[i, j] == 2) return true; // Traverse up bool up = isPath(matrix, i - 1, j, visited); // If path is found in up // direction return true if (up) return true; // Traverse left bool left = isPath(matrix, i, j - 1, visited); // If path is found in left // direction return true if (left) return true; // Traverse down bool down = isPath(matrix, i + 1, j, visited); // If path is found in down // direction return true if (down) return true; // Traverse right bool right = isPath(matrix, i, j + 1, visited); // If path is found in right // direction return true if (right) return true; } // No path has been found return false;} // Driver code static void Main(){ int[,] matrix = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // Calling isPath method isPath(matrix, 4);}} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program to find path between two// cell in matrix // Method for finding and printing // whether the path exists or notfunction isPath(matrix,n){ // Defining visited array to keep // track of already visited indexes let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=new Array(n); for(let j=0;j<n;j++) { visited[i][j]=false; } } // Flag to indicate whether the // path exists or not let flag = false; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // if matrix[i][j] is source // and it is not visited if ( matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (checkPath( matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) document.write("YES<br>"); else document.write("NO<br>");} // Method for checking boundariesfunction isSafe(i,j,matrix){ if ( i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length) return true; return false;} // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2)function checkPath(matrix,i,j,visited){ // Checking the boundaries, walls and // whether the cell is unvisited if ( isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up let up = checkPath( matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left let left = checkPath( matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down let down = checkPath( matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right let right = checkPath( matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false;} // driver program to// check above functionlet matrix= [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]]; // calling isPath method isPath(matrix, 4); // This code is contributed by ab2127 </script>
YES
Complexity Analysis:
Time Complexity: O(n*m), In the worst case, we have to visit each cell only one time because we keep the visited array for not visiting the already visited cell.
Space Complexity: O(n*m), Space is required to store the visited array.
Efficient solution: Graph.Approach: The idea is to use Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. so the total number of Node is N * N. So the idea is to do a breadth-first search from the starting cell till the ending cell is found.
Algorithm:
Create an empty Graph having N*N node(Vertex), push all nodes into a graph, and note down the source and sink vertex.Now apply BFS on the graph, create a queue and insert the source node in the queueRun a loop till the size of the queue is greater than 0Remove the front node of the queue and check if the node is the destination if the destination returns true. mark the nodeCheck all adjacent cells if unvisited and blank insert them in the queue.If the destination is not reached return true.
Create an empty Graph having N*N node(Vertex), push all nodes into a graph, and note down the source and sink vertex.
Now apply BFS on the graph, create a queue and insert the source node in the queue
Run a loop till the size of the queue is greater than 0
Remove the front node of the queue and check if the node is the destination if the destination returns true. mark the node
Check all adjacent cells if unvisited and blank insert them in the queue.
If the destination is not reached return true.
C++
Java
Python3
Javascript
// C++ program to find path// between two cell in matrix#include <bits/stdc++.h>using namespace std;#define N 4 class Graph { int V; list<int>* adj; public: Graph(int V) { this->V = V; adj = new list<int>[V]; } void addEdge(int s, int d); bool BFS(int s, int d);}; // add edge to graphvoid Graph::addEdge(int s, int d){ adj[s].push_back(d);} // BFS function to find path// from source to sinkbool Graph::BFS(int s, int d){ // Base case if (s == d) return true; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and // enqueue it visited[s] = true; queue.push_back(s); // it will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it for ( i = adj[s].begin(); i != adj[s].end(); ++i) { // If this adjacent node is the // destination node, then return true if (*i == d) return true; // Else, continue to do BFS if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } // If BFS is complete without visiting d return false;} bool isSafe(int i, int j, int M[][N]){ if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true;} // Returns true if there is// a path from a source (a// cell with value 1) to a// destination (a cell with// value 2)bool findPath(int M[][N]){ // source and destination int s, d; int V = N * N + 2; Graph g(V); // create graph with n*n node // each cell consider as node // Number of current vertex int k = 1; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) g.addEdge(k, k + 1); if (isSafe(i, j - 1, M)) g.addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) g.addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) g.addEdge(k, k - N); } // Source index if (M[i][j] == 1) s = k; // Destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return g.BFS(s, d);} // driver program to check// above functionint main(){ int M[N][N] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; (findPath(M) == true) ? cout << "Yes" : cout << "No" << endl; return 0;}
// Java program to find path between two// cell in matriximport java.util.*; class Graph { int V; List<List<Integer> > adj; Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) { adj.add(i, new ArrayList<>()); } } // add edge to graph void addEdge(int s, int d) { adj.get(s).add(d); } // BFS function to find path // from source to sink boolean BFS(int s, int d) { // Base case if (s == d) return true; // Mark all the vertices as not visited boolean[] visited = new boolean[V]; // Create a queue for BFS Queue<Integer> queue = new LinkedList<>(); // Mark the current node as visited and // enqueue it visited[s] = true; queue.offer(s); // it will be used to get all adjacent // vertices of a vertex List<Integer> edges; while (!queue.isEmpty()) { // Dequeue a vertex from queue s = queue.poll(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it edges = adj.get(s); for (int curr : edges) { // If this adjacent node is the // destination node, then return true if (curr == d) return true; // Else, continue to do BFS if (!visited[curr]) { visited[curr] = true; queue.offer(curr); } } } // If BFS is complete without visiting d return false; } static boolean isSafe( int i, int j, int[][] M) { int N = M.length; if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true; } // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2) static boolean findPath(int[][] M) { // Source and destination int s = -1, d = -1; int N = M.length; int V = N * N + 2; Graph g = new Graph(V); // Create graph with n*n node // each cell consider as node int k = 1; // Number of current vertex for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) g.addEdge(k, k + 1); if (isSafe(i, j - 1, M)) g.addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) g.addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) g.addEdge(k, k - N); } // source index if (M[i][j] == 1) s = k; // destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return g.BFS(s, d); } // Driver program to check above function public static void main( String[] args) throws Exception { int[][] M = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; System.out.println( ((findPath(M)) ? "Yes" : "No")); }} // This code is contributed by abhay379201
# Python3 program to find path between two# cell in matrixfrom collections import defaultdictclass Graph: def __init__(self): self.graph = defaultdict(list) # add edge to graph def addEdge(self, u, v): self.graph[u].append(v) # BFS function to find path from source to sink def BFS(self, s, d): # Base case if s == d: return True # Mark all the vertices as not visited visited = [False]*(len(self.graph) + 1) # Create a queue for BFS queue = [] queue.append(s) # Mark the current node as visited and # enqueue it visited[s] = True while(queue): # Dequeue a vertex from queue s = queue.pop(0) # Get all adjacent vertices of the # dequeued vertex s. If a adjacent has # not been visited, then mark it visited # and enqueue it for i in self.graph[s]: # If this adjacent node is the destination # node, then return true if i == d: return True # Else, continue to do BFS if visited[i] == False: queue.append(i) visited[i] = True # If BFS is complete without visiting d return False def isSafe(i, j, matrix): if i >= 0 and i <= len(matrix) and j >= 0 and j <= len(matrix[0]): return True else: return False # Returns true if there is a path from a source (a# cell with value 1) to a destination (a cell with# value 2)def findPath(M): s, d = None, None # source and destination N = len(M) g = Graph() # create graph with n * n node # each cell consider as node k = 1 # Number of current vertex for i in range(N): for j in range(N): if (M[i][j] != 0): # connect all 4 adjacent cell to # current cell if (isSafe(i, j + 1, M)): g.addEdge(k, k + 1) if (isSafe(i, j - 1, M)): g.addEdge(k, k - 1) if (isSafe(i + 1, j, M)): g.addEdge(k, k + N) if (isSafe(i - 1, j, M)): g.addEdge(k, k - N) if (M[i][j] == 1): s = k # destination index if (M[i][j] == 2): d = k k += 1 # find path Using BFS return g.BFS(s, d) # Driver codeif __name__=='__main__': M =[[0, 3, 0, 1], [3, 0, 3, 3], [2, 3, 3, 3], [0, 3, 3, 3]] if findPath(M): print("Yes") else: print("No") # This Code is Contributed by Vikash Kumar 37
<script> // JavaScript program to find path between two// cell in matrix let V;let adj=[]; function Graph(v){ V=v; for (let i = 0; i < V; i++) { adj.push([]); }} // add edge to graphfunction addEdge(s,d){ adj[s].push(d);} // BFS function to find path // from source to sinkfunction BFS(s,d){ // Base case if (s == d) return true; // Mark all the vertices as not visited let visited = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } // Create a queue for BFS let queue=[]; // Mark the current node as visited and // enqueue it visited[s] = true; queue.push(s); // it will be used to get all adjacent // vertices of a vertex let edges; while (queue.length!=0) { // Dequeue a vertex from queue s = queue.shift(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it edges = adj[s]; for (let curr=0;curr< edges.length;curr++) { // If this adjacent node is the // destination node, then return true if (edges[curr] == d) return true; // Else, continue to do BFS if (!visited[edges[curr]]) { visited[edges[curr]] = true; queue.push(edges[curr]); } } } // If BFS is complete without visiting d return false;} function isSafe(i,j,M){ let N = M.length; if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true;} // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2)function findPath(M){ // Source and destination let s = -1, d = -1; let N = M.length; let V = N * N + 2; Graph(V); // Create graph with n*n node // each cell consider as node let k = 1; // Number of current vertex for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) addEdge(k, k + 1); if (isSafe(i, j - 1, M)) addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) addEdge(k, k - N); } // source index if (M[i][j] == 1) s = k; // destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return BFS(s, d);} // Driver program to check above functionlet M = [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]];document.write(((findPath(M)) ? "Yes" : "No")); // This code is contributed by patel2127 </script>
Yes
Complexity Analysis:
Time Complexity: O(n*m). Every cell of the matrix is visited only once so the time complexity is O(n*m).
Space Complexity: O(n*m). Space is required to store the visited array and to create the queue.
Simple and Efficient solution: The graph is the matrix in itself.
Approach: The idea is to use Breadth-First Search on the matrix itself.
Consider a cell=(i,j) as a vertex v in the BFS queue. A new vertex u is placed in the BFS queue if u=(i+1,j) or u=(i-1,j) or u=(i,j+1) or u=(i,j-1). Starting the BFS algorithm from cell=(i,j) such that M[i][j] is 1 and stopping either if there was a reachable vertex u=(i,j) such that M[i][j] is 2 and returning true or every cell was covered and there was no such a cell and returning false.
Algorithm:
1) Create BFS queue q
2) scan the matrix, if there exists a cell in the matrix such that its value is 1 then push it to q
3) run BFS algorithm with q, skipping cells which are not valid. i.e: they are walls (value is 0) or outside the matrix bounds and marking them as walls upon successful visitation.
3.1) if in the BFS algorithm process there was a vertex x=(i,j) such that M[i][j] is 2 stop and return true
4) BFS algorithm terminated without returning true then there was no element M[i][j] which is 2, then return false
C++
Java
Python3
C#
Javascript
#include <iostream>#include <queue>using namespace std;#define R 4#define C 4 // Structure to define a vertex u=(i,j)typedef struct BFSElement { BFSElement(int i, int j) { this->i = i; this->j = j; } int i; int j;} BFSElement; bool findPath(int M[R][C]){ // 1) Create BFS queue q queue<BFSElement> q; // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.push(BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (!q.empty()) { BFSElement x = q.front(); q.pop(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i > R || j < 0 || j > C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.push(BFSElement(i + k, j)); q.push(BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false;} // Main Driver codeint main(){ int M[R][C] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; (findPath(M) == true) ? cout << "Yes" : cout << "No" << endl; return 0;}
import java.io.*;import java.util.*; class BFSElement{ int i, j; BFSElement(int i, int j) { this.i = i; this.j = j; }} class GFG { static int R = 4, C = 4; BFSElement b; static boolean findPath(int M[][]) { // 1) Create BFS queue q Queue<BFSElement> q = new LinkedList<>(); // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.add(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.size() != 0) { BFSElement x = q.peek(); q.remove(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.add(new BFSElement(i + k, j)); q.add(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false; } // Main Driver code public static void main (String[] args) { int M[][] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; if(findPath(M) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by avanitrachhadiya2155
class BFSElement: def __init__(self, i, j): self.i = i self.j = j R,C = 4,4 def findPath(M): # 1) Create BFS queue q q = [] # 2)scan the matrix for i in range(R): for j in range(C): # if there exists a cell in the matrix such # that its value is 1 then append it to q if (M[i][j] == 1): q.append(BFSElement(i, j)) break # 3) run BFS algorithm with q. while (len(q) != 0): x = q[0] q = q[1:] i = x.i j = x.j # skipping cells which are not valid. # if outside the matrix bounds if (i < 0 or i >= R or j < 0 or j >= C): continue # if they are walls (value is 0). if (M[i][j] == 0): continue # 3.1) if in the BFS algorithm process there was a # vertex x=(i,j) such that M[i][j] is 2 stop and # return True if (M[i][j] == 2): return True # marking as wall upon successful visitation M[i][j] = 0 # appending to queue u=(i,j+1),u=(i,j-1) # u=(i+1,j),u=(i-1,j) for k in range(-1, 2, 2): q.append(BFSElement(i + k, j)) q.append(BFSElement(i, j + k)) # BFS algorithm terminated without returning True # then there was no element M[i][j] which is 2, then # return false return False # Main Driver codeM = [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]]if(findPath(M) == True): print("Yes")else: print("No") # This code is contributed by shinjanpatra
using System;using System.Collections.Generic; public class BFSElement{ public int i, j; public BFSElement(int i, int j) { this.i = i; this.j = j; }} public class GFG{ static int R = 4, C = 4; static bool findPath(int[,] M) { // 1) Create BFS queue q Queue<BFSElement> q = new Queue<BFSElement>(); // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i, j] == 1) { q.Enqueue(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.Count != 0) { BFSElement x = q.Peek(); q.Dequeue(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i, j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i, j] == 2) return true; // marking as wall upon successful visitation M[i, j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.Enqueue(new BFSElement(i + k, j)); q.Enqueue(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false; } // Main Driver code static public void Main (){ int[,] M = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; if(findPath(M) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by rag2127
<script> class BFSElement{ constructor(i,j) { this.i=i; this.j=j; }} let R = 4, C = 4;let b; function findPath(M){ // 1) Create BFS queue q let q = []; // 2)scan the matrix for (let i = 0; i < R; ++i) { for (let j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.push(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.length != 0) { let x = q.shift(); let i = x.i; let j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (let k = -1; k <= 1; k += 2) { q.push(new BFSElement(i + k, j)); q.push(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false;} // Main Driver codelet M=[[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]];if(findPath(M) == true) document.write("Yes");else document.write("No"); // This code is contributed by unknown2108</script>
Yes
Time Complexity: O(n*m).
Space Complexity: O(n*m).
The improvement is contributed by Ephi F.
This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
madhu priya
Vikash Kumar 37
RambhagwanPrajapat
abhay379201
andrew1234
vashisthamadhur2
ukasp
divyeshrabadiya07
ephi2g
sudhanshugupta2019a
avanitrachhadiya2155
rag2127
simranarora5sos
ab2127
patel2127
unknown2108
shinjanpatra
ayushak969
Adobe
Amazon
BFS
Morgan Stanley
Graph
Matrix
Morgan Stanley
Amazon
Adobe
Matrix
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "Given N X N matrix filled with 1, 0, 2, 3. Find whether there is a path possible from source to destination, traversing through blank cells only. You can traverse up, down, right, and left. "
},
{
"code": null,
"e": 277,
"s": 245,
"text": "A value of cell 1 means Source."
},
{
"code": null,
"e": 314,
"s": 277,
"text": "A value of cell 2 means Destination."
},
{
"code": null,
"e": 350,
"s": 314,
"text": "A value of cell 3 means Blank cell."
},
{
"code": null,
"e": 386,
"s": 350,
"text": "A value of cell 0 means Blank Wall."
},
{
"code": null,
"e": 457,
"s": 386,
"text": "Note: there are an only a single source and single destination(sink). "
},
{
"code": null,
"e": 468,
"s": 457,
"text": "Examples: "
},
{
"code": null,
"e": 554,
"s": 468,
"text": "Input: M[3][3] = {{ 0, 3, 2 }, { 3, 3, 0 }, { 1, 3, 0 }}; Output : Yes Explanation: "
},
{
"code": null,
"e": 664,
"s": 554,
"text": "Input: M[4][4] = {{ 0, 3, 1, 0 }, { 3, 0, 3, 3 }, { 2, 3, 0, 3 }, { 0, 3, 3, 3 }}; Output: Yes Explanation: "
},
{
"code": null,
"e": 694,
"s": 666,
"text": "Asked in: Adobe Interview "
},
{
"code": null,
"e": 966,
"s": 694,
"text": "Simple Solution: Recursion.Approach: Find the source index of the cell in each matrix and then recursively find a path from source index to destination in the matrix. The algorithm involves recursively finding all the paths until a final path is found to the destination."
},
{
"code": null,
"e": 980,
"s": 966,
"text": "Algorithm : "
},
{
"code": null,
"e": 1428,
"s": 980,
"text": "Traverse the matrix and find the starting index of the matrix.Create a recursive function that takes the index and visited matrix.Mark the current cell and check if the current cell is a destination or not. If the current cell is destination return true.Call the recursion function for all adjacent empty and unvisited cells.If any of the recursive functions returns true then unmark the cell and return true else unmark the cell and return false."
},
{
"code": null,
"e": 1491,
"s": 1428,
"text": "Traverse the matrix and find the starting index of the matrix."
},
{
"code": null,
"e": 1560,
"s": 1491,
"text": "Create a recursive function that takes the index and visited matrix."
},
{
"code": null,
"e": 1685,
"s": 1560,
"text": "Mark the current cell and check if the current cell is a destination or not. If the current cell is destination return true."
},
{
"code": null,
"e": 1757,
"s": 1685,
"text": "Call the recursion function for all adjacent empty and unvisited cells."
},
{
"code": null,
"e": 1880,
"s": 1757,
"text": "If any of the recursive functions returns true then unmark the cell and return true else unmark the cell and return false."
},
{
"code": null,
"e": 1884,
"s": 1880,
"text": "C++"
},
{
"code": null,
"e": 1889,
"s": 1884,
"text": "Java"
},
{
"code": null,
"e": 1897,
"s": 1889,
"text": "Python3"
},
{
"code": null,
"e": 1900,
"s": 1897,
"text": "C#"
},
{
"code": null,
"e": 1911,
"s": 1900,
"text": "Javascript"
},
{
"code": "// C++ program to find path between two// cell in matrix#include <iostream>using namespace std;#define N 4 // Method for checking boundariesbool isSafe(int i, int j, int matrix[][N]){ if (i >= 0 && i < N && j >= 0 && j < N) return true; return false;} // Returns true if there is a// path from a source (a// cell with value 1) to a// destination (a cell with// value 2)bool isPath(int matrix[][N], int i, int j, bool visited[][N]){ // Checking the boundaries, walls and // whether the cell is unvisited if (isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up bool up = isPath(matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left bool left = isPath(matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down bool down = isPath(matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right bool right = isPath(matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false;} // Method for finding and printing// whether the path exists or notvoid isPath(int matrix[][N]){ // Defining visited array to keep // track of already visited indexes bool visited[N][N]; // Flag to indicate whether the // path exists or not bool flag = false; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // if matrix[i][j] is source // and it is not visited if (matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (isPath(matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) cout << \"YES\"; else cout << \"NO\";} // Driver program to// check above functionint main(){ int matrix[N][N] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // calling isPath method isPath(matrix); return 0;} // This code is contributed by sudhanshugupta2019a.",
"e": 4377,
"s": 1911,
"text": null
},
{
"code": "// Java program to find path between two// cell in matrixclass Path { // Method for finding and printing // whether the path exists or not public static void isPath( int matrix[][], int n) { // Defining visited array to keep // track of already visited indexes boolean visited[][] = new boolean[n][n]; // Flag to indicate whether the // path exists or not boolean flag = false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // if matrix[i][j] is source // and it is not visited if ( matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (isPath( matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) System.out.println(\"YES\"); else System.out.println(\"NO\"); } // Method for checking boundaries public static boolean isSafe( int i, int j, int matrix[][]) { if ( i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length) return true; return false; } // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2) public static boolean isPath( int matrix[][], int i, int j, boolean visited[][]) { // Checking the boundaries, walls and // whether the cell is unvisited if ( isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up boolean up = isPath( matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left boolean left = isPath( matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down boolean down = isPath( matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right boolean right = isPath( matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false; } // driver program to // check above function public static void main(String[] args) { int matrix[][] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // calling isPath method isPath(matrix, 4); }} /* This code is contributed by Madhu Priya */",
"e": 7899,
"s": 4377,
"text": null
},
{
"code": "# Python3 program to find# path between two cell in matrix # Method for finding and printing# whether the path exists or notdef isPath(matrix, n): # Defining visited array to keep # track of already visited indexes visited = [[False for x in range (n)] for y in range (n)] # Flag to indicate whether the # path exists or not flag = False for i in range (n): for j in range (n): # If matrix[i][j] is source # and it is not visited if (matrix[i][j] == 1 and not visited[i][j]): # Starting from i, j and # then finding the path if (checkPath(matrix, i, j, visited)): # If path exists flag = True break if (flag): print(\"YES\") else: print(\"NO\") # Method for checking boundariesdef isSafe(i, j, matrix): if (i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix[0])): return True return False # Returns true if there is a# path from a source(a# cell with value 1) to a# destination(a cell with# value 2)def checkPath(matrix, i, j, visited): # Checking the boundaries, walls and # whether the cell is unvisited if (isSafe(i, j, matrix) and matrix[i][j] != 0 and not visited[i][j]): # Make the cell visited visited[i][j] = True # If the cell is the required # destination then return true if (matrix[i][j] == 2): return True # traverse up up = checkPath(matrix, i - 1, j, visited) # If path is found in up # direction return true if (up): return True # Traverse left left = checkPath(matrix, i, j - 1, visited) # If path is found in left # direction return true if (left): return True # Traverse down down = checkPath(matrix, i + 1, j, visited) # If path is found in down # direction return true if (down): return True # Traverse right right = checkPath(matrix, i, j + 1, visited) # If path is found in right # direction return true if (right): return True # No path has been found return False # Driver codeif __name__ == \"__main__\": matrix = [[0, 3, 0, 1], [3, 0, 3, 3], [2, 3, 3, 3], [0, 3, 3, 3]] # calling isPath method isPath(matrix, 4) # This code is contributed by Chitranayal",
"e": 10624,
"s": 7899,
"text": null
},
{
"code": "// C# program to find path between two// cell in matrixusing System; class GFG{ // Method for finding and printing// whether the path exists or notstatic void isPath(int[,] matrix, int n){ // Defining visited array to keep // track of already visited indexes bool[,] visited = new bool[n, n]; // Flag to indicate whether the // path exists or not bool flag = false; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If matrix[i][j] is source // and it is not visited if (matrix[i, j] == 1 && !visited[i, j]) // Starting from i, j and // then finding the path if (isPath(matrix, i, j, visited)) { // If path exists flag = true; break; } } } if (flag) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");} // Method for checking boundariespublic static bool isSafe(int i, int j, int[,] matrix){ if (i >= 0 && i < matrix.GetLength(0) && j >= 0 && j < matrix.GetLength(1)) return true; return false;} // Returns true if there is a path from// a source (a cell with value 1) to a// destination (a cell with value 2)public static bool isPath(int[,] matrix, int i, int j, bool[,] visited){ // Checking the boundaries, walls and // whether the cell is unvisited if (isSafe(i, j, matrix) && matrix[i, j] != 0 && !visited[i, j]) { // Make the cell visited visited[i, j] = true; // If the cell is the required // destination then return true if (matrix[i, j] == 2) return true; // Traverse up bool up = isPath(matrix, i - 1, j, visited); // If path is found in up // direction return true if (up) return true; // Traverse left bool left = isPath(matrix, i, j - 1, visited); // If path is found in left // direction return true if (left) return true; // Traverse down bool down = isPath(matrix, i + 1, j, visited); // If path is found in down // direction return true if (down) return true; // Traverse right bool right = isPath(matrix, i, j + 1, visited); // If path is found in right // direction return true if (right) return true; } // No path has been found return false;} // Driver code static void Main(){ int[,] matrix = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; // Calling isPath method isPath(matrix, 4);}} // This code is contributed by divyeshrabadiya07",
"e": 13703,
"s": 10624,
"text": null
},
{
"code": "<script> // JavaScript program to find path between two// cell in matrix // Method for finding and printing // whether the path exists or notfunction isPath(matrix,n){ // Defining visited array to keep // track of already visited indexes let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=new Array(n); for(let j=0;j<n;j++) { visited[i][j]=false; } } // Flag to indicate whether the // path exists or not let flag = false; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // if matrix[i][j] is source // and it is not visited if ( matrix[i][j] == 1 && !visited[i][j]) // Starting from i, j and // then finding the path if (checkPath( matrix, i, j, visited)) { // if path exists flag = true; break; } } } if (flag) document.write(\"YES<br>\"); else document.write(\"NO<br>\");} // Method for checking boundariesfunction isSafe(i,j,matrix){ if ( i >= 0 && i < matrix.length && j >= 0 && j < matrix[0].length) return true; return false;} // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2)function checkPath(matrix,i,j,visited){ // Checking the boundaries, walls and // whether the cell is unvisited if ( isSafe(i, j, matrix) && matrix[i][j] != 0 && !visited[i][j]) { // Make the cell visited visited[i][j] = true; // if the cell is the required // destination then return true if (matrix[i][j] == 2) return true; // traverse up let up = checkPath( matrix, i - 1, j, visited); // if path is found in up // direction return true if (up) return true; // traverse left let left = checkPath( matrix, i, j - 1, visited); // if path is found in left // direction return true if (left) return true; // traverse down let down = checkPath( matrix, i + 1, j, visited); // if path is found in down // direction return true if (down) return true; // traverse right let right = checkPath( matrix, i, j + 1, visited); // if path is found in right // direction return true if (right) return true; } // no path has been found return false;} // driver program to// check above functionlet matrix= [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]]; // calling isPath method isPath(matrix, 4); // This code is contributed by ab2127 </script>",
"e": 17110,
"s": 13703,
"text": null
},
{
"code": null,
"e": 17114,
"s": 17110,
"text": "YES"
},
{
"code": null,
"e": 17137,
"s": 17114,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 17299,
"s": 17137,
"text": "Time Complexity: O(n*m), In the worst case, we have to visit each cell only one time because we keep the visited array for not visiting the already visited cell."
},
{
"code": null,
"e": 17371,
"s": 17299,
"text": "Space Complexity: O(n*m), Space is required to store the visited array."
},
{
"code": null,
"e": 17674,
"s": 17371,
"text": "Efficient solution: Graph.Approach: The idea is to use Breadth-First Search. Consider each cell as a node and each boundary between any two adjacent cells be an edge. so the total number of Node is N * N. So the idea is to do a breadth-first search from the starting cell till the ending cell is found."
},
{
"code": null,
"e": 17687,
"s": 17674,
"text": "Algorithm: "
},
{
"code": null,
"e": 18183,
"s": 17687,
"text": "Create an empty Graph having N*N node(Vertex), push all nodes into a graph, and note down the source and sink vertex.Now apply BFS on the graph, create a queue and insert the source node in the queueRun a loop till the size of the queue is greater than 0Remove the front node of the queue and check if the node is the destination if the destination returns true. mark the nodeCheck all adjacent cells if unvisited and blank insert them in the queue.If the destination is not reached return true."
},
{
"code": null,
"e": 18301,
"s": 18183,
"text": "Create an empty Graph having N*N node(Vertex), push all nodes into a graph, and note down the source and sink vertex."
},
{
"code": null,
"e": 18384,
"s": 18301,
"text": "Now apply BFS on the graph, create a queue and insert the source node in the queue"
},
{
"code": null,
"e": 18440,
"s": 18384,
"text": "Run a loop till the size of the queue is greater than 0"
},
{
"code": null,
"e": 18563,
"s": 18440,
"text": "Remove the front node of the queue and check if the node is the destination if the destination returns true. mark the node"
},
{
"code": null,
"e": 18637,
"s": 18563,
"text": "Check all adjacent cells if unvisited and blank insert them in the queue."
},
{
"code": null,
"e": 18684,
"s": 18637,
"text": "If the destination is not reached return true."
},
{
"code": null,
"e": 18688,
"s": 18684,
"text": "C++"
},
{
"code": null,
"e": 18693,
"s": 18688,
"text": "Java"
},
{
"code": null,
"e": 18701,
"s": 18693,
"text": "Python3"
},
{
"code": null,
"e": 18712,
"s": 18701,
"text": "Javascript"
},
{
"code": "// C++ program to find path// between two cell in matrix#include <bits/stdc++.h>using namespace std;#define N 4 class Graph { int V; list<int>* adj; public: Graph(int V) { this->V = V; adj = new list<int>[V]; } void addEdge(int s, int d); bool BFS(int s, int d);}; // add edge to graphvoid Graph::addEdge(int s, int d){ adj[s].push_back(d);} // BFS function to find path// from source to sinkbool Graph::BFS(int s, int d){ // Base case if (s == d) return true; // Mark all the vertices as not visited bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and // enqueue it visited[s] = true; queue.push_back(s); // it will be used to get all adjacent // vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it for ( i = adj[s].begin(); i != adj[s].end(); ++i) { // If this adjacent node is the // destination node, then return true if (*i == d) return true; // Else, continue to do BFS if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } // If BFS is complete without visiting d return false;} bool isSafe(int i, int j, int M[][N]){ if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true;} // Returns true if there is// a path from a source (a// cell with value 1) to a// destination (a cell with// value 2)bool findPath(int M[][N]){ // source and destination int s, d; int V = N * N + 2; Graph g(V); // create graph with n*n node // each cell consider as node // Number of current vertex int k = 1; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) g.addEdge(k, k + 1); if (isSafe(i, j - 1, M)) g.addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) g.addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) g.addEdge(k, k - N); } // Source index if (M[i][j] == 1) s = k; // Destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return g.BFS(s, d);} // driver program to check// above functionint main(){ int M[N][N] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; (findPath(M) == true) ? cout << \"Yes\" : cout << \"No\" << endl; return 0;}",
"e": 21895,
"s": 18712,
"text": null
},
{
"code": "// Java program to find path between two// cell in matriximport java.util.*; class Graph { int V; List<List<Integer> > adj; Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) { adj.add(i, new ArrayList<>()); } } // add edge to graph void addEdge(int s, int d) { adj.get(s).add(d); } // BFS function to find path // from source to sink boolean BFS(int s, int d) { // Base case if (s == d) return true; // Mark all the vertices as not visited boolean[] visited = new boolean[V]; // Create a queue for BFS Queue<Integer> queue = new LinkedList<>(); // Mark the current node as visited and // enqueue it visited[s] = true; queue.offer(s); // it will be used to get all adjacent // vertices of a vertex List<Integer> edges; while (!queue.isEmpty()) { // Dequeue a vertex from queue s = queue.poll(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it edges = adj.get(s); for (int curr : edges) { // If this adjacent node is the // destination node, then return true if (curr == d) return true; // Else, continue to do BFS if (!visited[curr]) { visited[curr] = true; queue.offer(curr); } } } // If BFS is complete without visiting d return false; } static boolean isSafe( int i, int j, int[][] M) { int N = M.length; if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true; } // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2) static boolean findPath(int[][] M) { // Source and destination int s = -1, d = -1; int N = M.length; int V = N * N + 2; Graph g = new Graph(V); // Create graph with n*n node // each cell consider as node int k = 1; // Number of current vertex for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) g.addEdge(k, k + 1); if (isSafe(i, j - 1, M)) g.addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) g.addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) g.addEdge(k, k - N); } // source index if (M[i][j] == 1) s = k; // destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return g.BFS(s, d); } // Driver program to check above function public static void main( String[] args) throws Exception { int[][] M = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; System.out.println( ((findPath(M)) ? \"Yes\" : \"No\")); }} // This code is contributed by abhay379201",
"e": 25620,
"s": 21895,
"text": null
},
{
"code": "# Python3 program to find path between two# cell in matrixfrom collections import defaultdictclass Graph: def __init__(self): self.graph = defaultdict(list) # add edge to graph def addEdge(self, u, v): self.graph[u].append(v) # BFS function to find path from source to sink def BFS(self, s, d): # Base case if s == d: return True # Mark all the vertices as not visited visited = [False]*(len(self.graph) + 1) # Create a queue for BFS queue = [] queue.append(s) # Mark the current node as visited and # enqueue it visited[s] = True while(queue): # Dequeue a vertex from queue s = queue.pop(0) # Get all adjacent vertices of the # dequeued vertex s. If a adjacent has # not been visited, then mark it visited # and enqueue it for i in self.graph[s]: # If this adjacent node is the destination # node, then return true if i == d: return True # Else, continue to do BFS if visited[i] == False: queue.append(i) visited[i] = True # If BFS is complete without visiting d return False def isSafe(i, j, matrix): if i >= 0 and i <= len(matrix) and j >= 0 and j <= len(matrix[0]): return True else: return False # Returns true if there is a path from a source (a# cell with value 1) to a destination (a cell with# value 2)def findPath(M): s, d = None, None # source and destination N = len(M) g = Graph() # create graph with n * n node # each cell consider as node k = 1 # Number of current vertex for i in range(N): for j in range(N): if (M[i][j] != 0): # connect all 4 adjacent cell to # current cell if (isSafe(i, j + 1, M)): g.addEdge(k, k + 1) if (isSafe(i, j - 1, M)): g.addEdge(k, k - 1) if (isSafe(i + 1, j, M)): g.addEdge(k, k + N) if (isSafe(i - 1, j, M)): g.addEdge(k, k - N) if (M[i][j] == 1): s = k # destination index if (M[i][j] == 2): d = k k += 1 # find path Using BFS return g.BFS(s, d) # Driver codeif __name__=='__main__': M =[[0, 3, 0, 1], [3, 0, 3, 3], [2, 3, 3, 3], [0, 3, 3, 3]] if findPath(M): print(\"Yes\") else: print(\"No\") # This Code is Contributed by Vikash Kumar 37",
"e": 28349,
"s": 25620,
"text": null
},
{
"code": "<script> // JavaScript program to find path between two// cell in matrix let V;let adj=[]; function Graph(v){ V=v; for (let i = 0; i < V; i++) { adj.push([]); }} // add edge to graphfunction addEdge(s,d){ adj[s].push(d);} // BFS function to find path // from source to sinkfunction BFS(s,d){ // Base case if (s == d) return true; // Mark all the vertices as not visited let visited = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } // Create a queue for BFS let queue=[]; // Mark the current node as visited and // enqueue it visited[s] = true; queue.push(s); // it will be used to get all adjacent // vertices of a vertex let edges; while (queue.length!=0) { // Dequeue a vertex from queue s = queue.shift(); // Get all adjacent vertices of the // dequeued vertex s. If a adjacent has // not been visited, then mark it visited // and enqueue it edges = adj[s]; for (let curr=0;curr< edges.length;curr++) { // If this adjacent node is the // destination node, then return true if (edges[curr] == d) return true; // Else, continue to do BFS if (!visited[edges[curr]]) { visited[edges[curr]] = true; queue.push(edges[curr]); } } } // If BFS is complete without visiting d return false;} function isSafe(i,j,M){ let N = M.length; if ( (i < 0 || i >= N) || (j < 0 || j >= N) || M[i][j] == 0) return false; return true;} // Returns true if there is a // path from a source (a // cell with value 1) to a // destination (a cell with // value 2)function findPath(M){ // Source and destination let s = -1, d = -1; let N = M.length; let V = N * N + 2; Graph(V); // Create graph with n*n node // each cell consider as node let k = 1; // Number of current vertex for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (M[i][j] != 0) { // connect all 4 adjacent // cell to current cell if (isSafe(i, j + 1, M)) addEdge(k, k + 1); if (isSafe(i, j - 1, M)) addEdge(k, k - 1); if (i < N - 1 && isSafe(i + 1, j, M)) addEdge(k, k + N); if (i > 0 && isSafe(i - 1, j, M)) addEdge(k, k - N); } // source index if (M[i][j] == 1) s = k; // destination index if (M[i][j] == 2) d = k; k++; } } // find path Using BFS return BFS(s, d);} // Driver program to check above functionlet M = [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]];document.write(((findPath(M)) ? \"Yes\" : \"No\")); // This code is contributed by patel2127 </script>",
"e": 31758,
"s": 28349,
"text": null
},
{
"code": null,
"e": 31762,
"s": 31758,
"text": "Yes"
},
{
"code": null,
"e": 31785,
"s": 31762,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 31890,
"s": 31785,
"text": "Time Complexity: O(n*m). Every cell of the matrix is visited only once so the time complexity is O(n*m)."
},
{
"code": null,
"e": 31986,
"s": 31890,
"text": "Space Complexity: O(n*m). Space is required to store the visited array and to create the queue."
},
{
"code": null,
"e": 32052,
"s": 31986,
"text": "Simple and Efficient solution: The graph is the matrix in itself."
},
{
"code": null,
"e": 32124,
"s": 32052,
"text": "Approach: The idea is to use Breadth-First Search on the matrix itself."
},
{
"code": null,
"e": 32517,
"s": 32124,
"text": "Consider a cell=(i,j) as a vertex v in the BFS queue. A new vertex u is placed in the BFS queue if u=(i+1,j) or u=(i-1,j) or u=(i,j+1) or u=(i,j-1). Starting the BFS algorithm from cell=(i,j) such that M[i][j] is 1 and stopping either if there was a reachable vertex u=(i,j) such that M[i][j] is 2 and returning true or every cell was covered and there was no such a cell and returning false."
},
{
"code": null,
"e": 32530,
"s": 32517,
"text": "Algorithm: "
},
{
"code": null,
"e": 32552,
"s": 32530,
"text": "1) Create BFS queue q"
},
{
"code": null,
"e": 32652,
"s": 32552,
"text": "2) scan the matrix, if there exists a cell in the matrix such that its value is 1 then push it to q"
},
{
"code": null,
"e": 32833,
"s": 32652,
"text": "3) run BFS algorithm with q, skipping cells which are not valid. i.e: they are walls (value is 0) or outside the matrix bounds and marking them as walls upon successful visitation."
},
{
"code": null,
"e": 32944,
"s": 32833,
"text": " 3.1) if in the BFS algorithm process there was a vertex x=(i,j) such that M[i][j] is 2 stop and return true"
},
{
"code": null,
"e": 33059,
"s": 32944,
"text": "4) BFS algorithm terminated without returning true then there was no element M[i][j] which is 2, then return false"
},
{
"code": null,
"e": 33063,
"s": 33059,
"text": "C++"
},
{
"code": null,
"e": 33068,
"s": 33063,
"text": "Java"
},
{
"code": null,
"e": 33076,
"s": 33068,
"text": "Python3"
},
{
"code": null,
"e": 33079,
"s": 33076,
"text": "C#"
},
{
"code": null,
"e": 33090,
"s": 33079,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <queue>using namespace std;#define R 4#define C 4 // Structure to define a vertex u=(i,j)typedef struct BFSElement { BFSElement(int i, int j) { this->i = i; this->j = j; } int i; int j;} BFSElement; bool findPath(int M[R][C]){ // 1) Create BFS queue q queue<BFSElement> q; // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.push(BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (!q.empty()) { BFSElement x = q.front(); q.pop(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i > R || j < 0 || j > C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.push(BFSElement(i + k, j)); q.push(BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false;} // Main Driver codeint main(){ int M[R][C] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; (findPath(M) == true) ? cout << \"Yes\" : cout << \"No\" << endl; return 0;}",
"e": 35096,
"s": 33090,
"text": null
},
{
"code": "import java.io.*;import java.util.*; class BFSElement{ int i, j; BFSElement(int i, int j) { this.i = i; this.j = j; }} class GFG { static int R = 4, C = 4; BFSElement b; static boolean findPath(int M[][]) { // 1) Create BFS queue q Queue<BFSElement> q = new LinkedList<>(); // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.add(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.size() != 0) { BFSElement x = q.peek(); q.remove(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.add(new BFSElement(i + k, j)); q.add(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false; } // Main Driver code public static void main (String[] args) { int M[][] = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; if(findPath(M) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by avanitrachhadiya2155",
"e": 37501,
"s": 35096,
"text": null
},
{
"code": "class BFSElement: def __init__(self, i, j): self.i = i self.j = j R,C = 4,4 def findPath(M): # 1) Create BFS queue q q = [] # 2)scan the matrix for i in range(R): for j in range(C): # if there exists a cell in the matrix such # that its value is 1 then append it to q if (M[i][j] == 1): q.append(BFSElement(i, j)) break # 3) run BFS algorithm with q. while (len(q) != 0): x = q[0] q = q[1:] i = x.i j = x.j # skipping cells which are not valid. # if outside the matrix bounds if (i < 0 or i >= R or j < 0 or j >= C): continue # if they are walls (value is 0). if (M[i][j] == 0): continue # 3.1) if in the BFS algorithm process there was a # vertex x=(i,j) such that M[i][j] is 2 stop and # return True if (M[i][j] == 2): return True # marking as wall upon successful visitation M[i][j] = 0 # appending to queue u=(i,j+1),u=(i,j-1) # u=(i+1,j),u=(i-1,j) for k in range(-1, 2, 2): q.append(BFSElement(i + k, j)) q.append(BFSElement(i, j + k)) # BFS algorithm terminated without returning True # then there was no element M[i][j] which is 2, then # return false return False # Main Driver codeM = [[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]]if(findPath(M) == True): print(\"Yes\")else: print(\"No\") # This code is contributed by shinjanpatra",
"e": 39169,
"s": 37501,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class BFSElement{ public int i, j; public BFSElement(int i, int j) { this.i = i; this.j = j; }} public class GFG{ static int R = 4, C = 4; static bool findPath(int[,] M) { // 1) Create BFS queue q Queue<BFSElement> q = new Queue<BFSElement>(); // 2)scan the matrix for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i, j] == 1) { q.Enqueue(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.Count != 0) { BFSElement x = q.Peek(); q.Dequeue(); int i = x.i; int j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i, j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i, j] == 2) return true; // marking as wall upon successful visitation M[i, j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (int k = -1; k <= 1; k += 2) { q.Enqueue(new BFSElement(i + k, j)); q.Enqueue(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false; } // Main Driver code static public void Main (){ int[,] M = { { 0, 3, 0, 1 }, { 3, 0, 3, 3 }, { 2, 3, 3, 3 }, { 0, 3, 3, 3 } }; if(findPath(M) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by rag2127",
"e": 41112,
"s": 39169,
"text": null
},
{
"code": "<script> class BFSElement{ constructor(i,j) { this.i=i; this.j=j; }} let R = 4, C = 4;let b; function findPath(M){ // 1) Create BFS queue q let q = []; // 2)scan the matrix for (let i = 0; i < R; ++i) { for (let j = 0; j < C; ++j) { // if there exists a cell in the matrix such // that its value is 1 then push it to q if (M[i][j] == 1) { q.push(new BFSElement(i, j)); break; } } } // 3) run BFS algorithm with q. while (q.length != 0) { let x = q.shift(); let i = x.i; let j = x.j; // skipping cells which are not valid. // if outside the matrix bounds if (i < 0 || i >= R || j < 0 || j >= C) continue; // if they are walls (value is 0). if (M[i][j] == 0) continue; // 3.1) if in the BFS algorithm process there was a // vertex x=(i,j) such that M[i][j] is 2 stop and // return true if (M[i][j] == 2) return true; // marking as wall upon successful visitation M[i][j] = 0; // pushing to queue u=(i,j+1),u=(i,j-1) // u=(i+1,j),u=(i-1,j) for (let k = -1; k <= 1; k += 2) { q.push(new BFSElement(i + k, j)); q.push(new BFSElement(i, j + k)); } } // BFS algorithm terminated without returning true // then there was no element M[i][j] which is 2, then // return false return false;} // Main Driver codelet M=[[ 0, 3, 0, 1 ], [ 3, 0, 3, 3 ], [ 2, 3, 3, 3 ], [ 0, 3, 3, 3 ]];if(findPath(M) == true) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by unknown2108</script>",
"e": 43205,
"s": 41112,
"text": null
},
{
"code": null,
"e": 43209,
"s": 43205,
"text": "Yes"
},
{
"code": null,
"e": 43235,
"s": 43209,
"text": "Time Complexity: O(n*m)."
},
{
"code": null,
"e": 43261,
"s": 43235,
"text": "Space Complexity: O(n*m)."
},
{
"code": null,
"e": 43303,
"s": 43261,
"text": "The improvement is contributed by Ephi F."
},
{
"code": null,
"e": 43724,
"s": 43303,
"text": "This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43736,
"s": 43724,
"text": "madhu priya"
},
{
"code": null,
"e": 43752,
"s": 43736,
"text": "Vikash Kumar 37"
},
{
"code": null,
"e": 43771,
"s": 43752,
"text": "RambhagwanPrajapat"
},
{
"code": null,
"e": 43783,
"s": 43771,
"text": "abhay379201"
},
{
"code": null,
"e": 43794,
"s": 43783,
"text": "andrew1234"
},
{
"code": null,
"e": 43811,
"s": 43794,
"text": "vashisthamadhur2"
},
{
"code": null,
"e": 43817,
"s": 43811,
"text": "ukasp"
},
{
"code": null,
"e": 43835,
"s": 43817,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 43842,
"s": 43835,
"text": "ephi2g"
},
{
"code": null,
"e": 43862,
"s": 43842,
"text": "sudhanshugupta2019a"
},
{
"code": null,
"e": 43883,
"s": 43862,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 43891,
"s": 43883,
"text": "rag2127"
},
{
"code": null,
"e": 43907,
"s": 43891,
"text": "simranarora5sos"
},
{
"code": null,
"e": 43914,
"s": 43907,
"text": "ab2127"
},
{
"code": null,
"e": 43924,
"s": 43914,
"text": "patel2127"
},
{
"code": null,
"e": 43936,
"s": 43924,
"text": "unknown2108"
},
{
"code": null,
"e": 43949,
"s": 43936,
"text": "shinjanpatra"
},
{
"code": null,
"e": 43960,
"s": 43949,
"text": "ayushak969"
},
{
"code": null,
"e": 43966,
"s": 43960,
"text": "Adobe"
},
{
"code": null,
"e": 43973,
"s": 43966,
"text": "Amazon"
},
{
"code": null,
"e": 43977,
"s": 43973,
"text": "BFS"
},
{
"code": null,
"e": 43992,
"s": 43977,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 43998,
"s": 43992,
"text": "Graph"
},
{
"code": null,
"e": 44005,
"s": 43998,
"text": "Matrix"
},
{
"code": null,
"e": 44020,
"s": 44005,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 44027,
"s": 44020,
"text": "Amazon"
},
{
"code": null,
"e": 44033,
"s": 44027,
"text": "Adobe"
},
{
"code": null,
"e": 44040,
"s": 44033,
"text": "Matrix"
},
{
"code": null,
"e": 44046,
"s": 44040,
"text": "Graph"
},
{
"code": null,
"e": 44050,
"s": 44046,
"text": "BFS"
}
] |
NavigableSet in Java with Examples
|
28 Jun, 2021
NavigableSet represents a navigable set in Java Collection Framework. The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet. For example, the NavigableSet interface can navigate the set in reverse order compared to the order defined in SortedSet. A NavigableSet may be accessed and traversed in either ascending or descending order. The classes that implement this interface are, TreeSet and ConcurrentSkipListSet
Here, E is the type of elements maintained by this set.
All Superinterfaces:
Collection<E>, Iterable<E>, Set<E>, SortedSet<E>
All Known Implementing Classes:
ConcurrentSkipListSet, TreeSet<E>
Declaration: The NavigableSet is declared as
public interface NavigableSet<E> extends SortedSet<E>
Creating NavigableSet Objects
Since NavigableSet is an interface, objects cannot be created of the type NavigableSet. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the NavigableSet. This type-safe set can be defined as:
// Obj is the type of the object to be stored in NavigableSet
NavigableSet<Obj> set = new TreeSet<Obj> ();
Example:
Java
// Java program to demonstrate// the working of NavigableSetimport java.util.NavigableSet;import java.util.TreeSet; public class NavigableSetDemo{ public static void main(String[] args) { NavigableSet<Integer> ns = new TreeSet<>(); ns.add(0); ns.add(1); ns.add(2); ns.add(3); ns.add(4); ns.add(5); ns.add(6); // Get a reverse view of the navigable set NavigableSet<Integer> reverseNs = ns.descendingSet(); // Print the normal and reverse views System.out.println("Normal order: " + ns); System.out.println("Reverse order: " + reverseNs); NavigableSet<Integer> threeOrMore = ns.tailSet(3, true); System.out.println("3 or more: " + threeOrMore); System.out.println("lower(3): " + ns.lower(3)); System.out.println("floor(3): " + ns.floor(3)); System.out.println("higher(3): " + ns.higher(3)); System.out.println("ceiling(3): " + ns.ceiling(3)); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollLast(): " + ns.pollLast()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("Navigable Set: " + ns); System.out.println("pollFirst(): " + ns.pollFirst()); System.out.println("pollLast(): " + ns.pollLast()); }}
Normal order: [0, 1, 2, 3, 4, 5, 6]
Reverse order: [6, 5, 4, 3, 2, 1, 0]
3 or more: [3, 4, 5, 6]
lower(3): 2
floor(3): 3
higher(3): 4
ceiling(3): 3
pollFirst(): 0
Navigable Set: [1, 2, 3, 4, 5, 6]
pollLast(): 6
Navigable Set: [1, 2, 3, 4, 5]
pollFirst(): 1
Navigable Set: [2, 3, 4, 5]
pollFirst(): 2
Navigable Set: [3, 4, 5]
pollFirst(): 3
Navigable Set: [4, 5]
pollFirst(): 4
pollLast(): 5
Since NavigableSet is an interface, it can be used only with a class that implements this interface. TreeSet is the class that implements the NavigableSet interface. Now, let’s see how to perform a few frequently used operations on the TreeSet.
1. Adding Elements: In order to add an element to the NavigableSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in the ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the NavigableSet.
Java
// Java code to demonstrate// adding of elements in// NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("A"); System.out.println(ts); }}
Output:
[A, B, C]
2. Accessing the Elements: After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc.
contains()
first()
last()
Java
// Java program to access// the elements of NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("A"); System.out.println("Navigable Set is " + ts); String check = "D"; // Check if the above string exists in // the NavigableSet or not System.out.println("Contains " + check + " " + ts.contains(check)); // Print the first element in // the NavigableSet System.out.println("First Value " + ts.first()); // Print the last element in // the NavigableSet System.out.println("Last Value " + ts.last()); }}
Output:
Navigable Set is [A, B, C]
Contains D false
First Value A
Last Value C
3. Removing the Values: The values can be removed from the NavigableSet using the remove(), pollFirst(), pollLast() methods.
remove()
pollFirst()
pollLast()
Java
// Java Program to remove the// elements from NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("A"); ts.add("B"); ts.add("C"); ts.add("B"); ts.add("D"); ts.add("E"); System.out.println("Initial TreeSet " + ts); // Removing the element b ts.remove("B"); System.out.println("After removing element " + ts); // Remove the First element of TreeSet ts.pollFirst(); System.out.println( "After the removal of First Element " + ts); // Remove the Last element of TreeSet ts.pollLast(); System.out.println( "After the removal of Last Element " + ts); }}
Output:
Initial TreeSet [A, B, C, D, E]
After removing element [A, C, D, E]
After the removal of First Element [C, D, E]
After the removal of Last Element [C, D]
4. Iterating through the NavigableSet: There are various ways to iterate through the NavigableSet. The most famous one is to use the enhanced for loop.
Java
// Java program to iterate// through NavigableSet import java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add("C"); ts.add("D"); ts.add("E"); ts.add("A"); ts.add("B"); ts.add("Z"); // Iterating though the NavigableSet for (String value : ts) System.out.print(value + ", "); System.out.println(); }}
Output:
A, B, C, D, E, Z,
The following are the methods present in the NavigableSet interface.
METHOD
DESCRIPTION
subSet(E fromElement, boolean
fromInclusive, E toElement, boolean toInclusive)
METHOD
DESCRIPTION
METHOD
DESCRIPTION
This method is used to check whether the set contains all the elements present in the given collection or not.
This method returns true if the set contains all the elements and returns false if any of the elements are missing.
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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ganeshchowdharysadanala
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 622,
"s": 52,
"text": "NavigableSet represents a navigable set in Java Collection Framework. The NavigableSet interface inherits from the SortedSet interface. It behaves like a SortedSet with the exception that we have navigation methods available in addition to the sorting mechanisms of the SortedSet. For example, the NavigableSet interface can navigate the set in reverse order compared to the order defined in SortedSet. A NavigableSet may be accessed and traversed in either ascending or descending order. The classes that implement this interface are, TreeSet and ConcurrentSkipListSet"
},
{
"code": null,
"e": 678,
"s": 622,
"text": "Here, E is the type of elements maintained by this set."
},
{
"code": null,
"e": 699,
"s": 678,
"text": "All Superinterfaces:"
},
{
"code": null,
"e": 748,
"s": 699,
"text": "Collection<E>, Iterable<E>, Set<E>, SortedSet<E>"
},
{
"code": null,
"e": 780,
"s": 748,
"text": "All Known Implementing Classes:"
},
{
"code": null,
"e": 814,
"s": 780,
"text": "ConcurrentSkipListSet, TreeSet<E>"
},
{
"code": null,
"e": 859,
"s": 814,
"text": "Declaration: The NavigableSet is declared as"
},
{
"code": null,
"e": 915,
"s": 859,
"text": "public interface NavigableSet<E> extends SortedSet<E> "
},
{
"code": null,
"e": 945,
"s": 915,
"text": "Creating NavigableSet Objects"
},
{
"code": null,
"e": 1291,
"s": 945,
"text": "Since NavigableSet is an interface, objects cannot be created of the type NavigableSet. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the NavigableSet. This type-safe set can be defined as:"
},
{
"code": null,
"e": 1353,
"s": 1291,
"text": "// Obj is the type of the object to be stored in NavigableSet"
},
{
"code": null,
"e": 1398,
"s": 1353,
"text": "NavigableSet<Obj> set = new TreeSet<Obj> ();"
},
{
"code": null,
"e": 1407,
"s": 1398,
"text": "Example:"
},
{
"code": null,
"e": 1412,
"s": 1407,
"text": "Java"
},
{
"code": "// Java program to demonstrate// the working of NavigableSetimport java.util.NavigableSet;import java.util.TreeSet; public class NavigableSetDemo{ public static void main(String[] args) { NavigableSet<Integer> ns = new TreeSet<>(); ns.add(0); ns.add(1); ns.add(2); ns.add(3); ns.add(4); ns.add(5); ns.add(6); // Get a reverse view of the navigable set NavigableSet<Integer> reverseNs = ns.descendingSet(); // Print the normal and reverse views System.out.println(\"Normal order: \" + ns); System.out.println(\"Reverse order: \" + reverseNs); NavigableSet<Integer> threeOrMore = ns.tailSet(3, true); System.out.println(\"3 or more: \" + threeOrMore); System.out.println(\"lower(3): \" + ns.lower(3)); System.out.println(\"floor(3): \" + ns.floor(3)); System.out.println(\"higher(3): \" + ns.higher(3)); System.out.println(\"ceiling(3): \" + ns.ceiling(3)); System.out.println(\"pollFirst(): \" + ns.pollFirst()); System.out.println(\"Navigable Set: \" + ns); System.out.println(\"pollLast(): \" + ns.pollLast()); System.out.println(\"Navigable Set: \" + ns); System.out.println(\"pollFirst(): \" + ns.pollFirst()); System.out.println(\"Navigable Set: \" + ns); System.out.println(\"pollFirst(): \" + ns.pollFirst()); System.out.println(\"Navigable Set: \" + ns); System.out.println(\"pollFirst(): \" + ns.pollFirst()); System.out.println(\"Navigable Set: \" + ns); System.out.println(\"pollFirst(): \" + ns.pollFirst()); System.out.println(\"pollLast(): \" + ns.pollLast()); }}",
"e": 3093,
"s": 1412,
"text": null
},
{
"code": null,
"e": 3494,
"s": 3093,
"text": "Normal order: [0, 1, 2, 3, 4, 5, 6]\nReverse order: [6, 5, 4, 3, 2, 1, 0]\n3 or more: [3, 4, 5, 6]\nlower(3): 2\nfloor(3): 3\nhigher(3): 4\nceiling(3): 3\npollFirst(): 0\nNavigable Set: [1, 2, 3, 4, 5, 6]\npollLast(): 6\nNavigable Set: [1, 2, 3, 4, 5]\npollFirst(): 1\nNavigable Set: [2, 3, 4, 5]\npollFirst(): 2\nNavigable Set: [3, 4, 5]\npollFirst(): 3\nNavigable Set: [4, 5]\npollFirst(): 4\npollLast(): 5\n\n\n"
},
{
"code": null,
"e": 3739,
"s": 3494,
"text": "Since NavigableSet is an interface, it can be used only with a class that implements this interface. TreeSet is the class that implements the NavigableSet interface. Now, let’s see how to perform a few frequently used operations on the TreeSet."
},
{
"code": null,
"e": 4154,
"s": 3739,
"text": "1. Adding Elements: In order to add an element to the NavigableSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in the ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the NavigableSet."
},
{
"code": null,
"e": 4159,
"s": 4154,
"text": "Java"
},
{
"code": "// Java code to demonstrate// adding of elements in// NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add(\"A\"); ts.add(\"B\"); ts.add(\"C\"); ts.add(\"A\"); System.out.println(ts); }}",
"e": 4558,
"s": 4159,
"text": null
},
{
"code": null,
"e": 4566,
"s": 4558,
"text": "Output:"
},
{
"code": null,
"e": 4579,
"s": 4566,
"text": "[A, B, C]\n\n\n"
},
{
"code": null,
"e": 4734,
"s": 4579,
"text": "2. Accessing the Elements: After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc."
},
{
"code": null,
"e": 4745,
"s": 4734,
"text": "contains()"
},
{
"code": null,
"e": 4753,
"s": 4745,
"text": "first()"
},
{
"code": null,
"e": 4760,
"s": 4753,
"text": "last()"
},
{
"code": null,
"e": 4765,
"s": 4760,
"text": "Java"
},
{
"code": "// Java program to access// the elements of NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add(\"A\"); ts.add(\"B\"); ts.add(\"C\"); ts.add(\"A\"); System.out.println(\"Navigable Set is \" + ts); String check = \"D\"; // Check if the above string exists in // the NavigableSet or not System.out.println(\"Contains \" + check + \" \" + ts.contains(check)); // Print the first element in // the NavigableSet System.out.println(\"First Value \" + ts.first()); // Print the last element in // the NavigableSet System.out.println(\"Last Value \" + ts.last()); }}",
"e": 5625,
"s": 4765,
"text": null
},
{
"code": null,
"e": 5633,
"s": 5625,
"text": "Output:"
},
{
"code": null,
"e": 5707,
"s": 5633,
"text": "Navigable Set is [A, B, C]\nContains D false\nFirst Value A\nLast Value C\n\n\n"
},
{
"code": null,
"e": 5832,
"s": 5707,
"text": "3. Removing the Values: The values can be removed from the NavigableSet using the remove(), pollFirst(), pollLast() methods."
},
{
"code": null,
"e": 5841,
"s": 5832,
"text": "remove()"
},
{
"code": null,
"e": 5853,
"s": 5841,
"text": "pollFirst()"
},
{
"code": null,
"e": 5864,
"s": 5853,
"text": "pollLast()"
},
{
"code": null,
"e": 5869,
"s": 5864,
"text": "Java"
},
{
"code": "// Java Program to remove the// elements from NavigableSetimport java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add(\"A\"); ts.add(\"B\"); ts.add(\"C\"); ts.add(\"B\"); ts.add(\"D\"); ts.add(\"E\"); System.out.println(\"Initial TreeSet \" + ts); // Removing the element b ts.remove(\"B\"); System.out.println(\"After removing element \" + ts); // Remove the First element of TreeSet ts.pollFirst(); System.out.println( \"After the removal of First Element \" + ts); // Remove the Last element of TreeSet ts.pollLast(); System.out.println( \"After the removal of Last Element \" + ts); }}",
"e": 6743,
"s": 5869,
"text": null
},
{
"code": null,
"e": 6751,
"s": 6743,
"text": "Output:"
},
{
"code": null,
"e": 6908,
"s": 6751,
"text": "Initial TreeSet [A, B, C, D, E]\nAfter removing element [A, C, D, E]\nAfter the removal of First Element [C, D, E]\nAfter the removal of Last Element [C, D]\n\n\n"
},
{
"code": null,
"e": 7060,
"s": 6908,
"text": "4. Iterating through the NavigableSet: There are various ways to iterate through the NavigableSet. The most famous one is to use the enhanced for loop."
},
{
"code": null,
"e": 7065,
"s": 7060,
"text": "Java"
},
{
"code": "// Java program to iterate// through NavigableSet import java.util.*;import java.io.*; class NavigableSetDemo { public static void main(String[] args) { NavigableSet<String> ts = new TreeSet<String>(); // Elements are added using add() method ts.add(\"C\"); ts.add(\"D\"); ts.add(\"E\"); ts.add(\"A\"); ts.add(\"B\"); ts.add(\"Z\"); // Iterating though the NavigableSet for (String value : ts) System.out.print(value + \", \"); System.out.println(); }}",
"e": 7606,
"s": 7065,
"text": null
},
{
"code": null,
"e": 7614,
"s": 7606,
"text": "Output:"
},
{
"code": null,
"e": 7637,
"s": 7614,
"text": "A, B, C, D, E, Z, \n\n\n"
},
{
"code": null,
"e": 7707,
"s": 7637,
"text": "The following are the methods present in the NavigableSet interface. "
},
{
"code": null,
"e": 7714,
"s": 7707,
"text": "METHOD"
},
{
"code": null,
"e": 7726,
"s": 7714,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 7757,
"s": 7726,
"text": "subSet(E fromElement, boolean"
},
{
"code": null,
"e": 7806,
"s": 7757,
"text": "fromInclusive, E toElement, boolean toInclusive)"
},
{
"code": null,
"e": 7813,
"s": 7806,
"text": "METHOD"
},
{
"code": null,
"e": 7825,
"s": 7813,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 7832,
"s": 7825,
"text": "METHOD"
},
{
"code": null,
"e": 7844,
"s": 7832,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 7955,
"s": 7844,
"text": "This method is used to check whether the set contains all the elements present in the given collection or not."
},
{
"code": null,
"e": 8071,
"s": 7955,
"text": "This method returns true if the set contains all the elements and returns false if any of the elements are missing."
},
{
"code": null,
"e": 8494,
"s": 8071,
"text": "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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8518,
"s": 8494,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 8535,
"s": 8518,
"text": "Java-Collections"
},
{
"code": null,
"e": 8540,
"s": 8535,
"text": "Java"
},
{
"code": null,
"e": 8545,
"s": 8540,
"text": "Java"
},
{
"code": null,
"e": 8562,
"s": 8545,
"text": "Java-Collections"
}
] |
How to simulate pressing enter in HTML text input with Selenium ? - GeeksforGeeks
|
15 Dec, 2021
Selenium is an inbuilt module available in python that allows users to make automated suites and tests. We can build code or scripts to perform tasks automatically in a web browser using selenium. Selenium is used to test the software by automation. Also, programmers can create automated test cases for the software or app using the selenium.
By reading this tutorial, users will be able to simulate pressing enter in HTML text input with selenium. Also, we will write a simple code that can search text on the Wikipedia website automatically and perform automated login on the Geeksforgeeks website.
Prerequisite:
Python 3.7+
Selenium
web driver
Users should have installed python 3.7+ in their system to work with the selenium. To install selenium run the below command on the terminal.
pip install selenium
Download chrome webdriver: Next, users need to download webdriver according to which browser they want to run automated software. Chrome webdriver is one of the best webdriver. Users can download chrome webdriver from here. While downloading the chrome webdriver, make sure that the webdriver version is compatible with the browser version.
To simulate the pressing enter, users can add the below line in the python automation script code.
HTML_ELEMENT.send_keys(Keys.ENTER)
Search text using selenium on Wikipedia: In this part, we will cover that how users can open Wikipedia sites and search text automatically on Wikipedia or other websites using selenium.
Approach:
Import webdriver from seleniumInitialize webdriver pathOpen any URLFind the search element using any method from belowInput text into the search fieldPress enter key to search input text
Import webdriver from selenium
Initialize webdriver path
Open any URL
Find the search element using any method from below
Input text into the search field
Press enter key to search input text
Example:
Python3
# Python program to search automatically# on wikipedia using selenium # Import webdriverfrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom time import sleep, strftime # Initialize webdriver objectchromedriver_path = '<Chrome webdriver path>'webdriver = webdriver.Chrome(executable_path=chromedriver_path) try: # Opening wikipedia website webdriver.get("https://en.wikipedia.org") # Finding the search field by id input = webdriver.find_element_by_id("searchInput") # Sending input text to search field input.send_keys("Python") # Pressing enter to search input text input.send_keys(Keys.ENTER) sleep(10) finally: # Closing the webdriver webdriver.close()
Note: Don’t forget to set the chrome web driver’s path.
Output:
Log in automatically to GeeksForGeeks using the selenium module: In this part, we will cover that how users can log in to Geeksforgeeks using the selenium bot.
Approach:
Import webdriver from seleniumInitialize webdriver pathOpen Geeksforgeeks URLFind and press enter on the sign-in buttonFind the username and password element on Geeksforgeeks websiteSet username and password into the input fieldFind the login buttonPressing enter or click on the login button
Import webdriver from selenium
Initialize webdriver path
Open Geeksforgeeks URL
Find and press enter on the sign-in button
Find the username and password element on Geeksforgeeks website
Set username and password into the input field
Find the login button
Pressing enter or click on the login button
Example:
Python3
# Python program to login to the Geeksforgeeks# using selenium from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom time import sleep, strftime chromedriver_path = '<chrome web driver path>'webdriver = webdriver.Chrome(executable_path=chromedriver_path) try: # Opening the geeksforgeeks website webdriver.get('https://www.geeksforgeeks.org/') # Clicking on the sign in button signIn = webdriver.find_element_by_css_selector('#userProfileId > a') signIn.click() sleep(4) # Finding the username input field and sending the username username = webdriver.find_element_by_css_selector('#luser') username.send_keys('<Geeksforgeeks Username>') # Finding the password input field and sending password password = webdriver.find_element_by_css_selector('#password') password.send_keys('<Geeksforgeeks password>') # Pressing enter on the signin button button_login = webdriver.find_element_by_css_selector( '#Login > button') button_login.click() sleep(6) finally: webdriver.close()
Note: Don’t forget to set web driver’s path, Geeksforgeeks username, and password.
Output:
gabaa406
Picked
Python-selenium
selenium
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25539,
"s": 25511,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25883,
"s": 25539,
"text": "Selenium is an inbuilt module available in python that allows users to make automated suites and tests. We can build code or scripts to perform tasks automatically in a web browser using selenium. Selenium is used to test the software by automation. Also, programmers can create automated test cases for the software or app using the selenium."
},
{
"code": null,
"e": 26141,
"s": 25883,
"text": "By reading this tutorial, users will be able to simulate pressing enter in HTML text input with selenium. Also, we will write a simple code that can search text on the Wikipedia website automatically and perform automated login on the Geeksforgeeks website."
},
{
"code": null,
"e": 26155,
"s": 26141,
"text": "Prerequisite:"
},
{
"code": null,
"e": 26167,
"s": 26155,
"text": "Python 3.7+"
},
{
"code": null,
"e": 26176,
"s": 26167,
"text": "Selenium"
},
{
"code": null,
"e": 26187,
"s": 26176,
"text": "web driver"
},
{
"code": null,
"e": 26329,
"s": 26187,
"text": "Users should have installed python 3.7+ in their system to work with the selenium. To install selenium run the below command on the terminal."
},
{
"code": null,
"e": 26350,
"s": 26329,
"text": "pip install selenium"
},
{
"code": null,
"e": 26691,
"s": 26350,
"text": "Download chrome webdriver: Next, users need to download webdriver according to which browser they want to run automated software. Chrome webdriver is one of the best webdriver. Users can download chrome webdriver from here. While downloading the chrome webdriver, make sure that the webdriver version is compatible with the browser version."
},
{
"code": null,
"e": 26790,
"s": 26691,
"text": "To simulate the pressing enter, users can add the below line in the python automation script code."
},
{
"code": null,
"e": 26825,
"s": 26790,
"text": "HTML_ELEMENT.send_keys(Keys.ENTER)"
},
{
"code": null,
"e": 27012,
"s": 26825,
"text": "Search text using selenium on Wikipedia: In this part, we will cover that how users can open Wikipedia sites and search text automatically on Wikipedia or other websites using selenium. "
},
{
"code": null,
"e": 27022,
"s": 27012,
"text": "Approach:"
},
{
"code": null,
"e": 27209,
"s": 27022,
"text": "Import webdriver from seleniumInitialize webdriver pathOpen any URLFind the search element using any method from belowInput text into the search fieldPress enter key to search input text"
},
{
"code": null,
"e": 27240,
"s": 27209,
"text": "Import webdriver from selenium"
},
{
"code": null,
"e": 27266,
"s": 27240,
"text": "Initialize webdriver path"
},
{
"code": null,
"e": 27279,
"s": 27266,
"text": "Open any URL"
},
{
"code": null,
"e": 27331,
"s": 27279,
"text": "Find the search element using any method from below"
},
{
"code": null,
"e": 27364,
"s": 27331,
"text": "Input text into the search field"
},
{
"code": null,
"e": 27401,
"s": 27364,
"text": "Press enter key to search input text"
},
{
"code": null,
"e": 27410,
"s": 27401,
"text": "Example:"
},
{
"code": null,
"e": 27418,
"s": 27410,
"text": "Python3"
},
{
"code": "# Python program to search automatically# on wikipedia using selenium # Import webdriverfrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom time import sleep, strftime # Initialize webdriver objectchromedriver_path = '<Chrome webdriver path>'webdriver = webdriver.Chrome(executable_path=chromedriver_path) try: # Opening wikipedia website webdriver.get(\"https://en.wikipedia.org\") # Finding the search field by id input = webdriver.find_element_by_id(\"searchInput\") # Sending input text to search field input.send_keys(\"Python\") # Pressing enter to search input text input.send_keys(Keys.ENTER) sleep(10) finally: # Closing the webdriver webdriver.close()",
"e": 28157,
"s": 27418,
"text": null
},
{
"code": null,
"e": 28213,
"s": 28157,
"text": "Note: Don’t forget to set the chrome web driver’s path."
},
{
"code": null,
"e": 28221,
"s": 28213,
"text": "Output:"
},
{
"code": null,
"e": 28382,
"s": 28221,
"text": "Log in automatically to GeeksForGeeks using the selenium module: In this part, we will cover that how users can log in to Geeksforgeeks using the selenium bot. "
},
{
"code": null,
"e": 28392,
"s": 28382,
"text": "Approach:"
},
{
"code": null,
"e": 28685,
"s": 28392,
"text": "Import webdriver from seleniumInitialize webdriver pathOpen Geeksforgeeks URLFind and press enter on the sign-in buttonFind the username and password element on Geeksforgeeks websiteSet username and password into the input fieldFind the login buttonPressing enter or click on the login button"
},
{
"code": null,
"e": 28716,
"s": 28685,
"text": "Import webdriver from selenium"
},
{
"code": null,
"e": 28742,
"s": 28716,
"text": "Initialize webdriver path"
},
{
"code": null,
"e": 28765,
"s": 28742,
"text": "Open Geeksforgeeks URL"
},
{
"code": null,
"e": 28808,
"s": 28765,
"text": "Find and press enter on the sign-in button"
},
{
"code": null,
"e": 28872,
"s": 28808,
"text": "Find the username and password element on Geeksforgeeks website"
},
{
"code": null,
"e": 28919,
"s": 28872,
"text": "Set username and password into the input field"
},
{
"code": null,
"e": 28941,
"s": 28919,
"text": "Find the login button"
},
{
"code": null,
"e": 28985,
"s": 28941,
"text": "Pressing enter or click on the login button"
},
{
"code": null,
"e": 28994,
"s": 28985,
"text": "Example:"
},
{
"code": null,
"e": 29002,
"s": 28994,
"text": "Python3"
},
{
"code": "# Python program to login to the Geeksforgeeks# using selenium from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom time import sleep, strftime chromedriver_path = '<chrome web driver path>'webdriver = webdriver.Chrome(executable_path=chromedriver_path) try: # Opening the geeksforgeeks website webdriver.get('https://www.geeksforgeeks.org/') # Clicking on the sign in button signIn = webdriver.find_element_by_css_selector('#userProfileId > a') signIn.click() sleep(4) # Finding the username input field and sending the username username = webdriver.find_element_by_css_selector('#luser') username.send_keys('<Geeksforgeeks Username>') # Finding the password input field and sending password password = webdriver.find_element_by_css_selector('#password') password.send_keys('<Geeksforgeeks password>') # Pressing enter on the signin button button_login = webdriver.find_element_by_css_selector( '#Login > button') button_login.click() sleep(6) finally: webdriver.close()",
"e": 30082,
"s": 29002,
"text": null
},
{
"code": null,
"e": 30165,
"s": 30082,
"text": "Note: Don’t forget to set web driver’s path, Geeksforgeeks username, and password."
},
{
"code": null,
"e": 30173,
"s": 30165,
"text": "Output:"
},
{
"code": null,
"e": 30182,
"s": 30173,
"text": "gabaa406"
},
{
"code": null,
"e": 30189,
"s": 30182,
"text": "Picked"
},
{
"code": null,
"e": 30205,
"s": 30189,
"text": "Python-selenium"
},
{
"code": null,
"e": 30214,
"s": 30205,
"text": "selenium"
},
{
"code": null,
"e": 30221,
"s": 30214,
"text": "Python"
},
{
"code": null,
"e": 30238,
"s": 30221,
"text": "Web Technologies"
},
{
"code": null,
"e": 30336,
"s": 30238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30368,
"s": 30336,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30410,
"s": 30368,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30452,
"s": 30410,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30479,
"s": 30452,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30535,
"s": 30479,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30575,
"s": 30535,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30608,
"s": 30575,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30653,
"s": 30608,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30696,
"s": 30653,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Django model data types and fields list - GeeksforGeeks
|
04 Jan, 2022
The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.
Example:
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
instrument = models.CharField(max_length=200)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
Setting a field for storing any type of data is like deciding a data type in C/C++ for storing a particular integer, char etc. Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields. This post revolves around major fields one can use in Django Models.
Here are some key attributes one should be aware of before starting to use Django Fields.
Each field in the model should be an instance of the appropriate Field class. Django uses field class types to determine a few things:
The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT).
The default HTML widget to use when rendering a form field (e.g. <input type=”text”>, <select>).
The minimal validation requirements, used in Django’s admin and in automatically-generated forms.
Django ships with dozens of built-in field types which can be used to save any type of data from number to entire HTML file too. Here is a list of all Field types used in Django.
Django also defines a set of fields that represent relations.
NaveenArora
junejavaibhav92
rathoreparikshit893
Sapna2001
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25519,
"s": 25491,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25778,
"s": 25519,
"text": "The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. "
},
{
"code": null,
"e": 25788,
"s": 25778,
"text": "Example: "
},
{
"code": null,
"e": 26212,
"s": 25788,
"text": "from django.db import models\n\nclass Musician(models.Model):\n first_name = models.CharField(max_length=200)\n last_name = models.CharField(max_length=200)\n instrument = models.CharField(max_length=200)\n\nclass Album(models.Model):\n artist = models.ForeignKey(Musician, on_delete=models.CASCADE)\n name = models.CharField(max_length=100)\n release_date = models.DateField()\n num_stars = models.IntegerField()"
},
{
"code": null,
"e": 26690,
"s": 26212,
"text": "Setting a field for storing any type of data is like deciding a data type in C/C++ for storing a particular integer, char etc. Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields. This post revolves around major fields one can use in Django Models. "
},
{
"code": null,
"e": 26782,
"s": 26690,
"text": "Here are some key attributes one should be aware of before starting to use Django Fields. "
},
{
"code": null,
"e": 26918,
"s": 26782,
"text": "Each field in the model should be an instance of the appropriate Field class. Django uses field class types to determine a few things: "
},
{
"code": null,
"e": 27018,
"s": 26918,
"text": "The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT)."
},
{
"code": null,
"e": 27115,
"s": 27018,
"text": "The default HTML widget to use when rendering a form field (e.g. <input type=”text”>, <select>)."
},
{
"code": null,
"e": 27213,
"s": 27115,
"text": "The minimal validation requirements, used in Django’s admin and in automatically-generated forms."
},
{
"code": null,
"e": 27394,
"s": 27213,
"text": "Django ships with dozens of built-in field types which can be used to save any type of data from number to entire HTML file too. Here is a list of all Field types used in Django. "
},
{
"code": null,
"e": 27459,
"s": 27396,
"text": "Django also defines a set of fields that represent relations. "
},
{
"code": null,
"e": 27473,
"s": 27461,
"text": "NaveenArora"
},
{
"code": null,
"e": 27489,
"s": 27473,
"text": "junejavaibhav92"
},
{
"code": null,
"e": 27509,
"s": 27489,
"text": "rathoreparikshit893"
},
{
"code": null,
"e": 27519,
"s": 27509,
"text": "Sapna2001"
},
{
"code": null,
"e": 27533,
"s": 27519,
"text": "Django-models"
},
{
"code": null,
"e": 27547,
"s": 27533,
"text": "Python Django"
},
{
"code": null,
"e": 27554,
"s": 27547,
"text": "Python"
},
{
"code": null,
"e": 27652,
"s": 27554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27670,
"s": 27652,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27705,
"s": 27670,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27737,
"s": 27705,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27759,
"s": 27737,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27801,
"s": 27759,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27831,
"s": 27801,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27857,
"s": 27831,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27886,
"s": 27857,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27930,
"s": 27886,
"text": "Reading and Writing to text files in Python"
}
] |
Python | Multiply elements of Tuple - GeeksforGeeks
|
11 Dec, 2019
Given, a list of tuples, the task is to multiply the elements of the tuple and return list of the multiplied elements.
Examples:
Input: [(2, 3), (4, 5), (6, 7), (2, 8)]Output: [6, 20, 42, 16]
Input: [(11, 22), (33, 55), (55, 77), (11, 44)]Output: [242, 1815, 4235, 484]
There are multiple ways to multiply elements of a tuple. Let’s see a couple of them.
# Method 1: Using IterationThis is the most naive method to achieve a solution to this task. In this, we iterate over the whole list of tuples and multiply the elements in each tuple to get the list of elements.
# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple. # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)] # Output list initialisationOutput = [] # Iteration to multiply element and append multiplied element in # new listfor elem in Input: temp = elem[0]*elem[1] Output.append(temp) # printing outputprint("The original list of tuple is ")print(Input) print("\nThe answer is")print(Output)
Output:
The original list of tuple is
[(2, 3), (4, 5), (6, 7), (2, 8)]
The answer is
[6, 20, 42, 16]
# Method 2: Using list comprehensionThis is the one-liner approach to achieve the solution to this task.
# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple. # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)] # Iteration to multiply element and append multiplied element in # new listOutput = [(x * y) for x, y in Input] # printing outputprint("The original list of tuple is ")print(Input) print("\nThe answer is")print(Output)
Output:
The original list of tuple is
[(2, 3), (4, 5), (6, 7), (2, 8)]
The answer is
[6, 20, 42, 16]
python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25735,
"s": 25707,
"text": "\n11 Dec, 2019"
},
{
"code": null,
"e": 25854,
"s": 25735,
"text": "Given, a list of tuples, the task is to multiply the elements of the tuple and return list of the multiplied elements."
},
{
"code": null,
"e": 25864,
"s": 25854,
"text": "Examples:"
},
{
"code": null,
"e": 25927,
"s": 25864,
"text": "Input: [(2, 3), (4, 5), (6, 7), (2, 8)]Output: [6, 20, 42, 16]"
},
{
"code": null,
"e": 26005,
"s": 25927,
"text": "Input: [(11, 22), (33, 55), (55, 77), (11, 44)]Output: [242, 1815, 4235, 484]"
},
{
"code": null,
"e": 26090,
"s": 26005,
"text": "There are multiple ways to multiply elements of a tuple. Let’s see a couple of them."
},
{
"code": null,
"e": 26302,
"s": 26090,
"text": "# Method 1: Using IterationThis is the most naive method to achieve a solution to this task. In this, we iterate over the whole list of tuples and multiply the elements in each tuple to get the list of elements."
},
{
"code": "# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple. # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)] # Output list initialisationOutput = [] # Iteration to multiply element and append multiplied element in # new listfor elem in Input: temp = elem[0]*elem[1] Output.append(temp) # printing outputprint(\"The original list of tuple is \")print(Input) print(\"\\nThe answer is\")print(Output)",
"e": 26768,
"s": 26302,
"text": null
},
{
"code": null,
"e": 26776,
"s": 26768,
"text": "Output:"
},
{
"code": null,
"e": 26872,
"s": 26776,
"text": "The original list of tuple is \n[(2, 3), (4, 5), (6, 7), (2, 8)]\n\nThe answer is\n[6, 20, 42, 16]\n"
},
{
"code": null,
"e": 26977,
"s": 26872,
"text": "# Method 2: Using list comprehensionThis is the one-liner approach to achieve the solution to this task."
},
{
"code": "# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple. # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)] # Iteration to multiply element and append multiplied element in # new listOutput = [(x * y) for x, y in Input] # printing outputprint(\"The original list of tuple is \")print(Input) print(\"\\nThe answer is\")print(Output)",
"e": 27371,
"s": 26977,
"text": null
},
{
"code": null,
"e": 27379,
"s": 27371,
"text": "Output:"
},
{
"code": null,
"e": 27475,
"s": 27379,
"text": "The original list of tuple is \n[(2, 3), (4, 5), (6, 7), (2, 8)]\n\nThe answer is\n[6, 20, 42, 16]\n"
},
{
"code": null,
"e": 27488,
"s": 27475,
"text": "python-tuple"
},
{
"code": null,
"e": 27495,
"s": 27488,
"text": "Python"
},
{
"code": null,
"e": 27593,
"s": 27495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27611,
"s": 27593,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27646,
"s": 27611,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27678,
"s": 27646,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27700,
"s": 27678,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27742,
"s": 27700,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27772,
"s": 27742,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27798,
"s": 27772,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27827,
"s": 27798,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27871,
"s": 27827,
"text": "Reading and Writing to text files in Python"
}
] |
Program to find remainder without using modulo or % operator - GeeksforGeeks
|
14 Jan, 2022
Given two numbers ‘num’ and ‘divisor’, find remainder when ‘num’ is divided by ‘divisor’. The use of modulo or % operator is not allowed.Examples :
Input: num = 100, divisor = 7
Output: 2
Input: num = 30, divisor = 9
Output: 3
Method 1 :
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find remainder without using// modulo operator#include <iostream>using namespace std; // This function returns remainder of num/divisor// without using % (modulo) operatorint getRemainder(int num, int divisor){ return (num - divisor * (num / divisor));} // Driver program to test above functionsint main(){ // cout << 100 %0; cout << getRemainder(100, 7); return 0;}
// Java program to find remainder without// using modulo operatorimport java.io.*; class GFG { // This function returns remainder of // num/divisor without using % (modulo) // operator static int getRemainder(int num, int divisor) { return (num - divisor * (num / divisor)); } // Driver program to test above functions public static void main(String[] args) { // print 100 % 0; System.out.println(getRemainder(100, 7)); }} // This code is contributed by Sam007.
# Python program to find remainder# without using modulo operator # This function returns remainder of# num / divisor without using % (modulo)# operatordef getRemainder(num, divisor): return (num - divisor * (num // divisor)) # Driver program to test above functionsnum = 100divisor = 7print(getRemainder(num, divisor)) # This code is contributed by Danish Raza
// C# program to find remainder without using// modulo operatorusing System; class GFG { // This function returns remainder of // num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { return (num - divisor * (num / divisor)); } // Driver program to test above functions public static void Main() { // print 100 % 0; Console.Write(getRemainder(100, 7)); }} // This code is contributed by Sam007.
<?php// PHP program to find remainder// without using modulo operator // This function returns remainder// of num/divisor without using// % (modulo) operatorfunction getRemainder($num, $divisor){ $t = ($num - $divisor * (int)($num / $divisor)); return $t;} // Driver Codeecho getRemainder(100, 7); // This code is contributed by ajit?>
<script>// Javascript program to find remainder// without using modulo operator // This function returns remainder// of num/divisor without using// % (modulo) operatorfunction getRemainder(num, divisor){ let t = (num - divisor * parseInt(num / divisor)); return t;} // Driver Codedocument.write(getRemainder(100, 7)); // This code is contributed by _saurabh_jaiswal</script>
Output :
2
This method is contributed by Bishal Kumar Dubey
Method 2
The idea is simple, we run a loop to find the largest multiple of ‘divisor’ that is smaller than or equal to ‘num’. Once we find such a multiple, we subtract the multiple from ‘num’ to find the divisor.Following is the implementation of above idea. Thanks to eleventyone for suggesting this solution in a comment.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find remainder without using modulo operator#include <iostream>using namespace std; // This function returns remainder of num/divisor without// using % (modulo) operatorint getRemainder(int num, int divisor){ // Handle divisor equals to 0 case if (divisor == 0) { cout << "Error: divisor can't be zero \n"; return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' that is smaller // than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor);} // Driver program to test above functionsint main(){ // cout << 100 %0; cout << getRemainder(100, 7); return 0;}
// Java program to find remainder without// using modulo operatorimport java.io.*; class GFG { // This function returns remainder // of num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { // Handle divisor equals to 0 case if (divisor == 0) { System.out.println("Error: divisor " + "can't be zero \n"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor); } // Driver program to test above functions public static void main(String[] args) { // print 100 % 0; System.out.println(getRemainder(100, 7)); }} // This code is contributed by Sam007.
# Python program to find remainder without# using modulo operator. This function# returns remainder of num / divisor without# using % (modulo) operator def getRemainder(num, divisor): # Handle divisor equals to 0 case if (divisor == 0): return False # Handle negative values if (divisor < 0): divisor = -divisor if (num < 0): num = -num # Find the largest product of 'divisor' # that is smaller than or equal to 'num' i = 1 product = 0 while (product <= num): product = divisor * i i += 1 # return remainder return num - (product - divisor) # Driver program to test above functionsnum = 100divisor = 7print(getRemainder(num, divisor)) # This code is contributed by Danish Raza
// C# program to find remainder without// using modulo operatorusing System; class GFG { // This function returns remainder // of num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { // Handle divisor equals to 0 case if (divisor == 0) { Console.WriteLine("Error: divisor " + "can't be zero \n"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor); } // Driver program to test above functions public static void Main() { // print 100 %0; Console.Write(getRemainder(100, 7)); }} // This code is contributed by Sam007.
<?php // php program to find remainder without// using modulo operator // This function returns remainder of// num/divisor without using % (modulo)// operator function getRemainder($num, $divisor){ // Handle divisor equals to 0 case if ($divisor == 0) { echo "Error: divisor can't be zero \n"; return -1; } // Handle negative values if ($divisor < 0) $divisor = -$divisor; if ($num < 0) $num = -$num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' $i = 1; $product = 0; while ($product <= $num) { $product = $divisor * $i; $i++; } // return remainder return $num - ($product - $divisor);} // Driver program to test above functionsecho getRemainder(100, 7); // This code is contributed by ajit.?>
// Javascript program to find remainder without// using modulo operator // This function returns remainder of// num/divisor without using % (modulo)// operator function getRemainder(num, divisor){ // Handle divisor equals to 0 case if (divisor == 0) { document.write("Error: divisor can't be zero <br>"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' let i = 1; let product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor);} // Driver program to test above functionsdocument.write(getRemainder(100, 7)); // This code is contributed by _saurabh_jaiswal
Output :
2
This article is contributed by Chirag. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Method 3
Keep subtracting the denominator from numerator until the numerator is less than the denominator.
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return num % divisor// without using % (modulo) operatorint getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codeint main(){ int num = 100, divisor = 7; cout << getRemainder(num, divisor); return 0;}
// A Java implementation of the approachimport java.util.*; class GFG{ // Function to return num % divisor// without using % (modulo) operatorstatic int getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codepublic static void main(String[] args){ int num = 100, divisor = 7; System.out.println(getRemainder(num, divisor));}} // This code is contributed by Princi Singh
# Python3 implementation of the approach # Function to return num % divisor# without using % (modulo) operatordef getRemainder(num, divisor): # While divisor is smaller # than n, keep subtracting # it from num while (num >= divisor): num -= divisor; return num; # Driver codeif __name__ == '__main__': num = 100; divisor = 7; print(getRemainder(num, divisor)); # This code is contributed by Princi Singh
// C# implementation of the approachusing System; class GFG{ // Function to return num % divisor// without using % (modulo) operatorstatic int getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codepublic static void Main(String[] args){ int num = 100, divisor = 7; Console.WriteLine(getRemainder(num, divisor));}} // This code is contributed by PrinciRaj1992
// Javascript implementation of the approach // Function to return num % divisor// without using % (modulo) operatorfunction getRemainder(num, divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codelet num = 100, divisor = 7;document.write(getRemainder(num, divisor)); // This code is contributed by _saurabh_jaiswal
Output :
2
Sam007
jit_t
Swathi__Hegde
princi singh
princiraj1992
_saurabh_jaiswal
amartyaghoshgfg
Chalk Studio
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Sieve of Eratosthenes
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
Operators in C / C++
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 26032,
"s": 26004,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 26181,
"s": 26032,
"text": "Given two numbers ‘num’ and ‘divisor’, find remainder when ‘num’ is divided by ‘divisor’. The use of modulo or % operator is not allowed.Examples : "
},
{
"code": null,
"e": 26263,
"s": 26181,
"text": "Input: num = 100, divisor = 7\nOutput: 2\n\nInput: num = 30, divisor = 9\nOutput: 3"
},
{
"code": null,
"e": 26278,
"s": 26267,
"text": "Method 1 :"
},
{
"code": null,
"e": 26284,
"s": 26280,
"text": "C++"
},
{
"code": null,
"e": 26289,
"s": 26284,
"text": "Java"
},
{
"code": null,
"e": 26297,
"s": 26289,
"text": "Python3"
},
{
"code": null,
"e": 26300,
"s": 26297,
"text": "C#"
},
{
"code": null,
"e": 26304,
"s": 26300,
"text": "PHP"
},
{
"code": null,
"e": 26315,
"s": 26304,
"text": "Javascript"
},
{
"code": "// C++ program to find remainder without using// modulo operator#include <iostream>using namespace std; // This function returns remainder of num/divisor// without using % (modulo) operatorint getRemainder(int num, int divisor){ return (num - divisor * (num / divisor));} // Driver program to test above functionsint main(){ // cout << 100 %0; cout << getRemainder(100, 7); return 0;}",
"e": 26712,
"s": 26315,
"text": null
},
{
"code": "// Java program to find remainder without// using modulo operatorimport java.io.*; class GFG { // This function returns remainder of // num/divisor without using % (modulo) // operator static int getRemainder(int num, int divisor) { return (num - divisor * (num / divisor)); } // Driver program to test above functions public static void main(String[] args) { // print 100 % 0; System.out.println(getRemainder(100, 7)); }} // This code is contributed by Sam007.",
"e": 27228,
"s": 26712,
"text": null
},
{
"code": "# Python program to find remainder# without using modulo operator # This function returns remainder of# num / divisor without using % (modulo)# operatordef getRemainder(num, divisor): return (num - divisor * (num // divisor)) # Driver program to test above functionsnum = 100divisor = 7print(getRemainder(num, divisor)) # This code is contributed by Danish Raza",
"e": 27594,
"s": 27228,
"text": null
},
{
"code": "// C# program to find remainder without using// modulo operatorusing System; class GFG { // This function returns remainder of // num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { return (num - divisor * (num / divisor)); } // Driver program to test above functions public static void Main() { // print 100 % 0; Console.Write(getRemainder(100, 7)); }} // This code is contributed by Sam007.",
"e": 28085,
"s": 27594,
"text": null
},
{
"code": "<?php// PHP program to find remainder// without using modulo operator // This function returns remainder// of num/divisor without using// % (modulo) operatorfunction getRemainder($num, $divisor){ $t = ($num - $divisor * (int)($num / $divisor)); return $t;} // Driver Codeecho getRemainder(100, 7); // This code is contributed by ajit?>",
"e": 28435,
"s": 28085,
"text": null
},
{
"code": "<script>// Javascript program to find remainder// without using modulo operator // This function returns remainder// of num/divisor without using// % (modulo) operatorfunction getRemainder(num, divisor){ let t = (num - divisor * parseInt(num / divisor)); return t;} // Driver Codedocument.write(getRemainder(100, 7)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 28824,
"s": 28435,
"text": null
},
{
"code": null,
"e": 28834,
"s": 28824,
"text": "Output : "
},
{
"code": null,
"e": 28836,
"s": 28834,
"text": "2"
},
{
"code": null,
"e": 28886,
"s": 28836,
"text": "This method is contributed by Bishal Kumar Dubey "
},
{
"code": null,
"e": 28895,
"s": 28886,
"text": "Method 2"
},
{
"code": null,
"e": 29211,
"s": 28895,
"text": "The idea is simple, we run a loop to find the largest multiple of ‘divisor’ that is smaller than or equal to ‘num’. Once we find such a multiple, we subtract the multiple from ‘num’ to find the divisor.Following is the implementation of above idea. Thanks to eleventyone for suggesting this solution in a comment. "
},
{
"code": null,
"e": 29215,
"s": 29211,
"text": "C++"
},
{
"code": null,
"e": 29220,
"s": 29215,
"text": "Java"
},
{
"code": null,
"e": 29228,
"s": 29220,
"text": "Python3"
},
{
"code": null,
"e": 29231,
"s": 29228,
"text": "C#"
},
{
"code": null,
"e": 29235,
"s": 29231,
"text": "PHP"
},
{
"code": null,
"e": 29246,
"s": 29235,
"text": "Javascript"
},
{
"code": "// C++ program to find remainder without using modulo operator#include <iostream>using namespace std; // This function returns remainder of num/divisor without// using % (modulo) operatorint getRemainder(int num, int divisor){ // Handle divisor equals to 0 case if (divisor == 0) { cout << \"Error: divisor can't be zero \\n\"; return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' that is smaller // than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor);} // Driver program to test above functionsint main(){ // cout << 100 %0; cout << getRemainder(100, 7); return 0;}",
"e": 30102,
"s": 29246,
"text": null
},
{
"code": "// Java program to find remainder without// using modulo operatorimport java.io.*; class GFG { // This function returns remainder // of num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { // Handle divisor equals to 0 case if (divisor == 0) { System.out.println(\"Error: divisor \" + \"can't be zero \\n\"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor); } // Driver program to test above functions public static void main(String[] args) { // print 100 % 0; System.out.println(getRemainder(100, 7)); }} // This code is contributed by Sam007.",
"e": 31203,
"s": 30102,
"text": null
},
{
"code": "# Python program to find remainder without# using modulo operator. This function# returns remainder of num / divisor without# using % (modulo) operator def getRemainder(num, divisor): # Handle divisor equals to 0 case if (divisor == 0): return False # Handle negative values if (divisor < 0): divisor = -divisor if (num < 0): num = -num # Find the largest product of 'divisor' # that is smaller than or equal to 'num' i = 1 product = 0 while (product <= num): product = divisor * i i += 1 # return remainder return num - (product - divisor) # Driver program to test above functionsnum = 100divisor = 7print(getRemainder(num, divisor)) # This code is contributed by Danish Raza",
"e": 31962,
"s": 31203,
"text": null
},
{
"code": "// C# program to find remainder without// using modulo operatorusing System; class GFG { // This function returns remainder // of num/divisor without using % // (modulo) operator static int getRemainder(int num, int divisor) { // Handle divisor equals to 0 case if (divisor == 0) { Console.WriteLine(\"Error: divisor \" + \"can't be zero \\n\"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' int i = 1; int product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor); } // Driver program to test above functions public static void Main() { // print 100 %0; Console.Write(getRemainder(100, 7)); }} // This code is contributed by Sam007.",
"e": 33036,
"s": 31962,
"text": null
},
{
"code": "<?php // php program to find remainder without// using modulo operator // This function returns remainder of// num/divisor without using % (modulo)// operator function getRemainder($num, $divisor){ // Handle divisor equals to 0 case if ($divisor == 0) { echo \"Error: divisor can't be zero \\n\"; return -1; } // Handle negative values if ($divisor < 0) $divisor = -$divisor; if ($num < 0) $num = -$num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' $i = 1; $product = 0; while ($product <= $num) { $product = $divisor * $i; $i++; } // return remainder return $num - ($product - $divisor);} // Driver program to test above functionsecho getRemainder(100, 7); // This code is contributed by ajit.?>",
"e": 33856,
"s": 33036,
"text": null
},
{
"code": "// Javascript program to find remainder without// using modulo operator // This function returns remainder of// num/divisor without using % (modulo)// operator function getRemainder(num, divisor){ // Handle divisor equals to 0 case if (divisor == 0) { document.write(\"Error: divisor can't be zero <br>\"); return -1; } // Handle negative values if (divisor < 0) divisor = -divisor; if (num < 0) num = -num; // Find the largest product of 'divisor' // that is smaller than or equal to 'num' let i = 1; let product = 0; while (product <= num) { product = divisor * i; i++; } // return remainder return num - (product - divisor);} // Driver program to test above functionsdocument.write(getRemainder(100, 7)); // This code is contributed by _saurabh_jaiswal",
"e": 34698,
"s": 33856,
"text": null
},
{
"code": null,
"e": 34708,
"s": 34698,
"text": "Output : "
},
{
"code": null,
"e": 34710,
"s": 34708,
"text": "2"
},
{
"code": null,
"e": 34874,
"s": 34710,
"text": "This article is contributed by Chirag. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 34883,
"s": 34874,
"text": "Method 3"
},
{
"code": null,
"e": 34983,
"s": 34883,
"text": "Keep subtracting the denominator from numerator until the numerator is less than the denominator. "
},
{
"code": null,
"e": 34987,
"s": 34983,
"text": "C++"
},
{
"code": null,
"e": 34992,
"s": 34987,
"text": "Java"
},
{
"code": null,
"e": 35000,
"s": 34992,
"text": "Python3"
},
{
"code": null,
"e": 35003,
"s": 35000,
"text": "C#"
},
{
"code": null,
"e": 35014,
"s": 35003,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return num % divisor// without using % (modulo) operatorint getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codeint main(){ int num = 100, divisor = 7; cout << getRemainder(num, divisor); return 0;}",
"e": 35460,
"s": 35014,
"text": null
},
{
"code": "// A Java implementation of the approachimport java.util.*; class GFG{ // Function to return num % divisor// without using % (modulo) operatorstatic int getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codepublic static void main(String[] args){ int num = 100, divisor = 7; System.out.println(getRemainder(num, divisor));}} // This code is contributed by Princi Singh",
"e": 35978,
"s": 35460,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return num % divisor# without using % (modulo) operatordef getRemainder(num, divisor): # While divisor is smaller # than n, keep subtracting # it from num while (num >= divisor): num -= divisor; return num; # Driver codeif __name__ == '__main__': num = 100; divisor = 7; print(getRemainder(num, divisor)); # This code is contributed by Princi Singh",
"e": 36413,
"s": 35978,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return num % divisor// without using % (modulo) operatorstatic int getRemainder(int num, int divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codepublic static void Main(String[] args){ int num = 100, divisor = 7; Console.WriteLine(getRemainder(num, divisor));}} // This code is contributed by PrinciRaj1992",
"e": 36925,
"s": 36413,
"text": null
},
{
"code": "// Javascript implementation of the approach // Function to return num % divisor// without using % (modulo) operatorfunction getRemainder(num, divisor){ // While divisor is smaller // than n, keep subtracting // it from num while (num >= divisor) num -= divisor; return num;} // Driver codelet num = 100, divisor = 7;document.write(getRemainder(num, divisor)); // This code is contributed by _saurabh_jaiswal",
"e": 37358,
"s": 36925,
"text": null
},
{
"code": null,
"e": 37368,
"s": 37358,
"text": "Output : "
},
{
"code": null,
"e": 37370,
"s": 37368,
"text": "2"
},
{
"code": null,
"e": 37379,
"s": 37372,
"text": "Sam007"
},
{
"code": null,
"e": 37385,
"s": 37379,
"text": "jit_t"
},
{
"code": null,
"e": 37399,
"s": 37385,
"text": "Swathi__Hegde"
},
{
"code": null,
"e": 37412,
"s": 37399,
"text": "princi singh"
},
{
"code": null,
"e": 37426,
"s": 37412,
"text": "princiraj1992"
},
{
"code": null,
"e": 37443,
"s": 37426,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 37459,
"s": 37443,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 37472,
"s": 37459,
"text": "Chalk Studio"
},
{
"code": null,
"e": 37491,
"s": 37472,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37504,
"s": 37491,
"text": "Mathematical"
},
{
"code": null,
"e": 37517,
"s": 37504,
"text": "Mathematical"
},
{
"code": null,
"e": 37536,
"s": 37517,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 37634,
"s": 37536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37658,
"s": 37634,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 37672,
"s": 37658,
"text": "Prime Numbers"
},
{
"code": null,
"e": 37714,
"s": 37672,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 37787,
"s": 37714,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 37809,
"s": 37787,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 37852,
"s": 37809,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 37893,
"s": 37852,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 37914,
"s": 37893,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 37967,
"s": 37914,
"text": "Find minimum number of coins that make a given value"
}
] |
marshal — Internal Python object serialization - GeeksforGeeks
|
01 Feb, 2022
Serializing a data means converting it into a string of bytes and later reconstructing it from such a string. If the data is composed entirely of fundamental Python objects, the fastest way to serialize the data is by using marshal module (For user defined classes, Pickle should be preferred). Marshal module contains functions that can read and write Python values in a binary format.
The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files. This module doesn’t support all Python object types.
The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, frozensets, dictionaries, and code objects, where it should be understood that tuples, lists, sets, frozensets and dictionaries are only supported as long as the values contained therein are themselves supported. The singletons None, Ellipsis and StopIteration can also be marshalled and unmarshalled.
Functions :
marshal.version :It indicates the format used by the module.Version 0 – Historical formatVersion 1 – Shares interned stringsVersion 2 – Uses a binary format for floating point numbersVersion 3 – Support for object instancing and recursionVersion 4 – Current Versionmarshal.dumps(value[, version]) :The function returns the bytes object that would be written to a file by dump(value, file). The version argument indicates the data format that dumps should use. A ValueError exception is raised if the value has (or contains an object that has) an unsupported type.ExamplePython3Python3# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)Output{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}
marshal.loads(bytes) :This function can reconstruct the data by converting the bytes-like object to a value. EOFError, ValueError or TypeError is raised if no value is found.ExamplePython3Python3# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)Output{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}
marshal.dump(value, file[, version]) :This function is used to write the supported type value on the open writeable binary file. A ValueError exception is raised if the value has an unsupported type.marshal.load(file) :This function reads one value from the open readable binary file and returns it. EOFError, ValueError or TypeError is raised if no value is read.
marshal.version :It indicates the format used by the module.Version 0 – Historical formatVersion 1 – Shares interned stringsVersion 2 – Uses a binary format for floating point numbersVersion 3 – Support for object instancing and recursionVersion 4 – Current Version
Version 0 – Historical format
Version 1 – Shares interned strings
Version 2 – Uses a binary format for floating point numbers
Version 3 – Support for object instancing and recursion
Version 4 – Current Version
marshal.dumps(value[, version]) :The function returns the bytes object that would be written to a file by dump(value, file). The version argument indicates the data format that dumps should use. A ValueError exception is raised if the value has (or contains an object that has) an unsupported type.ExamplePython3Python3# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)Output{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}
Example
Python3
# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)
Output
{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}
marshal.loads(bytes) :This function can reconstruct the data by converting the bytes-like object to a value. EOFError, ValueError or TypeError is raised if no value is found.ExamplePython3Python3# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)Output{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}
Example
Python3
# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)
{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}
marshal.dump(value, file[, version]) :This function is used to write the supported type value on the open writeable binary file. A ValueError exception is raised if the value has an unsupported type.
marshal.load(file) :This function reads one value from the open readable binary file and returns it. EOFError, ValueError or TypeError is raised if no value is read.
This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sagar0719kumar
gabaa406
prachisoda1234
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 25924,
"s": 25537,
"text": "Serializing a data means converting it into a string of bytes and later reconstructing it from such a string. If the data is composed entirely of fundamental Python objects, the fastest way to serialize the data is by using marshal module (For user defined classes, Pickle should be preferred). Marshal module contains functions that can read and write Python values in a binary format."
},
{
"code": null,
"e": 26102,
"s": 25924,
"text": "The marshal module exists mainly to support reading and writing the “pseudo-compiled” code for Python modules of .pyc files. This module doesn’t support all Python object types."
},
{
"code": null,
"e": 26549,
"s": 26102,
"text": "The following types are supported: booleans, integers, floating point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, frozensets, dictionaries, and code objects, where it should be understood that tuples, lists, sets, frozensets and dictionaries are only supported as long as the values contained therein are themselves supported. The singletons None, Ellipsis and StopIteration can also be marshalled and unmarshalled."
},
{
"code": null,
"e": 26561,
"s": 26549,
"text": "Functions :"
},
{
"code": null,
"e": 28227,
"s": 26561,
"text": "marshal.version :It indicates the format used by the module.Version 0 – Historical formatVersion 1 – Shares interned stringsVersion 2 – Uses a binary format for floating point numbersVersion 3 – Support for object instancing and recursionVersion 4 – Current Versionmarshal.dumps(value[, version]) :The function returns the bytes object that would be written to a file by dump(value, file). The version argument indicates the data format that dumps should use. A ValueError exception is raised if the value has (or contains an object that has) an unsupported type.ExamplePython3Python3# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)Output{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}\nmarshal.loads(bytes) :This function can reconstruct the data by converting the bytes-like object to a value. EOFError, ValueError or TypeError is raised if no value is found.ExamplePython3Python3# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)Output{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}\nmarshal.dump(value, file[, version]) :This function is used to write the supported type value on the open writeable binary file. A ValueError exception is raised if the value has an unsupported type.marshal.load(file) :This function reads one value from the open readable binary file and returns it. EOFError, ValueError or TypeError is raised if no value is read."
},
{
"code": null,
"e": 28493,
"s": 28227,
"text": "marshal.version :It indicates the format used by the module.Version 0 – Historical formatVersion 1 – Shares interned stringsVersion 2 – Uses a binary format for floating point numbersVersion 3 – Support for object instancing and recursionVersion 4 – Current Version"
},
{
"code": null,
"e": 28523,
"s": 28493,
"text": "Version 0 – Historical format"
},
{
"code": null,
"e": 28559,
"s": 28523,
"text": "Version 1 – Shares interned strings"
},
{
"code": null,
"e": 28619,
"s": 28559,
"text": "Version 2 – Uses a binary format for floating point numbers"
},
{
"code": null,
"e": 28675,
"s": 28619,
"text": "Version 3 – Support for object instancing and recursion"
},
{
"code": null,
"e": 28703,
"s": 28675,
"text": "Version 4 – Current Version"
},
{
"code": null,
"e": 29252,
"s": 28703,
"text": "marshal.dumps(value[, version]) :The function returns the bytes object that would be written to a file by dump(value, file). The version argument indicates the data format that dumps should use. A ValueError exception is raised if the value has (or contains an object that has) an unsupported type.ExamplePython3Python3# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)Output{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}\n"
},
{
"code": null,
"e": 29260,
"s": 29252,
"text": "Example"
},
{
"code": null,
"e": 29268,
"s": 29260,
"text": "Python3"
},
{
"code": "# Python code to demonstrate serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data) print (bytes)",
"e": 29445,
"s": 29268,
"text": null
},
{
"code": null,
"e": 29452,
"s": 29445,
"text": "Output"
},
{
"code": null,
"e": 29500,
"s": 29452,
"text": "{tfeep[tctitatog®Gáz®ó?y@@ittwelve(iiiuwer0}\n"
},
{
"code": null,
"e": 29989,
"s": 29500,
"text": "marshal.loads(bytes) :This function can reconstruct the data by converting the bytes-like object to a value. EOFError, ValueError or TypeError is raised if no value is found.ExamplePython3Python3# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)Output{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}\n"
},
{
"code": null,
"e": 29997,
"s": 29989,
"text": "Example"
},
{
"code": null,
"e": 30005,
"s": 29997,
"text": "Python3"
},
{
"code": "# Python code to demonstrate de-serializationimport marshal data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}bytes = marshal.dumps(data)redata = marshal.loads(bytes) print (redata)",
"e": 30215,
"s": 30005,
"text": null
},
{
"code": null,
"e": 30294,
"s": 30215,
"text": "{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}\n"
},
{
"code": null,
"e": 30494,
"s": 30294,
"text": "marshal.dump(value, file[, version]) :This function is used to write the supported type value on the open writeable binary file. A ValueError exception is raised if the value has an unsupported type."
},
{
"code": null,
"e": 30660,
"s": 30494,
"text": "marshal.load(file) :This function reads one value from the open readable binary file and returns it. EOFError, ValueError or TypeError is raised if no value is read."
},
{
"code": null,
"e": 30959,
"s": 30660,
"text": "This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31084,
"s": 30959,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31099,
"s": 31084,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 31108,
"s": 31099,
"text": "gabaa406"
},
{
"code": null,
"e": 31123,
"s": 31108,
"text": "prachisoda1234"
},
{
"code": null,
"e": 31138,
"s": 31123,
"text": "Python-Library"
},
{
"code": null,
"e": 31145,
"s": 31138,
"text": "Python"
},
{
"code": null,
"e": 31243,
"s": 31145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31275,
"s": 31243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31317,
"s": 31275,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31359,
"s": 31317,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31386,
"s": 31359,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31442,
"s": 31386,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31464,
"s": 31442,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31503,
"s": 31464,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31534,
"s": 31503,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31563,
"s": 31534,
"text": "Create a directory in Python"
}
] |
Count substrings with same first and last characters - GeeksforGeeks
|
22 Oct, 2021
We are given a string S, we need to find count of all contiguous substrings starting and ending with same character.
Examples :
Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.
Input : S = "aba"
Output : 4
The substrings are a, b, a and aba
Method 1 (Simple): In this approach, we use brute force and find all the sub-strings and pass them through our function checkEquality to see if starting and ending characters are same.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count all substrings with same// first and last characters.#include <bits/stdc++.h>using namespace std; // Returns true if first and last characters// of s are same.int checkEquality(string s){ return (s[0] == s[s.size() - 1]);} int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substr(i, len))) result++; return result;} // Driver functionint main(){ string s("abcab"); cout << countSubstringWithEqualEnds(s); return 0;}
// Java program to count all substrings with same// first and last characters.public class GFG { // Returns true if first and last characters // of s are same. static boolean checkEquality(String s) { return (s.charAt(0) == s.charAt(s.length() - 1)); } static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substring(i, i + len))) result++; return result; } // Driver function public static void main(String args[]) { String s = "abcab"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh
# Python program to count all substrings with same# first and last characters. # Returns true if first and last characters# of s are same.def checkEquality(s): return (ord(s[0]) == ord(s[len(s) - 1])); def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Starting point of substring for i in range(n): # Length of substring for j in range(1,n-i+1): # Check if current substring has same # starting and ending characters. if (checkEquality(s[i:i+j])): result+=1; return result; # Driver codes = "abcab";print(countSubstringWithEqualEnds(s)); # This code contributed by PrinciRaj1992
// C# program to count all// substrings with same// first and last characters.using System; class GFG{ // Returns true if first and // last characters of s are same. static bool checkEquality(string s) { return (s[0] == s[s.Length - 1]); } static int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.Length; // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.Substring(i, len))) result++; return result; } // Driver code public static void Main() { string s = "abcab"; Console.WriteLine(countSubstringWithEqualEnds(s)); }} // This code is contributed by Code_Mech
<?php// PHP program to count all substrings// with same first and last characters. // Returns true if first and last// characters of s are same.function checkEquality($s){ return ($s[0] == $s[strlen($s) - 1]);} function countSubstringWithEqualEnds($s){ $result = 0; $n = strlen($s); // Starting point of substring for ($i = 0; $i < $n; $i++) // Length of substring for ($len = 1; $len <= $n - $i; $len++) // Check if current substring has same // starting and ending characters. if (checkEquality(substr($s, $i, $len))) $result++; return $result;} // Driver Code$s = "abcab";print(countSubstringWithEqualEnds($s)); // This code is contributed by chandan_jnu?>
<script> // JavaScript program to count all substrings// with same first and last characters. // Returns true if first and last characters// of s are same.function checkEquality(s){ return (s.charAt(0) == s.charAt(s.length - 1));} function countSubstringWithEqualEnds(s){ var result = 0; var n = s.length; // Starting point of substring for (var i = 0; i < n; i++) // Length of substring for (var len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substring(i, i + len))) result++; return result;} // Driver function var s = "abcab"; document.write(countSubstringWithEqualEnds(s)); // This code contributed by shikhasingrajput </script>
Output:
7
Although the above code works fine, it’s not efficient as its time complexity is O(n2). Note that there are n*(n+1)/2 substrings of a string of length n. This solution also requires O(n) extra space as we one by one create all substrings. Method 2 (Space Efficient): In this approach we don’t actually generate substrings rather we traverse the string in such a manner so that we can easily compare first and last characters.
C++
Java
Python3
C#
PHP
Javascript
// Space efficient C++ program to count all// substrings with same first and last characters.#include <bits/stdc++.h>using namespace std; int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Iterating through all substrings in // way so that we can find first and last // character easily for (int i=0; i<n; i++) for (int j=i; j<n; j++) if (s[i] == s[j]) result++; return result;} // Driver functionint main(){ string s("abcab"); cout << countSubstringWithEqualEnds(s); return 0;}
// Space efficient Java program to count all// substrings with same first and last characters.public class GFG { static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Iterating through all substrings in // way so that we can find first and last // character easily for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (s.charAt(i) == s.charAt(j)) result++; return result; } // Driver function public static void main(String args[]) { String s = "abcab"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh
# Space efficient Python3 program to count all# substrings with same first and last characters.def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Iterating through all substrings in # way so that we can find first and # last character easily for i in range(n): for j in range(i, n): if (s[i] == s[j]): result = result + 1 return result # Driver Codes = "abcab";print(countSubstringWithEqualEnds(s)) # This code is contributed# by Akanksha Rai
// Space efficient C# program to count all// substrings with same first and last characters.using System; public class GFG { static int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.Length; // Iterating through all substrings in // way so that we can find first and last // character easily for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (s[i] == s[j]) result++; return result; } // Driver function public static void Main() { string s = "abcab"; Console.Write(countSubstringWithEqualEnds(s)); }} // This code is contributed by nitin mittal
<?php// Space efficient PHP program to count all// substrings with same first and last characters. function countSubstringWithEqualEnds($s){ $result = 0; $n = strlen($s); // Iterating through all substrings in // way so that we can find first and last // character easily for ($i = 0; $i < $n; $i++) for ($j = $i; $j < $n; $j++) if ($s[$i] == $s[$j]) $result++; return $result;} // Driver Code$s = "abcab";echo countSubstringWithEqualEnds($s); // This code is contributed// by Akanksha Rai
<script> // Space efficient javascript program to count all// substrings with same first and last characters.function countSubstringWithEqualEnds(s){ var result = 0; var n = s.length; // Iterating through all substrings in // way so that we can find first and last // character easily for(i = 0; i < n; i++) for(j = i; j < n; j++) if (s.charAt(i) == s.charAt(j)) result++; return result;} // Driver codevar s = "abcab";document.write(countSubstringWithEqualEnds(s)); // This code is contributed by Princi Singh </script>
Output:
7
In the above code although we have reduced the extra space to O(1) time complexity is still O(n^2). Method 3 (Best approach) : Now if we carefully observe then we can realize that the answer just depends on frequencies of characters in the original string. For example in string abcab, frequency of ‘a’ is 2, and substrings contributing to answering are a, abca and a respectively, a total of 3, which is calculated by (frequency of ‘a’+1)C2.
C++
Java
Python3
C#
PHP
Javascript
// Most efficient C++ program to count all // substrings with same first and last characters.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // assuming lower case only int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int count[MAX_CHAR] = {0}; for (int i=0; i<n; i++) count[s[i]-'a']++; // Computing result using counts for (int i=0; i<MAX_CHAR; i++) result += (count[i]*(count[i]+1)/2); return result;} // Driver functionint main(){ string s("abcab"); cout << countSubstringWithEqualEnds(s); return 0;}
// Most efficient Java program to count all // substrings with same first and last characters.public class GFG { // assuming lower case only static final int MAX_CHAR = 26; static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int[] count = new int[MAX_CHAR]; for (int i = 0; i < n; i++) count[s.charAt(i)-'a']++; // Computing result using counts for (int i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver function public static void main(String args[]) { String s = "abcab"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh
# Most efficient Python program to count all# substrings with same first and last characters. MAX_CHAR = 26; # assuming lower case only def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Calculating frequency of each character # in the string. count = [0]*MAX_CHAR; for i in range(n): count[ord(s[i])-ord('a')]+=1; # Computing result using counts for i in range(MAX_CHAR): result += (count[i]*(count[i]+1)/2); return result; # Driver codes = "abcab";print(countSubstringWithEqualEnds(s)); # This code is contributed by 29AjayKumar
// Most efficient C# program to count all// substrings with same first and last characters.using System; class GFG { // assuming lower case only static readonly int MAX_CHAR = 26; static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.Length; // Calculating frequency of each character // in the string. int[] count = new int[MAX_CHAR]; for (int i = 0; i < n; i++) count[s[i] - 'a']++; // Computing result using counts for (int i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver code public static void Main() { String s = "abcab"; Console.Write(countSubstringWithEqualEnds(s)); }} // This code is contributed by 29AjayKumar
<?php// Most efficient PHP program to count all// substrings with same first and last characters.$MAX_CHAR = 26; // assuming lower case only function countSubstringWithEqualEnds($s){ global $MAX_CHAR; $result = 0; $n = strlen($s); // Calculating frequency of each // character in the string. $count = array_fill(0, $MAX_CHAR, 0); for ($i = 0; $i < $n; $i++) $count[ord($s[$i]) - ord('a')]++; // Computing result using counts for ($i = 0; $i < $MAX_CHAR; $i++) $result += ($count[$i] * ($count[$i] + 1) / 2); return $result;} // Driver Code$s = "abcab";echo countSubstringWithEqualEnds($s); // This code is contributed by mits?>
<script>// Most efficient javascript program to count all // substrings with same first and last characters. // assuming lower case only var MAX_CHAR = 26; function countSubstringWithEqualEnds(s) { var result = 0; var n = s.length; // Calculating frequency of each character // in the string. var count = Array.from({length: MAX_CHAR}, (_, i) => 0); for (var i = 0; i < n; i++) count[s.charAt(i).charCodeAt(0)-'a'.charCodeAt(0)]++; // Computing result using counts for (var i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver function var s = "abcab"; document.write(countSubstringWithEqualEnds(s)); // This code is contributed by 29AjayKumar</script>
Output:
7
The above code has time complexity of O(n) and requires O(1) extra space.Recursive solution to count substrings with same first and last charactersThis article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above..
nitin mittal
29AjayKumar
Mithun Kumar
Akanksha_Rai
Chandan_Kumar
Code_Mech
princiraj1992
princi singh
shikhasingrajput
anikaseth98
arorakashish0911
Amazon
Mathematical
Strings
Technical Scripter
Amazon
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 26383,
"s": 26355,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 26500,
"s": 26383,
"text": "We are given a string S, we need to find count of all contiguous substrings starting and ending with same character."
},
{
"code": null,
"e": 26512,
"s": 26500,
"text": "Examples : "
},
{
"code": null,
"e": 26794,
"s": 26512,
"text": "Input : S = \"abcab\"\nOutput : 7\nThere are 15 substrings of \"abcab\"\na, ab, abc, abca, abcab, b, bc, bca\nbcab, c, ca, cab, a, ab, b\nOut of the above substrings, there \nare 7 substrings : a, abca, b, bcab, \nc, a and b.\n\nInput : S = \"aba\"\nOutput : 4\nThe substrings are a, b, a and aba"
},
{
"code": null,
"e": 26979,
"s": 26794,
"text": "Method 1 (Simple): In this approach, we use brute force and find all the sub-strings and pass them through our function checkEquality to see if starting and ending characters are same."
},
{
"code": null,
"e": 26983,
"s": 26979,
"text": "C++"
},
{
"code": null,
"e": 26988,
"s": 26983,
"text": "Java"
},
{
"code": null,
"e": 26996,
"s": 26988,
"text": "Python3"
},
{
"code": null,
"e": 26999,
"s": 26996,
"text": "C#"
},
{
"code": null,
"e": 27003,
"s": 26999,
"text": "PHP"
},
{
"code": null,
"e": 27014,
"s": 27003,
"text": "Javascript"
},
{
"code": "// C++ program to count all substrings with same// first and last characters.#include <bits/stdc++.h>using namespace std; // Returns true if first and last characters// of s are same.int checkEquality(string s){ return (s[0] == s[s.size() - 1]);} int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substr(i, len))) result++; return result;} // Driver functionint main(){ string s(\"abcab\"); cout << countSubstringWithEqualEnds(s); return 0;}",
"e": 27777,
"s": 27014,
"text": null
},
{
"code": "// Java program to count all substrings with same// first and last characters.public class GFG { // Returns true if first and last characters // of s are same. static boolean checkEquality(String s) { return (s.charAt(0) == s.charAt(s.length() - 1)); } static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substring(i, i + len))) result++; return result; } // Driver function public static void main(String args[]) { String s = \"abcab\"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh",
"e": 28762,
"s": 27777,
"text": null
},
{
"code": " # Python program to count all substrings with same# first and last characters. # Returns true if first and last characters# of s are same.def checkEquality(s): return (ord(s[0]) == ord(s[len(s) - 1])); def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Starting point of substring for i in range(n): # Length of substring for j in range(1,n-i+1): # Check if current substring has same # starting and ending characters. if (checkEquality(s[i:i+j])): result+=1; return result; # Driver codes = \"abcab\";print(countSubstringWithEqualEnds(s)); # This code contributed by PrinciRaj1992",
"e": 29430,
"s": 28762,
"text": null
},
{
"code": "// C# program to count all// substrings with same// first and last characters.using System; class GFG{ // Returns true if first and // last characters of s are same. static bool checkEquality(string s) { return (s[0] == s[s.Length - 1]); } static int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.Length; // Starting point of substring for (int i = 0; i < n; i++) // Length of substring for (int len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.Substring(i, len))) result++; return result; } // Driver code public static void Main() { string s = \"abcab\"; Console.WriteLine(countSubstringWithEqualEnds(s)); }} // This code is contributed by Code_Mech",
"e": 30359,
"s": 29430,
"text": null
},
{
"code": "<?php// PHP program to count all substrings// with same first and last characters. // Returns true if first and last// characters of s are same.function checkEquality($s){ return ($s[0] == $s[strlen($s) - 1]);} function countSubstringWithEqualEnds($s){ $result = 0; $n = strlen($s); // Starting point of substring for ($i = 0; $i < $n; $i++) // Length of substring for ($len = 1; $len <= $n - $i; $len++) // Check if current substring has same // starting and ending characters. if (checkEquality(substr($s, $i, $len))) $result++; return $result;} // Driver Code$s = \"abcab\";print(countSubstringWithEqualEnds($s)); // This code is contributed by chandan_jnu?>",
"e": 31079,
"s": 30359,
"text": null
},
{
"code": "<script> // JavaScript program to count all substrings// with same first and last characters. // Returns true if first and last characters// of s are same.function checkEquality(s){ return (s.charAt(0) == s.charAt(s.length - 1));} function countSubstringWithEqualEnds(s){ var result = 0; var n = s.length; // Starting point of substring for (var i = 0; i < n; i++) // Length of substring for (var len = 1; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substring(i, i + len))) result++; return result;} // Driver function var s = \"abcab\"; document.write(countSubstringWithEqualEnds(s)); // This code contributed by shikhasingrajput </script>",
"e": 31875,
"s": 31079,
"text": null
},
{
"code": null,
"e": 31884,
"s": 31875,
"text": "Output: "
},
{
"code": null,
"e": 31886,
"s": 31884,
"text": "7"
},
{
"code": null,
"e": 32314,
"s": 31886,
"text": "Although the above code works fine, it’s not efficient as its time complexity is O(n2). Note that there are n*(n+1)/2 substrings of a string of length n. This solution also requires O(n) extra space as we one by one create all substrings. Method 2 (Space Efficient): In this approach we don’t actually generate substrings rather we traverse the string in such a manner so that we can easily compare first and last characters. "
},
{
"code": null,
"e": 32318,
"s": 32314,
"text": "C++"
},
{
"code": null,
"e": 32323,
"s": 32318,
"text": "Java"
},
{
"code": null,
"e": 32331,
"s": 32323,
"text": "Python3"
},
{
"code": null,
"e": 32334,
"s": 32331,
"text": "C#"
},
{
"code": null,
"e": 32338,
"s": 32334,
"text": "PHP"
},
{
"code": null,
"e": 32349,
"s": 32338,
"text": "Javascript"
},
{
"code": "// Space efficient C++ program to count all// substrings with same first and last characters.#include <bits/stdc++.h>using namespace std; int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Iterating through all substrings in // way so that we can find first and last // character easily for (int i=0; i<n; i++) for (int j=i; j<n; j++) if (s[i] == s[j]) result++; return result;} // Driver functionint main(){ string s(\"abcab\"); cout << countSubstringWithEqualEnds(s); return 0;}",
"e": 32924,
"s": 32349,
"text": null
},
{
"code": "// Space efficient Java program to count all// substrings with same first and last characters.public class GFG { static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Iterating through all substrings in // way so that we can find first and last // character easily for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (s.charAt(i) == s.charAt(j)) result++; return result; } // Driver function public static void main(String args[]) { String s = \"abcab\"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh",
"e": 33667,
"s": 32924,
"text": null
},
{
"code": "# Space efficient Python3 program to count all# substrings with same first and last characters.def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Iterating through all substrings in # way so that we can find first and # last character easily for i in range(n): for j in range(i, n): if (s[i] == s[j]): result = result + 1 return result # Driver Codes = \"abcab\";print(countSubstringWithEqualEnds(s)) # This code is contributed# by Akanksha Rai",
"e": 34178,
"s": 33667,
"text": null
},
{
"code": "// Space efficient C# program to count all// substrings with same first and last characters.using System; public class GFG { static int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.Length; // Iterating through all substrings in // way so that we can find first and last // character easily for (int i = 0; i < n; i++) for (int j = i; j < n; j++) if (s[i] == s[j]) result++; return result; } // Driver function public static void Main() { string s = \"abcab\"; Console.Write(countSubstringWithEqualEnds(s)); }} // This code is contributed by nitin mittal",
"e": 34905,
"s": 34178,
"text": null
},
{
"code": "<?php// Space efficient PHP program to count all// substrings with same first and last characters. function countSubstringWithEqualEnds($s){ $result = 0; $n = strlen($s); // Iterating through all substrings in // way so that we can find first and last // character easily for ($i = 0; $i < $n; $i++) for ($j = $i; $j < $n; $j++) if ($s[$i] == $s[$j]) $result++; return $result;} // Driver Code$s = \"abcab\";echo countSubstringWithEqualEnds($s); // This code is contributed// by Akanksha Rai",
"e": 35451,
"s": 34905,
"text": null
},
{
"code": "<script> // Space efficient javascript program to count all// substrings with same first and last characters.function countSubstringWithEqualEnds(s){ var result = 0; var n = s.length; // Iterating through all substrings in // way so that we can find first and last // character easily for(i = 0; i < n; i++) for(j = i; j < n; j++) if (s.charAt(i) == s.charAt(j)) result++; return result;} // Driver codevar s = \"abcab\";document.write(countSubstringWithEqualEnds(s)); // This code is contributed by Princi Singh </script>",
"e": 36031,
"s": 35451,
"text": null
},
{
"code": null,
"e": 36039,
"s": 36031,
"text": "Output:"
},
{
"code": null,
"e": 36041,
"s": 36039,
"text": "7"
},
{
"code": null,
"e": 36485,
"s": 36041,
"text": "In the above code although we have reduced the extra space to O(1) time complexity is still O(n^2). Method 3 (Best approach) : Now if we carefully observe then we can realize that the answer just depends on frequencies of characters in the original string. For example in string abcab, frequency of ‘a’ is 2, and substrings contributing to answering are a, abca and a respectively, a total of 3, which is calculated by (frequency of ‘a’+1)C2. "
},
{
"code": null,
"e": 36489,
"s": 36485,
"text": "C++"
},
{
"code": null,
"e": 36494,
"s": 36489,
"text": "Java"
},
{
"code": null,
"e": 36502,
"s": 36494,
"text": "Python3"
},
{
"code": null,
"e": 36505,
"s": 36502,
"text": "C#"
},
{
"code": null,
"e": 36509,
"s": 36505,
"text": "PHP"
},
{
"code": null,
"e": 36520,
"s": 36509,
"text": "Javascript"
},
{
"code": "// Most efficient C++ program to count all // substrings with same first and last characters.#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // assuming lower case only int countSubstringWithEqualEnds(string s){ int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int count[MAX_CHAR] = {0}; for (int i=0; i<n; i++) count[s[i]-'a']++; // Computing result using counts for (int i=0; i<MAX_CHAR; i++) result += (count[i]*(count[i]+1)/2); return result;} // Driver functionint main(){ string s(\"abcab\"); cout << countSubstringWithEqualEnds(s); return 0;}",
"e": 37191,
"s": 36520,
"text": null
},
{
"code": "// Most efficient Java program to count all // substrings with same first and last characters.public class GFG { // assuming lower case only static final int MAX_CHAR = 26; static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int[] count = new int[MAX_CHAR]; for (int i = 0; i < n; i++) count[s.charAt(i)-'a']++; // Computing result using counts for (int i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver function public static void main(String args[]) { String s = \"abcab\"; System.out.println(countSubstringWithEqualEnds(s)); }}// This code is contributed by Sumit Ghosh",
"e": 38073,
"s": 37191,
"text": null
},
{
"code": "# Most efficient Python program to count all# substrings with same first and last characters. MAX_CHAR = 26; # assuming lower case only def countSubstringWithEqualEnds(s): result = 0; n = len(s); # Calculating frequency of each character # in the string. count = [0]*MAX_CHAR; for i in range(n): count[ord(s[i])-ord('a')]+=1; # Computing result using counts for i in range(MAX_CHAR): result += (count[i]*(count[i]+1)/2); return result; # Driver codes = \"abcab\";print(countSubstringWithEqualEnds(s)); # This code is contributed by 29AjayKumar",
"e": 38660,
"s": 38073,
"text": null
},
{
"code": "// Most efficient C# program to count all// substrings with same first and last characters.using System; class GFG { // assuming lower case only static readonly int MAX_CHAR = 26; static int countSubstringWithEqualEnds(String s) { int result = 0; int n = s.Length; // Calculating frequency of each character // in the string. int[] count = new int[MAX_CHAR]; for (int i = 0; i < n; i++) count[s[i] - 'a']++; // Computing result using counts for (int i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver code public static void Main() { String s = \"abcab\"; Console.Write(countSubstringWithEqualEnds(s)); }} // This code is contributed by 29AjayKumar",
"e": 39516,
"s": 38660,
"text": null
},
{
"code": "<?php// Most efficient PHP program to count all// substrings with same first and last characters.$MAX_CHAR = 26; // assuming lower case only function countSubstringWithEqualEnds($s){ global $MAX_CHAR; $result = 0; $n = strlen($s); // Calculating frequency of each // character in the string. $count = array_fill(0, $MAX_CHAR, 0); for ($i = 0; $i < $n; $i++) $count[ord($s[$i]) - ord('a')]++; // Computing result using counts for ($i = 0; $i < $MAX_CHAR; $i++) $result += ($count[$i] * ($count[$i] + 1) / 2); return $result;} // Driver Code$s = \"abcab\";echo countSubstringWithEqualEnds($s); // This code is contributed by mits?>",
"e": 40209,
"s": 39516,
"text": null
},
{
"code": "<script>// Most efficient javascript program to count all // substrings with same first and last characters. // assuming lower case only var MAX_CHAR = 26; function countSubstringWithEqualEnds(s) { var result = 0; var n = s.length; // Calculating frequency of each character // in the string. var count = Array.from({length: MAX_CHAR}, (_, i) => 0); for (var i = 0; i < n; i++) count[s.charAt(i).charCodeAt(0)-'a'.charCodeAt(0)]++; // Computing result using counts for (var i = 0; i < MAX_CHAR; i++) result += (count[i] * (count[i] + 1) / 2); return result; } // Driver function var s = \"abcab\"; document.write(countSubstringWithEqualEnds(s)); // This code is contributed by 29AjayKumar</script>",
"e": 41049,
"s": 40209,
"text": null
},
{
"code": null,
"e": 41057,
"s": 41049,
"text": "Output:"
},
{
"code": null,
"e": 41059,
"s": 41057,
"text": "7"
},
{
"code": null,
"e": 41628,
"s": 41059,
"text": "The above code has time complexity of O(n) and requires O(1) extra space.Recursive solution to count substrings with same first and last charactersThis article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.. "
},
{
"code": null,
"e": 41641,
"s": 41628,
"text": "nitin mittal"
},
{
"code": null,
"e": 41653,
"s": 41641,
"text": "29AjayKumar"
},
{
"code": null,
"e": 41666,
"s": 41653,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 41679,
"s": 41666,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 41693,
"s": 41679,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 41703,
"s": 41693,
"text": "Code_Mech"
},
{
"code": null,
"e": 41717,
"s": 41703,
"text": "princiraj1992"
},
{
"code": null,
"e": 41730,
"s": 41717,
"text": "princi singh"
},
{
"code": null,
"e": 41747,
"s": 41730,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 41759,
"s": 41747,
"text": "anikaseth98"
},
{
"code": null,
"e": 41776,
"s": 41759,
"text": "arorakashish0911"
},
{
"code": null,
"e": 41783,
"s": 41776,
"text": "Amazon"
},
{
"code": null,
"e": 41796,
"s": 41783,
"text": "Mathematical"
},
{
"code": null,
"e": 41804,
"s": 41796,
"text": "Strings"
},
{
"code": null,
"e": 41823,
"s": 41804,
"text": "Technical Scripter"
},
{
"code": null,
"e": 41830,
"s": 41823,
"text": "Amazon"
},
{
"code": null,
"e": 41838,
"s": 41830,
"text": "Strings"
},
{
"code": null,
"e": 41851,
"s": 41838,
"text": "Mathematical"
},
{
"code": null,
"e": 41949,
"s": 41851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41973,
"s": 41949,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 42016,
"s": 41973,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 42030,
"s": 42016,
"text": "Prime Numbers"
},
{
"code": null,
"e": 42072,
"s": 42030,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 42094,
"s": 42072,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 42140,
"s": 42094,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 42165,
"s": 42140,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 42199,
"s": 42165,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 42274,
"s": 42199,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
mount command in Linux with Examples - GeeksforGeeks
|
23 May, 2019
All files in a Linux filesystem are arranged in form of a big tree rooted at ‘/‘.These files can be spread out on various devices based on your partition table, initially your parent directory is mounted(i.e attached) to this tree at ‘/‘, others can be mounted manually using GUI interface(if available) or using mount command.mount command is used to mount the filesystem found on a device to big tree structure(Linux filesystem) rooted at ‘/‘. Conversely, another command umount can be used to detach these devices from the Tree.
Syntax:
mount -t type device dir
Other forms:
mount [-l|-h|-V]
mount -a [-fFnrsvw] [-t fstype] [-O optlist]
mount [-fnrsvw] [-o options] device|dir
mount [-fnrsvw] [-t fstype] [-o options] device dir
These commands tells the Kernel to attach the filesystem found at device to the dir.
Note:
If you leave the dir part of syntax it looks for a mount point in /etc/fstab.
You can use –source or –target to avoid ambivalent interpretation.mount --target /mountpoint
mount --target /mountpoint
/etc/fstab usually contains information about which device is need to be mounted where.
Most of the devices are indicated by files like /dev/sda4, etc. But it can be different for certain filesystems. Please refer below for more information.man mount
man mount
Note: It is important to note that we are only discussing the standard form of mount command given as syntax. Different forms are somewhat discussed because it has certain limitations on different kernels.
Some Important Options:
l : Lists all the file systems mounted yet.
h : Displays options for command.
V : Displays the version information.
a : Mounts all devices described at /etc/fstab.
t : Type of filesystem device uses.
T : Describes an alternative fstab file.
r : Read-only mode mounted.
Examples:
Displays information about file systems mounted:
Mounts file systems:
Displays version information:
Unmounts file systems:
linux-command
Linux-file-commands
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
|
[
{
"code": null,
"e": 25278,
"s": 25250,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 25810,
"s": 25278,
"text": "All files in a Linux filesystem are arranged in form of a big tree rooted at ‘/‘.These files can be spread out on various devices based on your partition table, initially your parent directory is mounted(i.e attached) to this tree at ‘/‘, others can be mounted manually using GUI interface(if available) or using mount command.mount command is used to mount the filesystem found on a device to big tree structure(Linux filesystem) rooted at ‘/‘. Conversely, another command umount can be used to detach these devices from the Tree."
},
{
"code": null,
"e": 25818,
"s": 25810,
"text": "Syntax:"
},
{
"code": null,
"e": 25843,
"s": 25818,
"text": "mount -t type device dir"
},
{
"code": null,
"e": 25856,
"s": 25843,
"text": "Other forms:"
},
{
"code": null,
"e": 26011,
"s": 25856,
"text": "mount [-l|-h|-V]\nmount -a [-fFnrsvw] [-t fstype] [-O optlist]\nmount [-fnrsvw] [-o options] device|dir\nmount [-fnrsvw] [-t fstype] [-o options] device dir\n"
},
{
"code": null,
"e": 26096,
"s": 26011,
"text": "These commands tells the Kernel to attach the filesystem found at device to the dir."
},
{
"code": null,
"e": 26102,
"s": 26096,
"text": "Note:"
},
{
"code": null,
"e": 26180,
"s": 26102,
"text": "If you leave the dir part of syntax it looks for a mount point in /etc/fstab."
},
{
"code": null,
"e": 26273,
"s": 26180,
"text": "You can use –source or –target to avoid ambivalent interpretation.mount --target /mountpoint"
},
{
"code": null,
"e": 26300,
"s": 26273,
"text": "mount --target /mountpoint"
},
{
"code": null,
"e": 26388,
"s": 26300,
"text": "/etc/fstab usually contains information about which device is need to be mounted where."
},
{
"code": null,
"e": 26551,
"s": 26388,
"text": "Most of the devices are indicated by files like /dev/sda4, etc. But it can be different for certain filesystems. Please refer below for more information.man mount"
},
{
"code": null,
"e": 26561,
"s": 26551,
"text": "man mount"
},
{
"code": null,
"e": 26767,
"s": 26561,
"text": "Note: It is important to note that we are only discussing the standard form of mount command given as syntax. Different forms are somewhat discussed because it has certain limitations on different kernels."
},
{
"code": null,
"e": 26791,
"s": 26767,
"text": "Some Important Options:"
},
{
"code": null,
"e": 26835,
"s": 26791,
"text": "l : Lists all the file systems mounted yet."
},
{
"code": null,
"e": 26869,
"s": 26835,
"text": "h : Displays options for command."
},
{
"code": null,
"e": 26907,
"s": 26869,
"text": "V : Displays the version information."
},
{
"code": null,
"e": 26955,
"s": 26907,
"text": "a : Mounts all devices described at /etc/fstab."
},
{
"code": null,
"e": 26991,
"s": 26955,
"text": "t : Type of filesystem device uses."
},
{
"code": null,
"e": 27032,
"s": 26991,
"text": "T : Describes an alternative fstab file."
},
{
"code": null,
"e": 27060,
"s": 27032,
"text": "r : Read-only mode mounted."
},
{
"code": null,
"e": 27070,
"s": 27060,
"text": "Examples:"
},
{
"code": null,
"e": 27119,
"s": 27070,
"text": "Displays information about file systems mounted:"
},
{
"code": null,
"e": 27140,
"s": 27119,
"text": "Mounts file systems:"
},
{
"code": null,
"e": 27170,
"s": 27140,
"text": "Displays version information:"
},
{
"code": null,
"e": 27193,
"s": 27170,
"text": "Unmounts file systems:"
},
{
"code": null,
"e": 27207,
"s": 27193,
"text": "linux-command"
},
{
"code": null,
"e": 27227,
"s": 27207,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 27249,
"s": 27227,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 27256,
"s": 27249,
"text": "Picked"
},
{
"code": null,
"e": 27267,
"s": 27256,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27365,
"s": 27267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27403,
"s": 27365,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27438,
"s": 27403,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27474,
"s": 27438,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27512,
"s": 27474,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27550,
"s": 27512,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27586,
"s": 27550,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27621,
"s": 27586,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 27658,
"s": 27621,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 27694,
"s": 27658,
"text": "echo command in Linux with Examples"
}
] |
Zoho Interview Experience | Set 12 (On-Campus) - GeeksforGeeks
|
05 Jul, 2016
Recently ZOHO visited our campus for recruitment and i would like to share my experience.Thanks to geeksforgeeks which contributed to most of my preparations..Round 1 : TIME : 2hrsI was expecting an aptitude written round .But they gave us 30 flowchart and asked us to go through each flowchart and the questions were based on the flowchart..Questions included finding the o/p of the flowchart , find the missing statement which when added produces the given o/p..If you concentrate and go through the flowchart it should be easy to crack the first round..
Round 2: TIME : 3hrsThey shortlisted 150 candidates from the first round..This was a programming round and consisted of straightforward questions..
1.Given two numbers a and b both < 200 we have to find the square numbers which lie between a and b(inclusive)
eg) i/p a = 20;b = 100;
o/p 25,36,49,64,81,100
2.Alternately sort an unsorted array..
eg) i/p {5,2,8,7,4,3,9}
o/p {9,2,8,3,7,4,5}
3. Given an array and a threshold value find the o/p
eg) i/p {5,8,10,13,6,2};threshold = 3;
o/p count = 17
explanation:
Number parts counts
5 {3,2} 2
8 {3,3,2} 3
10 {3,3,3,1} 4
13 {3,3,3,3,1} 5
6 {3,3} 2
2 {2} 1
4.a. Given two binary numbers add the two numbers in binary form without converting them to decimal value.
eg) a = 1010 b = 11001
o/p 100011
b.The two numbers were given in base n
eg) a = 123 b = 13 n = 4
o/p 202
5.Write a program to print the below pattern
for n = 6
1 7 12 16 19 21
2 8 13 17 20
3 9 14 18
4 10 15
5 11
6
6.Given bigger NxN matrix and a smaller MxM matrix print TRUE if the smaller matrix can be found in the bigger matrix else print FALSE
7.Given two matrices a and b both of size NxN find if matrix a can be transformed to matrix b by rotating it 90deg , 180deg , 270deg if so print TRUE else print FALSE
8 In addition to the above question you have to check if matrix a can be transformed by mirroring vertically or horizontally to matrix b.
I solved 7 questions .. Those who solved more than 5 were selected for the next round.
Round 3 : TIME : 3hrsAbout 50 – 60 were shortlisted .. This round was also a programming round..Questions were based of matrix transformation.Each question was an extension of the previous question in some way..There were 5 questions .. I solved only 2 But got selected for the next round , I think it was based on my performance on all previous rounds..
Round 4:We had both HR and technical HR.In technical HR if they found out that a candidate was not sure on some topic the candidate was asked questions on that topic for the rest of the round even after the candidate said he does not know that concept . In my case it was DBMS The round also consisted of 3 puzzles ..they were easy to solve , i solved all of them..
In HR round we had a friendly chat ..They didn’t want candidates who were willing to quit the job after a few years and go for higher studies( obviously )..I was asked about my family and my hobbies..
After round 4 we had to wait for almost 5 hrs before the results were announced..There were 2 packages x and x+y.. I was offered the x package mostly because i didn’t do round 3 well but they said that if we prove ourselves during the internship they would change the package to x+y so looking forward to that
Overall it was a good experience and i really appreciate ZOHO team for the amount of effort they invested in the interview process each round was both challenging and enjoyable in its own way If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1 (On-Campus)
|
[
{
"code": null,
"e": 26189,
"s": 26161,
"text": "\n05 Jul, 2016"
},
{
"code": null,
"e": 26746,
"s": 26189,
"text": "Recently ZOHO visited our campus for recruitment and i would like to share my experience.Thanks to geeksforgeeks which contributed to most of my preparations..Round 1 : TIME : 2hrsI was expecting an aptitude written round .But they gave us 30 flowchart and asked us to go through each flowchart and the questions were based on the flowchart..Questions included finding the o/p of the flowchart , find the missing statement which when added produces the given o/p..If you concentrate and go through the flowchart it should be easy to crack the first round.."
},
{
"code": null,
"e": 26894,
"s": 26746,
"text": "Round 2: TIME : 3hrsThey shortlisted 150 candidates from the first round..This was a programming round and consisted of straightforward questions.."
},
{
"code": null,
"e": 27005,
"s": 26894,
"text": "1.Given two numbers a and b both < 200 we have to find the square numbers which lie between a and b(inclusive)"
},
{
"code": null,
"e": 27059,
"s": 27005,
"text": "eg) i/p a = 20;b = 100;\n o/p 25,36,49,64,81,100 "
},
{
"code": null,
"e": 27098,
"s": 27059,
"text": "2.Alternately sort an unsorted array.."
},
{
"code": null,
"e": 27148,
"s": 27098,
"text": "eg) i/p {5,2,8,7,4,3,9}\n o/p {9,2,8,3,7,4,5}"
},
{
"code": null,
"e": 27201,
"s": 27148,
"text": "3. Given an array and a threshold value find the o/p"
},
{
"code": null,
"e": 27580,
"s": 27201,
"text": "eg) i/p {5,8,10,13,6,2};threshold = 3;\n o/p count = 17\n explanation:\nNumber\tparts\t counts\n5\t {3,2} 2\n8 {3,3,2} 3\n10 {3,3,3,1} 4\n13 {3,3,3,3,1} 5\n6 {3,3} 2\n2 {2} 1 "
},
{
"code": null,
"e": 27687,
"s": 27580,
"text": "4.a. Given two binary numbers add the two numbers in binary form without converting them to decimal value."
},
{
"code": null,
"e": 27827,
"s": 27687,
"text": "eg) a = 1010 b = 11001\n o/p 100011\t \n b.The two numbers were given in base n \n\teg) a = 123 b = 13 n = 4\n\t o/p 202"
},
{
"code": null,
"e": 27872,
"s": 27827,
"text": "5.Write a program to print the below pattern"
},
{
"code": null,
"e": 27941,
"s": 27872,
"text": "for n = 6\n\t1\t7\t12\t16\t19\t21\n\t2\t8\t13\t17\t20\n3\t9\t14\t18\t\n4\t10\t15\n5\t11\t\n6 "
},
{
"code": null,
"e": 28076,
"s": 27941,
"text": "6.Given bigger NxN matrix and a smaller MxM matrix print TRUE if the smaller matrix can be found in the bigger matrix else print FALSE"
},
{
"code": null,
"e": 28243,
"s": 28076,
"text": "7.Given two matrices a and b both of size NxN find if matrix a can be transformed to matrix b by rotating it 90deg , 180deg , 270deg if so print TRUE else print FALSE"
},
{
"code": null,
"e": 28381,
"s": 28243,
"text": "8 In addition to the above question you have to check if matrix a can be transformed by mirroring vertically or horizontally to matrix b."
},
{
"code": null,
"e": 28468,
"s": 28381,
"text": "I solved 7 questions .. Those who solved more than 5 were selected for the next round."
},
{
"code": null,
"e": 28824,
"s": 28468,
"text": "Round 3 : TIME : 3hrsAbout 50 – 60 were shortlisted .. This round was also a programming round..Questions were based of matrix transformation.Each question was an extension of the previous question in some way..There were 5 questions .. I solved only 2 But got selected for the next round , I think it was based on my performance on all previous rounds.."
},
{
"code": null,
"e": 29191,
"s": 28824,
"text": "Round 4:We had both HR and technical HR.In technical HR if they found out that a candidate was not sure on some topic the candidate was asked questions on that topic for the rest of the round even after the candidate said he does not know that concept . In my case it was DBMS The round also consisted of 3 puzzles ..they were easy to solve , i solved all of them.."
},
{
"code": null,
"e": 29392,
"s": 29191,
"text": "In HR round we had a friendly chat ..They didn’t want candidates who were willing to quit the job after a few years and go for higher studies( obviously )..I was asked about my family and my hobbies.."
},
{
"code": null,
"e": 29703,
"s": 29392,
"text": "After round 4 we had to wait for almost 5 hrs before the results were announced..There were 2 packages x and x+y.. I was offered the x package mostly because i didn’t do round 3 well but they said that if we prove ourselves during the internship they would change the package to x+y so looking forward to that "
},
{
"code": null,
"e": 30116,
"s": 29703,
"text": "Overall it was a good experience and i really appreciate ZOHO team for the amount of effort they invested in the interview process each round was both challenging and enjoyable in its own way If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30240,
"s": 30116,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 30245,
"s": 30240,
"text": "Zoho"
},
{
"code": null,
"e": 30267,
"s": 30245,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30272,
"s": 30267,
"text": "Zoho"
},
{
"code": null,
"e": 30370,
"s": 30272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30421,
"s": 30370,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 30463,
"s": 30421,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 30499,
"s": 30463,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 30555,
"s": 30499,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 30583,
"s": 30555,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 30621,
"s": 30583,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30660,
"s": 30621,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 30706,
"s": 30660,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30778,
"s": 30706,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
}
] |
How to set up the Game Loop in PygGame ? - GeeksforGeeks
|
01 Oct, 2021
In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks:
Update our game window to show visual changesUpdate our game states based on user inputsHandle different types of eventsKeep game window running
Update our game window to show visual changes
Update our game states based on user inputs
Handle different types of events
Keep game window running
Simply game loop is a while loop having only one condition to check whether our boolean condition to keep the game running is true.
Step 1: Declare a Boolean variable to true which will be used to check whether our player wants to keep playing our game or not.
keepGameRunning=true
Step 2: Create a while loop and check our above Boolean variable that whether it is true or not. If true keep the loop running which suggests keeping our game loop running. In this while loop check for events and if the event is quit then set the above variable too false to exit our game loop and end our pygame window.
while keepGameRunning:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGameRunning = False
Below is the complete implementation.
In the below code, we are creating a simple game loop that creates a pygame window and checks if the event type is quit and, if it is true then quit the game.
Python3
# import pygame packageimport pygame # initializing imported modulepygame.init() # displaying a window of height# 500 and width 400pygame.display.set_mode((400, 500)) # Setting name for windowpygame.display.set_caption('GeeksforGeeks') # creating a bool value which checks# if game is runningrunning = True # Game loop# keep game running till running is truewhile running: # Check for event if user has pushed # any event in queue for event in pygame.event.get(): # if event is of type quit then set # running bool to false if event.type == pygame.QUIT: running = False
Output:
In the below code, we added one more task to our game loop i.e. to update our screen in each loop. Here we change the background color for each loop by updating our screen in each loop.
Python3
# import pygame packageimport pygame # initializing imported modulepygame.init() # displaying a window of height# 500 and width 400window = pygame.display.set_mode((400, 500)) # creating a bool value which checks# if game is runningrunning = True # setting variable to storecolorcolor = "red" # keep game running till running is truewhile running: # Check for event if user has pushed # any event in queue for event in pygame.event.get(): # if event is of type quit then set # running bool to false if event.type == pygame.QUIT: running = False # set background color to our window window.fill(color) # Update our window pygame.display.flip() # if color is red change it to green and # vice-versa if(color == "red"): color = "green" else: color = "red"
Output:
anikaseth98
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 25767,
"s": 25537,
"text": "In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks:"
},
{
"code": null,
"e": 25912,
"s": 25767,
"text": "Update our game window to show visual changesUpdate our game states based on user inputsHandle different types of eventsKeep game window running"
},
{
"code": null,
"e": 25958,
"s": 25912,
"text": "Update our game window to show visual changes"
},
{
"code": null,
"e": 26002,
"s": 25958,
"text": "Update our game states based on user inputs"
},
{
"code": null,
"e": 26035,
"s": 26002,
"text": "Handle different types of events"
},
{
"code": null,
"e": 26060,
"s": 26035,
"text": "Keep game window running"
},
{
"code": null,
"e": 26192,
"s": 26060,
"text": "Simply game loop is a while loop having only one condition to check whether our boolean condition to keep the game running is true."
},
{
"code": null,
"e": 26323,
"s": 26192,
"text": "Step 1: Declare a Boolean variable to true which will be used to check whether our player wants to keep playing our game or not. "
},
{
"code": null,
"e": 26344,
"s": 26323,
"text": "keepGameRunning=true"
},
{
"code": null,
"e": 26665,
"s": 26344,
"text": "Step 2: Create a while loop and check our above Boolean variable that whether it is true or not. If true keep the loop running which suggests keeping our game loop running. In this while loop check for events and if the event is quit then set the above variable too false to exit our game loop and end our pygame window."
},
{
"code": null,
"e": 26800,
"s": 26665,
"text": "while keepGameRunning:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n keepGameRunning = False"
},
{
"code": null,
"e": 26838,
"s": 26800,
"text": "Below is the complete implementation."
},
{
"code": null,
"e": 26997,
"s": 26838,
"text": "In the below code, we are creating a simple game loop that creates a pygame window and checks if the event type is quit and, if it is true then quit the game."
},
{
"code": null,
"e": 27005,
"s": 26997,
"text": "Python3"
},
{
"code": "# import pygame packageimport pygame # initializing imported modulepygame.init() # displaying a window of height# 500 and width 400pygame.display.set_mode((400, 500)) # Setting name for windowpygame.display.set_caption('GeeksforGeeks') # creating a bool value which checks# if game is runningrunning = True # Game loop# keep game running till running is truewhile running: # Check for event if user has pushed # any event in queue for event in pygame.event.get(): # if event is of type quit then set # running bool to false if event.type == pygame.QUIT: running = False",
"e": 27626,
"s": 27005,
"text": null
},
{
"code": null,
"e": 27634,
"s": 27626,
"text": "Output:"
},
{
"code": null,
"e": 27820,
"s": 27634,
"text": "In the below code, we added one more task to our game loop i.e. to update our screen in each loop. Here we change the background color for each loop by updating our screen in each loop."
},
{
"code": null,
"e": 27828,
"s": 27820,
"text": "Python3"
},
{
"code": "# import pygame packageimport pygame # initializing imported modulepygame.init() # displaying a window of height# 500 and width 400window = pygame.display.set_mode((400, 500)) # creating a bool value which checks# if game is runningrunning = True # setting variable to storecolorcolor = \"red\" # keep game running till running is truewhile running: # Check for event if user has pushed # any event in queue for event in pygame.event.get(): # if event is of type quit then set # running bool to false if event.type == pygame.QUIT: running = False # set background color to our window window.fill(color) # Update our window pygame.display.flip() # if color is red change it to green and # vice-versa if(color == \"red\"): color = \"green\" else: color = \"red\"",
"e": 28696,
"s": 27828,
"text": null
},
{
"code": null,
"e": 28704,
"s": 28696,
"text": "Output:"
},
{
"code": null,
"e": 28716,
"s": 28704,
"text": "anikaseth98"
},
{
"code": null,
"e": 28723,
"s": 28716,
"text": "Picked"
},
{
"code": null,
"e": 28737,
"s": 28723,
"text": "Python-PyGame"
},
{
"code": null,
"e": 28744,
"s": 28737,
"text": "Python"
},
{
"code": null,
"e": 28842,
"s": 28744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28874,
"s": 28842,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28916,
"s": 28874,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28958,
"s": 28916,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28985,
"s": 28958,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29041,
"s": 28985,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29080,
"s": 29041,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29102,
"s": 29080,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29133,
"s": 29102,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29162,
"s": 29133,
"text": "Create a directory in Python"
}
] |
Range Queries for number of Armstrong numbers in an array with updates - GeeksforGeeks
|
07 Oct, 2021
Given an array arr[] of N integers, the task is to perform the following two queries:
query(start, end): Print the number of Armstrong numbers in the subarray from start to end
update(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x
Examples:
Input: arr = { 18, 153, 8, 9, 14, 5} Query 1: query(start = 0, end = 4) Query 2: update(i = 3, x = 11) Query 3: query(start = 0, end = 4) Output: 3 2 Explanation In Query 1, 18 -> 1*1 + 8*8 != 18 153 -> 1*1*1 + 5*5*5 + 3*3*3 = 153 8 -> 8 = 8 9 -> 9 = 9 14 -> 1*1 + 4*4 != 14 the subarray [0...4] has 3 Armstrong numbers viz. {18, 153, 8, 9, 14}In Query 2, the value at index 3 is updated to 11, the array arr now is, { 18, 153, 8, 11, 14, 5}In Query 3, 18 -> 1*1 + 8*8 != 18 153 -> 1*1*1 + 5*5*5 + 3*3*3 = 153 8 -> 8 = 8 9 -> 1*1 + 1*1 != 11 14 -> 1*1 + 4*4 != 14 the subarray [0...4] has 2 Armstrong numbers viz. {18, 153, 8, 11, 14}
Approach: To handle both point updates and range queries, a segment tree is optimal for this purpose.A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + ....
In order to check for Armstrong numbers, the idea is to first count number digits (or find order). Let the number of digits be n. For every digit r in input number x, compute r^n. If the sum of all such values is equal to n, then set it to 1 else to 0.
Building the segment tree:
The problem is now reduced to the subarray sum using segment tree problem.
Now, we can build the segment tree where a leaf node is represented as either 0 (if it is not an Armstrong number) or 1 (if it is Armstrong number).
The internal nodes of the segment tree equal to the sum of its child nodes, thus a node represent the total Armstrong numbers in the range from L to R with range [L, R] falling under this node and the sub-tree underneath it.
Handling Queries and Point Updates:
Whenever we receive a query from beginning to end, we can query the segment tree for the sum of nodes in the range from start to end, which in turn represents the number of Armstrong numbers in the range start to end.
To perform a point update and to update the value at index i to x, we check for the following cases: Let the old value of arri be y and the new value be x. Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment treeCase 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree
Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment treeCase 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree
Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment tree
Case 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment tree
Case 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment tree
Case 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree
Below is the implementation of the above approach:
C++
Python3
C#
// C++ program to find the number// of Armstrong numbers in a// subarray and performing updates #include <bits/stdc++.h>using namespace std; #define MAX 1000 // Function that return true// if num is armstrong// else return falsebool isArmstrong(int x){ int n = to_string(x).size(); int sum1 = 0; int temp = x; while (temp > 0) { int digit = temp % 10; sum1 += pow(digit, n); temp /= 10; } if (sum1 == x) return true; return false;} // A utility function to get the middle// index from corner indexes.int getMid(int s, int e){ return s + (e - s) / 2;} // Recursive function to get the number// of Armstrong numbers in a given range/* where st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int queryArmstrongUtil(int* st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part // of given range, then return // the number of Armstrong numbers // in the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node // is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return queryArmstrongUtil( st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil( st, mid + 1, se, qs, qe, 2 * index + 2);} // Recursive function to update// the nodes which have the given// index in their range./* where st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range*/void updateValueUtil(int* st, int ss, int se, int i, int diff, int si){ // Base Case: // If the input index lies outside // the range of this segment if (i < ss || i > se) return; // If the input index is in range // of this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // Function to update a value in the// input array and segment tree.// It uses updateValueUtil() to update// the value in segment treevoid updateValue(int arr[], int* st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { printf("Invalid Input"); return; } int diff, oldValue; oldValue = arr[i]; // Update the value in array arr[i] = new_val; // Case 1: Old and new values // both are Armstrong numbers if (isArmstrong(oldValue) && isArmstrong(new_val)) return; // Case 2: Old and new values // both not Armstrong numbers if (!isArmstrong(oldValue) && !isArmstrong(new_val)) return; // Case 3: Old value was Armstrong, // new value is non Armstrong if (isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = -1; } // Case 4: Old value was non Armstrong, // new_val is Armstrong if (!isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = 1; } // Update the values of // nodes in segment tree updateValueUtil( st, 0, n - 1, i, diff, 0);} // Return number of Armstrong numbers// in range from index qs (query start)// to qe (query end).// It mainly uses queryArmstrongUtil()void queryArmstrong(int* st, int n, int qs, int qe){ int ArmstrongInRange = queryArmstrongUtil(st, 0, n - 1, qs, qe, 0); cout << "Number of Armstrong numbers " << "in subarray from " << qs << " to " << qe << " = " << ArmstrongInRange << "\n";} // Recursive function that constructs// Segment Tree for array[ss..se].// si is index of current node// in segment tree stint constructSTUtil(int arr[], int ss, int se, int* st, int si){ // If there is one element in array, // check if it is Armstrong number // then store 1 in the segment tree // else store 0 and return if (ss == se) { // if arr[ss] is Armstrong number if (isArmstrong(arr[ss])) st[si] = 1; else st[si] = 0; return st[si]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of the // two values in this node int mid = getMid(ss, se); st[si] = constructSTUtil( arr, ss, mid, st, si * 2 + 1) + constructSTUtil( arr, mid + 1, se, st, si * 2 + 2); return st[si];} // Function to construct a segment// tree from given array.// This function allocates memory// for segment tree and// calls constructSTUtil() to// fill the allocated memoryint* constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; int* st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver Codeint main(){ int arr[] = { 18, 153, 8, 9, 14, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree from given array int* st = constructST(arr, n); // Query 1: Query(start = 0, end = 4) int start = 0; int end = 4; queryArmstrong(st, n, start, end); // Query 2: Update(i = 3, x = 11), // i.e Update a[i] to x int i = 3; int x = 11; updateValue(arr, st, n, i, x); // Print array after update cout << "Array after update: "; for (int i = 0; i < n; i++) cout << arr[i] << ", "; cout << endl; // Query 3: Query(start = 0, end = 4) start = 0; end = 4; queryArmstrong(st, n, start, end); return 0;}
# Python3 program to find the number# of Armstrong numbers in a# subarray and performing updatesimport math MAX = 1000 # Function that return true# if num is armstrong# else return falsedef isArmstrong(x): n = len(str(x)) sum1 = 0 temp = x while temp > 0: digit = temp % 10 sum1 += pow(digit, n) temp = temp // 10 if sum1 == x: return True return False # A utility function to get the middle# index from corner indexes.def getMid(s, e): return s + (e - s) // 2 # Recursive function to get the number# of Armstrong numbers in a given range# where# st --> Pointer to segment tree# index --> Index of current node in the# segment tree. Initially 0 is passed# as root is always at index 0# ss & se --> Starting and ending indexes of# the segment represented by current# node, i.e., st[index]# qs & qe --> Starting and ending indexes# of query rangedef queryArmstrongUtil(st, ss, se, qs, qe, index): # If segment of this node is a part # of given range, then return # the number of Armstrong numbers # in the segment if qs <= ss and qe >= se: return st[index] # If segment of this node # is outside the given range if se < qs or ss > qe: return 0 # If a part of this segment # overlaps with the given range mid = getMid(ss, se) return (queryArmstrongUtil(st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil(st, mid + 1, se, qs, qe, 2 * index + 2)) # Recursive function to update# the nodes which have the given# index in their range.# where# st, si, ss and se are same as getSumUtil()# i --> index of the element to be updated.# This index is in input array.# diff --> Value to be added to all nodes# which have i in rangedef updateValueUtil(st, ss, se, i, diff, si): # Base Case: # If the input index lies outside # the range of this segment if i < ss or i > se: return # If the input index is in range # of this node, then update the value # of the node and its children st[si] = st[si] + diff if se != ss: mid = getMid(ss, se) updateValueUtil(st, ss, mid, i, diff, 2 * si + 1) updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2) # Function to update a value in the# input array and segment tree.# It uses updateValueUtil() to update# the value in segment treedef updateValue(arr, st, n, i, new_val): # Check for erroneous input index if i < 0 or i > n - 1: print('Invalid Input') return oldValue = arr[i] # Update the value in array arr[i] = new_val # Case 1: Old and new values # both are Armstrong numbers if (isArmstrong(oldValue) and isArmstrong(new_val)): return # Case 2: Old and new values # both not Armstrong numbers if (not isArmstrong(oldValue) and not isArmstrong(new_val)): return # Case 3: Old value was Armstrong, # new value is non Armstrong if (isArmstrong(oldValue) and (not isArmstrong(new_val))): diff = -1 # Case 4: Old value was non Armstrong, # new_val is Armstrong if (not isArmstrong(oldValue) and not isArmstrong(new_val)): diff = 1 # Update the values of # nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0) # Return number of Armstrong numbers# in range from index qs (query start)# to qe (query end).# It mainly uses queryArmstrongUtil()def queryArmstrong(st, n, qs, qe): ArmstrongInRange = queryArmstrongUtil(st, 0, n - 1, qs, qe, 0) print("Number of Armstrong numbers in " "subarray from", qs, "to", qe, "=", ArmstrongInRange) # Recursive function that constructs# Segment Tree for array[ss..se].# si is index of current node# in segment tree stdef constructSTUtil(arr, ss, se, st, si): # If there is one element in array, # check if it is Armstrong number # then store 1 in the segment tree # else store 0 and return if ss == se: # If arr[ss] is Armstrong number if isArmstrong(arr[ss]): st[si] = 1 else: st[si] = 0 return st[si] # If there are more than one elements, # then recur for left and right subtrees # and store the sum of the # two values in this node mid = getMid(ss, se) st[si] = (constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] # Function to construct a segment# tree from given array.# This function allocates memory# for segment tree and# calls constructSTUtil() to# fill the allocated memorydef constructST(arr, n): # Allocate memory for segment tree # Height of segment tree x = int(math.ceil(math.log2(n))) # Maximum size of segment tree max_size = 2 * int(pow(2, x)) - 1 st = [-1] * max_size # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0) # Return the constructed segment tree return st # Driver codearr = [ 18, 153, 8, 9, 14, 5 ]n = len(arr) # Build segment tree from given arrayst = constructST(arr, n) # Query 1: Query(start = 0, end = 4)start = 0end = 4queryArmstrong(st, n, start, end) # Query 2: Update(i = 3, x = 11),# i.e Update a[i] to xi = 3x = 11updateValue(arr, st, n, i, x) # Print array after updateprint("Array after update:", end = " ")for i in range(n): print(arr[i], end = ", ") print() # Query 3: Query(start = 0, end = 4)start = 0end = 4queryArmstrong(st, n, start, end) # This code is contributed by stutipathak31jan
// C# program to find the number// of Armstrong numbers in a// subarray and performing updatesusing System; class GFG{ public int MAX = 1000; // Function that return true// if num is armstrong// else return falsestatic bool isArmstrong(int x){ int n = x.ToString().Length; int sum1 = 0; int temp = x; while (temp > 0) { int digit = temp % 10; sum1 += (int)Math.Pow(digit, n); temp /= 10; } if (sum1 == x) return true; return false;} // A utility function to get the middle// index from corner indexes.static int getMid(int s, int e){ return s + (e - s) / 2;} // Recursive function to get the number// of Armstrong numbers in a given range/* where st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */static int queryArmstrongUtil(int[] st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part // of given range, then return // the number of Armstrong numbers // in the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node // is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return queryArmstrongUtil(st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil(st, mid + 1, se, qs, qe, 2 * index + 2);} // Recursive function to update// the nodes which have the given// index in their range./* where st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range*/static void updateValueUtil(int[] st, int ss, int se, int i, int diff, int si){ // Base Case: // If the input index lies outside // the range of this segment if (i < ss || i > se) return; // If the input index is in range // of this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // Function to update a value in the// input array and segment tree.// It uses updateValueUtil() to update// the value in segment treestatic void updateValue(int[] arr, int[] st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { Console.Write("Invalid Input"); return; } int diff = 0, oldValue = 0; oldValue = arr[i]; // Update the value in array arr[i] = new_val; // Case 1: Old and new values // both are Armstrong numbers if (isArmstrong(oldValue) && isArmstrong(new_val)) return; // Case 2: Old and new values // both not Armstrong numbers if (!isArmstrong(oldValue) && !isArmstrong(new_val)) return; // Case 3: Old value was Armstrong, // new value is non Armstrong if (isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = -1; } // Case 4: Old value was non Armstrong, // new_val is Armstrong if (!isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = 1; } // Update the values of // nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0);} // Return number of Armstrong numbers// in range from index qs (query start)// to qe (query end).// It mainly uses queryArmstrongUtil()static void queryArmstrong(int[] st, int n, int qs, int qe){ int ArmstrongInRange = queryArmstrongUtil( st, 0, n - 1, qs, qe, 0); Console.WriteLine("Number of Armstrong numbers " + "in subarray from " + qs + " to " + qe + " = " + ArmstrongInRange);} // Recursive function that constructs// Segment Tree for array[ss..se].// si is index of current node// in segment tree ststatic int constructSTUtil(int[] arr, int ss, int se, int[] st, int si){ // If there is one element in array, // check if it is Armstrong number // then store 1 in the segment tree // else store 0 and return if (ss == se) { // If arr[ss] is Armstrong number if (isArmstrong(arr[ss])) st[si] = 1; else st[si] = 0; return st[si]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of the // two values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2); return st[si];} // Function to construct a segment// tree from given array.// This function allocates memory// for segment tree and// calls constructSTUtil() to// fill the allocated memorystatic int[] constructST(int[] arr, int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(Math.Ceiling(Math.Log(n, 2))); // Maximum size of segment tree int max_size = 2 * (int)Math.Pow(2, x) - 1; int[] st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver Codepublic static void Main(string[] args){ int[] arr = { 18, 153, 8, 9, 14, 5 }; int n = arr.Length; // Build segment tree from given array int[] st = constructST(arr, n); // Query 1: Query(start = 0, end = 4) int start = 0; int end = 4; queryArmstrong(st, n, start, end); // Query 2: Update(i = 3, x = 11), // i.e Update a[i] to x int i = 3; int x = 11; updateValue(arr, st, n, i, x); // Print array after update Console.Write("Array after update: "); for(int j = 0; j < n; j++) Console.Write(arr[j] + ", "); Console.WriteLine(); // Query 3: Query(start = 0, end = 4) start = 0; end = 4; queryArmstrong(st, n, start, end);}} // This code is contributed by ukasp
Number of Armstrong numbers in subarray from 0 to 4 = 3
Array after update: 18, 153, 8, 11, 14, 5,
Number of Armstrong numbers in subarray from 0 to 4 = 2
Time Complexity: The time complexity of each query and update is O(log N) and that of building the segment tree is O(N)
stutipathak31jan
ukasp
ruhelaa48
array-range-queries
Segment-Tree
subarray
Arrays
Competitive Programming
Divide and Conquer
Write From Home
Arrays
Divide and Conquer
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 26840,
"s": 26812,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26927,
"s": 26840,
"text": "Given an array arr[] of N integers, the task is to perform the following two queries: "
},
{
"code": null,
"e": 27018,
"s": 26927,
"text": "query(start, end): Print the number of Armstrong numbers in the subarray from start to end"
},
{
"code": null,
"e": 27108,
"s": 27018,
"text": "update(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x"
},
{
"code": null,
"e": 27119,
"s": 27108,
"text": "Examples: "
},
{
"code": null,
"e": 27756,
"s": 27119,
"text": "Input: arr = { 18, 153, 8, 9, 14, 5} Query 1: query(start = 0, end = 4) Query 2: update(i = 3, x = 11) Query 3: query(start = 0, end = 4) Output: 3 2 Explanation In Query 1, 18 -> 1*1 + 8*8 != 18 153 -> 1*1*1 + 5*5*5 + 3*3*3 = 153 8 -> 8 = 8 9 -> 9 = 9 14 -> 1*1 + 4*4 != 14 the subarray [0...4] has 3 Armstrong numbers viz. {18, 153, 8, 9, 14}In Query 2, the value at index 3 is updated to 11, the array arr now is, { 18, 153, 8, 11, 14, 5}In Query 3, 18 -> 1*1 + 8*8 != 18 153 -> 1*1*1 + 5*5*5 + 3*3*3 = 153 8 -> 8 = 8 9 -> 1*1 + 1*1 != 11 14 -> 1*1 + 4*4 != 14 the subarray [0...4] has 2 Armstrong numbers viz. {18, 153, 8, 11, 14} "
},
{
"code": null,
"e": 27963,
"s": 27756,
"text": "Approach: To handle both point updates and range queries, a segment tree is optimal for this purpose.A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. "
},
{
"code": null,
"e": 28027,
"s": 27963,
"text": "abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + .... "
},
{
"code": null,
"e": 28280,
"s": 28027,
"text": "In order to check for Armstrong numbers, the idea is to first count number digits (or find order). Let the number of digits be n. For every digit r in input number x, compute r^n. If the sum of all such values is equal to n, then set it to 1 else to 0."
},
{
"code": null,
"e": 28309,
"s": 28280,
"text": "Building the segment tree: "
},
{
"code": null,
"e": 28384,
"s": 28309,
"text": "The problem is now reduced to the subarray sum using segment tree problem."
},
{
"code": null,
"e": 28533,
"s": 28384,
"text": "Now, we can build the segment tree where a leaf node is represented as either 0 (if it is not an Armstrong number) or 1 (if it is Armstrong number)."
},
{
"code": null,
"e": 28758,
"s": 28533,
"text": "The internal nodes of the segment tree equal to the sum of its child nodes, thus a node represent the total Armstrong numbers in the range from L to R with range [L, R] falling under this node and the sub-tree underneath it."
},
{
"code": null,
"e": 28796,
"s": 28758,
"text": "Handling Queries and Point Updates: "
},
{
"code": null,
"e": 29016,
"s": 28796,
"text": "Whenever we receive a query from beginning to end, we can query the segment tree for the sum of nodes in the range from start to end, which in turn represents the number of Armstrong numbers in the range start to end. "
},
{
"code": null,
"e": 29951,
"s": 29016,
"text": "To perform a point update and to update the value at index i to x, we check for the following cases: Let the old value of arri be y and the new value be x. Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment treeCase 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree"
},
{
"code": null,
"e": 30730,
"s": 29951,
"text": "Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment treeCase 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment treeCase 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree"
},
{
"code": null,
"e": 30894,
"s": 30730,
"text": "Case 1: If x and y both are Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment tree"
},
{
"code": null,
"e": 31062,
"s": 30894,
"text": "Case 2: If x and y both are not Armstrong numbers Count of Armstrong numbers in the subarray does not change so we just update array and do not modify the segment tree"
},
{
"code": null,
"e": 31277,
"s": 31062,
"text": "Case 3: If y is a Armstrong number but x is not Count of Armstrong numbers in the subarray decreases so we update array and add -1 to every range. The index i which is to be updated is a part of in the segment tree"
},
{
"code": null,
"e": 31512,
"s": 31277,
"text": "Case 4: If y is not an Armstrong number but x is an Armstrong number Count of Armstrong numbers in the subarray increases so we update array and add 1 to every range. The index i which is to be updated is a part of in the segment tree"
},
{
"code": null,
"e": 31565,
"s": 31512,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31569,
"s": 31565,
"text": "C++"
},
{
"code": null,
"e": 31577,
"s": 31569,
"text": "Python3"
},
{
"code": null,
"e": 31580,
"s": 31577,
"text": "C#"
},
{
"code": "// C++ program to find the number// of Armstrong numbers in a// subarray and performing updates #include <bits/stdc++.h>using namespace std; #define MAX 1000 // Function that return true// if num is armstrong// else return falsebool isArmstrong(int x){ int n = to_string(x).size(); int sum1 = 0; int temp = x; while (temp > 0) { int digit = temp % 10; sum1 += pow(digit, n); temp /= 10; } if (sum1 == x) return true; return false;} // A utility function to get the middle// index from corner indexes.int getMid(int s, int e){ return s + (e - s) / 2;} // Recursive function to get the number// of Armstrong numbers in a given range/* where st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int queryArmstrongUtil(int* st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part // of given range, then return // the number of Armstrong numbers // in the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node // is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return queryArmstrongUtil( st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil( st, mid + 1, se, qs, qe, 2 * index + 2);} // Recursive function to update// the nodes which have the given// index in their range./* where st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range*/void updateValueUtil(int* st, int ss, int se, int i, int diff, int si){ // Base Case: // If the input index lies outside // the range of this segment if (i < ss || i > se) return; // If the input index is in range // of this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // Function to update a value in the// input array and segment tree.// It uses updateValueUtil() to update// the value in segment treevoid updateValue(int arr[], int* st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { printf(\"Invalid Input\"); return; } int diff, oldValue; oldValue = arr[i]; // Update the value in array arr[i] = new_val; // Case 1: Old and new values // both are Armstrong numbers if (isArmstrong(oldValue) && isArmstrong(new_val)) return; // Case 2: Old and new values // both not Armstrong numbers if (!isArmstrong(oldValue) && !isArmstrong(new_val)) return; // Case 3: Old value was Armstrong, // new value is non Armstrong if (isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = -1; } // Case 4: Old value was non Armstrong, // new_val is Armstrong if (!isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = 1; } // Update the values of // nodes in segment tree updateValueUtil( st, 0, n - 1, i, diff, 0);} // Return number of Armstrong numbers// in range from index qs (query start)// to qe (query end).// It mainly uses queryArmstrongUtil()void queryArmstrong(int* st, int n, int qs, int qe){ int ArmstrongInRange = queryArmstrongUtil(st, 0, n - 1, qs, qe, 0); cout << \"Number of Armstrong numbers \" << \"in subarray from \" << qs << \" to \" << qe << \" = \" << ArmstrongInRange << \"\\n\";} // Recursive function that constructs// Segment Tree for array[ss..se].// si is index of current node// in segment tree stint constructSTUtil(int arr[], int ss, int se, int* st, int si){ // If there is one element in array, // check if it is Armstrong number // then store 1 in the segment tree // else store 0 and return if (ss == se) { // if arr[ss] is Armstrong number if (isArmstrong(arr[ss])) st[si] = 1; else st[si] = 0; return st[si]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of the // two values in this node int mid = getMid(ss, se); st[si] = constructSTUtil( arr, ss, mid, st, si * 2 + 1) + constructSTUtil( arr, mid + 1, se, st, si * 2 + 2); return st[si];} // Function to construct a segment// tree from given array.// This function allocates memory// for segment tree and// calls constructSTUtil() to// fill the allocated memoryint* constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; int* st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver Codeint main(){ int arr[] = { 18, 153, 8, 9, 14, 5 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree from given array int* st = constructST(arr, n); // Query 1: Query(start = 0, end = 4) int start = 0; int end = 4; queryArmstrong(st, n, start, end); // Query 2: Update(i = 3, x = 11), // i.e Update a[i] to x int i = 3; int x = 11; updateValue(arr, st, n, i, x); // Print array after update cout << \"Array after update: \"; for (int i = 0; i < n; i++) cout << arr[i] << \", \"; cout << endl; // Query 3: Query(start = 0, end = 4) start = 0; end = 4; queryArmstrong(st, n, start, end); return 0;}",
"e": 38106,
"s": 31580,
"text": null
},
{
"code": "# Python3 program to find the number# of Armstrong numbers in a# subarray and performing updatesimport math MAX = 1000 # Function that return true# if num is armstrong# else return falsedef isArmstrong(x): n = len(str(x)) sum1 = 0 temp = x while temp > 0: digit = temp % 10 sum1 += pow(digit, n) temp = temp // 10 if sum1 == x: return True return False # A utility function to get the middle# index from corner indexes.def getMid(s, e): return s + (e - s) // 2 # Recursive function to get the number# of Armstrong numbers in a given range# where# st --> Pointer to segment tree# index --> Index of current node in the# segment tree. Initially 0 is passed# as root is always at index 0# ss & se --> Starting and ending indexes of# the segment represented by current# node, i.e., st[index]# qs & qe --> Starting and ending indexes# of query rangedef queryArmstrongUtil(st, ss, se, qs, qe, index): # If segment of this node is a part # of given range, then return # the number of Armstrong numbers # in the segment if qs <= ss and qe >= se: return st[index] # If segment of this node # is outside the given range if se < qs or ss > qe: return 0 # If a part of this segment # overlaps with the given range mid = getMid(ss, se) return (queryArmstrongUtil(st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil(st, mid + 1, se, qs, qe, 2 * index + 2)) # Recursive function to update# the nodes which have the given# index in their range.# where# st, si, ss and se are same as getSumUtil()# i --> index of the element to be updated.# This index is in input array.# diff --> Value to be added to all nodes# which have i in rangedef updateValueUtil(st, ss, se, i, diff, si): # Base Case: # If the input index lies outside # the range of this segment if i < ss or i > se: return # If the input index is in range # of this node, then update the value # of the node and its children st[si] = st[si] + diff if se != ss: mid = getMid(ss, se) updateValueUtil(st, ss, mid, i, diff, 2 * si + 1) updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2) # Function to update a value in the# input array and segment tree.# It uses updateValueUtil() to update# the value in segment treedef updateValue(arr, st, n, i, new_val): # Check for erroneous input index if i < 0 or i > n - 1: print('Invalid Input') return oldValue = arr[i] # Update the value in array arr[i] = new_val # Case 1: Old and new values # both are Armstrong numbers if (isArmstrong(oldValue) and isArmstrong(new_val)): return # Case 2: Old and new values # both not Armstrong numbers if (not isArmstrong(oldValue) and not isArmstrong(new_val)): return # Case 3: Old value was Armstrong, # new value is non Armstrong if (isArmstrong(oldValue) and (not isArmstrong(new_val))): diff = -1 # Case 4: Old value was non Armstrong, # new_val is Armstrong if (not isArmstrong(oldValue) and not isArmstrong(new_val)): diff = 1 # Update the values of # nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0) # Return number of Armstrong numbers# in range from index qs (query start)# to qe (query end).# It mainly uses queryArmstrongUtil()def queryArmstrong(st, n, qs, qe): ArmstrongInRange = queryArmstrongUtil(st, 0, n - 1, qs, qe, 0) print(\"Number of Armstrong numbers in \" \"subarray from\", qs, \"to\", qe, \"=\", ArmstrongInRange) # Recursive function that constructs# Segment Tree for array[ss..se].# si is index of current node# in segment tree stdef constructSTUtil(arr, ss, se, st, si): # If there is one element in array, # check if it is Armstrong number # then store 1 in the segment tree # else store 0 and return if ss == se: # If arr[ss] is Armstrong number if isArmstrong(arr[ss]): st[si] = 1 else: st[si] = 0 return st[si] # If there are more than one elements, # then recur for left and right subtrees # and store the sum of the # two values in this node mid = getMid(ss, se) st[si] = (constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] # Function to construct a segment# tree from given array.# This function allocates memory# for segment tree and# calls constructSTUtil() to# fill the allocated memorydef constructST(arr, n): # Allocate memory for segment tree # Height of segment tree x = int(math.ceil(math.log2(n))) # Maximum size of segment tree max_size = 2 * int(pow(2, x)) - 1 st = [-1] * max_size # Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0) # Return the constructed segment tree return st # Driver codearr = [ 18, 153, 8, 9, 14, 5 ]n = len(arr) # Build segment tree from given arrayst = constructST(arr, n) # Query 1: Query(start = 0, end = 4)start = 0end = 4queryArmstrong(st, n, start, end) # Query 2: Update(i = 3, x = 11),# i.e Update a[i] to xi = 3x = 11updateValue(arr, st, n, i, x) # Print array after updateprint(\"Array after update:\", end = \" \")for i in range(n): print(arr[i], end = \", \") print() # Query 3: Query(start = 0, end = 4)start = 0end = 4queryArmstrong(st, n, start, end) # This code is contributed by stutipathak31jan",
"e": 44021,
"s": 38106,
"text": null
},
{
"code": "// C# program to find the number// of Armstrong numbers in a// subarray and performing updatesusing System; class GFG{ public int MAX = 1000; // Function that return true// if num is armstrong// else return falsestatic bool isArmstrong(int x){ int n = x.ToString().Length; int sum1 = 0; int temp = x; while (temp > 0) { int digit = temp % 10; sum1 += (int)Math.Pow(digit, n); temp /= 10; } if (sum1 == x) return true; return false;} // A utility function to get the middle// index from corner indexes.static int getMid(int s, int e){ return s + (e - s) / 2;} // Recursive function to get the number// of Armstrong numbers in a given range/* where st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */static int queryArmstrongUtil(int[] st, int ss, int se, int qs, int qe, int index){ // If segment of this node is a part // of given range, then return // the number of Armstrong numbers // in the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node // is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment // overlaps with the given range int mid = getMid(ss, se); return queryArmstrongUtil(st, ss, mid, qs, qe, 2 * index + 1) + queryArmstrongUtil(st, mid + 1, se, qs, qe, 2 * index + 2);} // Recursive function to update// the nodes which have the given// index in their range./* where st, si, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range*/static void updateValueUtil(int[] st, int ss, int se, int i, int diff, int si){ // Base Case: // If the input index lies outside // the range of this segment if (i < ss || i > se) return; // If the input index is in range // of this node, then update the value // of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // Function to update a value in the// input array and segment tree.// It uses updateValueUtil() to update// the value in segment treestatic void updateValue(int[] arr, int[] st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { Console.Write(\"Invalid Input\"); return; } int diff = 0, oldValue = 0; oldValue = arr[i]; // Update the value in array arr[i] = new_val; // Case 1: Old and new values // both are Armstrong numbers if (isArmstrong(oldValue) && isArmstrong(new_val)) return; // Case 2: Old and new values // both not Armstrong numbers if (!isArmstrong(oldValue) && !isArmstrong(new_val)) return; // Case 3: Old value was Armstrong, // new value is non Armstrong if (isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = -1; } // Case 4: Old value was non Armstrong, // new_val is Armstrong if (!isArmstrong(oldValue) && !isArmstrong(new_val)) { diff = 1; } // Update the values of // nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0);} // Return number of Armstrong numbers// in range from index qs (query start)// to qe (query end).// It mainly uses queryArmstrongUtil()static void queryArmstrong(int[] st, int n, int qs, int qe){ int ArmstrongInRange = queryArmstrongUtil( st, 0, n - 1, qs, qe, 0); Console.WriteLine(\"Number of Armstrong numbers \" + \"in subarray from \" + qs + \" to \" + qe + \" = \" + ArmstrongInRange);} // Recursive function that constructs// Segment Tree for array[ss..se].// si is index of current node// in segment tree ststatic int constructSTUtil(int[] arr, int ss, int se, int[] st, int si){ // If there is one element in array, // check if it is Armstrong number // then store 1 in the segment tree // else store 0 and return if (ss == se) { // If arr[ss] is Armstrong number if (isArmstrong(arr[ss])) st[si] = 1; else st[si] = 0; return st[si]; } // If there are more than one elements, // then recur for left and right subtrees // and store the sum of the // two values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, st, si * 2 + 2); return st[si];} // Function to construct a segment// tree from given array.// This function allocates memory// for segment tree and// calls constructSTUtil() to// fill the allocated memorystatic int[] constructST(int[] arr, int n){ // Allocate memory for segment tree // Height of segment tree int x = (int)(Math.Ceiling(Math.Log(n, 2))); // Maximum size of segment tree int max_size = 2 * (int)Math.Pow(2, x) - 1; int[] st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver Codepublic static void Main(string[] args){ int[] arr = { 18, 153, 8, 9, 14, 5 }; int n = arr.Length; // Build segment tree from given array int[] st = constructST(arr, n); // Query 1: Query(start = 0, end = 4) int start = 0; int end = 4; queryArmstrong(st, n, start, end); // Query 2: Update(i = 3, x = 11), // i.e Update a[i] to x int i = 3; int x = 11; updateValue(arr, st, n, i, x); // Print array after update Console.Write(\"Array after update: \"); for(int j = 0; j < n; j++) Console.Write(arr[j] + \", \"); Console.WriteLine(); // Query 3: Query(start = 0, end = 4) start = 0; end = 4; queryArmstrong(st, n, start, end);}} // This code is contributed by ukasp",
"e": 50689,
"s": 44021,
"text": null
},
{
"code": null,
"e": 50845,
"s": 50689,
"text": "Number of Armstrong numbers in subarray from 0 to 4 = 3\nArray after update: 18, 153, 8, 11, 14, 5, \nNumber of Armstrong numbers in subarray from 0 to 4 = 2"
},
{
"code": null,
"e": 50968,
"s": 50847,
"text": "Time Complexity: The time complexity of each query and update is O(log N) and that of building the segment tree is O(N) "
},
{
"code": null,
"e": 50985,
"s": 50968,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 50991,
"s": 50985,
"text": "ukasp"
},
{
"code": null,
"e": 51001,
"s": 50991,
"text": "ruhelaa48"
},
{
"code": null,
"e": 51021,
"s": 51001,
"text": "array-range-queries"
},
{
"code": null,
"e": 51034,
"s": 51021,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51043,
"s": 51034,
"text": "subarray"
},
{
"code": null,
"e": 51050,
"s": 51043,
"text": "Arrays"
},
{
"code": null,
"e": 51074,
"s": 51050,
"text": "Competitive Programming"
},
{
"code": null,
"e": 51093,
"s": 51074,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 51109,
"s": 51093,
"text": "Write From Home"
},
{
"code": null,
"e": 51116,
"s": 51109,
"text": "Arrays"
},
{
"code": null,
"e": 51135,
"s": 51116,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 51148,
"s": 51135,
"text": "Segment-Tree"
},
{
"code": null,
"e": 51246,
"s": 51148,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51314,
"s": 51246,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 51358,
"s": 51314,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 51406,
"s": 51358,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 51429,
"s": 51406,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 51461,
"s": 51429,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 51504,
"s": 51461,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 51547,
"s": 51504,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 51588,
"s": 51547,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 51666,
"s": 51588,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Python | Pandas Series.dt.is_month_end - GeeksforGeeks
|
20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.is_month_end attribute return a boolean value Indicating whether the date is the last day of the month.
Syntax: Series.dt.is_month_end
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-1-31', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-1-1 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not.
# check if dates are the last# day of the month or notresult = sr.dt.is_month_end # print the resultprint(result)
Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not. Example #2 : Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-3-31 00:00', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not.
# check if dates are the last# day of the month or notresult = sr.dt.is_month_end # print the resultprint(result)
Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 26119,
"s": 26091,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 26344,
"s": 26119,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.is_month_end attribute return a boolean value Indicating whether the date is the last day of the month."
},
{
"code": null,
"e": 26375,
"s": 26344,
"text": "Syntax: Series.dt.is_month_end"
},
{
"code": null,
"e": 26392,
"s": 26375,
"text": "Parameter : None"
},
{
"code": null,
"e": 26414,
"s": 26392,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 26568,
"s": 26414,
"text": "Example #1: Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-1-31', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-1-1 00:00']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 26953,
"s": 26568,
"text": null
},
{
"code": null,
"e": 26962,
"s": 26953,
"text": "Output :"
},
{
"code": null,
"e": 27093,
"s": 26962,
"text": "Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not."
},
{
"code": "# check if dates are the last# day of the month or notresult = sr.dt.is_month_end # print the resultprint(result)",
"e": 27208,
"s": 27093,
"text": null
},
{
"code": null,
"e": 27558,
"s": 27208,
"text": "Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not. Example #2 : Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-3-31 00:00', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 27853,
"s": 27558,
"text": null
},
{
"code": null,
"e": 27862,
"s": 27853,
"text": "Output :"
},
{
"code": null,
"e": 27993,
"s": 27862,
"text": "Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not."
},
{
"code": "# check if dates are the last# day of the month or notresult = sr.dt.is_month_end # print the resultprint(result)",
"e": 28108,
"s": 27993,
"text": null
},
{
"code": null,
"e": 28303,
"s": 28108,
"text": "Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not."
},
{
"code": null,
"e": 28333,
"s": 28303,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 28347,
"s": 28333,
"text": "Python-pandas"
},
{
"code": null,
"e": 28354,
"s": 28347,
"text": "Python"
},
{
"code": null,
"e": 28452,
"s": 28354,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28470,
"s": 28452,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28502,
"s": 28470,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28524,
"s": 28502,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28566,
"s": 28524,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28595,
"s": 28566,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28639,
"s": 28595,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28676,
"s": 28639,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28712,
"s": 28676,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28754,
"s": 28712,
"text": "Check if element exists in list in Python"
}
] |
DateTimeOffset.ToUnixTimeMilliseconds() Method in C# - GeeksforGeeks
|
19 Mar, 2019
DateTimeOffset.ToUnixTimeMilliseconds Method is used to return the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z. This method will return a negative value for the date and time values before 1970-01-01T00:00:00Z.
Syntax: public long ToUnixTimeMilliseconds ();
Return Value: This method returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.
Below programs illustrate the use of DateTimeOffset.ToUnixTimeMilliseconds() Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // Returns the number of milliseconds // instance using ToUnixTimeMilliseconds() method long value = offset.ToUnixTimeMilliseconds(); // Display the time Console.WriteLine("Returns the number of"+ " milliseconds : {0}", value); }}
Returns the number of milliseconds : 1180702500000
Example 2:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(1960, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // Returns the number of milliseconds // instance using ToUnixTimeMilliseconds() method long value = offset.ToUnixTimeMilliseconds(); // Display the time Console.WriteLine("Returns the number "+ "of milliseconds : {0}", value); }}
Returns the number of milliseconds : -302439900000
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Data Types
C# | Arrays
HashSet in C# with Examples
|
[
{
"code": null,
"e": 25401,
"s": 25373,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 25640,
"s": 25401,
"text": "DateTimeOffset.ToUnixTimeMilliseconds Method is used to return the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z. This method will return a negative value for the date and time values before 1970-01-01T00:00:00Z."
},
{
"code": null,
"e": 25687,
"s": 25640,
"text": "Syntax: public long ToUnixTimeMilliseconds ();"
},
{
"code": null,
"e": 25798,
"s": 25687,
"text": "Return Value: This method returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z."
},
{
"code": null,
"e": 25883,
"s": 25798,
"text": "Below programs illustrate the use of DateTimeOffset.ToUnixTimeMilliseconds() Method:"
},
{
"code": null,
"e": 25894,
"s": 25883,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(2007, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // Returns the number of milliseconds // instance using ToUnixTimeMilliseconds() method long value = offset.ToUnixTimeMilliseconds(); // Display the time Console.WriteLine(\"Returns the number of\"+ \" milliseconds : {0}\", value); }}",
"e": 26534,
"s": 25894,
"text": null
},
{
"code": null,
"e": 26586,
"s": 26534,
"text": "Returns the number of milliseconds : 1180702500000\n"
},
{
"code": null,
"e": 26597,
"s": 26586,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Creating object of DateTimeOffset DateTimeOffset offset = new DateTimeOffset(1960, 6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0)); // Returns the number of milliseconds // instance using ToUnixTimeMilliseconds() method long value = offset.ToUnixTimeMilliseconds(); // Display the time Console.WriteLine(\"Returns the number \"+ \"of milliseconds : {0}\", value); }}",
"e": 27233,
"s": 26597,
"text": null
},
{
"code": null,
"e": 27285,
"s": 27233,
"text": "Returns the number of milliseconds : -302439900000\n"
},
{
"code": null,
"e": 27296,
"s": 27285,
"text": "Reference:"
},
{
"code": null,
"e": 27409,
"s": 27296,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.7.2"
},
{
"code": null,
"e": 27438,
"s": 27409,
"text": "CSharp-DateTimeOffset-Struct"
},
{
"code": null,
"e": 27452,
"s": 27438,
"text": "CSharp-method"
},
{
"code": null,
"e": 27455,
"s": 27452,
"text": "C#"
},
{
"code": null,
"e": 27553,
"s": 27455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27581,
"s": 27553,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 27596,
"s": 27581,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27642,
"s": 27596,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27665,
"s": 27642,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27696,
"s": 27665,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27736,
"s": 27696,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27758,
"s": 27736,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27774,
"s": 27758,
"text": "C# | Data Types"
},
{
"code": null,
"e": 27786,
"s": 27774,
"text": "C# | Arrays"
}
] |
Python: os.path.abspath() method with example
|
29 Dec, 2019
OS module in Python provides various methods for interacting with the operating system. It comes under Python’s standard utility module, so there is no need to install it externally. os.path is a submodule of OS module which contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing and retrieving path names in Python.
According to docs os.path.abspath() returns a normalized absolutized version of the pathname path which may sound fancy but it simply means that this method returns the pathname to the path passed as a parameter to this function.
Syntax: os.path.abspath(path)
Parameter:Path: A path-like object representing a file system path.
Return Type: This method returns a normalized version of the pathname path.
Example 1:
# Python program to demonstrate# os.path.abspath() import os.path # file name file_name = 'GFG.txt' # prints the absolute path of current# working directory with file nameprint(os.path.abspath(file_name))
Output:
/home/geeks/Desktop/gfg/GFG.txt
Example 2: This function can also return the normalized path after changing the current working directory.
# Python program to demonstrate# os.path.abspath() import os # file name file_name = 'GFG.txt' # change the current working# directoryos.chdir("/home/geeks/") # prints the absolute path of current# working directory with file nameprint(os.path.abspath(file_name))
Output:
/home/geeks/GFG.txt
Python directory-program
Python OS-path-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 494,
"s": 52,
"text": "OS module in Python provides various methods for interacting with the operating system. It comes under Python’s standard utility module, so there is no need to install it externally. os.path is a submodule of OS module which contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing and retrieving path names in Python."
},
{
"code": null,
"e": 724,
"s": 494,
"text": "According to docs os.path.abspath() returns a normalized absolutized version of the pathname path which may sound fancy but it simply means that this method returns the pathname to the path passed as a parameter to this function."
},
{
"code": null,
"e": 754,
"s": 724,
"text": "Syntax: os.path.abspath(path)"
},
{
"code": null,
"e": 822,
"s": 754,
"text": "Parameter:Path: A path-like object representing a file system path."
},
{
"code": null,
"e": 898,
"s": 822,
"text": "Return Type: This method returns a normalized version of the pathname path."
},
{
"code": null,
"e": 909,
"s": 898,
"text": "Example 1:"
},
{
"code": "# Python program to demonstrate# os.path.abspath() import os.path # file name file_name = 'GFG.txt' # prints the absolute path of current# working directory with file nameprint(os.path.abspath(file_name))",
"e": 1124,
"s": 909,
"text": null
},
{
"code": null,
"e": 1132,
"s": 1124,
"text": "Output:"
},
{
"code": null,
"e": 1165,
"s": 1132,
"text": "/home/geeks/Desktop/gfg/GFG.txt\n"
},
{
"code": null,
"e": 1272,
"s": 1165,
"text": "Example 2: This function can also return the normalized path after changing the current working directory."
},
{
"code": "# Python program to demonstrate# os.path.abspath() import os # file name file_name = 'GFG.txt' # change the current working# directoryos.chdir(\"/home/geeks/\") # prints the absolute path of current# working directory with file nameprint(os.path.abspath(file_name))",
"e": 1545,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1553,
"s": 1545,
"text": "Output:"
},
{
"code": null,
"e": 1574,
"s": 1553,
"text": "/home/geeks/GFG.txt\n"
},
{
"code": null,
"e": 1599,
"s": 1574,
"text": "Python directory-program"
},
{
"code": null,
"e": 1621,
"s": 1599,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 1628,
"s": 1621,
"text": "Python"
},
{
"code": null,
"e": 1644,
"s": 1628,
"text": "Python Programs"
},
{
"code": null,
"e": 1742,
"s": 1644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1774,
"s": 1742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1801,
"s": 1774,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1822,
"s": 1801,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1845,
"s": 1822,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1901,
"s": 1845,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1923,
"s": 1901,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1962,
"s": 1923,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2000,
"s": 1962,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2037,
"s": 2000,
"text": "Python Program for Fibonacci numbers"
}
] |
Data Structure - Expression Parsing
|
The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are −
Infix Notation
Prefix (Polish) Notation
Postfix (Reverse-Polish) Notation
These notations are named as how they use operator in expression. We shall learn the same here in this chapter.
We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is easy for us humans to read, write, and speak in infix notation but the same does not go well with computing devices. An algorithm to process infix notation could be difficult and costly in terms of time and space consumption.
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation.
This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix notation a + b.
The following table briefly tries to show the difference in all three notations −
As we have discussed, it is not a very efficient way to design an algorithm or program to parse infix notations. Instead, these infix notations are first converted into either postfix or prefix notations and then computed.
To parse any arithmetic expression, we need to take care of operator precedence and associativity also.
When an operand is in between two different operators, which operator will take the operand first, is decided by the precedence of an operator over others. For example −
As multiplication operation has precedence over addition, b * c will be evaluated first. A table of operator precedence is provided later.
Associativity describes the rule where operators with the same precedence appear in an expression. For example, in expression a + b − c, both + and – have the same precedence, then which part of the expression will be evaluated first, is determined by associativity of those operators. Here, both + and − are left associative, so the expression will be evaluated as (a + b) − c.
Precedence and associativity determines the order of evaluation of an expression. Following is an operator precedence and associativity table (highest to lowest) −
The above table shows the default behavior of operators. At any point of time in expression evaluation, the order can be altered by using parenthesis. For example −
In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over addition. We here use parenthesis for a + b to be evaluated first, like (a + b)*c.
We shall now look at the algorithm on how to evaluate postfix notation −
Step 1 − scan the expression from left to right
Step 2 − if it is an operand push it to stack
Step 3 − if it is an operator pull operand from stack and perform operation
Step 4 − store the output of step 3, back to stack
Step 5 − scan the expression until all operands are consumed
Step 6 − pop the stack and perform operation
To see the implementation in C programming language, please click here.
|
[
{
"code": null,
"e": 2947,
"s": 2714,
"text": "The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are −"
},
{
"code": null,
"e": 2962,
"s": 2947,
"text": "Infix Notation"
},
{
"code": null,
"e": 2987,
"s": 2962,
"text": "Prefix (Polish) Notation"
},
{
"code": null,
"e": 3021,
"s": 2987,
"text": "Postfix (Reverse-Polish) Notation"
},
{
"code": null,
"e": 3133,
"s": 3021,
"text": "These notations are named as how they use operator in expression. We shall learn the same here in this chapter."
},
{
"code": null,
"e": 3466,
"s": 3133,
"text": "We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is easy for us humans to read, write, and speak in infix notation but the same does not go well with computing devices. An algorithm to process infix notation could be difficult and costly in terms of time and space consumption."
},
{
"code": null,
"e": 3678,
"s": 3466,
"text": "In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation."
},
{
"code": null,
"e": 3918,
"s": 3678,
"text": "This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix notation a + b."
},
{
"code": null,
"e": 4000,
"s": 3918,
"text": "The following table briefly tries to show the difference in all three notations −"
},
{
"code": null,
"e": 4223,
"s": 4000,
"text": "As we have discussed, it is not a very efficient way to design an algorithm or program to parse infix notations. Instead, these infix notations are first converted into either postfix or prefix notations and then computed."
},
{
"code": null,
"e": 4327,
"s": 4223,
"text": "To parse any arithmetic expression, we need to take care of operator precedence and associativity also."
},
{
"code": null,
"e": 4497,
"s": 4327,
"text": "When an operand is in between two different operators, which operator will take the operand first, is decided by the precedence of an operator over others. For example −"
},
{
"code": null,
"e": 4636,
"s": 4497,
"text": "As multiplication operation has precedence over addition, b * c will be evaluated first. A table of operator precedence is provided later."
},
{
"code": null,
"e": 5015,
"s": 4636,
"text": "Associativity describes the rule where operators with the same precedence appear in an expression. For example, in expression a + b − c, both + and – have the same precedence, then which part of the expression will be evaluated first, is determined by associativity of those operators. Here, both + and − are left associative, so the expression will be evaluated as (a + b) − c."
},
{
"code": null,
"e": 5179,
"s": 5015,
"text": "Precedence and associativity determines the order of evaluation of an expression. Following is an operator precedence and associativity table (highest to lowest) −"
},
{
"code": null,
"e": 5344,
"s": 5179,
"text": "The above table shows the default behavior of operators. At any point of time in expression evaluation, the order can be altered by using parenthesis. For example −"
},
{
"code": null,
"e": 5527,
"s": 5344,
"text": "In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over addition. We here use parenthesis for a + b to be evaluated first, like (a + b)*c."
},
{
"code": null,
"e": 5600,
"s": 5527,
"text": "We shall now look at the algorithm on how to evaluate postfix notation −"
},
{
"code": null,
"e": 5933,
"s": 5600,
"text": "Step 1 − scan the expression from left to right \nStep 2 − if it is an operand push it to stack \nStep 3 − if it is an operator pull operand from stack and perform operation \nStep 4 − store the output of step 3, back to stack \nStep 5 − scan the expression until all operands are consumed \nStep 6 − pop the stack and perform operation\n"
}
] |
Java Program to double the size of an array
|
To double the size of an array, let us first create an array −
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
Now, get the length of the above array −
int len = arr.length;
Double the size of the above array −
intnewArray[] = new int[len*2];
Now, newArray[] will be having twice the length of the array arr[].
public class Demo {
public static void main (String args[]) {
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
System.out.println("Length of initial array = " + arr.length);
int len = arr.length;
int newArray[] = new int[len*2];
System.arraycopy(arr, 0, newArray, 0, len);
System.out.println("Length of new array = "+newArray.length);
}
}
Length of initial array = 10
Length of new array = 20
|
[
{
"code": null,
"e": 1250,
"s": 1187,
"text": "To double the size of an array, let us first create an array −"
},
{
"code": null,
"e": 1303,
"s": 1250,
"text": "int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};"
},
{
"code": null,
"e": 1344,
"s": 1303,
"text": "Now, get the length of the above array −"
},
{
"code": null,
"e": 1366,
"s": 1344,
"text": "int len = arr.length;"
},
{
"code": null,
"e": 1403,
"s": 1366,
"text": "Double the size of the above array −"
},
{
"code": null,
"e": 1435,
"s": 1403,
"text": "intnewArray[] = new int[len*2];"
},
{
"code": null,
"e": 1503,
"s": 1435,
"text": "Now, newArray[] will be having twice the length of the array arr[]."
},
{
"code": null,
"e": 1888,
"s": 1503,
"text": "public class Demo {\n public static void main (String args[]) {\n int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};\n System.out.println(\"Length of initial array = \" + arr.length);\n int len = arr.length;\n int newArray[] = new int[len*2];\n System.arraycopy(arr, 0, newArray, 0, len);\n System.out.println(\"Length of new array = \"+newArray.length);\n }\n}"
},
{
"code": null,
"e": 1942,
"s": 1888,
"text": "Length of initial array = 10\nLength of new array = 20"
}
] |
Python | Pandas Series.sum()
|
10 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.sum() method is used to get the sum of the values for the requested axis.
Syntax: Series.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0)
Parameters:axis : {index (0)}skipna[boolean, default True] : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel[int or level name, default None] : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only[boolean, default None] : Include only float, int, boolean data. If None, will attempt to use everything, then use only numeric data
Returns: Returns the sum of the values for the requested axis
Code #1: By default, the sum of an empty or all-NA Series is 0.
# importing pandas module import pandas as pd # min_count = 0 is the defaultpd.Series([]).sum() # When passed min_count = 1,# sum of an empty series will be NaNpd.Series([]).sum(min_count = 1)
Output:
0.0
nan
Code #2:
# importing pandas module import pandas as pd # making data frame csv at url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # sum of all salaryval = data['Salary'].sum() val
Output:
2159837111.0
Code #3:
# importing pandas module import pandas as pd # making a dict of listdata = {'name': ['John', 'Peter', 'Karl'], 'age' : [23, 42, 19]} val = pd.DataFrame(data) # sum of all salaryval['total'] = val['age'].sum() val
Output:
Python pandas-series
Python pandas-series-methods
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 330,
"s": 242,
"text": "Pandas Series.sum() method is used to get the sum of the values for the requested axis."
},
{
"code": null,
"e": 417,
"s": 330,
"text": "Syntax: Series.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0)"
},
{
"code": null,
"e": 841,
"s": 417,
"text": "Parameters:axis : {index (0)}skipna[boolean, default True] : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel[int or level name, default None] : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only[boolean, default None] : Include only float, int, boolean data. If None, will attempt to use everything, then use only numeric data"
},
{
"code": null,
"e": 903,
"s": 841,
"text": "Returns: Returns the sum of the values for the requested axis"
},
{
"code": null,
"e": 967,
"s": 903,
"text": "Code #1: By default, the sum of an empty or all-NA Series is 0."
},
{
"code": "# importing pandas module import pandas as pd # min_count = 0 is the defaultpd.Series([]).sum() # When passed min_count = 1,# sum of an empty series will be NaNpd.Series([]).sum(min_count = 1)",
"e": 1164,
"s": 967,
"text": null
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "Output:"
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "0.0\nnan"
},
{
"code": null,
"e": 1190,
"s": 1180,
"text": " Code #2:"
},
{
"code": "# importing pandas module import pandas as pd # making data frame csv at url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # sum of all salaryval = data['Salary'].sum() val",
"e": 1406,
"s": 1190,
"text": null
},
{
"code": null,
"e": 1414,
"s": 1406,
"text": "Output:"
},
{
"code": null,
"e": 1427,
"s": 1414,
"text": "2159837111.0"
},
{
"code": null,
"e": 1438,
"s": 1429,
"text": "Code #3:"
},
{
"code": "# importing pandas module import pandas as pd # making a dict of listdata = {'name': ['John', 'Peter', 'Karl'], 'age' : [23, 42, 19]} val = pd.DataFrame(data) # sum of all salaryval['total'] = val['age'].sum() val",
"e": 1666,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1674,
"s": 1666,
"text": "Output:"
},
{
"code": null,
"e": 1695,
"s": 1674,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1724,
"s": 1695,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 1738,
"s": 1724,
"text": "Python-pandas"
},
{
"code": null,
"e": 1745,
"s": 1738,
"text": "Python"
},
{
"code": null,
"e": 1843,
"s": 1745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1861,
"s": 1843,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1903,
"s": 1861,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1925,
"s": 1903,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1957,
"s": 1925,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1986,
"s": 1957,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2013,
"s": 1986,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2034,
"s": 2013,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2070,
"s": 2034,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2093,
"s": 2070,
"text": "Introduction To PYTHON"
}
] |
Handling nested data objects using jQuery DataTables plugin
|
08 Jan, 2021
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. It is a simple-to-use plug-in with many options for the developer’s custom changes. The common features of DataTables are sorting, ordering, searching, and pagination.
DataTables can easily read information for the columns from any nested JSON data source or arrays. The developer can try out many options given as per the application’s need.
The pre-compiled files needed for code implementation are as follows.
JavaScript:
https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
CSS:
https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css
Example: The following example demonstrates the Ajax loading of nested JSON data objects in DataTables with client-side processing. The option used is columns.data property.
The following is the nested data for many users with their details like name, address, designation, and salary. This sample data is used in the following code.
Filename: nestedJSONdata.txt
{
"data": [
{
"name": "Tina Mukherjee",
"details": {
"designation": "BPO member",
"salary": "300000"
},
"address": [
"24,chandni chowk",
"Pune"
]
},
{
"name": "Gaurav",
"details": {
"designation": "Teacher",
"salary": "100750"
},
"address": [
"esquare,JM road",
"Pune"
]
},
{
"name": "Ashtwini",
"details": {
"designation": "Junior engineer",
"salary": "860000"
},
"address": [
"Santa cruz",
"mumbai"
]
},
{
"name": "Celina",
"details": {
"designation": "Javascript Developer",
"salary": "430060"
},
"address": [
"crr lake side ville",
"tellapur"
]
},
{
"name": "Aisha",
"details": {
"designation": "Nurse",
"salary": "160000"
},
"address": [
"rk puram",
"Delhi"
]
},
{
"name": "Brad henry",
"details": {
"designation": "Accountant",
"salary": "370000"
},
"address": [
"chaurasi lane",
"Kolkatta"
]
},
{
"name": "Harry",
"details": {
"designation": "Salesman",
"salary": "130500"
},
"address": [
"32, krishna nagar",
"Navi mumbai"
]
},
{
"name": "Rhovina",
"details": {
"designation": "Amazon supporter",
"salary": "300900"
},
"address": [
"Aparna zone",
"hyderabad"
]
},
{
"name": "Celina",
"details": {
"designation": "Senior Developer",
"salary": "200000"
},
"address": [
"23, chandni chowk",
"pune"
]
},
{
"name": "Glenny",
"details": {
"designation": "Administrator",
"salary": "200500"
},
"address": [
"Nagpur",
"Maharashtra"
]
},
{
"name": "Brad Pitt",
"details": {
"designation": "Engineer",
"salary": "100000"
},
"address": [
"sainikpuri",
"Delhi"
]
},
{
"name": "Deepa",
"details": {
"designation": "Team Leader",
"salary": "200500"
},
"address": [
"Annanagar",
"Chennai"
]
},
{
"name": "Angelina",
"details": {
"designation": "CEO",
"salary": "1000000"
},
"address": [
"JM road",
"Aundh pune"
]
}
]
}
Filename: index.html
HTML
<!DOCTYPE html><html lang="en"><head> <meta content="initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport" /> <meta name="viewport" content="width=device-width" /> <!--Datatable plugin CSS file --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" /> <!--jQuery library file --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script> <!--Datatable plugin JS library file --> <script type="text/javascript" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"> </script></head><body> <h2>Handling nested objects using jQuery Datatables </h2> <!--HTML tables with user data--> <table id="tableID" class="display" style="width:100%"> <thead> <tr> <th>Name</th> <th>Designation</th> <th>Address</th> <th>City</th> <th>Salary</th> </tr> </thead> </table> <script> // Initialization of datatables $(document).ready(function () { $('#tableID').DataTable({ "processing": true, "ajax": "nestedJSONdata.txt", "columns": [ { "data": "name" }, { "data": "details.designation" }, { "data": "address.0" }, { "data": "address.1" }, { "data": "details.salary" } ] }); }); </script></body></html>
Common error: The very common error which occurs in DataTables is Invalid JSON response. When the data tables are loaded with data, it expects valid JSON. If it encounters invalid data in the JSON structure, it throws the following warning.
DataTables warning: table id={tableID} - Invalid JSON response
Where tableID is the id of the HTML table as in the above code implementation.
Output: The following output is shown in the case of valid JSON.
Before execution:
After execution:
jQuery-Plugin
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jan, 2021"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. It is a simple-to-use plug-in with many options for the developer’s custom changes. The common features of DataTables are sorting, ordering, searching, and pagination."
},
{
"code": null,
"e": 486,
"s": 311,
"text": "DataTables can easily read information for the columns from any nested JSON data source or arrays. The developer can try out many options given as per the application’s need."
},
{
"code": null,
"e": 556,
"s": 486,
"text": "The pre-compiled files needed for code implementation are as follows."
},
{
"code": null,
"e": 568,
"s": 556,
"text": "JavaScript:"
},
{
"code": null,
"e": 631,
"s": 568,
"text": "https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"
},
{
"code": null,
"e": 636,
"s": 631,
"text": "CSS:"
},
{
"code": null,
"e": 701,
"s": 636,
"text": "https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"
},
{
"code": null,
"e": 875,
"s": 701,
"text": "Example: The following example demonstrates the Ajax loading of nested JSON data objects in DataTables with client-side processing. The option used is columns.data property."
},
{
"code": null,
"e": 1035,
"s": 875,
"text": "The following is the nested data for many users with their details like name, address, designation, and salary. This sample data is used in the following code."
},
{
"code": null,
"e": 1065,
"s": 1035,
"text": "Filename: nestedJSONdata.txt "
},
{
"code": null,
"e": 3700,
"s": 1065,
"text": "{\n \"data\": [\n {\n \"name\": \"Tina Mukherjee\",\n \"details\": {\n \"designation\": \"BPO member\",\n \"salary\": \"300000\"\n },\n \"address\": [\n \"24,chandni chowk\",\n \"Pune\"\n ]\n },\n {\n \"name\": \"Gaurav\",\n \"details\": {\n \"designation\": \"Teacher\",\n \"salary\": \"100750\"\n },\n \"address\": [\n \"esquare,JM road\",\n \"Pune\"\n ]\n },\n {\n \"name\": \"Ashtwini\",\n \"details\": {\n \"designation\": \"Junior engineer\",\n \"salary\": \"860000\"\n },\n \"address\": [\n \"Santa cruz\",\n \"mumbai\"\n ]\n },\n {\n \"name\": \"Celina\",\n \"details\": {\n \"designation\": \"Javascript Developer\",\n \"salary\": \"430060\"\n },\n \"address\": [\n \"crr lake side ville\",\n \"tellapur\"\n ]\n },\n {\n \"name\": \"Aisha\",\n \"details\": {\n \"designation\": \"Nurse\",\n \"salary\": \"160000\"\n },\n \"address\": [\n \"rk puram\",\n \"Delhi\"\n ]\n },\n {\n \"name\": \"Brad henry\",\n \"details\": {\n \"designation\": \"Accountant\",\n \"salary\": \"370000\"\n },\n \"address\": [\n \"chaurasi lane\",\n \"Kolkatta\"\n ]\n },\n {\n \"name\": \"Harry\",\n \"details\": {\n \"designation\": \"Salesman\",\n \"salary\": \"130500\"\n },\n \"address\": [\n \"32, krishna nagar\",\n \"Navi mumbai\"\n ]\n },\n {\n \"name\": \"Rhovina\",\n \"details\": {\n \"designation\": \"Amazon supporter\",\n \"salary\": \"300900\"\n },\n \"address\": [\n \"Aparna zone\",\n \"hyderabad\"\n ]\n },\n {\n \"name\": \"Celina\",\n \"details\": {\n \"designation\": \"Senior Developer\",\n \"salary\": \"200000\"\n },\n \"address\": [\n \"23, chandni chowk\",\n \"pune\"\n ]\n }, \n {\n \"name\": \"Glenny\",\n \"details\": {\n \"designation\": \"Administrator\",\n \"salary\": \"200500\"\n },\n \"address\": [\n \"Nagpur\",\n \"Maharashtra\"\n ]\n },\n {\n \"name\": \"Brad Pitt\",\n \"details\": {\n \"designation\": \"Engineer\",\n \"salary\": \"100000\"\n },\n \"address\": [\n \"sainikpuri\",\n \"Delhi\"\n ]\n },\n {\n \"name\": \"Deepa\",\n \"details\": {\n \"designation\": \"Team Leader\",\n \"salary\": \"200500\"\n },\n \"address\": [\n \"Annanagar\",\n \"Chennai\"\n ]\n },\n {\n \"name\": \"Angelina\",\n \"details\": {\n \"designation\": \"CEO\",\n \"salary\": \"1000000\"\n },\n \"address\": [\n \"JM road\",\n \"Aundh pune\"\n ]\n }\n ]\n}"
},
{
"code": null,
"e": 3721,
"s": 3700,
"text": "Filename: index.html"
},
{
"code": null,
"e": 3726,
"s": 3721,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta content=\"initial-scale=1, maximum-scale=1, user-scalable=0\" name=\"viewport\" /> <meta name=\"viewport\" content=\"width=device-width\" /> <!--Datatable plugin CSS file --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css\" /> <!--jQuery library file --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"></script> <!--Datatable plugin JS library file --> <script type=\"text/javascript\" src=\"https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js\"> </script></head><body> <h2>Handling nested objects using jQuery Datatables </h2> <!--HTML tables with user data--> <table id=\"tableID\" class=\"display\" style=\"width:100%\"> <thead> <tr> <th>Name</th> <th>Designation</th> <th>Address</th> <th>City</th> <th>Salary</th> </tr> </thead> </table> <script> // Initialization of datatables $(document).ready(function () { $('#tableID').DataTable({ \"processing\": true, \"ajax\": \"nestedJSONdata.txt\", \"columns\": [ { \"data\": \"name\" }, { \"data\": \"details.designation\" }, { \"data\": \"address.0\" }, { \"data\": \"address.1\" }, { \"data\": \"details.salary\" } ] }); }); </script></body></html>",
"e": 5106,
"s": 3726,
"text": null
},
{
"code": null,
"e": 5347,
"s": 5106,
"text": "Common error: The very common error which occurs in DataTables is Invalid JSON response. When the data tables are loaded with data, it expects valid JSON. If it encounters invalid data in the JSON structure, it throws the following warning."
},
{
"code": null,
"e": 5410,
"s": 5347,
"text": "DataTables warning: table id={tableID} - Invalid JSON response"
},
{
"code": null,
"e": 5489,
"s": 5410,
"text": "Where tableID is the id of the HTML table as in the above code implementation."
},
{
"code": null,
"e": 5554,
"s": 5489,
"text": "Output: The following output is shown in the case of valid JSON."
},
{
"code": null,
"e": 5572,
"s": 5554,
"text": "Before execution:"
},
{
"code": null,
"e": 5589,
"s": 5572,
"text": "After execution:"
},
{
"code": null,
"e": 5603,
"s": 5589,
"text": "jQuery-Plugin"
},
{
"code": null,
"e": 5607,
"s": 5603,
"text": "CSS"
},
{
"code": null,
"e": 5612,
"s": 5607,
"text": "HTML"
},
{
"code": null,
"e": 5619,
"s": 5612,
"text": "JQuery"
},
{
"code": null,
"e": 5636,
"s": 5619,
"text": "Web Technologies"
},
{
"code": null,
"e": 5641,
"s": 5636,
"text": "HTML"
},
{
"code": null,
"e": 5739,
"s": 5641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5778,
"s": 5739,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5817,
"s": 5778,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5856,
"s": 5817,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 5885,
"s": 5856,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5922,
"s": 5885,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 5946,
"s": 5922,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5999,
"s": 5946,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 6059,
"s": 5999,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6120,
"s": 6059,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to hide scroll bar for inactivity?
|
27 Apr, 2020
There are many ways to hide the scroll bar when the page is inactive. One such way is using the onscroll, onmousewheel, onclick and onmousemove events, which help us to achieve our goal using basic HTML and JavaScript.
Approach:
The onscroll event is used to disable the scroll bar.
The onscroll event acts as soon as the page is scrolled. So, setTimeout() method is used to provide a delay to hide the scroll bar, so that we are able to scroll down first.
The time can be adjusted according to our requirement.
onmousemove event is used to enable scrolling as soon as the mouse pointer is moved. onclick event is used to enable scrolling as soon as the user clicks. onmousewheel event is used to enable scrolling as soon as the page is scrolled down. Thus, these events help us to enable scrolling when the page becomes active again.
Example 1: As soon as the mouse moves, the mouse is scrolled, or the user clicks, the enableScrolling() function is called which allows us to scroll down. When the user tries to scroll down, the disableScrolling() function is called, which makes the scroll bar disappear after 1000ms. This time can be varied. To enable the scroll bar again, move the mouse pointer, or click, or scroll the mouse pointer to call the enableScrolling() function. The styling of the text has been done using the ‘style’ tag. The HTML and JavaScript code is as follows:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title> How to hide scroll bar for inactivity? </title> <style> p { font-size: 2rem; } </style></head> <body onscroll="disableScrolling()" onmousewheel="enableScrolling()" onclick="enableScrolling()" onmousemove="enableScrolling()"> <p> Geeks for Geeks is a Computer Science Portal created with the goal of providing well written, well thought and well-explained solutions for selected questions. Geeks for Geeks has covered everything, ranging from algorithms and data structure courses to competitive exam preparation courses. Geeks for Geeks is in true sense a a haven for geeks, where Tech lovers can come together and share their knowledge. </p> <script> // JavaScript code function disableScrolling() { setTimeout(function() { document.body.style.overflow = 'hidden'; }, 1000); } function enableScrolling() { document.body.style.overflow = ''; } </script></body> </html>
Output:
Example 2: This example hides the scrollbar on the image.
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title> How to hide scroll bar for inactivity? </title> <style> img { display: block; margin-left: auto; margin-right: auto; width: 150%; } </style></head> <body onscroll="disableScrolling()" onmousewheel="enableScrolling()" onclick="enableScrolling()" onmousemove="enableScrolling()"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191024224332/Geeksforgeeks-Paid-Online-Courses.png" alt="GfG"> <script> // JavaScript code function disableScrolling() { setTimeout(function() { document.body.style.overflow = 'hidden'; }, 1000); } function enableScrolling() { document.body.style.overflow = ''; } </script></body> </html>
Output:
The main disadvantage of hiding the scroll bar for inactivity is that as soon as the scrollbar hides, the contents of the body ‘jump’ to fill up the space that was occupied by the scrollbar. Thus, it does not appear very appealing to the user.
shs_
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
How to select all child elements recursively using CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 272,
"s": 53,
"text": "There are many ways to hide the scroll bar when the page is inactive. One such way is using the onscroll, onmousewheel, onclick and onmousemove events, which help us to achieve our goal using basic HTML and JavaScript."
},
{
"code": null,
"e": 282,
"s": 272,
"text": "Approach:"
},
{
"code": null,
"e": 336,
"s": 282,
"text": "The onscroll event is used to disable the scroll bar."
},
{
"code": null,
"e": 510,
"s": 336,
"text": "The onscroll event acts as soon as the page is scrolled. So, setTimeout() method is used to provide a delay to hide the scroll bar, so that we are able to scroll down first."
},
{
"code": null,
"e": 565,
"s": 510,
"text": "The time can be adjusted according to our requirement."
},
{
"code": null,
"e": 888,
"s": 565,
"text": "onmousemove event is used to enable scrolling as soon as the mouse pointer is moved. onclick event is used to enable scrolling as soon as the user clicks. onmousewheel event is used to enable scrolling as soon as the page is scrolled down. Thus, these events help us to enable scrolling when the page becomes active again."
},
{
"code": null,
"e": 1437,
"s": 888,
"text": "Example 1: As soon as the mouse moves, the mouse is scrolled, or the user clicks, the enableScrolling() function is called which allows us to scroll down. When the user tries to scroll down, the disableScrolling() function is called, which makes the scroll bar disappear after 1000ms. This time can be varied. To enable the scroll bar again, move the mouse pointer, or click, or scroll the mouse pointer to call the enableScrolling() function. The styling of the text has been done using the ‘style’ tag. The HTML and JavaScript code is as follows:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title> How to hide scroll bar for inactivity? </title> <style> p { font-size: 2rem; } </style></head> <body onscroll=\"disableScrolling()\" onmousewheel=\"enableScrolling()\" onclick=\"enableScrolling()\" onmousemove=\"enableScrolling()\"> <p> Geeks for Geeks is a Computer Science Portal created with the goal of providing well written, well thought and well-explained solutions for selected questions. Geeks for Geeks has covered everything, ranging from algorithms and data structure courses to competitive exam preparation courses. Geeks for Geeks is in true sense a a haven for geeks, where Tech lovers can come together and share their knowledge. </p> <script> // JavaScript code function disableScrolling() { setTimeout(function() { document.body.style.overflow = 'hidden'; }, 1000); } function enableScrolling() { document.body.style.overflow = ''; } </script></body> </html>",
"e": 2653,
"s": 1437,
"text": null
},
{
"code": null,
"e": 2661,
"s": 2653,
"text": "Output:"
},
{
"code": null,
"e": 2719,
"s": 2661,
"text": "Example 2: This example hides the scrollbar on the image."
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <title> How to hide scroll bar for inactivity? </title> <style> img { display: block; margin-left: auto; margin-right: auto; width: 150%; } </style></head> <body onscroll=\"disableScrolling()\" onmousewheel=\"enableScrolling()\" onclick=\"enableScrolling()\" onmousemove=\"enableScrolling()\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191024224332/Geeksforgeeks-Paid-Online-Courses.png\" alt=\"GfG\"> <script> // JavaScript code function disableScrolling() { setTimeout(function() { document.body.style.overflow = 'hidden'; }, 1000); } function enableScrolling() { document.body.style.overflow = ''; } </script></body> </html>",
"e": 3643,
"s": 2719,
"text": null
},
{
"code": null,
"e": 3651,
"s": 3643,
"text": "Output:"
},
{
"code": null,
"e": 3895,
"s": 3651,
"text": "The main disadvantage of hiding the scroll bar for inactivity is that as soon as the scrollbar hides, the contents of the body ‘jump’ to fill up the space that was occupied by the scrollbar. Thus, it does not appear very appealing to the user."
},
{
"code": null,
"e": 3900,
"s": 3895,
"text": "shs_"
},
{
"code": null,
"e": 3909,
"s": 3900,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3919,
"s": 3909,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3935,
"s": 3919,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3942,
"s": 3935,
"text": "Picked"
},
{
"code": null,
"e": 3946,
"s": 3942,
"text": "CSS"
},
{
"code": null,
"e": 3951,
"s": 3946,
"text": "HTML"
},
{
"code": null,
"e": 3962,
"s": 3951,
"text": "JavaScript"
},
{
"code": null,
"e": 3979,
"s": 3962,
"text": "Web Technologies"
},
{
"code": null,
"e": 4006,
"s": 3979,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4022,
"s": 4006,
"text": "Write From Home"
},
{
"code": null,
"e": 4027,
"s": 4022,
"text": "HTML"
},
{
"code": null,
"e": 4125,
"s": 4027,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4164,
"s": 4125,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4203,
"s": 4164,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4267,
"s": 4203,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 4328,
"s": 4267,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4384,
"s": 4328,
"text": "How to select all child elements recursively using CSS?"
},
{
"code": null,
"e": 4408,
"s": 4384,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4461,
"s": 4408,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 4521,
"s": 4461,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4582,
"s": 4521,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Sum of Series | Practice | GeeksforGeeks
|
Write a program to find the sum of the given series 1+2+3+ . . . . . .(N terms)
Example 1:
Input:
N = 1
Output: 1
Explanation: For n = 1, sum will be 1.
Example 2:
Input:
N = 5
Output: 15
Explanation: For n = 5, sum will be 1
+ 2 + 3 + 4 + 5 = 15.
Your Task:
Complete the function seriesSum() which takes single integer n, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
0
vipulmrawal5 hours ago
class Solution{
public:
// function to return sum of 1, 2, ... n
long long seriesSum(int n) {
return (long )n*(long)(n+1)/2;
}
};
0
mohammadravoof5 days ago
c++ easy solution
class Solution{public:// function to return sum of 1, 2, ... nlong long seriesSum(long long n) { // code here return n * (n + 1) / 2;}};
0
muskanbhasin19aug2 weeks ago
class Solution{public:// function to return sum of 1, 2, ... nlong long seriesSum(int n) { // code here return (long long) n*(n+1)/2;}};
0
rohitpandey4842 weeks ago
int sum=0;
for(int i=0;i≤no;i++)
{
sum=sum+i;
}
return sum;
why this is not working
0
maneshram20Premium3 weeks ago
C++ easy solution
class Solution{
public:
// function to return sum of 1, 2, ... n
long long seriesSum(int n) {
return (long)n*(n+1)/2;
}
};
0
rumi1w8ry4 weeks ago
def seriesSum(self,n): return int((n*(n+1))/2)
0
joacrb18l1 month ago
def seriesSum(self,n): return int(n*(n+1)/2)
+2
ankitsingh2791101 month ago
long seriesSum(int n) { return (long)n*(n+1)/2; }}
please give vote to support me
0
arpitmanuja0002 months ago
return ((long)n*((long)n+1))/2;
without long it will not able to held large values .
0
pankajkumarravi2 months ago
one line solution
************************
return (long)n*(n+1)/2;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 307,
"s": 226,
"text": "Write a program to find the sum of the given series 1+2+3+ . . . . . .(N terms) "
},
{
"code": null,
"e": 318,
"s": 307,
"text": "Example 1:"
},
{
"code": null,
"e": 381,
"s": 318,
"text": "Input:\nN = 1\nOutput: 1\nExplanation: For n = 1, sum will be 1.\n"
},
{
"code": null,
"e": 392,
"s": 381,
"text": "Example 2:"
},
{
"code": null,
"e": 477,
"s": 392,
"text": "Input:\nN = 5\nOutput: 15\nExplanation: For n = 5, sum will be 1\n+ 2 + 3 + 4 + 5 = 15.\n"
},
{
"code": null,
"e": 658,
"s": 477,
"text": "Your Task:\nComplete the function seriesSum() which takes single integer n, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs."
},
{
"code": null,
"e": 720,
"s": 658,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 747,
"s": 720,
"text": "Constraints:\n1 <= N <= 105"
},
{
"code": null,
"e": 751,
"s": 749,
"text": "0"
},
{
"code": null,
"e": 774,
"s": 751,
"text": "vipulmrawal5 hours ago"
},
{
"code": null,
"e": 913,
"s": 774,
"text": "class Solution{\npublic:\n// function to return sum of 1, 2, ... n\nlong long seriesSum(int n) {\n \n return (long )n*(long)(n+1)/2;\n}\n};"
},
{
"code": null,
"e": 915,
"s": 913,
"text": "0"
},
{
"code": null,
"e": 940,
"s": 915,
"text": "mohammadravoof5 days ago"
},
{
"code": null,
"e": 958,
"s": 940,
"text": "c++ easy solution"
},
{
"code": null,
"e": 1106,
"s": 958,
"text": "class Solution{public:// function to return sum of 1, 2, ... nlong long seriesSum(long long n) { // code here return n * (n + 1) / 2;}};"
},
{
"code": null,
"e": 1108,
"s": 1106,
"text": "0"
},
{
"code": null,
"e": 1137,
"s": 1108,
"text": "muskanbhasin19aug2 weeks ago"
},
{
"code": null,
"e": 1281,
"s": 1137,
"text": "class Solution{public:// function to return sum of 1, 2, ... nlong long seriesSum(int n) { // code here return (long long) n*(n+1)/2;}}; "
},
{
"code": null,
"e": 1283,
"s": 1281,
"text": "0"
},
{
"code": null,
"e": 1309,
"s": 1283,
"text": "rohitpandey4842 weeks ago"
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": "int sum=0;"
},
{
"code": null,
"e": 1344,
"s": 1322,
"text": "for(int i=0;i≤no;i++)"
},
{
"code": null,
"e": 1346,
"s": 1344,
"text": "{"
},
{
"code": null,
"e": 1359,
"s": 1346,
"text": " sum=sum+i;"
},
{
"code": null,
"e": 1361,
"s": 1359,
"text": "}"
},
{
"code": null,
"e": 1373,
"s": 1361,
"text": "return sum;"
},
{
"code": null,
"e": 1398,
"s": 1373,
"text": "why this is not working"
},
{
"code": null,
"e": 1402,
"s": 1400,
"text": "0"
},
{
"code": null,
"e": 1432,
"s": 1402,
"text": "maneshram20Premium3 weeks ago"
},
{
"code": null,
"e": 1450,
"s": 1432,
"text": "C++ easy solution"
},
{
"code": null,
"e": 1582,
"s": 1450,
"text": "class Solution{\npublic:\n\t// function to return sum of 1, 2, ... n\n\tlong long seriesSum(int n) {\n\t return (long)n*(n+1)/2;\n\t}\n};"
},
{
"code": null,
"e": 1584,
"s": 1582,
"text": "0"
},
{
"code": null,
"e": 1605,
"s": 1584,
"text": "rumi1w8ry4 weeks ago"
},
{
"code": null,
"e": 1658,
"s": 1605,
"text": "def seriesSum(self,n): return int((n*(n+1))/2)"
},
{
"code": null,
"e": 1660,
"s": 1658,
"text": "0"
},
{
"code": null,
"e": 1681,
"s": 1660,
"text": "joacrb18l1 month ago"
},
{
"code": null,
"e": 1729,
"s": 1681,
"text": "def seriesSum(self,n): return int(n*(n+1)/2)"
},
{
"code": null,
"e": 1732,
"s": 1729,
"text": "+2"
},
{
"code": null,
"e": 1760,
"s": 1732,
"text": "ankitsingh2791101 month ago"
},
{
"code": null,
"e": 1819,
"s": 1760,
"text": "long seriesSum(int n) { return (long)n*(n+1)/2; }}"
},
{
"code": null,
"e": 1852,
"s": 1821,
"text": "please give vote to support me"
},
{
"code": null,
"e": 1856,
"s": 1854,
"text": "0"
},
{
"code": null,
"e": 1883,
"s": 1856,
"text": "arpitmanuja0002 months ago"
},
{
"code": null,
"e": 1916,
"s": 1883,
"text": " return ((long)n*((long)n+1))/2;"
},
{
"code": null,
"e": 1971,
"s": 1918,
"text": "without long it will not able to held large values ."
},
{
"code": null,
"e": 1975,
"s": 1973,
"text": "0"
},
{
"code": null,
"e": 2003,
"s": 1975,
"text": "pankajkumarravi2 months ago"
},
{
"code": null,
"e": 2021,
"s": 2003,
"text": "one line solution"
},
{
"code": null,
"e": 2046,
"s": 2021,
"text": "************************"
},
{
"code": null,
"e": 2071,
"s": 2046,
"text": " return (long)n*(n+1)/2;"
},
{
"code": null,
"e": 2217,
"s": 2071,
"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": 2253,
"s": 2217,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2263,
"s": 2253,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2273,
"s": 2263,
"text": "\nContest\n"
},
{
"code": null,
"e": 2336,
"s": 2273,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2521,
"s": 2336,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 2805,
"s": 2521,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 2951,
"s": 2805,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 3028,
"s": 2951,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 3069,
"s": 3028,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 3097,
"s": 3069,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 3168,
"s": 3097,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 3355,
"s": 3168,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to get the seed value of an identity column in MySQL?
|
For this, you can use SHOW VARIABLES command −
mysql> SHOW VARIABLES LIKE 'auto_inc%';
This will produce the following output −
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| auto_increment_increment | 1 |
| auto_increment_offset | 1 |
+--------------------------+-------+
2 rows in set (0.95 sec)
You can control over AUTO_INCREMENT outside.
Let us first create a table −
mysql> create table DemoTable
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY
-> );
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 1 |
| 2 |
+-----------+
2 rows in set (0.00 sec)
Now you can control over the AUTO_INCREMENT −
mysql> alter table DemoTable AUTO_INCREMENT=1000;
Query OK, 0 rows affected (0.50 sec)
Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.51 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (1.37 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 1 |
| 2 |
| 1000 |
| 1001 |
+-----------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1234,
"s": 1187,
"text": "For this, you can use SHOW VARIABLES command −"
},
{
"code": null,
"e": 1274,
"s": 1234,
"text": "mysql> SHOW VARIABLES LIKE 'auto_inc%';"
},
{
"code": null,
"e": 1315,
"s": 1274,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1562,
"s": 1315,
"text": "+--------------------------+-------+\n| Variable_name | Value |\n+--------------------------+-------+\n| auto_increment_increment | 1 |\n| auto_increment_offset | 1 |\n+--------------------------+-------+\n2 rows in set (0.95 sec)"
},
{
"code": null,
"e": 1607,
"s": 1562,
"text": "You can control over AUTO_INCREMENT outside."
},
{
"code": null,
"e": 1637,
"s": 1607,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1777,
"s": 1637,
"text": "mysql> create table DemoTable\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY\n -> );\nQuery OK, 0 rows affected (0.94 sec)"
},
{
"code": null,
"e": 1833,
"s": 1777,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1984,
"s": 1833,
"text": "mysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.44 sec)\n\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.26 sec)"
},
{
"code": null,
"e": 2044,
"s": 1984,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2075,
"s": 2044,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2116,
"s": 2075,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2225,
"s": 2116,
"text": "+-----------+\n| StudentId |\n+-----------+\n| 1 |\n| 2 |\n+-----------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2271,
"s": 2225,
"text": "Now you can control over the AUTO_INCREMENT −"
},
{
"code": null,
"e": 2397,
"s": 2271,
"text": "mysql> alter table DemoTable AUTO_INCREMENT=1000;\nQuery OK, 0 rows affected (0.50 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2453,
"s": 2397,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2604,
"s": 2453,
"text": "mysql> insert into DemoTable values();\nQuery OK, 1 row affected (0.51 sec)\n\nmysql> insert into DemoTable values();\nQuery OK, 1 row affected (1.37 sec)"
},
{
"code": null,
"e": 2664,
"s": 2604,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2695,
"s": 2664,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2736,
"s": 2695,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2873,
"s": 2736,
"text": "+-----------+\n| StudentId |\n+-----------+\n| 1 |\n| 2 |\n| 1000 |\n| 1001 |\n+-----------+\n4 rows in set (0.00 sec)"
}
] |
Python | Pandas Series.tz_convert
|
30 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.tz_convert() function works with time zone aware indexes. It convert tz-aware axis to target time zone.
Syntax: Series.tz_convert(tz, axis=0, level=None, copy=True)
Parameter :tz : string or pytz.timezone objectaxis : the axis to convertlevel : int, str, default Nonecopy : Also make a copy of the underlying data.
Returns : Series
Example #1: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Asia/Calcutta') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘US/Central’.
# convert to 'US / Central'sr.tz_convert('US/Central')
Output :As we can see in the output, the Series.tz_convert() function has converted the time zone of the index of the given series object to the desired time zone. Example #2: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 5, tz = 'Asia/Calcutta') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘Europe/Berlin’
# convert to 'Europe / Berlin'sr.tz_convert('Europe/Berlin')
Output :
Python pandas-series
Python pandas-series-methods
Python-pandas
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
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 499,
"s": 242,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 617,
"s": 499,
"text": "Pandas Series.tz_convert() function works with time zone aware indexes. It convert tz-aware axis to target time zone."
},
{
"code": null,
"e": 678,
"s": 617,
"text": "Syntax: Series.tz_convert(tz, axis=0, level=None, copy=True)"
},
{
"code": null,
"e": 828,
"s": 678,
"text": "Parameter :tz : string or pytz.timezone objectaxis : the axis to convertlevel : int, str, default Nonecopy : Also make a copy of the underlying data."
},
{
"code": null,
"e": 845,
"s": 828,
"text": "Returns : Series"
},
{
"code": null,
"e": 972,
"s": 845,
"text": "Example #1: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Asia/Calcutta') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 1330,
"s": 972,
"text": null
},
{
"code": null,
"e": 1339,
"s": 1330,
"text": "Output :"
},
{
"code": null,
"e": 1493,
"s": 1339,
"text": "Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘US/Central’."
},
{
"code": "# convert to 'US / Central'sr.tz_convert('US/Central')",
"e": 1548,
"s": 1493,
"text": null
},
{
"code": null,
"e": 1839,
"s": 1548,
"text": "Output :As we can see in the output, the Series.tz_convert() function has converted the time zone of the index of the given series object to the desired time zone. Example #2: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 5, tz = 'Asia/Calcutta') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 2166,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2175,
"s": 2166,
"text": "Output :"
},
{
"code": null,
"e": 2331,
"s": 2175,
"text": "Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘Europe/Berlin’"
},
{
"code": "# convert to 'Europe / Berlin'sr.tz_convert('Europe/Berlin')",
"e": 2392,
"s": 2331,
"text": null
},
{
"code": null,
"e": 2401,
"s": 2392,
"text": "Output :"
},
{
"code": null,
"e": 2422,
"s": 2401,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2451,
"s": 2422,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2465,
"s": 2451,
"text": "Python-pandas"
},
{
"code": null,
"e": 2472,
"s": 2465,
"text": "Python"
},
{
"code": null,
"e": 2570,
"s": 2472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2588,
"s": 2570,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2630,
"s": 2588,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2652,
"s": 2630,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2687,
"s": 2652,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2713,
"s": 2687,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2745,
"s": 2713,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2774,
"s": 2745,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2801,
"s": 2774,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2822,
"s": 2801,
"text": "Python OOPs Concepts"
}
] |
Program to toggle all characters in a string
|
06 Jul, 2022
Given a string, the task is to toggle all the characters of the string i.e to convert Upper case to Lower case and vice versa.
Examples:
Input : gfg
Output : GFG
Input : aBc12#
Output : AbC12#
Input : tu@kmiNi
Output : TU@KMInI
Traverse the given string, if uppercase characters come, convert into lowercase and lowercase letter convert into uppercase.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){ for (int i=0; str[i]!='\0'; i++) { if (str[i]>='A' && str[i]<='Z') str[i] = str[i] + 'a' - 'A'; else if (str[i]>='a' && str[i]<='z') str[i] = str[i] + 'A' - 'a'; }} // Driver codeint main(){ char str[] = "GeKf@rGeek$"; toggleChars(str); cout << "String after toggle " << endl; cout << str << endl; return 0;}
// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){ for (int i=0; i<str.length; i++) { if (str[i]>='A' && str[i]<='Z') str[i] = (char) (str[i] + 'a' - 'A'); else if (str[i]>='a' && str[i]<='z') str[i] = (char) (str[i] + 'A' - 'a'); }} // Driver codepublic static void main(String[] args){ char str[] = "GeKf@rGeek$".toCharArray(); toggleChars(str); System.out.println("String after toggle "); System.out.println(String.valueOf(str));}} // This code is contributed by 29AjayKumar
# Python3 program to toggle all charactersdef toggleChars(str): for i in range(len(str)): if (str[i] >= 'A' and str[i] <= 'Z'): str = str[:i] + chr(ord(str[i]) + \ ord('a') - ord('A')) + str[i + 1:]; else if (str[i] >= 'a' and str[i] <= 'z'): str = str[:i] + chr(ord(str[i]) + \ ord('A') - ord('a')) + str[i + 1:]; return str; # Driver codestr = "GeKf@rGeek$";str = toggleChars(str);print(str); # This code is contributed by 29AjayKumar
// C# program to toggle all charactersusing System; class GFG{ static void toggleChars(char []str){ for (int i = 0; i < str.Length; i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = (char) (str[i] + 'a' - 'A'); else if (str[i] >= 'a' && str[i] <= 'z') str[i] = (char) (str[i] + 'A' - 'a'); }} // Driver codepublic static void Main(String[] args){ char []str = "GeKf@rGeek$".ToCharArray(); toggleChars(str); Console.WriteLine("String after toggle "); Console.WriteLine(String.Join("",str));}} // This code is contributed by Princi Singh
<script> function toggleChars(str){ for (let i = 0; i < str.length; i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0)); else if (str[i] >= 'a' && str[i] <= 'z') str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'A'.charCodeAt(0) - 'a'.charCodeAt(0)); }} let str = "GeKf@rGeek$".split("");toggleChars(str);document.write("String after toggle ");document.write((str).join("")); // This code is contributed by rag2127.</script>
String after toggle
gEkF@RgEEK$
Time complexity: O(n), where n is length of stringAuxiliary space: O(1)
We can use the Bitwise XOR operation to toggle all the characters in given string
As we know the ascii value of small and capital char case is differ by just 1 bit (5th bit). We can simply toggle that bit to toggle the char case of a string.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){ for (int i=0; str[i]!='\0'; i++) { if (isalpha(str[i])) { str[i] = (char)(str[i]^(1<<5)); } }} // Driver codeint main(){ char str[] = "GeKf@rGeek$"; cout << "String before toggle " << endl; cout << str << endl; toggleChars(str); cout << "String after toggle " << endl; cout << str << endl; return 0;} // This code is contributed by @kaustubhvats08
// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){ for (int i=0; i<str.length; i++) { if (Character.isAlphabetic(str[i])) { str[i] = (char)(str[i]^(1<<5)); } }} // Driver codepublic static void main(String[] args){ char str[] = "GeKf@rGeek$".toCharArray(); System.out.println("String before toggle "); System.out.println(String.valueOf(str)); toggleChars(str); System.out.println("String after toggle "); System.out.println(String.valueOf(str));}} // This code is contributed by @kaustubhvats08
# Python3 program to toggle all charactersdef toggleChars(s): for i in range(len(s)): if s[i].isalpha(): s = s[:i] + str(chr(ord(s[i])^(1<<5))) + s[i+1:] return s; # Driver codes = "GeKf@rGeek$";print("String before toggle")print(s)s = toggleChars(s);print("String after toggle")print(s); # This code is contributed by @kaustubhvats08
// C# program to toggle all charactersusing System; class GFG{ static void toggleChars(char []str){ for (int i = 0; i < str.Length; i++) { if (Char.IsLetter(str[i])){ str[i] = (char)(str[i]^(1<<5)); } }} // Driver codepublic static void Main(String[] args){ char []str = "GeKf@rGeek$".ToCharArray(); Console.WriteLine("String before toggle "); Console.WriteLine(String.Join("",str)); toggleChars(str); Console.WriteLine("String after toggle "); Console.WriteLine(String.Join("",str));}} // This code is contributed by @kaustubhvats08
<script> function toggleChars(str){ for (let i = 0; i < str.length; i++) { if ((/[a-zA-Z]/).test(str[i])){ str[i] = (String.fromCharCode((str[i].charCodeAt(0)^(1<<5)))); } }} let str = "GeKf@rGeek$".split("");document.write("String before toggle ");document.write((str).join(""));toggleChars(str);document.write("String after toggle ");document.write((str).join("")); // This code is contributed by @kaustubhvats08.</script>
String before toggle
GeKf@rGeek$
String after toggle
gEkF@RgEEK$
Time complexity: O(n), where n is length of stringAuxiliary space: O(1)
This article is contributed by MATHE_KA_BANDA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
29AjayKumar
princi singh
AakashYadav4
rag2127
sweetyty
kaustubhvats08
surinderdawra388
shaheeneallamaiqbal
hardikkoriintern
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 179,
"s": 52,
"text": "Given a string, the task is to toggle all the characters of the string i.e to convert Upper case to Lower case and vice versa."
},
{
"code": null,
"e": 190,
"s": 179,
"text": "Examples: "
},
{
"code": null,
"e": 286,
"s": 190,
"text": "Input : gfg\nOutput : GFG\n\nInput : aBc12#\nOutput : AbC12#\n\nInput : tu@kmiNi\nOutput : TU@KMInI"
},
{
"code": null,
"e": 411,
"s": 286,
"text": "Traverse the given string, if uppercase characters come, convert into lowercase and lowercase letter convert into uppercase."
},
{
"code": null,
"e": 427,
"s": 411,
"text": "Implementation:"
},
{
"code": null,
"e": 431,
"s": 427,
"text": "C++"
},
{
"code": null,
"e": 436,
"s": 431,
"text": "Java"
},
{
"code": null,
"e": 444,
"s": 436,
"text": "Python3"
},
{
"code": null,
"e": 447,
"s": 444,
"text": "C#"
},
{
"code": null,
"e": 458,
"s": 447,
"text": "Javascript"
},
{
"code": "// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){ for (int i=0; str[i]!='\\0'; i++) { if (str[i]>='A' && str[i]<='Z') str[i] = str[i] + 'a' - 'A'; else if (str[i]>='a' && str[i]<='z') str[i] = str[i] + 'A' - 'a'; }} // Driver codeint main(){ char str[] = \"GeKf@rGeek$\"; toggleChars(str); cout << \"String after toggle \" << endl; cout << str << endl; return 0;}",
"e": 940,
"s": 458,
"text": null
},
{
"code": "// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){ for (int i=0; i<str.length; i++) { if (str[i]>='A' && str[i]<='Z') str[i] = (char) (str[i] + 'a' - 'A'); else if (str[i]>='a' && str[i]<='z') str[i] = (char) (str[i] + 'A' - 'a'); }} // Driver codepublic static void main(String[] args){ char str[] = \"GeKf@rGeek$\".toCharArray(); toggleChars(str); System.out.println(\"String after toggle \"); System.out.println(String.valueOf(str));}} // This code is contributed by 29AjayKumar",
"e": 1513,
"s": 940,
"text": null
},
{
"code": "# Python3 program to toggle all charactersdef toggleChars(str): for i in range(len(str)): if (str[i] >= 'A' and str[i] <= 'Z'): str = str[:i] + chr(ord(str[i]) + \\ ord('a') - ord('A')) + str[i + 1:]; else if (str[i] >= 'a' and str[i] <= 'z'): str = str[:i] + chr(ord(str[i]) + \\ ord('A') - ord('a')) + str[i + 1:]; return str; # Driver codestr = \"GeKf@rGeek$\";str = toggleChars(str);print(str); # This code is contributed by 29AjayKumar",
"e": 2037,
"s": 1513,
"text": null
},
{
"code": "// C# program to toggle all charactersusing System; class GFG{ static void toggleChars(char []str){ for (int i = 0; i < str.Length; i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = (char) (str[i] + 'a' - 'A'); else if (str[i] >= 'a' && str[i] <= 'z') str[i] = (char) (str[i] + 'A' - 'a'); }} // Driver codepublic static void Main(String[] args){ char []str = \"GeKf@rGeek$\".ToCharArray(); toggleChars(str); Console.WriteLine(\"String after toggle \"); Console.WriteLine(String.Join(\"\",str));}} // This code is contributed by Princi Singh",
"e": 2636,
"s": 2037,
"text": null
},
{
"code": "<script> function toggleChars(str){ for (let i = 0; i < str.length; i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0)); else if (str[i] >= 'a' && str[i] <= 'z') str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'A'.charCodeAt(0) - 'a'.charCodeAt(0)); }} let str = \"GeKf@rGeek$\".split(\"\");toggleChars(str);document.write(\"String after toggle \");document.write((str).join(\"\")); // This code is contributed by rag2127.</script>",
"e": 3193,
"s": 2636,
"text": null
},
{
"code": null,
"e": 3226,
"s": 3193,
"text": "String after toggle \ngEkF@RgEEK$"
},
{
"code": null,
"e": 3298,
"s": 3226,
"text": "Time complexity: O(n), where n is length of stringAuxiliary space: O(1)"
},
{
"code": null,
"e": 3380,
"s": 3298,
"text": "We can use the Bitwise XOR operation to toggle all the characters in given string"
},
{
"code": null,
"e": 3540,
"s": 3380,
"text": "As we know the ascii value of small and capital char case is differ by just 1 bit (5th bit). We can simply toggle that bit to toggle the char case of a string."
},
{
"code": null,
"e": 3556,
"s": 3540,
"text": "Implementation:"
},
{
"code": null,
"e": 3560,
"s": 3556,
"text": "C++"
},
{
"code": null,
"e": 3565,
"s": 3560,
"text": "Java"
},
{
"code": null,
"e": 3573,
"s": 3565,
"text": "Python3"
},
{
"code": null,
"e": 3576,
"s": 3573,
"text": "C#"
},
{
"code": null,
"e": 3587,
"s": 3576,
"text": "Javascript"
},
{
"code": "// C++ program to toggle all characters#include<bits/stdc++.h>using namespace std; void toggleChars(char str[]){ for (int i=0; str[i]!='\\0'; i++) { if (isalpha(str[i])) { str[i] = (char)(str[i]^(1<<5)); } }} // Driver codeint main(){ char str[] = \"GeKf@rGeek$\"; cout << \"String before toggle \" << endl; cout << str << endl; toggleChars(str); cout << \"String after toggle \" << endl; cout << str << endl; return 0;} // This code is contributed by @kaustubhvats08",
"e": 4105,
"s": 3587,
"text": null
},
{
"code": "// Java program to toggle all characters class GFG{ static void toggleChars(char str[]){ for (int i=0; i<str.length; i++) { if (Character.isAlphabetic(str[i])) { str[i] = (char)(str[i]^(1<<5)); } }} // Driver codepublic static void main(String[] args){ char str[] = \"GeKf@rGeek$\".toCharArray(); System.out.println(\"String before toggle \"); System.out.println(String.valueOf(str)); toggleChars(str); System.out.println(\"String after toggle \"); System.out.println(String.valueOf(str));}} // This code is contributed by @kaustubhvats08",
"e": 4690,
"s": 4105,
"text": null
},
{
"code": "# Python3 program to toggle all charactersdef toggleChars(s): for i in range(len(s)): if s[i].isalpha(): s = s[:i] + str(chr(ord(s[i])^(1<<5))) + s[i+1:] return s; # Driver codes = \"GeKf@rGeek$\";print(\"String before toggle\")print(s)s = toggleChars(s);print(\"String after toggle\")print(s); # This code is contributed by @kaustubhvats08",
"e": 5047,
"s": 4690,
"text": null
},
{
"code": "// C# program to toggle all charactersusing System; class GFG{ static void toggleChars(char []str){ for (int i = 0; i < str.Length; i++) { if (Char.IsLetter(str[i])){ str[i] = (char)(str[i]^(1<<5)); } }} // Driver codepublic static void Main(String[] args){ char []str = \"GeKf@rGeek$\".ToCharArray(); Console.WriteLine(\"String before toggle \"); Console.WriteLine(String.Join(\"\",str)); toggleChars(str); Console.WriteLine(\"String after toggle \"); Console.WriteLine(String.Join(\"\",str));}} // This code is contributed by @kaustubhvats08",
"e": 5635,
"s": 5047,
"text": null
},
{
"code": "<script> function toggleChars(str){ for (let i = 0; i < str.length; i++) { if ((/[a-zA-Z]/).test(str[i])){ str[i] = (String.fromCharCode((str[i].charCodeAt(0)^(1<<5)))); } }} let str = \"GeKf@rGeek$\".split(\"\");document.write(\"String before toggle \");document.write((str).join(\"\"));toggleChars(str);document.write(\"String after toggle \");document.write((str).join(\"\")); // This code is contributed by @kaustubhvats08.</script>",
"e": 6094,
"s": 5635,
"text": null
},
{
"code": null,
"e": 6161,
"s": 6094,
"text": "String before toggle \nGeKf@rGeek$\nString after toggle \ngEkF@RgEEK$"
},
{
"code": null,
"e": 6233,
"s": 6161,
"text": "Time complexity: O(n), where n is length of stringAuxiliary space: O(1)"
},
{
"code": null,
"e": 6531,
"s": 6233,
"text": "This article is contributed by MATHE_KA_BANDA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6543,
"s": 6531,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6556,
"s": 6543,
"text": "princi singh"
},
{
"code": null,
"e": 6569,
"s": 6556,
"text": "AakashYadav4"
},
{
"code": null,
"e": 6577,
"s": 6569,
"text": "rag2127"
},
{
"code": null,
"e": 6586,
"s": 6577,
"text": "sweetyty"
},
{
"code": null,
"e": 6601,
"s": 6586,
"text": "kaustubhvats08"
},
{
"code": null,
"e": 6618,
"s": 6601,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6638,
"s": 6618,
"text": "shaheeneallamaiqbal"
},
{
"code": null,
"e": 6655,
"s": 6638,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6663,
"s": 6655,
"text": "Strings"
},
{
"code": null,
"e": 6671,
"s": 6663,
"text": "Strings"
}
] |
Move all values equal to K to the end of the Array
|
11 Aug, 2021
Given an array arr[] of size N and an integer K, the task is to print the array after moving all value equal to K at the end of the array.
Examples:
Input: arr = [2, 1, 2, 2, 2, 3, 4, 2], K = 2 Output: [4, 1, 3, 2, 2, 2, 2, 2] Explanation: 2 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [4, 1, 3, 2, 2, 2, 2, 2]. The numbers 4, 1, and 3 could be ordered differently.
Input: arr = [1, 1, 3, 5, 6], K = 1 Output: [6, 5, 3, 1, 1 ] Explanation: 1 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [6, 5, 3, 1, 1 ].
Approach: To solve the problem mentioned above we use Two Pointer Technique.
Initialize two pointers where the left pointer marks the start of the array and the other one that is right one marks the end of the array, respectively.Decrement the count of right pointer long as it points to K, and increment the left pointer as long as it doesn’t point to the integer m.When both pointers aren’t moving, swap their values in place.Repeat this process until the pointers pass each other.
Initialize two pointers where the left pointer marks the start of the array and the other one that is right one marks the end of the array, respectively.
Decrement the count of right pointer long as it points to K, and increment the left pointer as long as it doesn’t point to the integer m.
When both pointers aren’t moving, swap their values in place.
Repeat this process until the pointers pass each other.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to move all values// equal to K to the end of the Array #include <bits/stdc++.h>using namespace std; // Function to move the element to the endvector<int> moveElementToEnd( vector<int> array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.size() - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // decrement right pointer j--; if (array[i] == toMove) // swap the two elements // in the array swap(array[i], array[j]); // increment left pointer i++; } // return the result return array;} // Driver codeint main(int argc, char* argv[]){ vector<int> arr = { 1, 1, 3, 5, 6 }; int K = 1; vector<int> ans = moveElementToEnd(arr, K); for (int i = 0; i < arr.size(); i++) cout << ans[i] << " "; return 0;}
// Java program to move all values// equal to K to the end of the Arrayclass GFG{ // Function to move the element to the endstatic int[] moveElementToEnd(int []array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void main(String[] args){ int []arr = { 1, 1, 3, 5, 6 }; int K = 1; int []ans = moveElementToEnd(arr, K); for(int i = 0; i < arr.length; i++) System.out.print(ans[i] + " ");}} // This code is contributed by Princi Singh
# Python3 program to move all values# equal to K to the end of the Array # Function to move the element to the enddef moveElementToEnd(array, toMove): # Mark left pointer i = 0 # Mark the right pointer j = len(array) - 1 # Iterate until left pointer # crosses the right pointer while (i < j): while (i < j and array[j] == toMove): # decrement right pointer j-=1 if (array[i] == toMove): # swap the two elements # in the array array[i], array[j] = array[j] , array[i] # increment left pointer i += 1 # return the result return array # Driver codeif __name__ =="__main__": arr = [ 1, 1, 3, 5, 6 ] K = 1 ans = moveElementToEnd(arr, K) for i in range(len(arr)): print(ans[i] ,end= " ") # This code is contributed by chitranayal
// C# program to move all values// equal to K to the end of the Arrayusing System;class GFG{ // Function to move the element to the endstatic int[] moveElementToEnd(int []array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.Length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 1, 3, 5, 6 }; int K = 1; int []ans = moveElementToEnd(arr, K); for(int i = 0; i < arr.Length; i++) Console.Write(ans[i] + " ");}} // This code is contributed by rock_cool
<script> // Javascript program to move all values // equal to K to the end of the Array // Function to move the element to the end function moveElementToEnd(array, toMove) { // Mark left pointer let i = 0; // Mark the right pointer let j = array.length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array; } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } let arr = [ 1, 1, 3, 5, 6 ]; let K = 1; let ans = moveElementToEnd(arr, K); for(let i = 0; i < arr.length; i++) document.write(ans[i] + " "); </script>
6 5 3 1 1
Time complexity: O(N), where N is the length of the array.Space complexity: O(1)
ukasp
princi singh
rock_cool
divyesh072019
arorakashish0911
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
What is Data Structure: Types, Classifications and Applications
Next Greater Element
Move all negative numbers to beginning and positive to end with constant extra space
Count pairs with given sum
Find subarray with given sum | Set 1 (Nonnegative Numbers)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 193,
"s": 54,
"text": "Given an array arr[] of size N and an integer K, the task is to print the array after moving all value equal to K at the end of the array."
},
{
"code": null,
"e": 204,
"s": 193,
"text": "Examples: "
},
{
"code": null,
"e": 493,
"s": 204,
"text": "Input: arr = [2, 1, 2, 2, 2, 3, 4, 2], K = 2 Output: [4, 1, 3, 2, 2, 2, 2, 2] Explanation: 2 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [4, 1, 3, 2, 2, 2, 2, 2]. The numbers 4, 1, and 3 could be ordered differently. "
},
{
"code": null,
"e": 705,
"s": 493,
"text": "Input: arr = [1, 1, 3, 5, 6], K = 1 Output: [6, 5, 3, 1, 1 ] Explanation: 1 is the number which has to be moved to the end of the array arr[]. Therefore, after making the change the array is [6, 5, 3, 1, 1 ]. "
},
{
"code": null,
"e": 784,
"s": 705,
"text": "Approach: To solve the problem mentioned above we use Two Pointer Technique. "
},
{
"code": null,
"e": 1191,
"s": 784,
"text": "Initialize two pointers where the left pointer marks the start of the array and the other one that is right one marks the end of the array, respectively.Decrement the count of right pointer long as it points to K, and increment the left pointer as long as it doesn’t point to the integer m.When both pointers aren’t moving, swap their values in place.Repeat this process until the pointers pass each other."
},
{
"code": null,
"e": 1345,
"s": 1191,
"text": "Initialize two pointers where the left pointer marks the start of the array and the other one that is right one marks the end of the array, respectively."
},
{
"code": null,
"e": 1483,
"s": 1345,
"text": "Decrement the count of right pointer long as it points to K, and increment the left pointer as long as it doesn’t point to the integer m."
},
{
"code": null,
"e": 1545,
"s": 1483,
"text": "When both pointers aren’t moving, swap their values in place."
},
{
"code": null,
"e": 1601,
"s": 1545,
"text": "Repeat this process until the pointers pass each other."
},
{
"code": null,
"e": 1654,
"s": 1601,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1658,
"s": 1654,
"text": "C++"
},
{
"code": null,
"e": 1663,
"s": 1658,
"text": "Java"
},
{
"code": null,
"e": 1671,
"s": 1663,
"text": "Python3"
},
{
"code": null,
"e": 1674,
"s": 1671,
"text": "C#"
},
{
"code": null,
"e": 1685,
"s": 1674,
"text": "Javascript"
},
{
"code": "// C++ program to move all values// equal to K to the end of the Array #include <bits/stdc++.h>using namespace std; // Function to move the element to the endvector<int> moveElementToEnd( vector<int> array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.size() - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // decrement right pointer j--; if (array[i] == toMove) // swap the two elements // in the array swap(array[i], array[j]); // increment left pointer i++; } // return the result return array;} // Driver codeint main(int argc, char* argv[]){ vector<int> arr = { 1, 1, 3, 5, 6 }; int K = 1; vector<int> ans = moveElementToEnd(arr, K); for (int i = 0; i < arr.size(); i++) cout << ans[i] << \" \"; return 0;}",
"e": 2660,
"s": 1685,
"text": null
},
{
"code": "// Java program to move all values// equal to K to the end of the Arrayclass GFG{ // Function to move the element to the endstatic int[] moveElementToEnd(int []array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void main(String[] args){ int []arr = { 1, 1, 3, 5, 6 }; int K = 1; int []ans = moveElementToEnd(arr, K); for(int i = 0; i < arr.length; i++) System.out.print(ans[i] + \" \");}} // This code is contributed by Princi Singh",
"e": 3759,
"s": 2660,
"text": null
},
{
"code": "# Python3 program to move all values# equal to K to the end of the Array # Function to move the element to the enddef moveElementToEnd(array, toMove): # Mark left pointer i = 0 # Mark the right pointer j = len(array) - 1 # Iterate until left pointer # crosses the right pointer while (i < j): while (i < j and array[j] == toMove): # decrement right pointer j-=1 if (array[i] == toMove): # swap the two elements # in the array array[i], array[j] = array[j] , array[i] # increment left pointer i += 1 # return the result return array # Driver codeif __name__ ==\"__main__\": arr = [ 1, 1, 3, 5, 6 ] K = 1 ans = moveElementToEnd(arr, K) for i in range(len(arr)): print(ans[i] ,end= \" \") # This code is contributed by chitranayal",
"e": 4638,
"s": 3759,
"text": null
},
{
"code": "// C# program to move all values// equal to K to the end of the Arrayusing System;class GFG{ // Function to move the element to the endstatic int[] moveElementToEnd(int []array, int toMove){ // Mark left pointer int i = 0; // Mark the right pointer int j = array.Length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void Main(string[] args){ int []arr = { 1, 1, 3, 5, 6 }; int K = 1; int []ans = moveElementToEnd(arr, K); for(int i = 0; i < arr.Length; i++) Console.Write(ans[i] + \" \");}} // This code is contributed by rock_cool",
"e": 5739,
"s": 4638,
"text": null
},
{
"code": "<script> // Javascript program to move all values // equal to K to the end of the Array // Function to move the element to the end function moveElementToEnd(array, toMove) { // Mark left pointer let i = 0; // Mark the right pointer let j = array.length - 1; // Iterate until left pointer // crosses the right pointer while (i < j) { while (i < j && array[j] == toMove) // Decrement right pointer j--; if (array[i] == toMove) // Swap the two elements // in the array swap(array, i, j); // Increment left pointer i++; } // Return the result return array; } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } let arr = [ 1, 1, 3, 5, 6 ]; let K = 1; let ans = moveElementToEnd(arr, K); for(let i = 0; i < arr.length; i++) document.write(ans[i] + \" \"); </script>",
"e": 6829,
"s": 5739,
"text": null
},
{
"code": null,
"e": 6839,
"s": 6829,
"text": "6 5 3 1 1"
},
{
"code": null,
"e": 6923,
"s": 6841,
"text": "Time complexity: O(N), where N is the length of the array.Space complexity: O(1) "
},
{
"code": null,
"e": 6929,
"s": 6923,
"text": "ukasp"
},
{
"code": null,
"e": 6942,
"s": 6929,
"text": "princi singh"
},
{
"code": null,
"e": 6952,
"s": 6942,
"text": "rock_cool"
},
{
"code": null,
"e": 6966,
"s": 6952,
"text": "divyesh072019"
},
{
"code": null,
"e": 6983,
"s": 6966,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6990,
"s": 6983,
"text": "Arrays"
},
{
"code": null,
"e": 6997,
"s": 6990,
"text": "Arrays"
},
{
"code": null,
"e": 7095,
"s": 6997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7127,
"s": 7095,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7152,
"s": 7127,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7199,
"s": 7152,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7230,
"s": 7199,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7288,
"s": 7230,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 7352,
"s": 7288,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7373,
"s": 7352,
"text": "Next Greater Element"
},
{
"code": null,
"e": 7458,
"s": 7373,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 7485,
"s": 7458,
"text": "Count pairs with given sum"
}
] |
Preorder Successor of a Node in Binary Tree
|
Difficulty Level :
Easy
Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link. Examples:
Consider the following binary tree
20
/ \
10 26
/ \ / \
4 18 24 27
/ \
14 19
/ \
13 15
Input : 4
Output : 18
Preorder traversal of given tree is 20, 10, 4,
18, 14, 13, 15, 19, 26, 24, 27.
Input : 19
Output : 26
A simple solution is to first store the Preorder traversal of the given tree in an array then linearly search the given node and print the node next to it. Time Complexity: O(n), as we will traverse the tree for searching the node.Auxiliary Space: O(n), as we need extra space for storing the elements of the tree.An efficient solution is based on the below observations.
If the left child of a given node exists, then the left child is the preorder successor.If the left child does not exist, however, the right child exists, then the preorder successor is the right child.If the left child and the right child does not exist and given node is the left child of its parent, then its sibling is its preorder successor.If none of the above conditions are satisfied (left child does not exist and given node is not left child of its parent), then we move up using parent pointers until one of the following happens. We reach the root. In this case, a preorder successor does not exist.The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node.
If the left child of a given node exists, then the left child is the preorder successor.
If the left child does not exist, however, the right child exists, then the preorder successor is the right child.
If the left child and the right child does not exist and given node is the left child of its parent, then its sibling is its preorder successor.
If none of the above conditions are satisfied (left child does not exist and given node is not left child of its parent), then we move up using parent pointers until one of the following happens. We reach the root. In this case, a preorder successor does not exist.The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node.
We reach the root. In this case, a preorder successor does not exist.
The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node.
C++
Java
Python3
C#
Javascript
// CPP program to find preorder successor of// a node in Binary Tree.#include <iostream>using namespace std; struct Node { struct Node *left, *right, *parent; int key;}; Node* newNode(int key){ Node* temp = new Node; temp->left = temp->right = temp->parent = NULL; temp->key = key; return temp;} Node* preorderSuccessor(Node* root, Node* n){ // If left child exists, then it is preorder // successor. if (n->left) return n->left; // If left child does not exist and right child // exists, then it is preorder successor. if (n->right) return n->right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node *curr = n, *parent = curr->parent; while (parent != NULL && parent->right == curr) { curr = curr->parent; parent = parent->parent; } // If we reached root, then the given // node has no preorder successor if (parent == NULL) return NULL; return parent->right;} int main(){ Node* root = newNode(20); root->parent = NULL; root->left = newNode(10); root->left->parent = root; root->left->left = newNode(4); root->left->left->parent = root->left; root->left->right = newNode(18); root->left->right->parent = root->left; root->right = newNode(26); root->right->parent = root; root->right->left = newNode(24); root->right->left->parent = root->right; root->right->right = newNode(27); root->right->right->parent = root->right; root->left->right->left = newNode(14); root->left->right->left->parent = root->left->right; root->left->right->left->left = newNode(13); root->left->right->left->left->parent = root->left->right->left; root->left->right->left->right = newNode(15); root->left->right->left->right->parent = root->left->right->left; root->left->right->right = newNode(19); root->left->right->right->parent = root->left->right; Node* res = preorderSuccessor(root, root->left->right->right); if (res) { printf("Preorder successor of %d is %d\n", root->left->right->right->key, res->key); } else { printf("Preorder successor of %d is NULL\n", root->left->right->right->key); } return 0;}
// Java program to find preorder successor of// a node in Binary Tree.class Solution{ static class Node{ Node left, right, parent; int key;}; static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = temp.parent = null; temp.key = key; return temp;} static Node preorderSuccessor(Node root, Node n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codepublic static void main(String args[]){ Node root = newNode(20); root.parent = null; root.left = newNode(10); root.left.parent = root; root.left.left = newNode(4); root.left.left.parent = root.left; root.left.right = newNode(18); root.left.right.parent = root.left; root.right = newNode(26); root.right.parent = root; root.right.left = newNode(24); root.right.left.parent = root.right; root.right.right = newNode(27); root.right.right.parent = root.right; root.left.right.left = newNode(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = newNode(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = newNode(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = newNode(19); root.left.right.right.parent = root.left.right; Node res = preorderSuccessor(root, root.left.right.right); if (res != null) { System.out.printf("Preorder successor of %d is %d\n", root.left.right.right.key, res.key); } else { System.out.printf("Preorder successor of %d is null\n", root.left.right.right.key); }}} // This code is contributed by Arnab Kundu
""" Python3 program to find preordersuccessor of a node in Binary Tree.""" # A Binary Tree Node# Utility function to create a new tree node class newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None self.parent = None def preorderSuccessor(root, n): # If left child exists, then it is # preorder successor. if (n.left): return n.left # If left child does not exist and right child # exists, then it is preorder successor. if (n.right): return n.right # If left child does not exist, then # travel up (using parent pointers) # until we reach a node which is left # child of its parent. curr = n parent = curr.parent while (parent != None and parent.right == curr): curr = curr.parent parent = parent.parent # If we reached root, then the given # node has no preorder successor if (parent == None): return None return parent.right # Driver Codeif __name__ == '__main__': root = newNode(20) root.parent = None root.left = newNode(10) root.left.parent = root root.left.left = newNode(4) root.left.left.parent = root.left root.left.right = newNode(18) root.left.right.parent = root.left root.right = newNode(26) root.right.parent = root root.right.left = newNode(24) root.right.left.parent = root.right root.right.right = newNode(27) root.right.right.parent = root.right root.left.right.left = newNode(14) root.left.right.left.parent = root.left.right root.left.right.left.left = newNode(13) root.left.right.left.left.parent = root.left.right.left root.left.right.left.right = newNode(15) root.left.right.left.right.parent = root.left.right.left root.left.right.right = newNode(19) root.left.right.right.parent = root.left.right res = preorderSuccessor(root, root.left.right.right) if (res): print("Preorder successor of", root.left.right.right.key, "is", res.key) else: print("Preorder successor of", root.left.right.right.key, "is None") # This code is contributed# by SHUBHAMSINGH10
// C# program to find preorder successor of// a node in Binary Tree.using System; class GFG{ public class Node{ public Node left, right, parent; public int key;}; static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = temp.parent = null; temp.key = key; return temp;} static Node preorderSuccessor(Node root, Node n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codepublic static void Main(String []args){ Node root = newNode(20); root.parent = null; root.left = newNode(10); root.left.parent = root; root.left.left = newNode(4); root.left.left.parent = root.left; root.left.right = newNode(18); root.left.right.parent = root.left; root.right = newNode(26); root.right.parent = root; root.right.left = newNode(24); root.right.left.parent = root.right; root.right.right = newNode(27); root.right.right.parent = root.right; root.left.right.left = newNode(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = newNode(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = newNode(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = newNode(19); root.left.right.right.parent = root.left.right; Node res = preorderSuccessor(root, root.left.right.right); if (res != null) { Console.Write("Preorder successor of {0} is {1}\n", root.left.right.right.key, res.key); } else { Console.Write("Preorder successor of {0} is null\n", root.left.right.right.key); }}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find preorder successor of// a node in Binary Tree. class Node{ constructor(key) { this.key=key; this.left=this.right=this.parent=null; }} function preorderSuccessor(root,n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. let curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codelet root = new Node(20); root.parent = null; root.left = new Node(10); root.left.parent = root; root.left.left = new Node(4); root.left.left.parent = root.left; root.left.right = new Node(18); root.left.right.parent = root.left; root.right = new Node(26); root.right.parent = root; root.right.left = new Node(24); root.right.left.parent = root.right; root.right.right = new Node(27); root.right.right.parent = root.right; root.left.right.left = new Node(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = new Node(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = new Node(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = new Node(19); root.left.right.right.parent = root.left.right; let res = preorderSuccessor(root, root.left.right.right); if (res != null) { document.write("Preorder successor of "+ root.left.right.right.key+" is "+res.key+"<br>"); } else { System.out.printf("Preorder successor of "+ root.left.right.right.key+" is null<br>"); } // This code is contributed by avanitrachhadiya2155 </script>
Preorder successor of 19 is 26
Time Complexity: O(h) where h is the height of the given Binary Tree, as we are not traversing all nodes. We have checked the child of each node that is equivalent to traversing the height of the tree.Auxiliary Space: O(1), as we are not using any extra space.
AnkurSachdeva1
SHUBHAMSINGH10
andrew1234
29AjayKumar
avanitrachhadiya2155
dhruvshah2597
rohitsingh07052
Binary Tree
Preorder Traversal
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Decision Tree
Diagonal Traversal of Binary Tree
Construct Tree from given Inorder and Preorder traversals
Insertion in a Binary Tree in level order
|
[
{
"code": null,
"e": 24,
"s": 0,
"text": "Difficulty Level :\nEasy"
},
{
"code": null,
"e": 187,
"s": 24,
"text": "Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link. Examples: "
},
{
"code": null,
"e": 562,
"s": 187,
"text": "Consider the following binary tree\n 20 \n / \\ \n 10 26 \n / \\ / \\ \n 4 18 24 27 \n / \\\n 14 19\n / \\\n 13 15\nInput : 4\nOutput : 18\nPreorder traversal of given tree is 20, 10, 4, \n18, 14, 13, 15, 19, 26, 24, 27.\n\nInput : 19\nOutput : 26"
},
{
"code": null,
"e": 937,
"s": 564,
"text": "A simple solution is to first store the Preorder traversal of the given tree in an array then linearly search the given node and print the node next to it. Time Complexity: O(n), as we will traverse the tree for searching the node.Auxiliary Space: O(n), as we need extra space for storing the elements of the tree.An efficient solution is based on the below observations. "
},
{
"code": null,
"e": 1710,
"s": 937,
"text": "If the left child of a given node exists, then the left child is the preorder successor.If the left child does not exist, however, the right child exists, then the preorder successor is the right child.If the left child and the right child does not exist and given node is the left child of its parent, then its sibling is its preorder successor.If none of the above conditions are satisfied (left child does not exist and given node is not left child of its parent), then we move up using parent pointers until one of the following happens. We reach the root. In this case, a preorder successor does not exist.The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node."
},
{
"code": null,
"e": 1799,
"s": 1710,
"text": "If the left child of a given node exists, then the left child is the preorder successor."
},
{
"code": null,
"e": 1914,
"s": 1799,
"text": "If the left child does not exist, however, the right child exists, then the preorder successor is the right child."
},
{
"code": null,
"e": 2059,
"s": 1914,
"text": "If the left child and the right child does not exist and given node is the left child of its parent, then its sibling is its preorder successor."
},
{
"code": null,
"e": 2486,
"s": 2059,
"text": "If none of the above conditions are satisfied (left child does not exist and given node is not left child of its parent), then we move up using parent pointers until one of the following happens. We reach the root. In this case, a preorder successor does not exist.The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node."
},
{
"code": null,
"e": 2556,
"s": 2486,
"text": "We reach the root. In this case, a preorder successor does not exist."
},
{
"code": null,
"e": 2718,
"s": 2556,
"text": "The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node."
},
{
"code": null,
"e": 2724,
"s": 2720,
"text": "C++"
},
{
"code": null,
"e": 2729,
"s": 2724,
"text": "Java"
},
{
"code": null,
"e": 2737,
"s": 2729,
"text": "Python3"
},
{
"code": null,
"e": 2740,
"s": 2737,
"text": "C#"
},
{
"code": null,
"e": 2751,
"s": 2740,
"text": "Javascript"
},
{
"code": "// CPP program to find preorder successor of// a node in Binary Tree.#include <iostream>using namespace std; struct Node { struct Node *left, *right, *parent; int key;}; Node* newNode(int key){ Node* temp = new Node; temp->left = temp->right = temp->parent = NULL; temp->key = key; return temp;} Node* preorderSuccessor(Node* root, Node* n){ // If left child exists, then it is preorder // successor. if (n->left) return n->left; // If left child does not exist and right child // exists, then it is preorder successor. if (n->right) return n->right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node *curr = n, *parent = curr->parent; while (parent != NULL && parent->right == curr) { curr = curr->parent; parent = parent->parent; } // If we reached root, then the given // node has no preorder successor if (parent == NULL) return NULL; return parent->right;} int main(){ Node* root = newNode(20); root->parent = NULL; root->left = newNode(10); root->left->parent = root; root->left->left = newNode(4); root->left->left->parent = root->left; root->left->right = newNode(18); root->left->right->parent = root->left; root->right = newNode(26); root->right->parent = root; root->right->left = newNode(24); root->right->left->parent = root->right; root->right->right = newNode(27); root->right->right->parent = root->right; root->left->right->left = newNode(14); root->left->right->left->parent = root->left->right; root->left->right->left->left = newNode(13); root->left->right->left->left->parent = root->left->right->left; root->left->right->left->right = newNode(15); root->left->right->left->right->parent = root->left->right->left; root->left->right->right = newNode(19); root->left->right->right->parent = root->left->right; Node* res = preorderSuccessor(root, root->left->right->right); if (res) { printf(\"Preorder successor of %d is %d\\n\", root->left->right->right->key, res->key); } else { printf(\"Preorder successor of %d is NULL\\n\", root->left->right->right->key); } return 0;}",
"e": 5074,
"s": 2751,
"text": null
},
{
"code": "// Java program to find preorder successor of// a node in Binary Tree.class Solution{ static class Node{ Node left, right, parent; int key;}; static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = temp.parent = null; temp.key = key; return temp;} static Node preorderSuccessor(Node root, Node n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codepublic static void main(String args[]){ Node root = newNode(20); root.parent = null; root.left = newNode(10); root.left.parent = root; root.left.left = newNode(4); root.left.left.parent = root.left; root.left.right = newNode(18); root.left.right.parent = root.left; root.right = newNode(26); root.right.parent = root; root.right.left = newNode(24); root.right.left.parent = root.right; root.right.right = newNode(27); root.right.right.parent = root.right; root.left.right.left = newNode(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = newNode(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = newNode(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = newNode(19); root.left.right.right.parent = root.left.right; Node res = preorderSuccessor(root, root.left.right.right); if (res != null) { System.out.printf(\"Preorder successor of %d is %d\\n\", root.left.right.right.key, res.key); } else { System.out.printf(\"Preorder successor of %d is null\\n\", root.left.right.right.key); }}} // This code is contributed by Arnab Kundu",
"e": 7401,
"s": 5074,
"text": null
},
{
"code": "\"\"\" Python3 program to find preordersuccessor of a node in Binary Tree.\"\"\" # A Binary Tree Node# Utility function to create a new tree node class newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None self.parent = None def preorderSuccessor(root, n): # If left child exists, then it is # preorder successor. if (n.left): return n.left # If left child does not exist and right child # exists, then it is preorder successor. if (n.right): return n.right # If left child does not exist, then # travel up (using parent pointers) # until we reach a node which is left # child of its parent. curr = n parent = curr.parent while (parent != None and parent.right == curr): curr = curr.parent parent = parent.parent # If we reached root, then the given # node has no preorder successor if (parent == None): return None return parent.right # Driver Codeif __name__ == '__main__': root = newNode(20) root.parent = None root.left = newNode(10) root.left.parent = root root.left.left = newNode(4) root.left.left.parent = root.left root.left.right = newNode(18) root.left.right.parent = root.left root.right = newNode(26) root.right.parent = root root.right.left = newNode(24) root.right.left.parent = root.right root.right.right = newNode(27) root.right.right.parent = root.right root.left.right.left = newNode(14) root.left.right.left.parent = root.left.right root.left.right.left.left = newNode(13) root.left.right.left.left.parent = root.left.right.left root.left.right.left.right = newNode(15) root.left.right.left.right.parent = root.left.right.left root.left.right.right = newNode(19) root.left.right.right.parent = root.left.right res = preorderSuccessor(root, root.left.right.right) if (res): print(\"Preorder successor of\", root.left.right.right.key, \"is\", res.key) else: print(\"Preorder successor of\", root.left.right.right.key, \"is None\") # This code is contributed# by SHUBHAMSINGH10",
"e": 9604,
"s": 7401,
"text": null
},
{
"code": "// C# program to find preorder successor of// a node in Binary Tree.using System; class GFG{ public class Node{ public Node left, right, parent; public int key;}; static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = temp.parent = null; temp.key = key; return temp;} static Node preorderSuccessor(Node root, Node n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. Node curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codepublic static void Main(String []args){ Node root = newNode(20); root.parent = null; root.left = newNode(10); root.left.parent = root; root.left.left = newNode(4); root.left.left.parent = root.left; root.left.right = newNode(18); root.left.right.parent = root.left; root.right = newNode(26); root.right.parent = root; root.right.left = newNode(24); root.right.left.parent = root.right; root.right.right = newNode(27); root.right.right.parent = root.right; root.left.right.left = newNode(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = newNode(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = newNode(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = newNode(19); root.left.right.right.parent = root.left.right; Node res = preorderSuccessor(root, root.left.right.right); if (res != null) { Console.Write(\"Preorder successor of {0} is {1}\\n\", root.left.right.right.key, res.key); } else { Console.Write(\"Preorder successor of {0} is null\\n\", root.left.right.right.key); }}} // This code is contributed by 29AjayKumar",
"e": 11952,
"s": 9604,
"text": null
},
{
"code": "<script> // JavaScript program to find preorder successor of// a node in Binary Tree. class Node{ constructor(key) { this.key=key; this.left=this.right=this.parent=null; }} function preorderSuccessor(root,n){ // If left child exists, then it is preorder // successor. if (n.left != null) return n.left; // If left child does not exist and right child // exists, then it is preorder successor. if (n.right != null) return n.right; // If left child does not exist, then // travel up (using parent pointers) // until we reach a node which is left // child of its parent. let curr = n, parent = curr.parent; while (parent != null && parent.right == curr) { curr = curr.parent; parent = parent.parent; } // If we reached root, then the given // node has no preorder successor if (parent == null) return null; return parent.right;} // Driver codelet root = new Node(20); root.parent = null; root.left = new Node(10); root.left.parent = root; root.left.left = new Node(4); root.left.left.parent = root.left; root.left.right = new Node(18); root.left.right.parent = root.left; root.right = new Node(26); root.right.parent = root; root.right.left = new Node(24); root.right.left.parent = root.right; root.right.right = new Node(27); root.right.right.parent = root.right; root.left.right.left = new Node(14); root.left.right.left.parent = root.left.right; root.left.right.left.left = new Node(13); root.left.right.left.left.parent = root.left.right.left; root.left.right.left.right = new Node(15); root.left.right.left.right.parent = root.left.right.left; root.left.right.right = new Node(19); root.left.right.right.parent = root.left.right; let res = preorderSuccessor(root, root.left.right.right); if (res != null) { document.write(\"Preorder successor of \"+ root.left.right.right.key+\" is \"+res.key+\"<br>\"); } else { System.out.printf(\"Preorder successor of \"+ root.left.right.right.key+\" is null<br>\"); } // This code is contributed by avanitrachhadiya2155 </script>",
"e": 14170,
"s": 11952,
"text": null
},
{
"code": null,
"e": 14201,
"s": 14170,
"text": "Preorder successor of 19 is 26"
},
{
"code": null,
"e": 14465,
"s": 14203,
"text": "Time Complexity: O(h) where h is the height of the given Binary Tree, as we are not traversing all nodes. We have checked the child of each node that is equivalent to traversing the height of the tree.Auxiliary Space: O(1), as we are not using any extra space. "
},
{
"code": null,
"e": 14480,
"s": 14465,
"text": "AnkurSachdeva1"
},
{
"code": null,
"e": 14495,
"s": 14480,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 14506,
"s": 14495,
"text": "andrew1234"
},
{
"code": null,
"e": 14518,
"s": 14506,
"text": "29AjayKumar"
},
{
"code": null,
"e": 14539,
"s": 14518,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14553,
"s": 14539,
"text": "dhruvshah2597"
},
{
"code": null,
"e": 14569,
"s": 14553,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 14581,
"s": 14569,
"text": "Binary Tree"
},
{
"code": null,
"e": 14600,
"s": 14581,
"text": "Preorder Traversal"
},
{
"code": null,
"e": 14605,
"s": 14600,
"text": "Tree"
},
{
"code": null,
"e": 14610,
"s": 14605,
"text": "Tree"
},
{
"code": null,
"e": 14708,
"s": 14610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14740,
"s": 14708,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 14776,
"s": 14740,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 14840,
"s": 14776,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 14873,
"s": 14840,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 14899,
"s": 14873,
"text": "Diameter of a Binary Tree"
},
{
"code": null,
"e": 14947,
"s": 14899,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 14961,
"s": 14947,
"text": "Decision Tree"
},
{
"code": null,
"e": 14995,
"s": 14961,
"text": "Diagonal Traversal of Binary Tree"
},
{
"code": null,
"e": 15053,
"s": 14995,
"text": "Construct Tree from given Inorder and Preorder traversals"
}
] |
Minimum distance between any two equal elements in an Array
|
15 Jun, 2021
Given an array arr, the task is to find the minimum distance between any two same elements in the array. If no such element is found, return -1.
Examples:
Input: arr = {1, 2, 3, 2, 1} Output: 2 Explanation: There are two matching pairs of values: 1 and 2 in this array. Minimum Distance between two 1’s = 4 Minimum Distance between two 2’s = 2 Therefore, Minimum distance between any two equal elements in the Array = 2
Input: arr = {3, 5, 4, 6, 5, 3} Output: 3 Explanation: There are two matching pairs of values: 3 and 5 in this array. Minimum Distance between two 3’s = 5 Minimum Distance between two 5’s = 3 Therefore, Minimum distance between any two equal elements in the Array = 3
Naive Approach: The simplest approach is using two nested for loops to form each and every combination. If the elements are equal, find the minimum distance. Time complexity: O(N2)
Efficient Approach: An efficient approach for this problem is to use map to store array elements as a key and their index as the values.
Below is the step by step algorithm:
Traverse the array one by one.Check if this element is in the map or not. If the map does not contain this element, insert it as (element, current index) pair.If the array element present in the map, fetch the previous index of this element from the map.Find the difference between the previous index and the current indexCompare each difference and find the minimum distance.If no such element found, return -1.
Traverse the array one by one.
Check if this element is in the map or not. If the map does not contain this element, insert it as (element, current index) pair.If the array element present in the map, fetch the previous index of this element from the map.
If the map does not contain this element, insert it as (element, current index) pair.
If the array element present in the map, fetch the previous index of this element from the map.
Find the difference between the previous index and the current index
Compare each difference and find the minimum distance.
If no such element found, return -1.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the minimum distance// between two occurrences of the same element#include<bits/stdc++.h>using namespace std; // Function to find the minimum// distance between the same elementsint minimumDistance(int a[], int n){ // Create a HashMap to // store (key, values) pair. map<int,int> hmap; int minDistance = INT_MAX; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (int i = 0; i < n; i++) { if (hmap.find(a[i])!=hmap.end()) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap[a[i]]; // Find the minimum distance. minDistance = min((currentIndex - previousIndex),minDistance); } // Update the map. hmap[a[i]] = i; } // return minimum distance, // if no such elements found, return -1 return (minDistance == INT_MAX ? -1 : minDistance);} // Driver codeint main(){ // Test Case 1: int a1[] = { 1, 2, 3, 2, 1 }; int n = sizeof(a1)/sizeof(a1[0]); cout << minimumDistance(a1, n) << endl; // Test Case 2: int a2[] = { 3, 5, 4, 6, 5, 3 }; n = sizeof(a2)/sizeof(a2[0]); cout << minimumDistance(a2, n) << endl; // Test Case 3: int a3[] = { 1, 2, 1, 4, 1 }; n = sizeof(a3)/sizeof(a3[0]); cout << minimumDistance(a3, n) << endl;} // This code is contributed by Sanjit_Prasad
// Java program to find the minimum distance// between two occurrences of the same element import java.util.*;import java.math.*; class GFG { // Function to find the minimum // distance between the same elements static int minimumDistance(int[] a) { // Create a HashMap to // store (key, values) pair. HashMap<Integer, Integer> hmap = new HashMap<>(); int minDistance = Integer.MAX_VALUE; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (int i = 0; i < a.length; i++) { if (hmap.containsKey(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap.get(a[i]); // Find the minimum distance. minDistance = Math.min( (currentIndex - previousIndex), minDistance); } // Update the map. hmap.put(a[i], i); } // return minimum distance, // if no such elements found, return -1 return ( minDistance == Integer.MAX_VALUE ? -1 : minDistance); } // Driver code public static void main(String args[]) { // Test Case 1: int a1[] = { 1, 2, 3, 2, 1 }; System.out.println(minimumDistance(a1)); // Test Case 2: int a2[] = { 3, 5, 4, 6, 5, 3 }; System.out.println(minimumDistance(a2)); // Test Case 3: int a3[] = { 1, 2, 1, 4, 1 }; System.out.println(minimumDistance(a3)); }}
# Python3 program to find the minimum distance# between two occurrences of the same element # Function to find the minimum# distance between the same elementsdef minimumDistance(a): # Create a HashMap to # store (key, values) pair. hmap = dict() minDistance = 10**9 # Initialize previousIndex # and currentIndex as 0 previousIndex = 0 currentIndex = 0 # Traverse the array and # find the minimum distance # between the same elements with map for i in range(len(a)): if a[i] in hmap: currentIndex = i # Fetch the previous index from map. previousIndex = hmap[a[i]] # Find the minimum distance. minDistance = min((currentIndex - previousIndex), minDistance) # Update the map. hmap[a[i]] = i # return minimum distance, # if no such elements found, return -1 if minDistance == 10**9: return -1 return minDistance # Driver codeif __name__ == '__main__': # Test Case 1: a1 = [1, 2, 3, 2, 1 ] print(minimumDistance(a1)) # Test Case 2: a2 = [3, 5, 4, 6, 5,3] print(minimumDistance(a2)) # Test Case 3: a3 = [1, 2, 1, 4, 1 ] print(minimumDistance(a3)) # This code is contributed by mohit kumar 29
// C# program to find the minimum distance// between two occurrences of the same elementusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum// distance between the same elementsstatic int minimumDistance(int[] a){ // Create a HashMap to // store (key, values) pair. Dictionary<int, int> hmap = new Dictionary<int, int>(); int minDistance = Int32.MaxValue; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for(int i = 0; i < a.Length; i++) { if (hmap.ContainsKey(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap[a[i]]; // Find the minimum distance. minDistance = Math.Min((currentIndex - previousIndex), minDistance); } // Update the map. if (!hmap.ContainsKey(a[i])) hmap.Add(a[i], i); else hmap[a[i]] = i; } // Return minimum distance, // if no such elements found, return -1 return(minDistance == Int32.MaxValue ? -1 : minDistance);} // Driver codestatic public void Main(){ // Test Case 1: int[] a1 = { 1, 2, 3, 2, 1 }; Console.WriteLine(minimumDistance(a1)); // Test Case 2: int[] a2 = { 3, 5, 4, 6, 5, 3 }; Console.WriteLine(minimumDistance(a2)); // Test Case 3: int[] a3 = { 1, 2, 1, 4, 1 }; Console.WriteLine(minimumDistance(a3));}} // This code is contributed by unknown2108
<script> // Javascript program to find the minimum distance// between two occurrences of the same element // Function to find the minimum// distance between the same elementsfunction minimumDistance(a, n){ // Create a HashMap to // store (key, values) pair. var hmap = new Map(); var minDistance = 1000000000; // Initialize previousIndex // and currentIndex as 0 var previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (var i = 0; i < n; i++) { if (hmap.has(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap.get(a[i]); // Find the minimum distance. minDistance = Math.min((currentIndex - previousIndex),minDistance); } // Update the map. hmap.set(a[i], i); } // return minimum distance, // if no such elements found, return -1 return (minDistance == 1000000000 ? -1 : minDistance);} // Driver code// Test Case 1:var a1 = [1, 2, 3, 2, 1];var n = a1.length;document.write( minimumDistance(a1, n) + "<br>"); // Test Case 2:var a2 = [3, 5, 4, 6, 5, 3];n = a2.length;document.write( minimumDistance(a2, n) + "<br>"); // Test Case 3:var a3 = [1, 2, 1, 4, 1];n = a3.length;document.write( minimumDistance(a3, n)); // This code is contributed by famously.</script>
2
3
2
Time complexity: O(N)
mohit kumar 29
Sanjit_Prasad
famously
unknown2108
cpp-map
Java-HashMap
java-map
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
Introduction to Data Structures
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 199,
"s": 54,
"text": "Given an array arr, the task is to find the minimum distance between any two same elements in the array. If no such element is found, return -1."
},
{
"code": null,
"e": 211,
"s": 199,
"text": "Examples: "
},
{
"code": null,
"e": 476,
"s": 211,
"text": "Input: arr = {1, 2, 3, 2, 1} Output: 2 Explanation: There are two matching pairs of values: 1 and 2 in this array. Minimum Distance between two 1’s = 4 Minimum Distance between two 2’s = 2 Therefore, Minimum distance between any two equal elements in the Array = 2"
},
{
"code": null,
"e": 746,
"s": 476,
"text": "Input: arr = {3, 5, 4, 6, 5, 3} Output: 3 Explanation: There are two matching pairs of values: 3 and 5 in this array. Minimum Distance between two 3’s = 5 Minimum Distance between two 5’s = 3 Therefore, Minimum distance between any two equal elements in the Array = 3 "
},
{
"code": null,
"e": 927,
"s": 746,
"text": "Naive Approach: The simplest approach is using two nested for loops to form each and every combination. If the elements are equal, find the minimum distance. Time complexity: O(N2)"
},
{
"code": null,
"e": 1065,
"s": 927,
"text": "Efficient Approach: An efficient approach for this problem is to use map to store array elements as a key and their index as the values. "
},
{
"code": null,
"e": 1104,
"s": 1065,
"text": "Below is the step by step algorithm: "
},
{
"code": null,
"e": 1517,
"s": 1104,
"text": "Traverse the array one by one.Check if this element is in the map or not. If the map does not contain this element, insert it as (element, current index) pair.If the array element present in the map, fetch the previous index of this element from the map.Find the difference between the previous index and the current indexCompare each difference and find the minimum distance.If no such element found, return -1."
},
{
"code": null,
"e": 1548,
"s": 1517,
"text": "Traverse the array one by one."
},
{
"code": null,
"e": 1773,
"s": 1548,
"text": "Check if this element is in the map or not. If the map does not contain this element, insert it as (element, current index) pair.If the array element present in the map, fetch the previous index of this element from the map."
},
{
"code": null,
"e": 1859,
"s": 1773,
"text": "If the map does not contain this element, insert it as (element, current index) pair."
},
{
"code": null,
"e": 1955,
"s": 1859,
"text": "If the array element present in the map, fetch the previous index of this element from the map."
},
{
"code": null,
"e": 2024,
"s": 1955,
"text": "Find the difference between the previous index and the current index"
},
{
"code": null,
"e": 2079,
"s": 2024,
"text": "Compare each difference and find the minimum distance."
},
{
"code": null,
"e": 2116,
"s": 2079,
"text": "If no such element found, return -1."
},
{
"code": null,
"e": 2169,
"s": 2116,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 2173,
"s": 2169,
"text": "C++"
},
{
"code": null,
"e": 2178,
"s": 2173,
"text": "Java"
},
{
"code": null,
"e": 2186,
"s": 2178,
"text": "Python3"
},
{
"code": null,
"e": 2189,
"s": 2186,
"text": "C#"
},
{
"code": null,
"e": 2200,
"s": 2189,
"text": "Javascript"
},
{
"code": "// C++ program to find the minimum distance// between two occurrences of the same element#include<bits/stdc++.h>using namespace std; // Function to find the minimum// distance between the same elementsint minimumDistance(int a[], int n){ // Create a HashMap to // store (key, values) pair. map<int,int> hmap; int minDistance = INT_MAX; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (int i = 0; i < n; i++) { if (hmap.find(a[i])!=hmap.end()) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap[a[i]]; // Find the minimum distance. minDistance = min((currentIndex - previousIndex),minDistance); } // Update the map. hmap[a[i]] = i; } // return minimum distance, // if no such elements found, return -1 return (minDistance == INT_MAX ? -1 : minDistance);} // Driver codeint main(){ // Test Case 1: int a1[] = { 1, 2, 3, 2, 1 }; int n = sizeof(a1)/sizeof(a1[0]); cout << minimumDistance(a1, n) << endl; // Test Case 2: int a2[] = { 3, 5, 4, 6, 5, 3 }; n = sizeof(a2)/sizeof(a2[0]); cout << minimumDistance(a2, n) << endl; // Test Case 3: int a3[] = { 1, 2, 1, 4, 1 }; n = sizeof(a3)/sizeof(a3[0]); cout << minimumDistance(a3, n) << endl;} // This code is contributed by Sanjit_Prasad",
"e": 3754,
"s": 2200,
"text": null
},
{
"code": "// Java program to find the minimum distance// between two occurrences of the same element import java.util.*;import java.math.*; class GFG { // Function to find the minimum // distance between the same elements static int minimumDistance(int[] a) { // Create a HashMap to // store (key, values) pair. HashMap<Integer, Integer> hmap = new HashMap<>(); int minDistance = Integer.MAX_VALUE; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (int i = 0; i < a.length; i++) { if (hmap.containsKey(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap.get(a[i]); // Find the minimum distance. minDistance = Math.min( (currentIndex - previousIndex), minDistance); } // Update the map. hmap.put(a[i], i); } // return minimum distance, // if no such elements found, return -1 return ( minDistance == Integer.MAX_VALUE ? -1 : minDistance); } // Driver code public static void main(String args[]) { // Test Case 1: int a1[] = { 1, 2, 3, 2, 1 }; System.out.println(minimumDistance(a1)); // Test Case 2: int a2[] = { 3, 5, 4, 6, 5, 3 }; System.out.println(minimumDistance(a2)); // Test Case 3: int a3[] = { 1, 2, 1, 4, 1 }; System.out.println(minimumDistance(a3)); }}",
"e": 5527,
"s": 3754,
"text": null
},
{
"code": "# Python3 program to find the minimum distance# between two occurrences of the same element # Function to find the minimum# distance between the same elementsdef minimumDistance(a): # Create a HashMap to # store (key, values) pair. hmap = dict() minDistance = 10**9 # Initialize previousIndex # and currentIndex as 0 previousIndex = 0 currentIndex = 0 # Traverse the array and # find the minimum distance # between the same elements with map for i in range(len(a)): if a[i] in hmap: currentIndex = i # Fetch the previous index from map. previousIndex = hmap[a[i]] # Find the minimum distance. minDistance = min((currentIndex - previousIndex), minDistance) # Update the map. hmap[a[i]] = i # return minimum distance, # if no such elements found, return -1 if minDistance == 10**9: return -1 return minDistance # Driver codeif __name__ == '__main__': # Test Case 1: a1 = [1, 2, 3, 2, 1 ] print(minimumDistance(a1)) # Test Case 2: a2 = [3, 5, 4, 6, 5,3] print(minimumDistance(a2)) # Test Case 3: a3 = [1, 2, 1, 4, 1 ] print(minimumDistance(a3)) # This code is contributed by mohit kumar 29 ",
"e": 6817,
"s": 5527,
"text": null
},
{
"code": "// C# program to find the minimum distance// between two occurrences of the same elementusing System;using System.Collections.Generic; class GFG{ // Function to find the minimum// distance between the same elementsstatic int minimumDistance(int[] a){ // Create a HashMap to // store (key, values) pair. Dictionary<int, int> hmap = new Dictionary<int, int>(); int minDistance = Int32.MaxValue; // Initialize previousIndex // and currentIndex as 0 int previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for(int i = 0; i < a.Length; i++) { if (hmap.ContainsKey(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap[a[i]]; // Find the minimum distance. minDistance = Math.Min((currentIndex - previousIndex), minDistance); } // Update the map. if (!hmap.ContainsKey(a[i])) hmap.Add(a[i], i); else hmap[a[i]] = i; } // Return minimum distance, // if no such elements found, return -1 return(minDistance == Int32.MaxValue ? -1 : minDistance);} // Driver codestatic public void Main(){ // Test Case 1: int[] a1 = { 1, 2, 3, 2, 1 }; Console.WriteLine(minimumDistance(a1)); // Test Case 2: int[] a2 = { 3, 5, 4, 6, 5, 3 }; Console.WriteLine(minimumDistance(a2)); // Test Case 3: int[] a3 = { 1, 2, 1, 4, 1 }; Console.WriteLine(minimumDistance(a3));}} // This code is contributed by unknown2108",
"e": 8592,
"s": 6817,
"text": null
},
{
"code": "<script> // Javascript program to find the minimum distance// between two occurrences of the same element // Function to find the minimum// distance between the same elementsfunction minimumDistance(a, n){ // Create a HashMap to // store (key, values) pair. var hmap = new Map(); var minDistance = 1000000000; // Initialize previousIndex // and currentIndex as 0 var previousIndex = 0, currentIndex = 0; // Traverse the array and // find the minimum distance // between the same elements with map for (var i = 0; i < n; i++) { if (hmap.has(a[i])) { currentIndex = i; // Fetch the previous index from map. previousIndex = hmap.get(a[i]); // Find the minimum distance. minDistance = Math.min((currentIndex - previousIndex),minDistance); } // Update the map. hmap.set(a[i], i); } // return minimum distance, // if no such elements found, return -1 return (minDistance == 1000000000 ? -1 : minDistance);} // Driver code// Test Case 1:var a1 = [1, 2, 3, 2, 1];var n = a1.length;document.write( minimumDistance(a1, n) + \"<br>\"); // Test Case 2:var a2 = [3, 5, 4, 6, 5, 3];n = a2.length;document.write( minimumDistance(a2, n) + \"<br>\"); // Test Case 3:var a3 = [1, 2, 1, 4, 1];n = a3.length;document.write( minimumDistance(a3, n)); // This code is contributed by famously.</script>",
"e": 10028,
"s": 8592,
"text": null
},
{
"code": null,
"e": 10034,
"s": 10028,
"text": "2\n3\n2"
},
{
"code": null,
"e": 10059,
"s": 10036,
"text": "Time complexity: O(N) "
},
{
"code": null,
"e": 10074,
"s": 10059,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10088,
"s": 10074,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 10097,
"s": 10088,
"text": "famously"
},
{
"code": null,
"e": 10109,
"s": 10097,
"text": "unknown2108"
},
{
"code": null,
"e": 10117,
"s": 10109,
"text": "cpp-map"
},
{
"code": null,
"e": 10130,
"s": 10117,
"text": "Java-HashMap"
},
{
"code": null,
"e": 10139,
"s": 10130,
"text": "java-map"
},
{
"code": null,
"e": 10146,
"s": 10139,
"text": "Arrays"
},
{
"code": null,
"e": 10153,
"s": 10146,
"text": "Arrays"
},
{
"code": null,
"e": 10251,
"s": 10153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10319,
"s": 10251,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10363,
"s": 10319,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10395,
"s": 10363,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 10443,
"s": 10395,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 10457,
"s": 10443,
"text": "Linear Search"
},
{
"code": null,
"e": 10480,
"s": 10457,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 10565,
"s": 10480,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 10592,
"s": 10565,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 10637,
"s": 10592,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
Nexphisher – Advanced Phishing tool for Kali Linux
|
30 Jun, 2021
Nexphisher is an open-source tool with 30 distinct types of phishing sites via which you may get the credentials of a social media account. It was initially developed to carry out phishing assaults through social engineering.
NexPhisher is a Linux-based simple phishing tool. The phishing pages are taken from Zphisher, thus it appears to be a combination of Hidden Eye and Zphisher. The wonderful thing about this tool is that it isn’t difficult to use; all you have to do is choose a website and it will produce a phishing link for you.
The Nexphisher Tool contains nearly every social media phishing website, such as Facebook phishing, Instagram phishing, Whatsapp phishing, and all the others. Because this program employs NGrok tunneling, it may be used on public networks.
NexPhisher is a free and open-source program.
NexPhisher is a Kali Linux utility.
In Phishing attacks, NexPhisher is utilized.
The NexPhisher tool is a very simple and easy tool.
NexPhisher tool is a very simple and easy tool. NexPhisher is written in bash language.
The NexPhisher tool is a small and light instrument. This does not take up any additional space.
NexPhisher is written in the Bash programming language.
NexPhisher makes phishing pages for over 30 different websites.
NexPhisher generates phishing pages for famous websites including Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, LinkedIn, WordPress, Origin, Steam, Microsoft, and so on.
Step 1: Before we install any tool on Kali, we must first update all the pre-installed packages so that we do not encounter any errors while using the tool.
sudo apt-get update && apt-get upgrade -y
Step 2: The NexPhisher tool will now be cloned from the GitHub repository. Simply copy and paste the command below, and the tool will be installed in less than a minute.
sudo git clone git://github.com/htr-tech/nexphisher.git
Step 3: Now that the Archive file from Github has been installed in your kali, we must move the working directory to the nexPhisher folder.
cd nexphisher
Step 4: We’ll install all the necessary requirements for the Nexphisher tool to operate in this phase. Don’t worry, we’re not going to install them one by one; instead, we’ll run the “Setup” file created by the Nexphisher using the command below.
sudo bash setup
This tool’s setup will take some time, although that time may vary depending on your network and computer configuration.
To use the NexPhisher Tool, simply run the bash file provided in the tool; simply type the following command and the tool will begin to run.
bash nexphisher
After that, we can use the following command to start the tool. You can see the tool’s first appearance below, and we’ve chosen any choice for demonstration reasons.
The Nexphisher tool’s main menu will now appear. Now you must choose a social networking platform, such as Facebook or Instagram. To choose a social media, type the number in front of it and press Enter.
Type 2 to select Instagram.
You may now choose any choice you choose, depending on your social engineering strategies. All of the alternatives are fantastic; but, for basic Instagram hacking, choose option 1 and click Enter.
After picking the phishing template, you will be presented with a number of port forwarding choices from which to choose.
Your link will be generated here, and all you have to do now is copy it and email it to the victim. Keep in mind that you must copy the entire URL.
After the victim clicks on the link, the phishing website looks like this.
Wait, when the victim clicks on the link, he will be sent to a phony Instagram page, where he will fill out the information and click the login button, and you will have the victim’s username and password. To exit the tool, use CTRL + C on your keyboard.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "Nexphisher is an open-source tool with 30 distinct types of phishing sites via which you may get the credentials of a social media account. It was initially developed to carry out phishing assaults through social engineering."
},
{
"code": null,
"e": 567,
"s": 254,
"text": "NexPhisher is a Linux-based simple phishing tool. The phishing pages are taken from Zphisher, thus it appears to be a combination of Hidden Eye and Zphisher. The wonderful thing about this tool is that it isn’t difficult to use; all you have to do is choose a website and it will produce a phishing link for you."
},
{
"code": null,
"e": 807,
"s": 567,
"text": "The Nexphisher Tool contains nearly every social media phishing website, such as Facebook phishing, Instagram phishing, Whatsapp phishing, and all the others. Because this program employs NGrok tunneling, it may be used on public networks."
},
{
"code": null,
"e": 853,
"s": 807,
"text": "NexPhisher is a free and open-source program."
},
{
"code": null,
"e": 889,
"s": 853,
"text": "NexPhisher is a Kali Linux utility."
},
{
"code": null,
"e": 934,
"s": 889,
"text": "In Phishing attacks, NexPhisher is utilized."
},
{
"code": null,
"e": 986,
"s": 934,
"text": "The NexPhisher tool is a very simple and easy tool."
},
{
"code": null,
"e": 1074,
"s": 986,
"text": "NexPhisher tool is a very simple and easy tool. NexPhisher is written in bash language."
},
{
"code": null,
"e": 1171,
"s": 1074,
"text": "The NexPhisher tool is a small and light instrument. This does not take up any additional space."
},
{
"code": null,
"e": 1227,
"s": 1171,
"text": "NexPhisher is written in the Bash programming language."
},
{
"code": null,
"e": 1291,
"s": 1227,
"text": "NexPhisher makes phishing pages for over 30 different websites."
},
{
"code": null,
"e": 1499,
"s": 1291,
"text": "NexPhisher generates phishing pages for famous websites including Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, LinkedIn, WordPress, Origin, Steam, Microsoft, and so on."
},
{
"code": null,
"e": 1656,
"s": 1499,
"text": "Step 1: Before we install any tool on Kali, we must first update all the pre-installed packages so that we do not encounter any errors while using the tool."
},
{
"code": null,
"e": 1698,
"s": 1656,
"text": "sudo apt-get update && apt-get upgrade -y"
},
{
"code": null,
"e": 1868,
"s": 1698,
"text": "Step 2: The NexPhisher tool will now be cloned from the GitHub repository. Simply copy and paste the command below, and the tool will be installed in less than a minute."
},
{
"code": null,
"e": 1924,
"s": 1868,
"text": "sudo git clone git://github.com/htr-tech/nexphisher.git"
},
{
"code": null,
"e": 2064,
"s": 1924,
"text": "Step 3: Now that the Archive file from Github has been installed in your kali, we must move the working directory to the nexPhisher folder."
},
{
"code": null,
"e": 2078,
"s": 2064,
"text": "cd nexphisher"
},
{
"code": null,
"e": 2325,
"s": 2078,
"text": "Step 4: We’ll install all the necessary requirements for the Nexphisher tool to operate in this phase. Don’t worry, we’re not going to install them one by one; instead, we’ll run the “Setup” file created by the Nexphisher using the command below."
},
{
"code": null,
"e": 2341,
"s": 2325,
"text": "sudo bash setup"
},
{
"code": null,
"e": 2462,
"s": 2341,
"text": "This tool’s setup will take some time, although that time may vary depending on your network and computer configuration."
},
{
"code": null,
"e": 2603,
"s": 2462,
"text": "To use the NexPhisher Tool, simply run the bash file provided in the tool; simply type the following command and the tool will begin to run."
},
{
"code": null,
"e": 2619,
"s": 2603,
"text": "bash nexphisher"
},
{
"code": null,
"e": 2785,
"s": 2619,
"text": "After that, we can use the following command to start the tool. You can see the tool’s first appearance below, and we’ve chosen any choice for demonstration reasons."
},
{
"code": null,
"e": 2989,
"s": 2785,
"text": "The Nexphisher tool’s main menu will now appear. Now you must choose a social networking platform, such as Facebook or Instagram. To choose a social media, type the number in front of it and press Enter."
},
{
"code": null,
"e": 3017,
"s": 2989,
"text": "Type 2 to select Instagram."
},
{
"code": null,
"e": 3214,
"s": 3017,
"text": "You may now choose any choice you choose, depending on your social engineering strategies. All of the alternatives are fantastic; but, for basic Instagram hacking, choose option 1 and click Enter."
},
{
"code": null,
"e": 3336,
"s": 3214,
"text": "After picking the phishing template, you will be presented with a number of port forwarding choices from which to choose."
},
{
"code": null,
"e": 3484,
"s": 3336,
"text": "Your link will be generated here, and all you have to do now is copy it and email it to the victim. Keep in mind that you must copy the entire URL."
},
{
"code": null,
"e": 3559,
"s": 3484,
"text": "After the victim clicks on the link, the phishing website looks like this."
},
{
"code": null,
"e": 3814,
"s": 3559,
"text": "Wait, when the victim clicks on the link, he will be sent to a phony Instagram page, where he will fill out the information and click the login button, and you will have the victim’s username and password. To exit the tool, use CTRL + C on your keyboard."
},
{
"code": null,
"e": 3825,
"s": 3814,
"text": "Kali-Linux"
},
{
"code": null,
"e": 3837,
"s": 3825,
"text": "Linux-Tools"
},
{
"code": null,
"e": 3848,
"s": 3837,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3946,
"s": 3848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3972,
"s": 3946,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 4007,
"s": 3972,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 4044,
"s": 4007,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 4073,
"s": 4044,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 4107,
"s": 4073,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 4144,
"s": 4107,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 4181,
"s": 4144,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 4220,
"s": 4181,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 4260,
"s": 4220,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
Site Reliability Engineering
|
10 Sep, 2020
Site Reliability Engineering, it is a practice that tech giants are practicing now a days where operation problems of an organization are treated as software engineering problem, in other way when a developer is assigned to solve operations problem. Basically, SREs are software engineers who build various softwares to make better reliable systems. The question that arises is isn’t that DevOps? or which is better SRE vs DevOps?
History :This term was first coined by Ben treynor, a software engineer at google in 2003, this practice started lot earlier than DevOps movement. Shortly, after implementing SRE at their premises treynor’s team shortly launched SRE ebook to aware the industry about the practice.
Responsibilities Of Site Reliability Engineers (SREs) :
SREs are accountable and take on-call duties for the systems that are running in production.
SREs are responsible for developing software(s) that improves the reliability of systems.
They are responsible for performing post incident reviews of the systems that fails.
SRE vs DevOps : Which is better?There’s a great analogy to understand the two terms better. So, here it goes, let’s consider DevOps as an interface i.e. similar to abstract class containing methods without definitions, and SRE as a concrete class implementing DevOps.
Interface DevOps{
Reduce Organizational silos();
Accepting failures();
Implement gradual changes();
Leverage Automation();
Measure Everything();
}
Now, SRE as a concrete class will implements DevOps, alongwith defining all methods as :
Reducing the organizational silos, by sharing the ownership among software engineers, product team and SREs by using same set of tools.
Accepting Failures, as no system is 100% reliable so faults will be there, SREs do Blameless post-martems of systems and generate metadata for the same.
Implementing small changes, smaller the change is, easier it is to identify the problem or faster it is to fix the change or rollback. Thereby, reducing the cost of failure.
Leveraging Automation, automating manual tasks, wherever possible on the production system such as user creation, installing packages, alerting or logging etc.
Measuring Everything, at the end monitoring the right things that has implemented, as on the end of the day you should have numbers or clear metrics that supports success.So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps.
So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Software Engineering | Black box testing
Unit Testing | Software Testing
System Testing
Software Engineering | Integration Testing
What is DFD(Data Flow Diagram)?
Software Engineering | Calculation of Function Point (FP)
Difference Between Edge Computing and Fog Computing
Software Development Life Cycle (SDLC)
Software Processes in Software Engineering
Software Engineering | Software Design Process
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 459,
"s": 28,
"text": "Site Reliability Engineering, it is a practice that tech giants are practicing now a days where operation problems of an organization are treated as software engineering problem, in other way when a developer is assigned to solve operations problem. Basically, SREs are software engineers who build various softwares to make better reliable systems. The question that arises is isn’t that DevOps? or which is better SRE vs DevOps?"
},
{
"code": null,
"e": 740,
"s": 459,
"text": "History :This term was first coined by Ben treynor, a software engineer at google in 2003, this practice started lot earlier than DevOps movement. Shortly, after implementing SRE at their premises treynor’s team shortly launched SRE ebook to aware the industry about the practice."
},
{
"code": null,
"e": 796,
"s": 740,
"text": "Responsibilities Of Site Reliability Engineers (SREs) :"
},
{
"code": null,
"e": 889,
"s": 796,
"text": "SREs are accountable and take on-call duties for the systems that are running in production."
},
{
"code": null,
"e": 979,
"s": 889,
"text": "SREs are responsible for developing software(s) that improves the reliability of systems."
},
{
"code": null,
"e": 1064,
"s": 979,
"text": "They are responsible for performing post incident reviews of the systems that fails."
},
{
"code": null,
"e": 1332,
"s": 1064,
"text": "SRE vs DevOps : Which is better?There’s a great analogy to understand the two terms better. So, here it goes, let’s consider DevOps as an interface i.e. similar to abstract class containing methods without definitions, and SRE as a concrete class implementing DevOps."
},
{
"code": null,
"e": 1480,
"s": 1332,
"text": "Interface DevOps{\nReduce Organizational silos();\nAccepting failures();\nImplement gradual changes();\nLeverage Automation();\nMeasure Everything();\n}\n"
},
{
"code": null,
"e": 1569,
"s": 1480,
"text": "Now, SRE as a concrete class will implements DevOps, alongwith defining all methods as :"
},
{
"code": null,
"e": 1705,
"s": 1569,
"text": "Reducing the organizational silos, by sharing the ownership among software engineers, product team and SREs by using same set of tools."
},
{
"code": null,
"e": 1858,
"s": 1705,
"text": "Accepting Failures, as no system is 100% reliable so faults will be there, SREs do Blameless post-martems of systems and generate metadata for the same."
},
{
"code": null,
"e": 2032,
"s": 1858,
"text": "Implementing small changes, smaller the change is, easier it is to identify the problem or faster it is to fix the change or rollback. Thereby, reducing the cost of failure."
},
{
"code": null,
"e": 2192,
"s": 2032,
"text": "Leveraging Automation, automating manual tasks, wherever possible on the production system such as user creation, installing packages, alerting or logging etc."
},
{
"code": null,
"e": 2476,
"s": 2192,
"text": "Measuring Everything, at the end monitoring the right things that has implemented, as on the end of the day you should have numbers or clear metrics that supports success.So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps."
},
{
"code": null,
"e": 2589,
"s": 2476,
"text": "So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps."
},
{
"code": null,
"e": 2606,
"s": 2589,
"text": "Software Testing"
},
{
"code": null,
"e": 2627,
"s": 2606,
"text": "Software Engineering"
},
{
"code": null,
"e": 2725,
"s": 2627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2766,
"s": 2725,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 2798,
"s": 2766,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 2813,
"s": 2798,
"text": "System Testing"
},
{
"code": null,
"e": 2856,
"s": 2813,
"text": "Software Engineering | Integration Testing"
},
{
"code": null,
"e": 2888,
"s": 2856,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 2946,
"s": 2888,
"text": "Software Engineering | Calculation of Function Point (FP)"
},
{
"code": null,
"e": 2998,
"s": 2946,
"text": "Difference Between Edge Computing and Fog Computing"
},
{
"code": null,
"e": 3037,
"s": 2998,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 3080,
"s": 3037,
"text": "Software Processes in Software Engineering"
}
] |
DataTables lengthChange Option
|
31 May, 2021
DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed.
The lengthChange option is used to specify whether the dropdown to change the number of rows per page is displayed or not. This dropdown is shown only when paging of the DataTable is enabled, as disabling it automatically removes the dropdown. A true value displays the dropdown and a false value removes it.
Syntax:
{ lengthChange: value }
Option Value: This option has a single value as mentioned above and described below:
value: This is a boolean value that specifies whether the dropdown to change the number of rows is displayed or not. The default value is true.
The below example illustrates the use of this option.
Example 1: This example disables the changing of the rows per page by removing the dropdown.
HTML
<html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables lengthChange Option</h3> <!-- HTML table with student data --> <table id="tableID" class="display"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Disable the option to change // length in the DataTable lengthChange: false }); }); </script></body></html>
Output:
Example 2: This example enables the changing of the rows per page of the DataTable.
HTML
<html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head><body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables lengthChange Option</h3> <!-- HTML table with student data --> <table id="tableID" class="display"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable the option to change // length in the DataTable lengthChange: true }); }); </script></body></html>
Output:
jQuery-DataTables
JQuery
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": "\n31 May, 2021"
},
{
"code": null,
"e": 366,
"s": 28,
"text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed."
},
{
"code": null,
"e": 675,
"s": 366,
"text": "The lengthChange option is used to specify whether the dropdown to change the number of rows per page is displayed or not. This dropdown is shown only when paging of the DataTable is enabled, as disabling it automatically removes the dropdown. A true value displays the dropdown and a false value removes it."
},
{
"code": null,
"e": 683,
"s": 675,
"text": "Syntax:"
},
{
"code": null,
"e": 707,
"s": 683,
"text": "{ lengthChange: value }"
},
{
"code": null,
"e": 792,
"s": 707,
"text": "Option Value: This option has a single value as mentioned above and described below:"
},
{
"code": null,
"e": 936,
"s": 792,
"text": "value: This is a boolean value that specifies whether the dropdown to change the number of rows is displayed or not. The default value is true."
},
{
"code": null,
"e": 990,
"s": 936,
"text": "The below example illustrates the use of this option."
},
{
"code": null,
"e": 1083,
"s": 990,
"text": "Example 1: This example disables the changing of the rows per page by removing the dropdown."
},
{
"code": null,
"e": 1088,
"s": 1083,
"text": "HTML"
},
{
"code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head><body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables lengthChange Option</h3> <!-- HTML table with student data --> <table id=\"tableID\" class=\"display\"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Disable the option to change // length in the DataTable lengthChange: false }); }); </script></body></html>",
"e": 3074,
"s": 1088,
"text": null
},
{
"code": null,
"e": 3082,
"s": 3074,
"text": "Output:"
},
{
"code": null,
"e": 3166,
"s": 3082,
"text": "Example 2: This example enables the changing of the rows per page of the DataTable."
},
{
"code": null,
"e": 3171,
"s": 3166,
"text": "HTML"
},
{
"code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head><body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables lengthChange Option</h3> <!-- HTML table with student data --> <table id=\"tableID\" class=\"display\"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Sam</td> <td>35</td> </tr> <tr> <td>2</td> <td>Sam</td> <td>30</td> </tr> <tr> <td>3</td> <td>Sameer</td> <td>45</td> </tr> <tr> <td>4</td> <td>Rob</td> <td>4</td> </tr> <tr> <td>5</td> <td>Robber</td> <td>68</td> </tr> <tr> <td>6</td> <td>Mikasa</td> <td>25</td> </tr> <tr> <td>7</td> <td>Eren</td> <td>23</td> </tr> <tr> <td>8</td> <td>Jean</td> <td>35</td> </tr> <tr> <td>9</td> <td>Walter</td> <td>65</td> </tr> <tr> <td>10</td> <td>Jessie</td> <td>28</td> </tr> <tr> <td>11</td> <td>Gabi</td> <td>20</td> </tr> <tr> <td>12</td> <td>Tim</td> <td>30</td> </tr> <tr> <td>13</td> <td>Max</td> <td>35</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable the option to change // length in the DataTable lengthChange: true }); }); </script></body></html>",
"e": 5155,
"s": 3171,
"text": null
},
{
"code": null,
"e": 5163,
"s": 5155,
"text": "Output:"
},
{
"code": null,
"e": 5181,
"s": 5163,
"text": "jQuery-DataTables"
},
{
"code": null,
"e": 5188,
"s": 5181,
"text": "JQuery"
},
{
"code": null,
"e": 5205,
"s": 5188,
"text": "Web Technologies"
}
] |
How to create a Confirmation Dialog Box in Java?
|
To create a confirmation dialog box in Java, use the Java Swing JOptionPane.showConfirmDialog() method, which allows you to create a dialog box that asks for confirmation from the user. For example, Do you want to restart the system?, “This file contains a virus, Do you want to still download?”, etc. Kt comes with a type JOptionPane.YES_NO_CANCEL_OPTION for the same confirmation.
The following is an example to create a Confirmation Dialog Box in Java −
package my;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class SwingDemo {
public static void main(String[] args) {
ImageIcon icon = new ImageIcon("E −\\new.PNG");
JPanel panel = new JPanel();
panel.setSize(new Dimension(250, 100));
panel.setLayout(null);
JLabel label1 = new JLabel("The file may contain virus.");
label1.setVerticalAlignment(SwingConstants.BOTTOM);
label1.setBounds(20, 20, 200, 30);
label1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(label1);
JLabel label2 = new JLabel("Do you still want to save it?");
label2.setVerticalAlignment(SwingConstants.TOP);
label2.setHorizontalAlignment(SwingConstants.CENTER);
label2.setBounds(20, 80, 200, 20);
panel.add(label2);
UIManager.put("OptionPane.minimumSize", new Dimension(400, 200));
int res = JOptionPane.showConfirmDialog(null, panel, "File",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, icon);
if(res == 0) {
System.out.println("Pressed YES");
} else if (res == 1) {
System.out.println("Pressed NO");
} else {
System.out.println("Pressed CANCEL");
}
}
}
Now, let’s say we clicked on the Yes button. In that case, we have displayed the following on Console. Here, 0 is returned for YES, 1 for NO and 2 for CANCEL −
|
[
{
"code": null,
"e": 1570,
"s": 1187,
"text": "To create a confirmation dialog box in Java, use the Java Swing JOptionPane.showConfirmDialog() method, which allows you to create a dialog box that asks for confirmation from the user. For example, Do you want to restart the system?, “This file contains a virus, Do you want to still download?”, etc. Kt comes with a type JOptionPane.YES_NO_CANCEL_OPTION for the same confirmation."
},
{
"code": null,
"e": 1644,
"s": 1570,
"text": "The following is an example to create a Confirmation Dialog Box in Java −"
},
{
"code": null,
"e": 3027,
"s": 1644,
"text": "package my;\nimport java.awt.Dimension;\nimport javax.swing.ImageIcon;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.SwingConstants;\nimport javax.swing.UIManager;\npublic class SwingDemo {\n public static void main(String[] args) {\n ImageIcon icon = new ImageIcon(\"E −\\\\new.PNG\");\n JPanel panel = new JPanel();\n panel.setSize(new Dimension(250, 100));\n panel.setLayout(null);\n JLabel label1 = new JLabel(\"The file may contain virus.\");\n label1.setVerticalAlignment(SwingConstants.BOTTOM);\n label1.setBounds(20, 20, 200, 30);\n label1.setHorizontalAlignment(SwingConstants.CENTER);\n panel.add(label1);\n JLabel label2 = new JLabel(\"Do you still want to save it?\");\n label2.setVerticalAlignment(SwingConstants.TOP);\n label2.setHorizontalAlignment(SwingConstants.CENTER);\n label2.setBounds(20, 80, 200, 20);\n panel.add(label2);\n UIManager.put(\"OptionPane.minimumSize\", new Dimension(400, 200));\n int res = JOptionPane.showConfirmDialog(null, panel, \"File\",\n JOptionPane.YES_NO_CANCEL_OPTION,\n JOptionPane.PLAIN_MESSAGE, icon);\n if(res == 0) {\n System.out.println(\"Pressed YES\");\n } else if (res == 1) {\n System.out.println(\"Pressed NO\");\n } else {\n System.out.println(\"Pressed CANCEL\");\n }\n }\n}"
},
{
"code": null,
"e": 3187,
"s": 3027,
"text": "Now, let’s say we clicked on the Yes button. In that case, we have displayed the following on Console. Here, 0 is returned for YES, 1 for NO and 2 for CANCEL −"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.