title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Creating a Tensor in Pytorch
04 Jul, 2021 All the deep learning is computations on tensors, which are generalizations of a matrix that can be indexed in more than 2 dimensions. Tensors can be created from Python lists with the torch.tensor() function. To create tensors with Pytorch we can simply use the tensor() method: Syntax: torch.tensor(Data) Example: Python3 import torch V_data = [1, 2, 3, 4]V = torch.tensor(V_data)print(V) Output: tensor([1, 2, 3, 4]) To create a matrix we can use: Python3 import torch M_data = [[1., 2., 3.], [4, 5, 6]]M = torch.tensor(M_data)print(M) Output: tensor([[1., 2., 3.], [4., 5., 6.]]) To create a 3D tensor you can use the following code template: Python3 import torch T_data = [[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]T = torch.tensor(T_data)print(T) Output: tensor([[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]) However, if we run the following code: Python3 import torch x = torch.tensor([[1, 2], [3, 4, 5]])print(x) Output: ValueError: expected sequence of length 2 at dim 1 (got 3) This happens because Tensors are basically matrices, and they cannot have an unequal number of elements in every dimension. The randint() method returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive) for a given shape. The shape is given by the user which can be a tuple or a list with non-negative members. The default value for low is 0. When only one int argument is passed, low gets the value 0, by default, and high gets the passed value. Like zeros() an empty tuple or list for the shape creates a tensor with zero dimension. Syntax: torch.randint(<low>,<high>,<shape>) Example: Python3 import torch randint_tensor = torch.randint(5, (3,3))print(randint_tensor) Output: tensor([[3, 2, 3], [4, 4, 0], [3, 3, 4]]) The complex() method takes two arguments (real and imag) and returns a complex tensor with its real part equal to real and its imaginary part equal to imag where both real and imag are tensors having the same datatype and same shape. Syntax: torch.complex(<real tensor>,<another real tensor which is to be used as imaginary part>) Example: Python3 import torch real = torch.rand(2, 2)print(real)imag = torch.rand(2, 2)print(imag)complex_tensor = torch.complex(real, imag)print(complex_tensor) Output: tensor([[0.7655, 0.7181], [0.8479, 0.0369]]) tensor([[0.5604, 0.0012], [0.6316, 0.6574]]) tensor([[0.7655+0.5604j, 0.7181+0.0012j], [0.8479+0.6316j, 0.0369+0.6574j]]) The eye() method returns a 2-D tensor with ones on the diagonal and zeros elsewhere(identity matrix) for a given shape (n,m) where n and m are non-negative. The number of rows is given by n and columns is given by m. The default value for m is the value of n and when only n is passed, it creates a tensor in the form of an identity matrix. Syntax: torch.eye(<n,m or the shape>) Example: Python3 import torch n = m = 3eye_tensor = torch.eye(n, m)print(eye_tensor) Output: tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) This method can be used when you need a tensor where all elements are zeros, of a specified shape. The shape can be given as a tuple or a list or neither. If you pass an empty tuple or an empty list then the zeros() method returns a tensor of shape (dimension) 0, having 0 as its only element, whose data type is float. Negative numbers or float cannot be passed as a shape. Syntax: torch.zero(D1,D2) Here, D1: It represents the horizontal dimension of the tensor. D2: It represents the vertical dimension of the tensor. Example: Python3 import torch zeros_tensor = torch.zeros(3,2)print(zeros_tensor) Output: tensor([[0., 0.], [0., 0.], [0., 0.]]) The rand() method returns a tensor filled with random numbers from a uniform distribution on the interval 0 (inclusive) to 1 (exclusive) for a given shape. The shape is given by the user and can be given as a tuple or list or neither. Similar to zeros() and ones() passing an empty tuple or list creates a scalar-tensor of zero dimension. Like zeros() the shape argument only takes a tuple or a list with non-negative members. An empty tuple or list creates a tensor with zero dimension. The rand() method can be used to set random weights and biases in a neural network. Syntax: torch.rand(<shape>) Python3 import torch rand_tensor = torch.rand(3, 3)print(rand_tensor) Output: tensor([[0.6307, 0.7281, 0.0130], [0.7359, 0.0241, 0.2845], [0.2154, 0.3773, 0.6545]]) Similar to zeros(), ones() returns a tensor where all elements are 1, of specified size (shape). Syntax: torch.tensor(<shape>) Example: Python3 import torch ones_tensor = torch.ones((4,4,4))print(ones_tensor) Output: tensor([[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]], [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]], [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]], [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]]) The arange() method is used to get a 1-D tensor(row matrix), with elements from start (inclusive) to end (exclusive) with a common difference step (the default value for start is 0 while that for step is 1). The elements of the tensor can be said to be in Arithmetic Progression, with the given step as a common difference. All three parameters, start, end, and step can be positive, negative, or float. Syntax: torch.arange(<start>,<end>,<step-size>) Example: Python3 import torch arange_tensor = torch.arange(2, 20, 2)print(arange_tensor) Output: tensor([ 2, 4, 6, 8, 10, 12, 14, 16, 18]) The full() method is used when we need a tensor of a shape given by the shape argument, with all its elements equal to the fill value given by the user. Again, passing an empty tuple or list creates a scalar-tensor of zero dimension. While using full, it is necessary to give shape as a tuple or a list (which can be empty), or it throws an error. Also, the members of the shape list cannot be negative or float. Syntax: torch.full(<shape>,<value to be filled with>) Example: Python3 import torch full_tensor = torch.full((3,2), 3)print(full_tensor) Output: tensor([[3, 3], [3, 3], [3, 3]]) The linspace() method returns a 1-D dimensional tensor too(row matrix), with elements from start (inclusive) to end (inclusive). However, unlike arange(), we pass the number of elements that we need in our 1D tensor instead of passing step size (as shown above). Pytorch calculates the step automatically for the given start and end values. It is understandable that the number of elements can only be a non-negative integer. Syntax: torch.linspace(<start> , <end>, <number of elements>) Example: Python3 import torch linspace_tensor = torch.linspace(1, 7.75, 4)print(linspace_tensor) Output: tensor([ 1.0000, 3.2500, 5.5000, 7.7500]) Unlike arange(), in linspace() we can have a start greater than end since the common difference is automatically calculated. Tensor([[0.6307, 0.7281, 0.0130], [0.7359, 0.0241, 0.2845], [0.2154, 0.3773, 0.6545]]) And that’s how we can create tensors in PyTorch. Picked Python-PyTorch Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 238, "s": 28, "text": "All the deep learning is computations on tensors, which are generalizations of a matrix that can be indexed in more than 2 dimensions. Tensors can be created from Python lists with the torch.tensor() function." }, { "code": null, "e": 308, "s": 238, "text": "To create tensors with Pytorch we can simply use the tensor() method:" }, { "code": null, "e": 317, "s": 308, "text": "Syntax: " }, { "code": null, "e": 336, "s": 317, "text": "torch.tensor(Data)" }, { "code": null, "e": 345, "s": 336, "text": "Example:" }, { "code": null, "e": 353, "s": 345, "text": "Python3" }, { "code": "import torch V_data = [1, 2, 3, 4]V = torch.tensor(V_data)print(V)", "e": 421, "s": 353, "text": null }, { "code": null, "e": 430, "s": 421, "text": "Output: " }, { "code": null, "e": 451, "s": 430, "text": "tensor([1, 2, 3, 4])" }, { "code": null, "e": 482, "s": 451, "text": "To create a matrix we can use:" }, { "code": null, "e": 490, "s": 482, "text": "Python3" }, { "code": "import torch M_data = [[1., 2., 3.], [4, 5, 6]]M = torch.tensor(M_data)print(M)", "e": 571, "s": 490, "text": null }, { "code": null, "e": 580, "s": 571, "text": "Output: " }, { "code": null, "e": 625, "s": 580, "text": "tensor([[1., 2., 3.],\n [4., 5., 6.]])" }, { "code": null, "e": 688, "s": 625, "text": "To create a 3D tensor you can use the following code template:" }, { "code": null, "e": 696, "s": 688, "text": "Python3" }, { "code": "import torch T_data = [[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]T = torch.tensor(T_data)print(T)", "e": 805, "s": 696, "text": null }, { "code": null, "e": 814, "s": 805, "text": "Output: " }, { "code": null, "e": 894, "s": 814, "text": "tensor([[[1., 2.],\n [3., 4.]],\n\n [[5., 6.],\n [7., 8.]]])" }, { "code": null, "e": 933, "s": 894, "text": "However, if we run the following code:" }, { "code": null, "e": 941, "s": 933, "text": "Python3" }, { "code": "import torch x = torch.tensor([[1, 2], [3, 4, 5]])print(x)", "e": 1001, "s": 941, "text": null }, { "code": null, "e": 1010, "s": 1001, "text": "Output: " }, { "code": null, "e": 1069, "s": 1010, "text": "ValueError: expected sequence of length 2 at dim 1 (got 3)" }, { "code": null, "e": 1193, "s": 1069, "text": "This happens because Tensors are basically matrices, and they cannot have an unequal number of elements in every dimension." }, { "code": null, "e": 1656, "s": 1193, "text": "The randint() method returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive) for a given shape. The shape is given by the user which can be a tuple or a list with non-negative members. The default value for low is 0. When only one int argument is passed, low gets the value 0, by default, and high gets the passed value. Like zeros() an empty tuple or list for the shape creates a tensor with zero dimension." }, { "code": null, "e": 1700, "s": 1656, "text": "Syntax: torch.randint(<low>,<high>,<shape>)" }, { "code": null, "e": 1709, "s": 1700, "text": "Example:" }, { "code": null, "e": 1717, "s": 1709, "text": "Python3" }, { "code": "import torch randint_tensor = torch.randint(5, (3,3))print(randint_tensor)", "e": 1793, "s": 1717, "text": null }, { "code": null, "e": 1801, "s": 1793, "text": "Output:" }, { "code": null, "e": 1859, "s": 1801, "text": "tensor([[3, 2, 3],\n [4, 4, 0],\n [3, 3, 4]])" }, { "code": null, "e": 2093, "s": 1859, "text": "The complex() method takes two arguments (real and imag) and returns a complex tensor with its real part equal to real and its imaginary part equal to imag where both real and imag are tensors having the same datatype and same shape." }, { "code": null, "e": 2190, "s": 2093, "text": "Syntax: torch.complex(<real tensor>,<another real tensor which is to be used as imaginary part>)" }, { "code": null, "e": 2199, "s": 2190, "text": "Example:" }, { "code": null, "e": 2207, "s": 2199, "text": "Python3" }, { "code": "import torch real = torch.rand(2, 2)print(real)imag = torch.rand(2, 2)print(imag)complex_tensor = torch.complex(real, imag)print(complex_tensor)", "e": 2353, "s": 2207, "text": null }, { "code": null, "e": 2361, "s": 2353, "text": "Output:" }, { "code": null, "e": 2552, "s": 2361, "text": "tensor([[0.7655, 0.7181],\n [0.8479, 0.0369]])\ntensor([[0.5604, 0.0012],\n [0.6316, 0.6574]])\ntensor([[0.7655+0.5604j, 0.7181+0.0012j],\n [0.8479+0.6316j, 0.0369+0.6574j]])" }, { "code": null, "e": 2894, "s": 2552, "text": "The eye() method returns a 2-D tensor with ones on the diagonal and zeros elsewhere(identity matrix) for a given shape (n,m) where n and m are non-negative. The number of rows is given by n and columns is given by m. The default value for m is the value of n and when only n is passed, it creates a tensor in the form of an identity matrix." }, { "code": null, "e": 2932, "s": 2894, "text": "Syntax: torch.eye(<n,m or the shape>)" }, { "code": null, "e": 2941, "s": 2932, "text": "Example:" }, { "code": null, "e": 2949, "s": 2941, "text": "Python3" }, { "code": "import torch n = m = 3eye_tensor = torch.eye(n, m)print(eye_tensor)", "e": 3018, "s": 2949, "text": null }, { "code": null, "e": 3026, "s": 3018, "text": "Output:" }, { "code": null, "e": 3093, "s": 3026, "text": "tensor([[1., 0., 0.],\n [0., 1., 0.],\n [0., 0., 1.]])" }, { "code": null, "e": 3468, "s": 3093, "text": "This method can be used when you need a tensor where all elements are zeros, of a specified shape. The shape can be given as a tuple or a list or neither. If you pass an empty tuple or an empty list then the zeros() method returns a tensor of shape (dimension) 0, having 0 as its only element, whose data type is float. Negative numbers or float cannot be passed as a shape." }, { "code": null, "e": 3477, "s": 3468, "text": "Syntax: " }, { "code": null, "e": 3616, "s": 3477, "text": "torch.zero(D1,D2)\n\nHere,\nD1: It represents the horizontal dimension of the tensor.\nD2: It represents the vertical dimension of the tensor." }, { "code": null, "e": 3625, "s": 3616, "text": "Example:" }, { "code": null, "e": 3633, "s": 3625, "text": "Python3" }, { "code": "import torch zeros_tensor = torch.zeros(3,2)print(zeros_tensor)", "e": 3698, "s": 3633, "text": null }, { "code": null, "e": 3707, "s": 3698, "text": "Output: " }, { "code": null, "e": 3762, "s": 3707, "text": "tensor([[0., 0.],\n [0., 0.],\n [0., 0.]])" }, { "code": null, "e": 4251, "s": 3762, "text": "The rand() method returns a tensor filled with random numbers from a uniform distribution on the interval 0 (inclusive) to 1 (exclusive) for a given shape. The shape is given by the user and can be given as a tuple or list or neither. Similar to zeros() and ones() passing an empty tuple or list creates a scalar-tensor of zero dimension. Like zeros() the shape argument only takes a tuple or a list with non-negative members. An empty tuple or list creates a tensor with zero dimension." }, { "code": null, "e": 4335, "s": 4251, "text": "The rand() method can be used to set random weights and biases in a neural network." }, { "code": null, "e": 4363, "s": 4335, "text": "Syntax: torch.rand(<shape>)" }, { "code": null, "e": 4371, "s": 4363, "text": "Python3" }, { "code": "import torch rand_tensor = torch.rand(3, 3)print(rand_tensor)", "e": 4434, "s": 4371, "text": null }, { "code": null, "e": 4442, "s": 4434, "text": "Output:" }, { "code": null, "e": 4545, "s": 4442, "text": "tensor([[0.6307, 0.7281, 0.0130],\n [0.7359, 0.0241, 0.2845],\n [0.2154, 0.3773, 0.6545]])" }, { "code": null, "e": 4642, "s": 4545, "text": "Similar to zeros(), ones() returns a tensor where all elements are 1, of specified size (shape)." }, { "code": null, "e": 4672, "s": 4642, "text": "Syntax: torch.tensor(<shape>)" }, { "code": null, "e": 4681, "s": 4672, "text": "Example:" }, { "code": null, "e": 4689, "s": 4681, "text": "Python3" }, { "code": "import torch ones_tensor = torch.ones((4,4,4))print(ones_tensor)", "e": 4755, "s": 4689, "text": null }, { "code": null, "e": 4764, "s": 4755, "text": "Output: " }, { "code": null, "e": 5204, "s": 4764, "text": "tensor([[[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.]],\n\n [[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.]],\n\n [[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.]],\n\n [[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.]]])" }, { "code": null, "e": 5608, "s": 5204, "text": "The arange() method is used to get a 1-D tensor(row matrix), with elements from start (inclusive) to end (exclusive) with a common difference step (the default value for start is 0 while that for step is 1). The elements of the tensor can be said to be in Arithmetic Progression, with the given step as a common difference. All three parameters, start, end, and step can be positive, negative, or float." }, { "code": null, "e": 5656, "s": 5608, "text": "Syntax: torch.arange(<start>,<end>,<step-size>)" }, { "code": null, "e": 5665, "s": 5656, "text": "Example:" }, { "code": null, "e": 5673, "s": 5665, "text": "Python3" }, { "code": "import torch arange_tensor = torch.arange(2, 20, 2)print(arange_tensor)", "e": 5746, "s": 5673, "text": null }, { "code": null, "e": 5754, "s": 5746, "text": "Output:" }, { "code": null, "e": 5800, "s": 5754, "text": " tensor([ 2, 4, 6, 8, 10, 12, 14, 16, 18])" }, { "code": null, "e": 6214, "s": 5800, "text": "The full() method is used when we need a tensor of a shape given by the shape argument, with all its elements equal to the fill value given by the user. Again, passing an empty tuple or list creates a scalar-tensor of zero dimension. While using full, it is necessary to give shape as a tuple or a list (which can be empty), or it throws an error. Also, the members of the shape list cannot be negative or float." }, { "code": null, "e": 6268, "s": 6214, "text": "Syntax: torch.full(<shape>,<value to be filled with>)" }, { "code": null, "e": 6277, "s": 6268, "text": "Example:" }, { "code": null, "e": 6285, "s": 6277, "text": "Python3" }, { "code": "import torch full_tensor = torch.full((3,2), 3)print(full_tensor)", "e": 6352, "s": 6285, "text": null }, { "code": null, "e": 6360, "s": 6352, "text": "Output:" }, { "code": null, "e": 6409, "s": 6360, "text": "tensor([[3, 3],\n [3, 3],\n [3, 3]])" }, { "code": null, "e": 6835, "s": 6409, "text": "The linspace() method returns a 1-D dimensional tensor too(row matrix), with elements from start (inclusive) to end (inclusive). However, unlike arange(), we pass the number of elements that we need in our 1D tensor instead of passing step size (as shown above). Pytorch calculates the step automatically for the given start and end values. It is understandable that the number of elements can only be a non-negative integer." }, { "code": null, "e": 6897, "s": 6835, "text": "Syntax: torch.linspace(<start> , <end>, <number of elements>)" }, { "code": null, "e": 6906, "s": 6897, "text": "Example:" }, { "code": null, "e": 6914, "s": 6906, "text": "Python3" }, { "code": "import torch linspace_tensor = torch.linspace(1, 7.75, 4)print(linspace_tensor)", "e": 6995, "s": 6914, "text": null }, { "code": null, "e": 7004, "s": 6995, "text": "Output: " }, { "code": null, "e": 7049, "s": 7004, "text": "tensor([ 1.0000, 3.2500, 5.5000, 7.7500])" }, { "code": null, "e": 7174, "s": 7049, "text": "Unlike arange(), in linspace() we can have a start greater than end since the common difference is automatically calculated." }, { "code": null, "e": 7277, "s": 7174, "text": "Tensor([[0.6307, 0.7281, 0.0130],\n [0.7359, 0.0241, 0.2845],\n [0.2154, 0.3773, 0.6545]])" }, { "code": null, "e": 7327, "s": 7277, "text": "And that’s how we can create tensors in PyTorch. " }, { "code": null, "e": 7334, "s": 7327, "text": "Picked" }, { "code": null, "e": 7349, "s": 7334, "text": "Python-PyTorch" }, { "code": null, "e": 7356, "s": 7349, "text": "Python" } ]
Set in Scala | Set-1
01 Feb, 2019 A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request.Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, item3) or val variable_name = Set(item1, item2, item3) // Mutable Set var variable_name: Set[type] = Set(item1, item2, item3) or var variable_name = Set(item1, item2, item3) Some Important Points about Set in Scala In Scala, both mutable and immutable sets are available. Mutable set is those set in which the value of the object is change but, in the immutable set, the value of the object is not changed itself. By default set in Scala are immutable. In Scala, the immutable set is defined under Scala.collection.immutable._ package and mutable set are defined under Scala.collection.mutable._ package. We can also define a mutable set under Scala.collection.immutable._ package as shown in the below example. A Set has various methods to add, remove clear, size, etc. to enhance the usage of the set. In Scala, We are allowed to create empty set.Syntax:// Immutable empty set val variable_name = Set() // Mutable empty set var variable_name = Set() // Immutable empty set val variable_name = Set() // Mutable empty set var variable_name = Set() Example 1: // Scala program to illustrate the // use of immutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing immutable sets val myset1: Set[String] = Set("Geeks", "GFG", "GeeksforGeeks", "Geek123") val myset2 = Set("C", "C#", "Java", "Scala", "PHP", "Ruby") // Display the value of myset1 println("Set 1:") println(myset1) // Display the value of myset2 using for loop println("\nSet 2:") for(myset<-myset2) { println(myset) } }} Output: Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: Scala C# Ruby PHP C Java Example 2: // Scala program to illustrate the // use of mutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing mutable sets var myset1: Set[String] = Set("Geeks", "GFG", "GeeksforGeeks", "Geek123") var myset2 = Set(10, 100, 1000, 10000, 100000) // Display the value of myset1 println("Set 1:") println(myset1) // Display the value of myset2 // using a foreach loop println("\nSet 2:") myset2.foreach((item:Int)=>println(item)) }} Output: Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: 10 100000 10000 1000 100 Example 3: // Scala program to illustrate the // use of empty setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating empty sets val myset = Set() // Display the value of myset println("The empty set is:") println(myset) }} Output: The empty set is: Set() In Set, SortedSet is used to get values from the set in sorted order. SortedSet is only work for immutable set.Example: // Scala program to get sorted values // from the setimport scala.collection.immutable.SortedSet object Main{ def main(args: Array[String]) { // Using SortedSet to get sorted values val myset: SortedSet[Int] = SortedSet(87, 0, 3, 45, 7, 56, 8,6) myset.foreach((items: Int)=> println(items)) }} Output: 0 3 6 7 8 45 56 87 Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 258, "s": 28, "text": "A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request.Syntax:" }, { "code": null, "e": 501, "s": 258, "text": "// Immutable set\nval variable_name: Set[type] = Set(item1, item2, item3)\nor\nval variable_name = Set(item1, item2, item3)\n\n// Mutable Set\nvar variable_name: Set[type] = Set(item1, item2, item3)\nor\nvar variable_name = Set(item1, item2, item3)\n\n" }, { "code": null, "e": 542, "s": 501, "text": "Some Important Points about Set in Scala" }, { "code": null, "e": 741, "s": 542, "text": "In Scala, both mutable and immutable sets are available. Mutable set is those set in which the value of the object is change but, in the immutable set, the value of the object is not changed itself." }, { "code": null, "e": 780, "s": 741, "text": "By default set in Scala are immutable." }, { "code": null, "e": 932, "s": 780, "text": "In Scala, the immutable set is defined under Scala.collection.immutable._ package and mutable set are defined under Scala.collection.mutable._ package." }, { "code": null, "e": 1039, "s": 932, "text": "We can also define a mutable set under Scala.collection.immutable._ package as shown in the below example." }, { "code": null, "e": 1131, "s": 1039, "text": "A Set has various methods to add, remove clear, size, etc. to enhance the usage of the set." }, { "code": null, "e": 1280, "s": 1131, "text": "In Scala, We are allowed to create empty set.Syntax:// Immutable empty set\nval variable_name = Set()\n\n// Mutable empty set\nvar variable_name = Set()" }, { "code": null, "e": 1377, "s": 1280, "text": "// Immutable empty set\nval variable_name = Set()\n\n// Mutable empty set\nvar variable_name = Set()" }, { "code": null, "e": 1388, "s": 1377, "text": "Example 1:" }, { "code": "// Scala program to illustrate the // use of immutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing immutable sets val myset1: Set[String] = Set(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") val myset2 = Set(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") // Display the value of myset1 println(\"Set 1:\") println(myset1) // Display the value of myset2 using for loop println(\"\\nSet 2:\") for(myset<-myset2) { println(myset) } }}", "e": 2077, "s": 1388, "text": null }, { "code": null, "e": 2085, "s": 2077, "text": "Output:" }, { "code": null, "e": 2166, "s": 2085, "text": "Set 1:\nSet(Geeks, GFG, GeeksforGeeks, Geek123)\n\nSet 2:\nScala\nC#\nRuby\nPHP\nC\nJava\n" }, { "code": null, "e": 2177, "s": 2166, "text": "Example 2:" }, { "code": "// Scala program to illustrate the // use of mutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing mutable sets var myset1: Set[String] = Set(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") var myset2 = Set(10, 100, 1000, 10000, 100000) // Display the value of myset1 println(\"Set 1:\") println(myset1) // Display the value of myset2 // using a foreach loop println(\"\\nSet 2:\") myset2.foreach((item:Int)=>println(item)) }}", "e": 2802, "s": 2177, "text": null }, { "code": null, "e": 2810, "s": 2802, "text": "Output:" }, { "code": null, "e": 2891, "s": 2810, "text": "Set 1:\nSet(Geeks, GFG, GeeksforGeeks, Geek123)\n\nSet 2:\n10\n100000\n10000\n1000\n100\n" }, { "code": null, "e": 2902, "s": 2891, "text": "Example 3:" }, { "code": "// Scala program to illustrate the // use of empty setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating empty sets val myset = Set() // Display the value of myset println(\"The empty set is:\") println(myset) }}", "e": 3222, "s": 2902, "text": null }, { "code": null, "e": 3230, "s": 3222, "text": "Output:" }, { "code": null, "e": 3255, "s": 3230, "text": "The empty set is:\nSet()\n" }, { "code": null, "e": 3375, "s": 3255, "text": "In Set, SortedSet is used to get values from the set in sorted order. SortedSet is only work for immutable set.Example:" }, { "code": "// Scala program to get sorted values // from the setimport scala.collection.immutable.SortedSet object Main{ def main(args: Array[String]) { // Using SortedSet to get sorted values val myset: SortedSet[Int] = SortedSet(87, 0, 3, 45, 7, 56, 8,6) myset.foreach((items: Int)=> println(items)) }}", "e": 3712, "s": 3375, "text": null }, { "code": null, "e": 3720, "s": 3712, "text": "Output:" }, { "code": null, "e": 3740, "s": 3720, "text": "0\n3\n6\n7\n8\n45\n56\n87\n" }, { "code": null, "e": 3746, "s": 3740, "text": "Scala" }, { "code": null, "e": 3759, "s": 3746, "text": "Scala-Basics" }, { "code": null, "e": 3765, "s": 3759, "text": "Scala" } ]
How to change row values based on a column value in R dataframe ?
21 Apr, 2021 In this article, we will see how to change the values in rows based on the column values in Dataframe in R Programming Language. Syntax: df[expression ,] <- newrowvalue Arguments : df – Data frame to simulate the modification upon expression – Expression to evaluate the cell data based on a column value newrowvalue – The modified value to replace the old value with Returns : Doesn’t return anything, but makes changes to the data frame. The following code snippet is an example of changing the row value based on a column value in R. It checks if in C3 column, the cell value is less than 11, it replaces the corresponding row value, keeping the column the same with NA. This approach takes quadratic time equivalent to the dimensions of the data frame. Example: R # declaring a data frame in Rdata_frame = data.frame(C1= c(5:8),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print("Original data frame")print(data_frame) # replace the row value with NA if the col # value in C3 is less than 11 looping over # the data frame valuesfor (i in 1:nrow(data_frame)){for(j in 1:ncol(data_frame)) { # checking if the column is C3 that is # j index is 3 if(j==3){ # checking if the row value of c3 is # less than 11 if(data_frame[i,j]<11){ # changing the row value in the # data frame data_frame[i,j] <- NA } } }} # printing modified data frameprint ("Modified data frame")print (data_frame) Output: [1] “Original data frame” C1 C2 C3 C4 1 5 1 9 13 2 6 2 10 14 3 7 3 11 15 4 8 4 12 16 [1] “Modified data frame” C1 C2 C3 C4 1 5 1 NA 13 2 6 2 NA 14 3 7 3 11 15 4 8 4 12 16 This approach can be optimized, in case we know the index value of the column to carry out the evaluation. In that case, we will not iterate over the entire data frame but only over the column values. Example: R # declaring a data frame in Rdata_frame = data.frame(C1= c(5:8),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print("Original data frame")print(data_frame) # replace the row value with 0 if the# data element at col index 2 is divisible # by 2 looping over the rows of data framefor (i in 1:nrow(data_frame)){ # iterate over the 2nd column only of the # data frame and check if divisible by 2 if(data_frame[i,2]%%2){ # replace the value with 0 data_frame[i,2]<-0 }} # printing modified data frameprint ("Modified data frame")print (data_frame) Output: [1] “Original data frame” C1 C2 C3 C4 1 5 1 9 13 2 6 2 10 14 3 7 3 11 15 4 8 4 12 16 [1] “Modified data frame” C1 C2 C3 C4 1 5 0 9 13 2 6 2 10 14 3 7 0 11 15 4 8 4 12 16 R also provides an inbuilt way of handling these row transformations, by simply specifying the condition to be evaluated as the row index of the data frame. The reassigned values are replaced within the data frame. Explicit iteration over the data frame is not required in this case. Example: R # declaring a data frame in Rdata_frame = data.frame(C1= c(1,2,2,1),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print("Original data frame")print(data_frame) # check if c1 value is greater than# equal to 1, replaced by 3data_frame[data_frame$C1>=1 ,] <- 3 print("Modified data frame")print(data_frame) Output: [1] “Original data frame” C1 C2 C3 C4 1 1 1 9 13 2 2 2 10 14 3 2 3 11 15 4 1 4 12 16 [1] “Modified data frame” C1 C2 C3 C4 1 3 3 3 3 2 3 3 3 3 3 3 3 3 3 4 3 3 3 3 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 157, "s": 28, "text": "In this article, we will see how to change the values in rows based on the column values in Dataframe in R Programming Language." }, { "code": null, "e": 197, "s": 157, "text": "Syntax: df[expression ,] <- newrowvalue" }, { "code": null, "e": 210, "s": 197, "text": "Arguments : " }, { "code": null, "e": 260, "s": 210, "text": "df – Data frame to simulate the modification upon" }, { "code": null, "e": 334, "s": 260, "text": "expression – Expression to evaluate the cell data based on a column value" }, { "code": null, "e": 397, "s": 334, "text": "newrowvalue – The modified value to replace the old value with" }, { "code": null, "e": 470, "s": 397, "text": "Returns : Doesn’t return anything, but makes changes to the data frame. " }, { "code": null, "e": 788, "s": 470, "text": "The following code snippet is an example of changing the row value based on a column value in R. It checks if in C3 column, the cell value is less than 11, it replaces the corresponding row value, keeping the column the same with NA. This approach takes quadratic time equivalent to the dimensions of the data frame. " }, { "code": null, "e": 797, "s": 788, "text": "Example:" }, { "code": null, "e": 799, "s": 797, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(5:8),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print(\"Original data frame\")print(data_frame) # replace the row value with NA if the col # value in C3 is less than 11 looping over # the data frame valuesfor (i in 1:nrow(data_frame)){for(j in 1:ncol(data_frame)) { # checking if the column is C3 that is # j index is 3 if(j==3){ # checking if the row value of c3 is # less than 11 if(data_frame[i,j]<11){ # changing the row value in the # data frame data_frame[i,j] <- NA } } }} # printing modified data frameprint (\"Modified data frame\")print (data_frame)", "e": 1570, "s": 799, "text": null }, { "code": null, "e": 1578, "s": 1570, "text": "Output:" }, { "code": null, "e": 1604, "s": 1578, "text": "[1] “Original data frame”" }, { "code": null, "e": 1617, "s": 1604, "text": " C1 C2 C3 C4" }, { "code": null, "e": 1631, "s": 1617, "text": "1 5 1 9 13" }, { "code": null, "e": 1645, "s": 1631, "text": "2 6 2 10 14" }, { "code": null, "e": 1659, "s": 1645, "text": "3 7 3 11 15" }, { "code": null, "e": 1673, "s": 1659, "text": "4 8 4 12 16" }, { "code": null, "e": 1699, "s": 1673, "text": "[1] “Modified data frame”" }, { "code": null, "e": 1712, "s": 1699, "text": " C1 C2 C3 C4" }, { "code": null, "e": 1726, "s": 1712, "text": "1 5 1 NA 13" }, { "code": null, "e": 1740, "s": 1726, "text": "2 6 2 NA 14" }, { "code": null, "e": 1754, "s": 1740, "text": "3 7 3 11 15" }, { "code": null, "e": 1768, "s": 1754, "text": "4 8 4 12 16" }, { "code": null, "e": 1970, "s": 1768, "text": "This approach can be optimized, in case we know the index value of the column to carry out the evaluation. In that case, we will not iterate over the entire data frame but only over the column values. " }, { "code": null, "e": 1979, "s": 1970, "text": "Example:" }, { "code": null, "e": 1981, "s": 1979, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(5:8),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print(\"Original data frame\")print(data_frame) # replace the row value with 0 if the# data element at col index 2 is divisible # by 2 looping over the rows of data framefor (i in 1:nrow(data_frame)){ # iterate over the 2nd column only of the # data frame and check if divisible by 2 if(data_frame[i,2]%%2){ # replace the value with 0 data_frame[i,2]<-0 }} # printing modified data frameprint (\"Modified data frame\")print (data_frame)", "e": 2591, "s": 1981, "text": null }, { "code": null, "e": 2599, "s": 2591, "text": "Output:" }, { "code": null, "e": 2625, "s": 2599, "text": "[1] “Original data frame”" }, { "code": null, "e": 2638, "s": 2625, "text": " C1 C2 C3 C4" }, { "code": null, "e": 2652, "s": 2638, "text": "1 5 1 9 13" }, { "code": null, "e": 2666, "s": 2652, "text": "2 6 2 10 14" }, { "code": null, "e": 2680, "s": 2666, "text": "3 7 3 11 15" }, { "code": null, "e": 2694, "s": 2680, "text": "4 8 4 12 16" }, { "code": null, "e": 2720, "s": 2694, "text": "[1] “Modified data frame”" }, { "code": null, "e": 2733, "s": 2720, "text": " C1 C2 C3 C4" }, { "code": null, "e": 2747, "s": 2733, "text": "1 5 0 9 13" }, { "code": null, "e": 2761, "s": 2747, "text": "2 6 2 10 14" }, { "code": null, "e": 2775, "s": 2761, "text": "3 7 0 11 15" }, { "code": null, "e": 2789, "s": 2775, "text": "4 8 4 12 16" }, { "code": null, "e": 3074, "s": 2789, "text": "R also provides an inbuilt way of handling these row transformations, by simply specifying the condition to be evaluated as the row index of the data frame. The reassigned values are replaced within the data frame. Explicit iteration over the data frame is not required in this case. " }, { "code": null, "e": 3083, "s": 3074, "text": "Example:" }, { "code": null, "e": 3085, "s": 3083, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(1,2,2,1),C2 = c(1:4), C3 = c(9:12),C4 =c(13:16)) print(\"Original data frame\")print(data_frame) # check if c1 value is greater than# equal to 1, replaced by 3data_frame[data_frame$C1>=1 ,] <- 3 print(\"Modified data frame\")print(data_frame)", "e": 3409, "s": 3085, "text": null }, { "code": null, "e": 3417, "s": 3409, "text": "Output:" }, { "code": null, "e": 3443, "s": 3417, "text": "[1] “Original data frame”" }, { "code": null, "e": 3456, "s": 3443, "text": " C1 C2 C3 C4" }, { "code": null, "e": 3470, "s": 3456, "text": "1 1 1 9 13" }, { "code": null, "e": 3484, "s": 3470, "text": "2 2 2 10 14" }, { "code": null, "e": 3498, "s": 3484, "text": "3 2 3 11 15" }, { "code": null, "e": 3512, "s": 3498, "text": "4 1 4 12 16" }, { "code": null, "e": 3538, "s": 3512, "text": "[1] “Modified data frame”" }, { "code": null, "e": 3551, "s": 3538, "text": " C1 C2 C3 C4" }, { "code": null, "e": 3565, "s": 3551, "text": "1 3 3 3 3" }, { "code": null, "e": 3579, "s": 3565, "text": "2 3 3 3 3" }, { "code": null, "e": 3593, "s": 3579, "text": "3 3 3 3 3" }, { "code": null, "e": 3607, "s": 3593, "text": "4 3 3 3 3" }, { "code": null, "e": 3614, "s": 3607, "text": "Picked" }, { "code": null, "e": 3635, "s": 3614, "text": "R DataFrame-Programs" }, { "code": null, "e": 3647, "s": 3635, "text": "R-DataFrame" }, { "code": null, "e": 3658, "s": 3647, "text": "R Language" }, { "code": null, "e": 3669, "s": 3658, "text": "R Programs" } ]
Shuffle a deck of cards
17 Apr, 2019 Given a deck of cards, the task is to shuffle them. Asked in Amazon Interview Prerequisite : Shuffle a given array Algorithm: 1. First, fill the array with the values in order. 2. Go through the array and exchange each element with the randomly chosen element in the range from itself to the end. // It is possible that an element will be swap // with itself, but there is no problem with that. C++ Java Python3 C# // C++ program for shuffling desk of cards.#include <bits/stdc++.h>using namespace std; // Function which shuffle and print the arrayvoid shuffle(int card[], int n){ // Initialize seed randomly srand(time(0)); for (int i=0; i<n ;i++) { // Random for remaining positions. int r = i + (rand() % (52 -i)); swap(card[i], card[r]); }} // Driver codeint main(){ // Array from 0 to 51 int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i=0; i<52; i++) cout << a[i] << " "; cout << endl; return 0;} // Java Code for Shuffle a deck of cardsimport java.util.Random; class GFG { // Function which shuffle and print the array public static void shuffle(int card[], int n) { Random rand = new Random(); for (int i = 0; i < n; i++) { // Random for remaining positions. int r = i + rand.nextInt(52 - i); //swapping the elements int temp = card[r]; card[r] = card[i]; card[i] = temp; } } // Driver code public static void main(String[] args) { // Array from 0 to 51 int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i = 0; i < 52; i ++) System.out.print(a[i]+" "); }}// This code is contributed by Arnav Kr. Mandal # Python3 program for shuffling desk of cards# Function which shuffle and print the array import randomdef shuffle(card,n) : # Initialize seed randomly for i in range(n): # Random for remaining positions. r = i + (random.randint(0,55) % (52 -i)) tmp=card[i] card[i]=card[r] card[r]=tmp#Driver codeif __name__=='__main__': a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51] shuffle(a,52) print(a) #this code is contributed by sahilshelangia // C# Code for Shuffle a deck of cardsusing System; class GFG { // Function which shuffle and // print the array public static void shuffle(int []card, int n) { Random rand = new Random(); for (int i = 0; i < n; i++) { // Random for remaining positions. int r = i + rand.Next(52 - i); //swapping the elements int temp = card[r]; card[r] = card[i]; card[i] = temp; } } // Driver code public static void Main() { // Array from 0 to 51 int []a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i = 0; i < 52; i ++) Console.Write(a[i]+" "); }} // This code is contributed by Nitin Mittal. 29 27 20 23 26 21 35 51 15 18 46 32 33 19 24 30 3 45 40 34 16 11 36 50 17 10 7 5 4 39 6 47 38 28 13 44 49 1 8 42 43 48 0 12 37 41 25 2 31 14 22 Note : Output will be different each time because of the random function used in the program.Please refer Shuffle a given array for details. This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal sahilshelangia imSaiful Randomized Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Generating Random String Using PHP Operations on Sparse Matrices Random Walk (Implementation in Python) Primality Test | Set 2 (Fermat Method) Randomized Algorithms | Set 1 (Introduction and Analysis) Birthday Paradox Randomized Binary Search Algorithm Expected Number of Trials until Success Number guessing game in C Generate 0 and 1 with 25% and 75% probability
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Apr, 2019" }, { "code": null, "e": 104, "s": 52, "text": "Given a deck of cards, the task is to shuffle them." }, { "code": null, "e": 130, "s": 104, "text": "Asked in Amazon Interview" }, { "code": null, "e": 167, "s": 130, "text": "Prerequisite : Shuffle a given array" }, { "code": null, "e": 178, "s": 167, "text": "Algorithm:" }, { "code": null, "e": 458, "s": 178, "text": "1. First, fill the array with the values in order.\n2. Go through the array and exchange each element \n with the randomly chosen element in the range \n from itself to the end.\n\n// It is possible that an element will be swap\n// with itself, but there is no problem with that. \n" }, { "code": null, "e": 462, "s": 458, "text": "C++" }, { "code": null, "e": 467, "s": 462, "text": "Java" }, { "code": null, "e": 475, "s": 467, "text": "Python3" }, { "code": null, "e": 478, "s": 475, "text": "C#" }, { "code": "// C++ program for shuffling desk of cards.#include <bits/stdc++.h>using namespace std; // Function which shuffle and print the arrayvoid shuffle(int card[], int n){ // Initialize seed randomly srand(time(0)); for (int i=0; i<n ;i++) { // Random for remaining positions. int r = i + (rand() % (52 -i)); swap(card[i], card[r]); }} // Driver codeint main(){ // Array from 0 to 51 int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i=0; i<52; i++) cout << a[i] << \" \"; cout << endl; return 0;}", "e": 1370, "s": 478, "text": null }, { "code": "// Java Code for Shuffle a deck of cardsimport java.util.Random; class GFG { // Function which shuffle and print the array public static void shuffle(int card[], int n) { Random rand = new Random(); for (int i = 0; i < n; i++) { // Random for remaining positions. int r = i + rand.nextInt(52 - i); //swapping the elements int temp = card[r]; card[r] = card[i]; card[i] = temp; } } // Driver code public static void main(String[] args) { // Array from 0 to 51 int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i = 0; i < 52; i ++) System.out.print(a[i]+\" \"); }}// This code is contributed by Arnav Kr. Mandal", "e": 2588, "s": 1370, "text": null }, { "code": "# Python3 program for shuffling desk of cards# Function which shuffle and print the array import randomdef shuffle(card,n) : # Initialize seed randomly for i in range(n): # Random for remaining positions. r = i + (random.randint(0,55) % (52 -i)) tmp=card[i] card[i]=card[r] card[r]=tmp#Driver codeif __name__=='__main__': a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51] shuffle(a,52) print(a) #this code is contributed by sahilshelangia", "e": 3298, "s": 2588, "text": null }, { "code": "// C# Code for Shuffle a deck of cardsusing System; class GFG { // Function which shuffle and // print the array public static void shuffle(int []card, int n) { Random rand = new Random(); for (int i = 0; i < n; i++) { // Random for remaining positions. int r = i + rand.Next(52 - i); //swapping the elements int temp = card[r]; card[r] = card[i]; card[i] = temp; } } // Driver code public static void Main() { // Array from 0 to 51 int []a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51}; shuffle(a, 52); // Printing all shuffled elements of cards for (int i = 0; i < 52; i ++) Console.Write(a[i]+\" \"); }} // This code is contributed by Nitin Mittal.", "e": 4524, "s": 3298, "text": null }, { "code": null, "e": 4672, "s": 4524, "text": "29 27 20 23 26 21 35 51 15 18 46 32 33 19 \n24 30 3 45 40 34 16 11 36 50 17 10 7 5 4 \n39 6 47 38 28 13 44 49 1 8 42 43 48 0 12 \n37 41 25 2 31 14 22\n" }, { "code": null, "e": 4813, "s": 4672, "text": "Note : Output will be different each time because of the random function used in the program.Please refer Shuffle a given array for details." }, { "code": null, "e": 5113, "s": 4813, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5238, "s": 5113, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5251, "s": 5238, "text": "nitin mittal" }, { "code": null, "e": 5266, "s": 5251, "text": "sahilshelangia" }, { "code": null, "e": 5275, "s": 5266, "text": "imSaiful" }, { "code": null, "e": 5286, "s": 5275, "text": "Randomized" }, { "code": null, "e": 5384, "s": 5286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5419, "s": 5384, "text": "Generating Random String Using PHP" }, { "code": null, "e": 5449, "s": 5419, "text": "Operations on Sparse Matrices" }, { "code": null, "e": 5488, "s": 5449, "text": "Random Walk (Implementation in Python)" }, { "code": null, "e": 5527, "s": 5488, "text": "Primality Test | Set 2 (Fermat Method)" }, { "code": null, "e": 5585, "s": 5527, "text": "Randomized Algorithms | Set 1 (Introduction and Analysis)" }, { "code": null, "e": 5602, "s": 5585, "text": "Birthday Paradox" }, { "code": null, "e": 5637, "s": 5602, "text": "Randomized Binary Search Algorithm" }, { "code": null, "e": 5677, "s": 5637, "text": "Expected Number of Trials until Success" }, { "code": null, "e": 5703, "s": 5677, "text": "Number guessing game in C" } ]
String Comparison in Python
25 Oct, 2020 Let us see how to compare Strings in Python. Method 1: Using Relational Operators The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. It then returns a boolean value according to the operator used. Example: “Geek” == “Geek” will return True as the Unicode of all the characters are equal In case of “Geek” and “geek” as the unicode of G is \u0047 and of g is \u0067“Geek” < “geek” will return True and“Geek” > “geek” will return False Python3 print("Geek" == "Geek")print("Geek" < "geek")print("Geek" > "geek")print("Geek" != "Geek") Output: True True False False Method 2: Using is and is not The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. The same is the case for != and is not. Let us understand this with an example: Python3 str1 = "Geek"str2 = "Geek"str3 = str1 print("ID of str1 =", hex(id(str1)))print("ID of str2 =", hex(id(str2)))print("ID of str3 =", hex(id(str3)))print(str1 is str1)print(str1 is str2)print(str1 is str3) str1 += "s"str4 = "Geeks" print("\nID of changed str1 =", hex(id(str1)))print("ID of str4 =", hex(id(str4)))print(str1 is str4) Output: ID of str1 = 0x7f6037051570 ID of str2 = 0x7f6037051570 ID of str3 = 0x7f6037051570 True True True ID of changed str1 = 0x7f60356137d8 ID of str4 = 0x7f60356137a0 False The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1, the answer will be false as their object IDs are different. Vice-versa will happen with is not. Method 3: Creating a user-defined function. By using relational operators we can only compare the strings by their unicodes. In order to compare two strings according to some other parameters, we can make user-defined functions. In the following code, our user-defined function will compare the strings based upon the number of digits. Python3 # function to compare string# based on the number of digitsdef compare_strings(str1, str2): count1 = 0 count2 = 0 for i in range(len(str1)): if str1[i] >= "0" and str1[i] <= "9": count1 += 1 for i in range(len(str2)): if str2[i] >= "0" and str2[i] <= "9": count2 += 1 return count1 == count2 print(compare_strings("123", "12345"))print(compare_strings("12345", "geeks"))print(compare_strings("12geeks", "geeks12")) Output: False False True python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python - Pandas dataframe.append() Create a directory in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Oct, 2020" }, { "code": null, "e": 99, "s": 53, "text": "Let us see how to compare Strings in Python. " }, { "code": null, "e": 136, "s": 99, "text": "Method 1: Using Relational Operators" }, { "code": null, "e": 335, "s": 136, "text": "The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. It then returns a boolean value according to the operator used." }, { "code": null, "e": 344, "s": 335, "text": "Example:" }, { "code": null, "e": 425, "s": 344, "text": "“Geek” == “Geek” will return True as the Unicode of all the characters are equal" }, { "code": null, "e": 572, "s": 425, "text": "In case of “Geek” and “geek” as the unicode of G is \\u0047 and of g is \\u0067“Geek” < “geek” will return True and“Geek” > “geek” will return False" }, { "code": null, "e": 580, "s": 572, "text": "Python3" }, { "code": "print(\"Geek\" == \"Geek\")print(\"Geek\" < \"geek\")print(\"Geek\" > \"geek\")print(\"Geek\" != \"Geek\")", "e": 671, "s": 580, "text": null }, { "code": null, "e": 679, "s": 671, "text": "Output:" }, { "code": null, "e": 702, "s": 679, "text": "True\nTrue\nFalse\nFalse\n" }, { "code": null, "e": 732, "s": 702, "text": "Method 2: Using is and is not" }, { "code": null, "e": 946, "s": 732, "text": "The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. The same is the case for != and is not." }, { "code": null, "e": 986, "s": 946, "text": "Let us understand this with an example:" }, { "code": null, "e": 994, "s": 986, "text": "Python3" }, { "code": "str1 = \"Geek\"str2 = \"Geek\"str3 = str1 print(\"ID of str1 =\", hex(id(str1)))print(\"ID of str2 =\", hex(id(str2)))print(\"ID of str3 =\", hex(id(str3)))print(str1 is str1)print(str1 is str2)print(str1 is str3) str1 += \"s\"str4 = \"Geeks\" print(\"\\nID of changed str1 =\", hex(id(str1)))print(\"ID of str4 =\", hex(id(str4)))print(str1 is str4)", "e": 1329, "s": 994, "text": null }, { "code": null, "e": 1337, "s": 1329, "text": "Output:" }, { "code": null, "e": 1508, "s": 1337, "text": "ID of str1 = 0x7f6037051570\nID of str2 = 0x7f6037051570\nID of str3 = 0x7f6037051570\nTrue\nTrue\nTrue\n\nID of changed str1 = 0x7f60356137d8\nID of str4 = 0x7f60356137a0\nFalse\n" }, { "code": null, "e": 1884, "s": 1508, "text": "The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1, the answer will be false as their object IDs are different." }, { "code": null, "e": 1920, "s": 1884, "text": "Vice-versa will happen with is not." }, { "code": null, "e": 1964, "s": 1920, "text": "Method 3: Creating a user-defined function." }, { "code": null, "e": 2149, "s": 1964, "text": "By using relational operators we can only compare the strings by their unicodes. In order to compare two strings according to some other parameters, we can make user-defined functions." }, { "code": null, "e": 2256, "s": 2149, "text": "In the following code, our user-defined function will compare the strings based upon the number of digits." }, { "code": null, "e": 2264, "s": 2256, "text": "Python3" }, { "code": "# function to compare string# based on the number of digitsdef compare_strings(str1, str2): count1 = 0 count2 = 0 for i in range(len(str1)): if str1[i] >= \"0\" and str1[i] <= \"9\": count1 += 1 for i in range(len(str2)): if str2[i] >= \"0\" and str2[i] <= \"9\": count2 += 1 return count1 == count2 print(compare_strings(\"123\", \"12345\"))print(compare_strings(\"12345\", \"geeks\"))print(compare_strings(\"12geeks\", \"geeks12\"))", "e": 2751, "s": 2264, "text": null }, { "code": null, "e": 2759, "s": 2751, "text": "Output:" }, { "code": null, "e": 2777, "s": 2759, "text": "False\nFalse\nTrue\n" }, { "code": null, "e": 2791, "s": 2777, "text": "python-string" }, { "code": null, "e": 2798, "s": 2791, "text": "Python" }, { "code": null, "e": 2896, "s": 2798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2928, "s": 2896, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2949, "s": 2928, "text": "Python OOPs Concepts" }, { "code": null, "e": 2976, "s": 2949, "text": "Python Classes and Objects" }, { "code": null, "e": 2999, "s": 2976, "text": "Introduction To PYTHON" }, { "code": null, "e": 3030, "s": 2999, "text": "Python | os.path.join() method" }, { "code": null, "e": 3086, "s": 3030, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3128, "s": 3086, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3170, "s": 3128, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3205, "s": 3170, "text": "Python - Pandas dataframe.append()" } ]
Classful Vs Classless Addressing
03 Nov, 2021 Classful Addressing: Introduced in 1981, with classful routing, IP v4 addresses were divided into 5 classes(A to E). Classes A-C: unicast addresses Class D: multicast addresses Class E: reserved for future use Class A : In a class A address, the first bit of the first octet is always ‘0’. Thus, class A addresses range from 0.0.0.0 to 127.255.255.255(as 01111111 in binary converts to 127 in decimal). The first 8 bits or the first octet denote the network portion and the rest 24 bits or the 3 octets belong to the host portion. Its Subnet mask is 255.0.0.0. Example: 10.1.1.1 Exception – - 127.X.X.X is reserved for loopback - 0.X.X.X is reserved for default network Therefore, the actual range of class A addresses is: 1.0.0.0 to 126.255.255.255 Class B :In a class B address, the first octet would always start with ’10’. Thus, class B addresses range from 128.0.0.0 to 191.255.255.255. The first 16 bits or the first two octets denote the network portion and the remaining 16 bits or two octets belong to the host portion. Its Subnet mask is 255.255.0.0. Example: 172.16.1.1 Class C : In a class C address, the first octet would always start with ‘110’. Thus, class C addresses range from 192.0.0.0 to 223.255.255.255. The first 24 bits or the first three octets denote the network portion and the rest 8 bits or the remaining one octet belong to the host portion. Its Subnet mask is 255.255.255.0. Example: 192.168.1.1 Class D : Class D is used for multicast addressing and in a class D address the first octet would always start with ‘1110’. Thus, class D addresses range from 224.0.0.0 to 239.255.255.255. Its Subnet mask is not defined. Example: 239.2.2.2 Class D addresses are used by routing protocols like OSPF, RIP, etc. Class E : Class E addresses are reserved for research purposes and future use. The first octet in a class E address starts with ‘1111’. Thus, class E addresses range from 240.0.0.0 to 255.255.255.255. Its Subnet mask is not defined. Disadvantage of Classful Addressing: Class A with a mask of 255.0.0.0 can support 128 Network, 16,777,216 addresses per network and a total of 2,147,483,648 addresses. Class B with a mask of 255.255.0.0 can support 16,384 Network, 65,536 addresses per network and a total of 1,073,741,824 addresses. Class C with a mask of 255.255.255.0 can support 2,097,152 Network, 256 addresses per network and a total of 536,870,912 addresses. Class A with a mask of 255.0.0.0 can support 128 Network, 16,777,216 addresses per network and a total of 2,147,483,648 addresses. Class B with a mask of 255.255.0.0 can support 16,384 Network, 65,536 addresses per network and a total of 1,073,741,824 addresses. Class C with a mask of 255.255.255.0 can support 2,097,152 Network, 256 addresses per network and a total of 536,870,912 addresses. But what if someone requires 2000 addresses ? One way to address this situation would be to provide the person with class B network. But that would result in a waste of so many addresses. Another possible way is to provide multiple class C networks, but that too can cause a problem as there would be too many networks to handle. To resolve problems like the one mentioned above CIDR was introduced. Classless Inter-Domain Routing (CIDR): CIDR or Class Inter-Domain Routing was introduced in 1993 to replace classful addressing. It allows the user to use VLSM or Variable Length Subnet Masks. CIDR notation: In CIDR subnet masks are denoted by /X. For example a subnet of 255.255.255.0 would be denoted by /24. To work a subnet mask in CIDR, we have to first convert each octet into its respective binary value. For example, if the subnet is of 255.255.255.0. then : First Octet – 255 has 8 binary 1's when converted to binary Second Octet – 255 has 8 binary 1's when converted to binary Third Octet – 255 has 8 binary 1's when converted to binary Fourth Octet – 0 has 0 binary 1's when converted to binary Therefore, in total there are 24 binary 1’s, so the subnet mask is /24. While creating a network in CIDR, a person has to make sure that the masks are contiguous, i.e. a subnet mask like 10111111.X.X.X can’t exist. With CIDR, we can create Variable Length Subnet Masks, leading to less wastage of IP addresses. It is not necessary that the divider between the network and the host portions is at an octet boundary. For example, in CIDR a subnet mask like 255.224.0.0 or 11111111.11100000.00000000.00000000 can exist. MeghaKakkar scaryassmonster kmbh Computer Networks-IP Addressing Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Nov, 2021" }, { "code": null, "e": 173, "s": 54, "text": "Classful Addressing: Introduced in 1981, with classful routing, IP v4 addresses were divided into 5 classes(A to E). " }, { "code": null, "e": 267, "s": 173, "text": "Classes A-C: unicast addresses\nClass D: multicast addresses\nClass E: reserved for future use " }, { "code": null, "e": 618, "s": 267, "text": "Class A : In a class A address, the first bit of the first octet is always ‘0’. Thus, class A addresses range from 0.0.0.0 to 127.255.255.255(as 01111111 in binary converts to 127 in decimal). The first 8 bits or the first octet denote the network portion and the rest 24 bits or the 3 octets belong to the host portion. Its Subnet mask is 255.0.0.0." }, { "code": null, "e": 637, "s": 618, "text": "Example: 10.1.1.1 " }, { "code": null, "e": 649, "s": 637, "text": "Exception –" }, { "code": null, "e": 729, "s": 649, "text": "- 127.X.X.X is reserved for loopback\n- 0.X.X.X is reserved for default network " }, { "code": null, "e": 810, "s": 729, "text": "Therefore, the actual range of class A addresses is: 1.0.0.0 to 126.255.255.255 " }, { "code": null, "e": 1121, "s": 810, "text": "Class B :In a class B address, the first octet would always start with ’10’. Thus, class B addresses range from 128.0.0.0 to 191.255.255.255. The first 16 bits or the first two octets denote the network portion and the remaining 16 bits or two octets belong to the host portion. Its Subnet mask is 255.255.0.0." }, { "code": null, "e": 1142, "s": 1121, "text": "Example: 172.16.1.1 " }, { "code": null, "e": 1466, "s": 1142, "text": "Class C : In a class C address, the first octet would always start with ‘110’. Thus, class C addresses range from 192.0.0.0 to 223.255.255.255. The first 24 bits or the first three octets denote the network portion and the rest 8 bits or the remaining one octet belong to the host portion. Its Subnet mask is 255.255.255.0." }, { "code": null, "e": 1488, "s": 1466, "text": "Example: 192.168.1.1 " }, { "code": null, "e": 1709, "s": 1488, "text": "Class D : Class D is used for multicast addressing and in a class D address the first octet would always start with ‘1110’. Thus, class D addresses range from 224.0.0.0 to 239.255.255.255. Its Subnet mask is not defined." }, { "code": null, "e": 1729, "s": 1709, "text": "Example: 239.2.2.2 " }, { "code": null, "e": 1799, "s": 1729, "text": "Class D addresses are used by routing protocols like OSPF, RIP, etc. " }, { "code": null, "e": 2032, "s": 1799, "text": "Class E : Class E addresses are reserved for research purposes and future use. The first octet in a class E address starts with ‘1111’. Thus, class E addresses range from 240.0.0.0 to 255.255.255.255. Its Subnet mask is not defined." }, { "code": null, "e": 2070, "s": 2032, "text": "Disadvantage of Classful Addressing: " }, { "code": null, "e": 2467, "s": 2070, "text": "Class A with a mask of 255.0.0.0 can support 128 Network, 16,777,216 addresses per network and a total of 2,147,483,648 addresses. Class B with a mask of 255.255.0.0 can support 16,384 Network, 65,536 addresses per network and a total of 1,073,741,824 addresses. Class C with a mask of 255.255.255.0 can support 2,097,152 Network, 256 addresses per network and a total of 536,870,912 addresses. " }, { "code": null, "e": 2599, "s": 2467, "text": "Class A with a mask of 255.0.0.0 can support 128 Network, 16,777,216 addresses per network and a total of 2,147,483,648 addresses. " }, { "code": null, "e": 2733, "s": 2599, "text": "Class B with a mask of 255.255.0.0 can support 16,384 Network, 65,536 addresses per network and a total of 1,073,741,824 addresses. " }, { "code": null, "e": 2866, "s": 2733, "text": "Class C with a mask of 255.255.255.0 can support 2,097,152 Network, 256 addresses per network and a total of 536,870,912 addresses. " }, { "code": null, "e": 3197, "s": 2866, "text": "But what if someone requires 2000 addresses ? One way to address this situation would be to provide the person with class B network. But that would result in a waste of so many addresses. Another possible way is to provide multiple class C networks, but that too can cause a problem as there would be too many networks to handle. " }, { "code": null, "e": 3268, "s": 3197, "text": "To resolve problems like the one mentioned above CIDR was introduced. " }, { "code": null, "e": 3462, "s": 3268, "text": "Classless Inter-Domain Routing (CIDR): CIDR or Class Inter-Domain Routing was introduced in 1993 to replace classful addressing. It allows the user to use VLSM or Variable Length Subnet Masks. " }, { "code": null, "e": 3737, "s": 3462, "text": "CIDR notation: In CIDR subnet masks are denoted by /X. For example a subnet of 255.255.255.0 would be denoted by /24. To work a subnet mask in CIDR, we have to first convert each octet into its respective binary value. For example, if the subnet is of 255.255.255.0. then : " }, { "code": null, "e": 3751, "s": 3737, "text": "First Octet –" }, { "code": null, "e": 3798, "s": 3751, "text": "255 has 8 binary 1's when converted to binary " }, { "code": null, "e": 3813, "s": 3798, "text": "Second Octet –" }, { "code": null, "e": 3860, "s": 3813, "text": "255 has 8 binary 1's when converted to binary " }, { "code": null, "e": 3874, "s": 3860, "text": "Third Octet –" }, { "code": null, "e": 3921, "s": 3874, "text": "255 has 8 binary 1's when converted to binary " }, { "code": null, "e": 3936, "s": 3921, "text": "Fourth Octet –" }, { "code": null, "e": 3981, "s": 3936, "text": "0 has 0 binary 1's when converted to binary " }, { "code": null, "e": 4053, "s": 3981, "text": "Therefore, in total there are 24 binary 1’s, so the subnet mask is /24." }, { "code": null, "e": 4197, "s": 4053, "text": "While creating a network in CIDR, a person has to make sure that the masks are contiguous, i.e. a subnet mask like 10111111.X.X.X can’t exist. " }, { "code": null, "e": 4500, "s": 4197, "text": "With CIDR, we can create Variable Length Subnet Masks, leading to less wastage of IP addresses. It is not necessary that the divider between the network and the host portions is at an octet boundary. For example, in CIDR a subnet mask like 255.224.0.0 or 11111111.11100000.00000000.00000000 can exist. " }, { "code": null, "e": 4512, "s": 4500, "text": "MeghaKakkar" }, { "code": null, "e": 4528, "s": 4512, "text": "scaryassmonster" }, { "code": null, "e": 4533, "s": 4528, "text": "kmbh" }, { "code": null, "e": 4565, "s": 4533, "text": "Computer Networks-IP Addressing" }, { "code": null, "e": 4583, "s": 4565, "text": "Computer Networks" }, { "code": null, "e": 4591, "s": 4583, "text": "GATE CS" }, { "code": null, "e": 4609, "s": 4591, "text": "Computer Networks" } ]
HTTP headers | User-Agent
11 Oct, 2019 The HTTP headers User-Agent is a request header that allows a characteristic string that allows network protocol peers to identify the Operating System and Browser of the web-server. Your browser sends the user agent to every website you connect to. There is no conventional way of writing a user agent string as different browsers use different formats and many web browsers load a lot of information onto their user agents.When your browser is connected to a website, a User-Agent field is included in the HTTP header. The data of the header field varies from browser to browser. This information is used to serve different websites to different web browsers and different operating systems. Syntax: User-Agent: <product> / <product-version> <comment> or User-Agent: Mozilla/<version> (<system-information>) <platform> (<platform-details>) <extensions> Directives There are three directives in HTTP headers user-agent. product: This holds the product identity. product-version: This holds the product version of the used product. comment: This holds the sub-product information of the used product You can also check your User-agent with the help of http://whatsmyuseragent.com/. Example: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 The following conclusions can be drawn with the help of user-agent header: The user agent application is Mozilla version 5.0. The operating system is NT version 10.0 (and is running on a Windows(64-bit) Machine). The engine responsible for displaying content on this device is AppleWebKit version 537.36 (KHTML, an open-source layout engine, is present too). The client is Chrome version 77.0.3865.90. The client is based on Safari version 537.36. Examples: Mozilla:Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4 Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4 Chrome:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 Safari:Mozilla/5.0 (iPhone; CPU iPhone OS 11_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 Mozilla/5.0 (iPhone; CPU iPhone OS 11_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1 Supported Browsers: The browsers compatible with HTTP headers User-Agent are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 722, "s": 28, "text": "The HTTP headers User-Agent is a request header that allows a characteristic string that allows network protocol peers to identify the Operating System and Browser of the web-server. Your browser sends the user agent to every website you connect to. There is no conventional way of writing a user agent string as different browsers use different formats and many web browsers load a lot of information onto their user agents.When your browser is connected to a website, a User-Agent field is included in the HTTP header. The data of the header field varies from browser to browser. This information is used to serve different websites to different web browsers and different operating systems." }, { "code": null, "e": 730, "s": 722, "text": "Syntax:" }, { "code": null, "e": 782, "s": 730, "text": "User-Agent: <product> / <product-version> <comment>" }, { "code": null, "e": 785, "s": 782, "text": "or" }, { "code": null, "e": 884, "s": 785, "text": "User-Agent: Mozilla/<version> (<system-information>) <platform> (<platform-details>) \n<extensions>" }, { "code": null, "e": 950, "s": 884, "text": "Directives There are three directives in HTTP headers user-agent." }, { "code": null, "e": 992, "s": 950, "text": "product: This holds the product identity." }, { "code": null, "e": 1061, "s": 992, "text": "product-version: This holds the product version of the used product." }, { "code": null, "e": 1129, "s": 1061, "text": "comment: This holds the sub-product information of the used product" }, { "code": null, "e": 1211, "s": 1129, "text": "You can also check your User-agent with the help of http://whatsmyuseragent.com/." }, { "code": null, "e": 1220, "s": 1211, "text": "Example:" }, { "code": null, "e": 1335, "s": 1220, "text": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" }, { "code": null, "e": 1410, "s": 1335, "text": "The following conclusions can be drawn with the help of user-agent header:" }, { "code": null, "e": 1461, "s": 1410, "text": "The user agent application is Mozilla version 5.0." }, { "code": null, "e": 1548, "s": 1461, "text": "The operating system is NT version 10.0 (and is running on a Windows(64-bit) Machine)." }, { "code": null, "e": 1694, "s": 1548, "text": "The engine responsible for displaying content on this device is AppleWebKit version 537.36 (KHTML, an open-source layout engine, is present too)." }, { "code": null, "e": 1737, "s": 1694, "text": "The client is Chrome version 77.0.3865.90." }, { "code": null, "e": 1783, "s": 1737, "text": "The client is based on Safari version 537.36." }, { "code": null, "e": 1793, "s": 1783, "text": "Examples:" }, { "code": null, "e": 1960, "s": 1793, "text": "Mozilla:Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3\nMozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4" }, { "code": null, "e": 2119, "s": 1960, "text": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3\nMozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4" }, { "code": null, "e": 2231, "s": 2119, "text": "Chrome:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" }, { "code": null, "e": 2336, "s": 2231, "text": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" }, { "code": null, "e": 2482, "s": 2336, "text": "Safari:Mozilla/5.0 (iPhone; CPU iPhone OS 11_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) \nVersion/10.0 Mobile/14E304 Safari/602.1" }, { "code": null, "e": 2621, "s": 2482, "text": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) \nVersion/10.0 Mobile/14E304 Safari/602.1" }, { "code": null, "e": 2712, "s": 2621, "text": "Supported Browsers: The browsers compatible with HTTP headers User-Agent are listed below:" }, { "code": null, "e": 2726, "s": 2712, "text": "Google Chrome" }, { "code": null, "e": 2744, "s": 2726, "text": "Internet Explorer" }, { "code": null, "e": 2752, "s": 2744, "text": "Firefox" }, { "code": null, "e": 2759, "s": 2752, "text": "Safari" }, { "code": null, "e": 2765, "s": 2759, "text": "Opera" }, { "code": null, "e": 2778, "s": 2765, "text": "HTTP-headers" }, { "code": null, "e": 2785, "s": 2778, "text": "Picked" }, { "code": null, "e": 2802, "s": 2785, "text": "Web Technologies" } ]
C# | Dictionary.Clear Method
01 Feb, 2019 This method is used to remove all key/value pairs from the Dictionary<TKey,TValue>. Syntax: public void Clear (); Below are the programs to illustrate the use of above-discussed method: Example 1: // C# code to remove all pairs// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // Remove all pairs from the Dictionary myDict.Clear(); Console.WriteLine("After clear operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in"+ " myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 After clear operation Total key/value pairs in myDict are : 0 Example 2: // C# code to remove all pairs// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // Remove all pairs from the Dictionary myDict.Clear(); Console.WriteLine("After clear operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 4 After clear operation Total key/value pairs in myDict are : 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.clear?view=netframework-4.7.2 CSharp Dictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 112, "s": 28, "text": "This method is used to remove all key/value pairs from the Dictionary<TKey,TValue>." }, { "code": null, "e": 120, "s": 112, "text": "Syntax:" }, { "code": null, "e": 143, "s": 120, "text": "public void Clear ();\n" }, { "code": null, "e": 215, "s": 143, "text": "Below are the programs to illustrate the use of above-discussed method:" }, { "code": null, "e": 226, "s": 215, "text": "Example 1:" }, { "code": "// C# code to remove all pairs// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // Remove all pairs from the Dictionary myDict.Clear(); Console.WriteLine(\"After clear operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs in\"+ \" myDict are : \" + myDict.Count); }}", "e": 1295, "s": 226, "text": null }, { "code": null, "e": 1399, "s": 1295, "text": "Total key/value pairs in myDict are : 6\nAfter clear operation\nTotal key/value pairs in myDict are : 0\n" }, { "code": null, "e": 1410, "s": 1399, "text": "Example 2:" }, { "code": "// C# code to remove all pairs// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // Remove all pairs from the Dictionary myDict.Clear(); Console.WriteLine(\"After clear operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); }}", "e": 2310, "s": 1410, "text": null }, { "code": null, "e": 2414, "s": 2310, "text": "Total key/value pairs in myDict are : 4\nAfter clear operation\nTotal key/value pairs in myDict are : 0\n" }, { "code": null, "e": 2425, "s": 2414, "text": "Reference:" }, { "code": null, "e": 2539, "s": 2425, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.clear?view=netframework-4.7.2" }, { "code": null, "e": 2563, "s": 2539, "text": "CSharp Dictionary Class" }, { "code": null, "e": 2588, "s": 2563, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 2602, "s": 2588, "text": "CSharp-method" }, { "code": null, "e": 2605, "s": 2602, "text": "C#" } ]
Matplotlib.pyplot.xlabels() in Python
12 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The xlabel() function in pyplot module of matplotlib library is used to set the label for the x-axis.. Syntax: matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, **kwargs) Parameters: This method accept the following parameters that are described below: xlabel: This parameter is the label text. And contains the string value. labelpad: This parameter is used for spacing in points from the axes bounding box including ticks and tick labels and its default value is None. **kwargs: This parameter is Text properties that is used to control the appearance of the labels. Below examples illustrate the matplotlib.pyplot.xlabel() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib.pyplot.xlabels()# function import numpy as npimport matplotlib.pyplot as plt t = np.arange(-180.0, 180.0, 0.1)s = np.radians(t)/2. plt.plot(t, s, '-', lw = 2) plt.xlabel('Longitude')plt.ylabel('Latitude')plt.title('xlabels() function')plt.grid(True) plt.show() Output: Example #2: # Implementation of matplotlib.pyplot.xlabels()# function import numpy as npimport matplotlib.pyplot as plt valx1 = np.linspace(0.0, 5.0)x2 = np.linspace(0.0, 2.0) valy1 = np.cos(2 * np.pi * valx1) * np.exp(-valx1)y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 1, 1)plt.plot(valx1, valy1, 'o-')plt.title('xlabel() Example')plt.ylabel('Damped oscillation') plt.subplot(2, 1, 2)plt.plot(x2, y2, '.-')plt.xlabel('time (s)')plt.ylabel('Undamped') plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2020" }, { "code": null, "e": 247, "s": 52, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 350, "s": 247, "text": "The xlabel() function in pyplot module of matplotlib library is used to set the label for the x-axis.." }, { "code": null, "e": 431, "s": 350, "text": "Syntax: matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, **kwargs)" }, { "code": null, "e": 513, "s": 431, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 586, "s": 513, "text": "xlabel: This parameter is the label text. And contains the string value." }, { "code": null, "e": 731, "s": 586, "text": "labelpad: This parameter is used for spacing in points from the axes bounding box including ticks and tick labels and its default value is None." }, { "code": null, "e": 829, "s": 731, "text": "**kwargs: This parameter is Text properties that is used to control the appearance of the labels." }, { "code": null, "e": 917, "s": 829, "text": "Below examples illustrate the matplotlib.pyplot.xlabel() function in matplotlib.pyplot:" }, { "code": null, "e": 929, "s": 917, "text": "Example #1:" }, { "code": "# Implementation of matplotlib.pyplot.xlabels()# function import numpy as npimport matplotlib.pyplot as plt t = np.arange(-180.0, 180.0, 0.1)s = np.radians(t)/2. plt.plot(t, s, '-', lw = 2) plt.xlabel('Longitude')plt.ylabel('Latitude')plt.title('xlabels() function')plt.grid(True) plt.show()", "e": 1227, "s": 929, "text": null }, { "code": null, "e": 1235, "s": 1227, "text": "Output:" }, { "code": null, "e": 1247, "s": 1235, "text": "Example #2:" }, { "code": "# Implementation of matplotlib.pyplot.xlabels()# function import numpy as npimport matplotlib.pyplot as plt valx1 = np.linspace(0.0, 5.0)x2 = np.linspace(0.0, 2.0) valy1 = np.cos(2 * np.pi * valx1) * np.exp(-valx1)y2 = np.cos(2 * np.pi * x2) plt.subplot(2, 1, 1)plt.plot(valx1, valy1, 'o-')plt.title('xlabel() Example')plt.ylabel('Damped oscillation') plt.subplot(2, 1, 2)plt.plot(x2, y2, '.-')plt.xlabel('time (s)')plt.ylabel('Undamped') plt.show()", "e": 1704, "s": 1247, "text": null }, { "code": null, "e": 1712, "s": 1704, "text": "Output:" }, { "code": null, "e": 1730, "s": 1712, "text": "Python-matplotlib" }, { "code": null, "e": 1737, "s": 1730, "text": "Python" } ]
Greater on right side | Practice | GeeksforGeeks
You are given an array Arr of size N. Replace every element with the next greatest element (greatest element on its right side) in the array. Also, since there is no element next to the last element, replace it with -1. Example 1: Input: N = 6 Arr[] = {16, 17, 4, 3, 5, 2} Output: 17 5 5 5 2 -1 Explanation: For 16 the greatest element on its right is 17. For 17 it's 5. For 4 it's 5. For 3 it's 5. For 5 it's 2. For 2 it's -1(no element to its right). So the answer is 17 5 5 5 2 -1 Example 2: Input: N = 4 Arr[] = {2, 3, 1, 9} Output: 9 9 9 -1 Explanation: For each element except 9 the greatest element on its right is 9. So the answer is 9 9 9 -1 Your Task: You don't need to read input or print anything. Your task is to complete the function nextGreatest() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 105 1 <= Arri <= 106 0 abhisheksanwal4 days ago class Solution: def nextGreatest(self,arr, n): curr_max=-1 for i in range(n-1,-1,-1): x=curr_max if arr[i]> curr_max: curr_max=arr[i] arr[i]=x return arr Just think to tackle this problem from right side it is very easy than. 0 sanjeevranjan12092 weeks ago Python Solution Full testcase passed class Solution: def nextGreatest(self,arr, n): m = max(arr[1:]) for i in range(n-1): if arr[i]!=m: arr[i]=m else: m = max(arr[i+1:]) arr[i]=m arr[n-1]=-1 return arr +1 maneshram202 weeks ago Best C++ solution class Solution{ public: /* Function to replace every element with the next greatest element */ void nextGreatest(int arr[], int n) { int hi = arr[n-1]; for(int i=n-2;i>=0;i--){ if(hi<arr[i]){ swap(hi,arr[i]); } else arr[i] = hi; } arr[n-1] = -1; } }; 0 amulmittal3 weeks ago def nextGreatest(self,arr, n): for i in range(0,n-1): if i!=0: if arr[i]<arr[i-1]: arr[i] = arr[i-1] else: arr[i] = max(arr[i+1:n]) else: arr[i] = max(arr[i+1:n]) arr[n-1] = -1 return arr 0 shubhamrikhari86511 month ago void nextGreatest(int arr[], int n) { int maxi = arr[n-1]; for(int i=n-1; i>=0; i--) { int temp = maxi; maxi = max(maxi, arr[i]); arr[i] = temp; } arr[n-1] = -1;} 0 optimusprime031 month ago easy using stack stack<int >st; vector<int >v; for(int i=n-1;i>=0;i-- ) { if(st.empty()==true) { v.push_back(-1); st.push(arr[i]); } else if(arr[i]>st.top()) { v.push_back(st.top()); st.push(arr[i]); //v.push_back(st.top()); } else { v.push_back(st.top()); } } reverse(v.begin(),v.end()); for(int i=0;i<n;i++) { arr[i]=v[i]; } 0 abhinavjain78981 month ago Easy Java Solution Time Complexity = O(N) Space Complexity = O(1) class Solution { void nextGreatest(int arr[], int n) { // code here int max = arr[n-1]; for(int i=n-1;i>=0;i--){ if(arr[i]>max){ int temp = arr[i]; arr[i] = max; max = temp; } else if(arr[i]<max){ arr[i] = max; } } arr[n-1] = -1; } } 0 anuragprajapati1 month ago //java solution class Solution { void nextGreatest(int arr[], int n) { // code here int max=arr[n-1]; for(int j=n-1; j>=0; j--){ if(max<arr[j]){ max=max+arr[j]; arr[j]=max-arr[j]; max=max-arr[j]; }else if(arr[j]<max){ arr[j]=max; } } arr[n-1]=-1; }} 0 alirezachaviwala1 month ago JAVA Solution Time Complexity O(N) Space Complexity O(1) int maxValue=arr[n-1]; for(int i=n-1;i>=0;i--){ if(arr[i]>maxValue){ maxValue+=arr[i]; arr[i]=maxValue-arr[i]; maxValue-=arr[i]; } else if(arr[i]<maxValue){ arr[i]=maxValue; } } arr[n-1]=-1; 0 rakeshklk1 month ago java solution : void nextGreatest(int arr[], int n) { int largest,x,y; for (x =0; x < n; x++) { largest=-1; for (y = x+1; y < n; y++) { if (largest < arr[y]) largest=arr[y]; } arr[x]=largest; } } 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": 446, "s": 226, "text": "You are given an array Arr of size N. Replace every element with the next greatest element (greatest element on its right side) in the array. Also, since there is no element next to the last element, replace it with -1." }, { "code": null, "e": 457, "s": 446, "text": "Example 1:" }, { "code": null, "e": 714, "s": 457, "text": "Input:\nN = 6\nArr[] = {16, 17, 4, 3, 5, 2}\nOutput:\n17 5 5 5 2 -1\nExplanation: For 16 the greatest element \non its right is 17. For 17 it's 5. \nFor 4 it's 5. For 3 it's 5. For 5 it's 2. \nFor 2 it's -1(no element to its right). \nSo the answer is 17 5 5 5 2 -1" }, { "code": null, "e": 725, "s": 714, "text": "Example 2:" }, { "code": null, "e": 881, "s": 725, "text": "Input:\nN = 4\nArr[] = {2, 3, 1, 9}\nOutput:\n9 9 9 -1\nExplanation: For each element except 9 the\ngreatest element on its right is 9.\nSo the answer is 9 9 9 -1" }, { "code": null, "e": 1108, "s": 881, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function nextGreatest() which takes the array of integers arr and n as parameters and returns void. You need to change the array itself." }, { "code": null, "e": 1170, "s": 1108, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1214, "s": 1170, "text": "Constraints:\n1 <= N <= 105\n1 <= Arri <= 106" }, { "code": null, "e": 1218, "s": 1216, "text": "0" }, { "code": null, "e": 1243, "s": 1218, "text": "abhisheksanwal4 days ago" }, { "code": null, "e": 1259, "s": 1243, "text": "class Solution:" }, { "code": null, "e": 1446, "s": 1259, "text": "def nextGreatest(self,arr, n): curr_max=-1 for i in range(n-1,-1,-1): x=curr_max if arr[i]> curr_max: curr_max=arr[i] arr[i]=x return arr" }, { "code": null, "e": 1522, "s": 1450, "text": "Just think to tackle this problem from right side it is very easy than." }, { "code": null, "e": 1524, "s": 1522, "text": "0" }, { "code": null, "e": 1553, "s": 1524, "text": "sanjeevranjan12092 weeks ago" }, { "code": null, "e": 1570, "s": 1553, "text": "Python Solution " }, { "code": null, "e": 1591, "s": 1570, "text": "Full testcase passed" }, { "code": null, "e": 1835, "s": 1591, "text": "class Solution:\n\n\tdef nextGreatest(self,arr, n):\n\t m = max(arr[1:])\n\t for i in range(n-1):\n\t if arr[i]!=m:\n\t arr[i]=m\n\t else:\n\t m = max(arr[i+1:])\n\t arr[i]=m\n\t arr[n-1]=-1\n\t return arr" }, { "code": null, "e": 1838, "s": 1835, "text": "+1" }, { "code": null, "e": 1861, "s": 1838, "text": "maneshram202 weeks ago" }, { "code": null, "e": 1879, "s": 1861, "text": "Best C++ solution" }, { "code": null, "e": 2195, "s": 1879, "text": "class Solution{\npublic:\t\n\t/* Function to replace every element with the\n\tnext greatest element */\n\tvoid nextGreatest(int arr[], int n) {\n\t int hi = arr[n-1];\n\t for(int i=n-2;i>=0;i--){\n\t if(hi<arr[i]){\n\t swap(hi,arr[i]);\n\t }\n\t else arr[i] = hi;\n\t }\n\t arr[n-1] = -1;\n\t}\n};" }, { "code": null, "e": 2197, "s": 2195, "text": "0" }, { "code": null, "e": 2219, "s": 2197, "text": "amulmittal3 weeks ago" }, { "code": null, "e": 2493, "s": 2219, "text": "def nextGreatest(self,arr, n): for i in range(0,n-1): if i!=0: if arr[i]<arr[i-1]: arr[i] = arr[i-1] else: arr[i] = max(arr[i+1:n]) else: arr[i] = max(arr[i+1:n]) arr[n-1] = -1 return arr" }, { "code": null, "e": 2495, "s": 2493, "text": "0" }, { "code": null, "e": 2525, "s": 2495, "text": "shubhamrikhari86511 month ago" }, { "code": null, "e": 2722, "s": 2525, "text": "void nextGreatest(int arr[], int n) { int maxi = arr[n-1]; for(int i=n-1; i>=0; i--) { int temp = maxi; maxi = max(maxi, arr[i]); arr[i] = temp; } arr[n-1] = -1;}" }, { "code": null, "e": 2724, "s": 2722, "text": "0" }, { "code": null, "e": 2750, "s": 2724, "text": "optimusprime031 month ago" }, { "code": null, "e": 2767, "s": 2750, "text": "easy using stack" }, { "code": null, "e": 3213, "s": 2767, "text": "stack<int >st; vector<int >v; for(int i=n-1;i>=0;i-- ) { if(st.empty()==true) { v.push_back(-1); st.push(arr[i]); } else if(arr[i]>st.top()) { v.push_back(st.top()); st.push(arr[i]); //v.push_back(st.top()); } else { v.push_back(st.top()); }" }, { "code": null, "e": 3366, "s": 3213, "text": " } reverse(v.begin(),v.end()); for(int i=0;i<n;i++) { arr[i]=v[i]; } " }, { "code": null, "e": 3368, "s": 3366, "text": "0" }, { "code": null, "e": 3395, "s": 3368, "text": "abhinavjain78981 month ago" }, { "code": null, "e": 3415, "s": 3395, "text": "Easy Java Solution " }, { "code": null, "e": 3438, "s": 3415, "text": "Time Complexity = O(N)" }, { "code": null, "e": 3462, "s": 3438, "text": "Space Complexity = O(1)" }, { "code": null, "e": 3865, "s": 3462, "text": "class Solution {\n void nextGreatest(int arr[], int n) {\n // code here\n int max = arr[n-1];\n for(int i=n-1;i>=0;i--){\n if(arr[i]>max){\n int temp = arr[i];\n arr[i] = max;\n max = temp;\n }\n else if(arr[i]<max){\n arr[i] = max;\n }\n }\n arr[n-1] = -1;\n \n }\n}" }, { "code": null, "e": 3867, "s": 3865, "text": "0" }, { "code": null, "e": 3894, "s": 3867, "text": "anuragprajapati1 month ago" }, { "code": null, "e": 3910, "s": 3894, "text": "//java solution" }, { "code": null, "e": 4300, "s": 3910, "text": "class Solution { void nextGreatest(int arr[], int n) { // code here int max=arr[n-1]; for(int j=n-1; j>=0; j--){ if(max<arr[j]){ max=max+arr[j]; arr[j]=max-arr[j]; max=max-arr[j]; }else if(arr[j]<max){ arr[j]=max; } } arr[n-1]=-1; }}" }, { "code": null, "e": 4302, "s": 4300, "text": "0" }, { "code": null, "e": 4330, "s": 4302, "text": "alirezachaviwala1 month ago" }, { "code": null, "e": 4387, "s": 4330, "text": "JAVA Solution Time Complexity O(N) Space Complexity O(1)" }, { "code": null, "e": 4619, "s": 4387, "text": "int maxValue=arr[n-1];\n\nfor(int i=n-1;i>=0;i--){\n if(arr[i]>maxValue){\n maxValue+=arr[i];\n arr[i]=maxValue-arr[i];\n maxValue-=arr[i];\n }\n else if(arr[i]<maxValue){\n arr[i]=maxValue;\n }\n}\narr[n-1]=-1;" }, { "code": null, "e": 4621, "s": 4619, "text": "0" }, { "code": null, "e": 4642, "s": 4621, "text": "rakeshklk1 month ago" }, { "code": null, "e": 4659, "s": 4642, "text": "java solution : " }, { "code": null, "e": 4695, "s": 4659, "text": "void nextGreatest(int arr[], int n)" }, { "code": null, "e": 4697, "s": 4695, "text": "{" }, { "code": null, "e": 4719, "s": 4697, "text": " int largest,x,y;" }, { "code": null, "e": 4912, "s": 4719, "text": " for (x =0; x < n; x++) { largest=-1; for (y = x+1; y < n; y++) { if (largest < arr[y]) largest=arr[y]; } arr[x]=largest; }" }, { "code": null, "e": 4914, "s": 4912, "text": "}" }, { "code": null, "e": 5060, "s": 4914, "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": 5096, "s": 5060, "text": " Login to access your submissions. " }, { "code": null, "e": 5106, "s": 5096, "text": "\nProblem\n" }, { "code": null, "e": 5116, "s": 5106, "text": "\nContest\n" }, { "code": null, "e": 5179, "s": 5116, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5364, "s": 5179, "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": 5648, "s": 5364, "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": 5794, "s": 5648, "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": 5871, "s": 5794, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5912, "s": 5871, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5940, "s": 5912, "text": "Disable browser extensions." }, { "code": null, "e": 6011, "s": 5940, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6198, "s": 6011, "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 set cursor position in content-editable element using JavaScript ?
28 Nov, 2019 In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange() method. Approach 1: First, create Range and set position using above syntax. Get user input from input tag using jQuery$("input']").val(); $("input']").val(); On button click assign input value to range function to return cursor position on div. Following syntax explain clearly: Syntax: // document.createRange() creates new range object var rangeobj = document.createRange(); // Here 'rangeobj' is created Range Object var selectobj = window.getSelection(); // Here 'selectobj' is created object for window // get selected or caret current position. // Setting start position of a Range rangeobj.setStart(startNode, startOffset); // Setting End position of a Range rangeobj.setEnd(endNode, endOffset); // Collapses the Range to one of its // boundary points rangeobj.collapse(true); // Removes all ranges from the selection // except Anchor Node and Focus Node selectobj.removeAllRanges(); // Adds a Range to a Selection selectobj.addRange(rangeobj); Example 1: Below example illustrate how to set caret cursor position on content-editable element div based on user input. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> div { outline-color: red; caret-color: red; color: #ddd; width: 550px; text-align: justify; border: 2px solid red; } </style></head> <body> <center> <h1 style="color:green;padding:13px;"> GeeksforGeeeks </h1> <br> <div id="editable" contenteditable="true" spellcheck="false"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format. </div> <br/> <input type="number" name="position" min="0" value="0" max="470" /> <button>Position Cursor</button> </center> <script> function setCursor(pos) { var tag = document.getElementById("editable"); // Creates range object var setpos = document.createRange(); // Creates object for selection var set = window.getSelection(); // Set start position of range setpos.setStart(tag.childNodes[0], pos); // Collapse range within its boundary points // Returns boolean setpos.collapse(true); // Remove all ranges set set.removeAllRanges(); // Add range with respect to range object. set.addRange(setpos); // Set cursor on focus tag.focus(); } $('button').click(function() { var $pos = $("input[name='position']").val(); setCursor($pos); }); </script></body> </html> Output: Before Entering the position: After Entering the position: Approach 2: First create Range and set position using above syntax. On button click trigger function to return cursor position on div. Example 2: Below example illustrates how to set caret cursor position on content-editable element div. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> div { outline-color: red; caret-color: red; color: #ddd; width: 550px; text-align: justify; border: 2px solid red; } </style></head> <body> <center> <h1 style="color:green;padding:13px;"> GeeksforGeeeks </h1> <br> <div id="editable" contenteditable="true" spellcheck="false"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format. </div> <br/> <button>Position Cursor</button> </center> <script> function positionCursor() { var tag = document.getElementById("editable"); // Creates range object var setpos = document.createRange(); // Creates object for selection var set = window.getSelection(); // Set start position of range setpos.setStart(tag.childNodes[0], 12); // Collapse range within its boundary points // Returns boolean setpos.collapse(true); // Remove all ranges set set.removeAllRanges(); // Add range with respect to range object. set.addRange(setpos); // Set cursor on focus tag.focus(); } $('button').click(function() { positionCursor(); }); </script></body> </html> Output: Before Clicking the Button: After Clicking the Button: Reference: https://developer.mozilla.org/en-US/docs/Web/API/Range JavaScript-Misc jQuery-Misc Picked 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": "\n28 Nov, 2019" }, { "code": null, "e": 213, "s": 28, "text": "In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange() method." }, { "code": null, "e": 225, "s": 213, "text": "Approach 1:" }, { "code": null, "e": 282, "s": 225, "text": "First, create Range and set position using above syntax." }, { "code": null, "e": 345, "s": 282, "text": "Get user input from input tag using jQuery$(\"input']\").val();\n" }, { "code": null, "e": 366, "s": 345, "text": "$(\"input']\").val();\n" }, { "code": null, "e": 453, "s": 366, "text": "On button click assign input value to range function to return cursor position on div." }, { "code": null, "e": 487, "s": 453, "text": "Following syntax explain clearly:" }, { "code": null, "e": 495, "s": 487, "text": "Syntax:" }, { "code": null, "e": 1167, "s": 495, "text": "// document.createRange() creates new range object\nvar rangeobj = document.createRange();\n\n// Here 'rangeobj' is created Range Object\nvar selectobj = window.getSelection();\n\n// Here 'selectobj' is created object for window\n// get selected or caret current position.\n// Setting start position of a Range\nrangeobj.setStart(startNode, startOffset);\n\n// Setting End position of a Range\nrangeobj.setEnd(endNode, endOffset);\n\n// Collapses the Range to one of its\n// boundary points\nrangeobj.collapse(true);\n\n// Removes all ranges from the selection\n// except Anchor Node and Focus Node\nselectobj.removeAllRanges();\n\n// Adds a Range to a Selection\nselectobj.addRange(rangeobj);\n" }, { "code": null, "e": 1289, "s": 1167, "text": "Example 1: Below example illustrate how to set caret cursor position on content-editable element div based on user input." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> div { outline-color: red; caret-color: red; color: #ddd; width: 550px; text-align: justify; border: 2px solid red; } </style></head> <body> <center> <h1 style=\"color:green;padding:13px;\"> GeeksforGeeeks </h1> <br> <div id=\"editable\" contenteditable=\"true\" spellcheck=\"false\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format. </div> <br/> <input type=\"number\" name=\"position\" min=\"0\" value=\"0\" max=\"470\" /> <button>Position Cursor</button> </center> <script> function setCursor(pos) { var tag = document.getElementById(\"editable\"); // Creates range object var setpos = document.createRange(); // Creates object for selection var set = window.getSelection(); // Set start position of range setpos.setStart(tag.childNodes[0], pos); // Collapse range within its boundary points // Returns boolean setpos.collapse(true); // Remove all ranges set set.removeAllRanges(); // Add range with respect to range object. set.addRange(setpos); // Set cursor on focus tag.focus(); } $('button').click(function() { var $pos = $(\"input[name='position']\").val(); setCursor($pos); }); </script></body> </html>", "e": 3711, "s": 1289, "text": null }, { "code": null, "e": 3719, "s": 3711, "text": "Output:" }, { "code": null, "e": 3749, "s": 3719, "text": "Before Entering the position:" }, { "code": null, "e": 3778, "s": 3749, "text": "After Entering the position:" }, { "code": null, "e": 3790, "s": 3778, "text": "Approach 2:" }, { "code": null, "e": 3846, "s": 3790, "text": "First create Range and set position using above syntax." }, { "code": null, "e": 3913, "s": 3846, "text": "On button click trigger function to return cursor position on div." }, { "code": null, "e": 4016, "s": 3913, "text": "Example 2: Below example illustrates how to set caret cursor position on content-editable element div." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> div { outline-color: red; caret-color: red; color: #ddd; width: 550px; text-align: justify; border: 2px solid red; } </style></head> <body> <center> <h1 style=\"color:green;padding:13px;\"> GeeksforGeeeks </h1> <br> <div id=\"editable\" contenteditable=\"true\" spellcheck=\"false\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. Markup language is used to define the text document within tag which defines the structure of web pages. HTML is a markup language which is used by the browser to manipulate text, images and other content to display it in required format. </div> <br/> <button>Position Cursor</button> </center> <script> function positionCursor() { var tag = document.getElementById(\"editable\"); // Creates range object var setpos = document.createRange(); // Creates object for selection var set = window.getSelection(); // Set start position of range setpos.setStart(tag.childNodes[0], 12); // Collapse range within its boundary points // Returns boolean setpos.collapse(true); // Remove all ranges set set.removeAllRanges(); // Add range with respect to range object. set.addRange(setpos); // Set cursor on focus tag.focus(); } $('button').click(function() { positionCursor(); }); </script></body> </html>", "e": 6307, "s": 4016, "text": null }, { "code": null, "e": 6315, "s": 6307, "text": "Output:" }, { "code": null, "e": 6343, "s": 6315, "text": "Before Clicking the Button:" }, { "code": null, "e": 6370, "s": 6343, "text": "After Clicking the Button:" }, { "code": null, "e": 6436, "s": 6370, "text": "Reference: https://developer.mozilla.org/en-US/docs/Web/API/Range" }, { "code": null, "e": 6452, "s": 6436, "text": "JavaScript-Misc" }, { "code": null, "e": 6464, "s": 6452, "text": "jQuery-Misc" }, { "code": null, "e": 6471, "s": 6464, "text": "Picked" }, { "code": null, "e": 6482, "s": 6471, "text": "JavaScript" }, { "code": null, "e": 6499, "s": 6482, "text": "Web Technologies" } ]
Java Program to Write Bytes using ByteStream
14 Sep, 2021 Java Byte streams are used to perform input and output of 8-bit bytes. To write Bytes using BytesStream to a file Java provides a specialized stream for writing files in the file system known as FileOutputStream. This stream provides the basic OutputStream functionality applied for writing the contents of a file. FileOutputStream class is an output stream for writing data to a file. It is a class that belongs to byte streams.The FileOutputStream class extends the OutputStream abstract class.So it inherits all the standard OutputStream functionality for writing to a file.FileOutputStream provides only a low-level interface to writing data. You can create a FileOutputStream from a String pathname or a File object.The FileOutputStream constructors don’t throw a FileNotFoundException. If the specified file doesn’t exist, the FileOutputStream creates the file. The FileOutputStream constructors can throw an IOException if some other I/O error occurs. If the specified file does exist, the FileOutputStream opens it for writing. When you actually call a write() method, the new data overwrites the current contents of the file. To append data to an existing file, use a different constructor that accepts an append flag. Now, discussing these inbuilt methods in order to understand internal working while dealing with file concepts in java. getBytes() Methodwrite() Methodclose() Method getBytes() Method write() Method close() Method Considering them individually, discussing methods for greater understanding. 1. getBytes() Method In order to write into a file, three arises a need to convert the text(content) into an array of bytes before writing it into the file. This method does the role by converting the characters in this String object to an array of byte values. The characters in the string are converted to bytes using the system’s default character encoding scheme. Syntax: public byte[] getBytes() ; Parameter: NA Returns: A byte array that contains the characters of this String 2. write() Method The write(byte[] b) method of FileOutputStream class is used to write b.length bytes from the specified byte array to this file output stream Syntax: public void write(byte[] b) throws IOException ; Parameters: The data Returns: This method does not return any value. 3. close() Method The close() method of FileOutputStream class is used to close the file output stream and releases all system resources associated with this stream. Syntax: public void close() ; Parameter: NA Returns: This method does not return any value. Implementation: Creating an object of the file and passing the local directory path of the file as input. Storing random text into String datatype. Converting a string into a byte array. Write byte data to file output. Close the file using the close() method. Example Java // Java program to write Bytes using ByteStream // Importing classesimport java.io.FileOutputStream;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String args[]) { // Try block to check if any exception/s occur try { // Step 1: Creating object of the file and // passing local directory path of file as input FileOutputStream fout = new FileOutputStream("demo.txt"); // Custom text to be written down in above file // Step 2: Storing text into String datatype String s = "Welcome to GFG! This is an example of Java program to write Bytes using ByteStream."; // Step 3: Converting string into byte array byte b[] = s.getBytes(); // Step 4: Write byte data to file output fout.write(b); // Step 5: Close the file using close() method fout.close(); } // Catch block to handle exceptions catch (IOException e) { // Display and print the exception System.out.println(e); } }} Output: A file is created in the path mentioned named as ‘demo’ with .txt extension After clicking onto this file the desired results are as follows which is the same as the text stored in the string datatype in the above program singghakshay Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 343, "s": 28, "text": "Java Byte streams are used to perform input and output of 8-bit bytes. To write Bytes using BytesStream to a file Java provides a specialized stream for writing files in the file system known as FileOutputStream. This stream provides the basic OutputStream functionality applied for writing the contents of a file." }, { "code": null, "e": 1256, "s": 343, "text": "FileOutputStream class is an output stream for writing data to a file. It is a class that belongs to byte streams.The FileOutputStream class extends the OutputStream abstract class.So it inherits all the standard OutputStream functionality for writing to a file.FileOutputStream provides only a low-level interface to writing data. You can create a FileOutputStream from a String pathname or a File object.The FileOutputStream constructors don’t throw a FileNotFoundException. If the specified file doesn’t exist, the FileOutputStream creates the file. The FileOutputStream constructors can throw an IOException if some other I/O error occurs. If the specified file does exist, the FileOutputStream opens it for writing. When you actually call a write() method, the new data overwrites the current contents of the file. To append data to an existing file, use a different constructor that accepts an append flag." }, { "code": null, "e": 1377, "s": 1256, "text": "Now, discussing these inbuilt methods in order to understand internal working while dealing with file concepts in java. " }, { "code": null, "e": 1423, "s": 1377, "text": "getBytes() Methodwrite() Methodclose() Method" }, { "code": null, "e": 1441, "s": 1423, "text": "getBytes() Method" }, { "code": null, "e": 1456, "s": 1441, "text": "write() Method" }, { "code": null, "e": 1471, "s": 1456, "text": "close() Method" }, { "code": null, "e": 1548, "s": 1471, "text": "Considering them individually, discussing methods for greater understanding." }, { "code": null, "e": 1569, "s": 1548, "text": "1. getBytes() Method" }, { "code": null, "e": 1916, "s": 1569, "text": "In order to write into a file, three arises a need to convert the text(content) into an array of bytes before writing it into the file. This method does the role by converting the characters in this String object to an array of byte values. The characters in the string are converted to bytes using the system’s default character encoding scheme." }, { "code": null, "e": 1924, "s": 1916, "text": "Syntax:" }, { "code": null, "e": 1953, "s": 1924, "text": " public byte[] getBytes() ; " }, { "code": null, "e": 1967, "s": 1953, "text": "Parameter: NA" }, { "code": null, "e": 2033, "s": 1967, "text": "Returns: A byte array that contains the characters of this String" }, { "code": null, "e": 2051, "s": 2033, "text": "2. write() Method" }, { "code": null, "e": 2193, "s": 2051, "text": "The write(byte[] b) method of FileOutputStream class is used to write b.length bytes from the specified byte array to this file output stream" }, { "code": null, "e": 2201, "s": 2193, "text": "Syntax:" }, { "code": null, "e": 2251, "s": 2201, "text": "public void write(byte[] b) throws IOException ; " }, { "code": null, "e": 2272, "s": 2251, "text": "Parameters: The data" }, { "code": null, "e": 2320, "s": 2272, "text": "Returns: This method does not return any value." }, { "code": null, "e": 2338, "s": 2320, "text": "3. close() Method" }, { "code": null, "e": 2486, "s": 2338, "text": "The close() method of FileOutputStream class is used to close the file output stream and releases all system resources associated with this stream." }, { "code": null, "e": 2494, "s": 2486, "text": "Syntax:" }, { "code": null, "e": 2517, "s": 2494, "text": "public void close() ; " }, { "code": null, "e": 2531, "s": 2517, "text": "Parameter: NA" }, { "code": null, "e": 2579, "s": 2531, "text": "Returns: This method does not return any value." }, { "code": null, "e": 2595, "s": 2579, "text": "Implementation:" }, { "code": null, "e": 2685, "s": 2595, "text": "Creating an object of the file and passing the local directory path of the file as input." }, { "code": null, "e": 2727, "s": 2685, "text": "Storing random text into String datatype." }, { "code": null, "e": 2766, "s": 2727, "text": "Converting a string into a byte array." }, { "code": null, "e": 2798, "s": 2766, "text": "Write byte data to file output." }, { "code": null, "e": 2839, "s": 2798, "text": "Close the file using the close() method." }, { "code": null, "e": 2847, "s": 2839, "text": "Example" }, { "code": null, "e": 2852, "s": 2847, "text": "Java" }, { "code": "// Java program to write Bytes using ByteStream // Importing classesimport java.io.FileOutputStream;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String args[]) { // Try block to check if any exception/s occur try { // Step 1: Creating object of the file and // passing local directory path of file as input FileOutputStream fout = new FileOutputStream(\"demo.txt\"); // Custom text to be written down in above file // Step 2: Storing text into String datatype String s = \"Welcome to GFG! This is an example of Java program to write Bytes using ByteStream.\"; // Step 3: Converting string into byte array byte b[] = s.getBytes(); // Step 4: Write byte data to file output fout.write(b); // Step 5: Close the file using close() method fout.close(); } // Catch block to handle exceptions catch (IOException e) { // Display and print the exception System.out.println(e); } }}", "e": 4017, "s": 2852, "text": null }, { "code": null, "e": 4030, "s": 4021, "text": "Output: " }, { "code": null, "e": 4108, "s": 4032, "text": "A file is created in the path mentioned named as ‘demo’ with .txt extension" }, { "code": null, "e": 4256, "s": 4110, "text": "After clicking onto this file the desired results are as follows which is the same as the text stored in the string datatype in the above program" }, { "code": null, "e": 4273, "s": 4260, "text": "singghakshay" }, { "code": null, "e": 4284, "s": 4273, "text": "Java-Files" }, { "code": null, "e": 4291, "s": 4284, "text": "Picked" }, { "code": null, "e": 4296, "s": 4291, "text": "Java" }, { "code": null, "e": 4310, "s": 4296, "text": "Java Programs" }, { "code": null, "e": 4315, "s": 4310, "text": "Java" }, { "code": null, "e": 4413, "s": 4315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4428, "s": 4413, "text": "Stream In Java" }, { "code": null, "e": 4449, "s": 4428, "text": "Introduction to Java" }, { "code": null, "e": 4470, "s": 4449, "text": "Constructors in Java" }, { "code": null, "e": 4489, "s": 4470, "text": "Exceptions in Java" }, { "code": null, "e": 4506, "s": 4489, "text": "Generics in Java" }, { "code": null, "e": 4532, "s": 4506, "text": "Java Programming Examples" }, { "code": null, "e": 4566, "s": 4532, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4613, "s": 4566, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4651, "s": 4613, "text": "Factory method design pattern in Java" } ]
Python | First Non-Empty String in list
15 Mar, 2019 Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the 1st valid element. Let’s discuss certain ways in which we can find the first Non-Empty String. Method #1 : Using next() + list comprehensionThe next function returns the iterator and hence its more efficient that conventional list comprehension and the logic part is handled using list comprehension which checks for the last None value. # Python3 code to demonstrate# First Non-Empty String in list# using next() + list comprehension # initializing listtest_list = ["", "", "Akshat", "Nikhil"] # printing original list print("The original list : " + str(test_list)) # using next() + list comprehension# First Non-Empty String in listres = next(sub for sub in test_list if sub) # printing resultprint("The first non empty string is : " + str(res)) The original list : ['', '', 'Akshat', 'Nikhil'] The first non empty string is : Akshat Method #2 : Using filter()The filter function can be used to find the Non empty strings and the 0th index is returned to get the first string among those. Works only with Python 2. # Python code to demonstrate# First Non-Empty String in list# using filter() # initializing listtest_list = ["", "", "Akshat", "Nikhil"] # printing original list print("The original list : " + str(test_list)) # using filter()# First Non-Empty String in listres = filter(None, test_list)[0] # printing resultprint("The first non empty string is : " + str(res)) The original list : ['', '', 'Akshat', 'Nikhil'] The first non empty string is : Akshat Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON 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": 28, "s": 0, "text": "\n15 Mar, 2019" }, { "code": null, "e": 363, "s": 28, "text": "Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the 1st valid element. Let’s discuss certain ways in which we can find the first Non-Empty String." }, { "code": null, "e": 606, "s": 363, "text": "Method #1 : Using next() + list comprehensionThe next function returns the iterator and hence its more efficient that conventional list comprehension and the logic part is handled using list comprehension which checks for the last None value." }, { "code": "# Python3 code to demonstrate# First Non-Empty String in list# using next() + list comprehension # initializing listtest_list = [\"\", \"\", \"Akshat\", \"Nikhil\"] # printing original list print(\"The original list : \" + str(test_list)) # using next() + list comprehension# First Non-Empty String in listres = next(sub for sub in test_list if sub) # printing resultprint(\"The first non empty string is : \" + str(res))", "e": 1020, "s": 606, "text": null }, { "code": null, "e": 1109, "s": 1020, "text": "The original list : ['', '', 'Akshat', 'Nikhil']\nThe first non empty string is : Akshat\n" }, { "code": null, "e": 1292, "s": 1111, "text": "Method #2 : Using filter()The filter function can be used to find the Non empty strings and the 0th index is returned to get the first string among those. Works only with Python 2." }, { "code": "# Python code to demonstrate# First Non-Empty String in list# using filter() # initializing listtest_list = [\"\", \"\", \"Akshat\", \"Nikhil\"] # printing original list print(\"The original list : \" + str(test_list)) # using filter()# First Non-Empty String in listres = filter(None, test_list)[0] # printing resultprint(\"The first non empty string is : \" + str(res))", "e": 1656, "s": 1292, "text": null }, { "code": null, "e": 1745, "s": 1656, "text": "The original list : ['', '', 'Akshat', 'Nikhil']\nThe first non empty string is : Akshat\n" }, { "code": null, "e": 1766, "s": 1745, "text": "Python list-programs" }, { "code": null, "e": 1773, "s": 1766, "text": "Python" }, { "code": null, "e": 1789, "s": 1773, "text": "Python Programs" }, { "code": null, "e": 1887, "s": 1789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1919, "s": 1887, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1946, "s": 1919, "text": "Python Classes and Objects" }, { "code": null, "e": 1967, "s": 1946, "text": "Python OOPs Concepts" }, { "code": null, "e": 1990, "s": 1967, "text": "Introduction To PYTHON" }, { "code": null, "e": 2046, "s": 1990, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2068, "s": 2046, "text": "Defaultdict in Python" }, { "code": null, "e": 2107, "s": 2068, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2145, "s": 2107, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2182, "s": 2145, "text": "Python Program for Fibonacci numbers" } ]
Overloading of Thread class run() method
04 Oct, 2017 Overloading of run() method is possible. But Thread class start() method can invoke no-argument method. The other overloaded method we have to call explicitly like a normal method call. // Java Program to illustrate the behavior of// run() method overloadingclass Geeks extends Thread { public void run() { System.out.println("GeeksforGeeks"); } public void run(int i) { System.out.println("Bishal"); }} class Test { public static void main(String[] args) { Geeks t = new Geeks(); t.start(); }} Output: GeeksforGeeks Runtime stack provided by JVM for the above program: NOTE : Overloaded run() method will be ignored by the Thread class unless we call it ourselves. The Thread class expect a run() with no-arg and that will execute in a separate call stack after the thread has been started. With run(int i), it will not start any separate call stack even if we call it directly. It will be in the same call stack like any other method (if you call from run() method). Example: // Java Program to illustrate the execution of// program using main threadclass Geeks extends Thread { public void run() { System.out.println("GeeksforGeeks"); } public void run(int i) { System.out.println("Bishal"); }} class Test extends Geeks { public static void main(String[] args) { Geeks t = new Geeks(); t.run(1); }} Output: Bishal Related Article : Overloading Overriding of Thread class start() method This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Oct, 2017" }, { "code": null, "e": 238, "s": 52, "text": "Overloading of run() method is possible. But Thread class start() method can invoke no-argument method. The other overloaded method we have to call explicitly like a normal method call." }, { "code": "// Java Program to illustrate the behavior of// run() method overloadingclass Geeks extends Thread { public void run() { System.out.println(\"GeeksforGeeks\"); } public void run(int i) { System.out.println(\"Bishal\"); }} class Test { public static void main(String[] args) { Geeks t = new Geeks(); t.start(); }}", "e": 604, "s": 238, "text": null }, { "code": null, "e": 612, "s": 604, "text": "Output:" }, { "code": null, "e": 626, "s": 612, "text": "GeeksforGeeks" }, { "code": null, "e": 679, "s": 626, "text": "Runtime stack provided by JVM for the above program:" }, { "code": null, "e": 1078, "s": 679, "text": "NOTE : Overloaded run() method will be ignored by the Thread class unless we call it ourselves. The Thread class expect a run() with no-arg and that will execute in a separate call stack after the thread has been started. With run(int i), it will not start any separate call stack even if we call it directly. It will be in the same call stack like any other method (if you call from run() method)." }, { "code": null, "e": 1087, "s": 1078, "text": "Example:" }, { "code": "// Java Program to illustrate the execution of// program using main threadclass Geeks extends Thread { public void run() { System.out.println(\"GeeksforGeeks\"); } public void run(int i) { System.out.println(\"Bishal\"); }} class Test extends Geeks { public static void main(String[] args) { Geeks t = new Geeks(); t.run(1); }}", "e": 1468, "s": 1087, "text": null }, { "code": null, "e": 1476, "s": 1468, "text": "Output:" }, { "code": null, "e": 1484, "s": 1476, "text": "Bishal\n" }, { "code": null, "e": 1556, "s": 1484, "text": "Related Article : Overloading Overriding of Thread class start() method" }, { "code": null, "e": 1862, "s": 1556, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1987, "s": 1862, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2007, "s": 1987, "text": "Java-Multithreading" }, { "code": null, "e": 2012, "s": 2007, "text": "Java" }, { "code": null, "e": 2017, "s": 2012, "text": "Java" } ]
Decision Making in Java (if, if-else, switch, break, continue, jump)
31 Mar, 2022 Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s Selection statements: if if-else nested-if if-else-if switch-case jump – break, continue, return 1. if: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. Syntax: if(condition) { // Statements to execute if // condition is true } Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it. If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example, if(condition) statement1; statement2; // Here if the condition is true, if block // will consider only statement1 to be inside // its block. Example: Java // Java program to illustrate If statementclass IfDemo { public static void main(String args[]) { int i = 10; if (i > 15) System.out.println("10 is less than 15"); // This statement will be executed // as if considers one statement by default System.out.println("I am Not in if"); }} I am Not in if 2. if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false. Syntax: if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false } Example: Java // Java program to illustrate if-else statementclass IfElseDemo { public static void main(String args[]) { int i = 10; if (i < 15) System.out.println("i is smaller than 15"); else System.out.println("i is greater than 15"); }} i is smaller than 15 Time Complexity: O(1) Auxiliary Space : O(1) 3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement. Syntax: if (condition1) { // Executes when condition1 is true if (condition2) { // Executes when condition2 is true } } Example: Java // Java program to illustrate nested-if statement class NestedIfDemo { public static void main(String args[]) { int i = 10; if (i == 10) { // First if statement if (i < 15) System.out.println("i is smaller than 15"); // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) System.out.println( "i is smaller than 12 too"); else System.out.println("i is greater than 15"); } }} i is smaller than 15 i is smaller than 12 too Time Complexity: O(1) Auxiliary Space : O(1) 4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if (condition) statement; else if (condition) statement; . . else statement; Example: Java // Java program to illustrate if-else-if ladder class ifelseifDemo { public static void main(String args[]) { int i = 20; if (i == 10) System.out.println("i is 10"); else if (i == 15) System.out.println("i is 15"); else if (i == 20) System.out.println("i is 20"); else System.out.println("i is not present"); }} i is 20 Time Complexity: O(1) Auxiliary Space : O(1) 5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Syntax: switch (expression) { case value1: statement1; break; case value2: statement2; break; . . case valueN: statementN; break; default: statementDefault; } The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7, expression can also be of type String. Duplicate case values are not allowed. The default statement is optional. The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. 6. jump: Java supports three jump statements: break, continue and return. These three statements transfer control to another part of the program. Break: In Java, a break is majorly used for: Terminate a sequence in a switch statement (discussed above).To exit a loop.Used as a “civilized” form of goto. Terminate a sequence in a switch statement (discussed above). To exit a loop. Used as a “civilized” form of goto. Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action. Example: Java // Java program to illustrate using// continue in an if statementclass ContinueDemo { public static void main(String args[]) { for (int i = 0; i < 10; i++) { // If the number is even // skip and continue if (i % 2 == 0) continue; // If number is odd, print it System.out.print(i + " "); } }} 1 3 5 7 9 Time Complexity: O(1) Auxiliary Space : O(1) Return: The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. Example: Java // Java program to illustrate using returnclass Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if (t) return; // Compiler will bypass every statement // after return System.out.println("This won't execute."); }} Before the return. Time Complexity: O(1) Auxiliary Space : O(1) This article is contributed by Anuj Chauhan and Harsh Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sonamchawla vrk-19 nishkarshgandhi rishavnitro java-basics Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Mar, 2022" }, { "code": null, "e": 256, "s": 52, "text": "Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. " }, { "code": null, "e": 491, "s": 256, "text": "A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. " }, { "code": null, "e": 521, "s": 491, "text": "Java’s Selection statements: " }, { "code": null, "e": 524, "s": 521, "text": "if" }, { "code": null, "e": 532, "s": 524, "text": "if-else" }, { "code": null, "e": 542, "s": 532, "text": "nested-if" }, { "code": null, "e": 553, "s": 542, "text": "if-else-if" }, { "code": null, "e": 565, "s": 553, "text": "switch-case" }, { "code": null, "e": 596, "s": 565, "text": "jump – break, continue, return" }, { "code": null, "e": 847, "s": 596, "text": "1. if: if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. " }, { "code": null, "e": 856, "s": 847, "text": "Syntax: " }, { "code": null, "e": 930, "s": 856, "text": "if(condition) \n{\n // Statements to execute if\n // condition is true\n}" }, { "code": null, "e": 1292, "s": 930, "text": "Here, the condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it. If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example, " }, { "code": null, "e": 1442, "s": 1292, "text": "if(condition)\n statement1;\n statement2;\n\n// Here if the condition is true, if block \n// will consider only statement1 to be inside \n// its block." }, { "code": null, "e": 1451, "s": 1442, "text": "Example:" }, { "code": null, "e": 1456, "s": 1451, "text": "Java" }, { "code": "// Java program to illustrate If statementclass IfDemo { public static void main(String args[]) { int i = 10; if (i > 15) System.out.println(\"10 is less than 15\"); // This statement will be executed // as if considers one statement by default System.out.println(\"I am Not in if\"); }}", "e": 1797, "s": 1456, "text": null }, { "code": null, "e": 1812, "s": 1797, "text": "I am Not in if" }, { "code": null, "e": 2166, "s": 1812, "text": "2. if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false. " }, { "code": null, "e": 2175, "s": 2166, "text": "Syntax: " }, { "code": null, "e": 2314, "s": 2175, "text": "if (condition)\n{\n // Executes this block if\n // condition is true\n}\nelse\n{\n // Executes this block if\n // condition is false\n}" }, { "code": null, "e": 2323, "s": 2314, "text": "Example:" }, { "code": null, "e": 2328, "s": 2323, "text": "Java" }, { "code": "// Java program to illustrate if-else statementclass IfElseDemo { public static void main(String args[]) { int i = 10; if (i < 15) System.out.println(\"i is smaller than 15\"); else System.out.println(\"i is greater than 15\"); }}", "e": 2608, "s": 2328, "text": null }, { "code": null, "e": 2629, "s": 2608, "text": "i is smaller than 15" }, { "code": null, "e": 2651, "s": 2629, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2674, "s": 2651, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 2955, "s": 2674, "text": "3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement. " }, { "code": null, "e": 2964, "s": 2955, "text": "Syntax: " }, { "code": null, "e": 3096, "s": 2964, "text": "if (condition1) \n{\n // Executes when condition1 is true\n if (condition2) \n {\n // Executes when condition2 is true\n }\n}" }, { "code": null, "e": 3105, "s": 3096, "text": "Example:" }, { "code": null, "e": 3110, "s": 3105, "text": "Java" }, { "code": "// Java program to illustrate nested-if statement class NestedIfDemo { public static void main(String args[]) { int i = 10; if (i == 10) { // First if statement if (i < 15) System.out.println(\"i is smaller than 15\"); // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) System.out.println( \"i is smaller than 12 too\"); else System.out.println(\"i is greater than 15\"); } }}", "e": 3698, "s": 3110, "text": null }, { "code": null, "e": 3744, "s": 3698, "text": "i is smaller than 15\ni is smaller than 12 too" }, { "code": null, "e": 3766, "s": 3744, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3789, "s": 3766, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 4144, "s": 3789, "text": "4. if-else-if ladder: Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. " }, { "code": null, "e": 4233, "s": 4144, "text": "if (condition)\n statement;\nelse if (condition)\n statement;\n.\n.\nelse\n statement;" }, { "code": null, "e": 4242, "s": 4233, "text": "Example:" }, { "code": null, "e": 4247, "s": 4242, "text": "Java" }, { "code": "// Java program to illustrate if-else-if ladder class ifelseifDemo { public static void main(String args[]) { int i = 20; if (i == 10) System.out.println(\"i is 10\"); else if (i == 15) System.out.println(\"i is 15\"); else if (i == 20) System.out.println(\"i is 20\"); else System.out.println(\"i is not present\"); }}", "e": 4648, "s": 4247, "text": null }, { "code": null, "e": 4656, "s": 4648, "text": "i is 20" }, { "code": null, "e": 4678, "s": 4656, "text": "Time Complexity: O(1)" }, { "code": null, "e": 4701, "s": 4678, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 4882, "s": 4701, "text": "5. switch-case: The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. " }, { "code": null, "e": 4891, "s": 4882, "text": "Syntax: " }, { "code": null, "e": 5082, "s": 4891, "text": "switch (expression)\n{\n case value1:\n statement1;\n break;\n case value2:\n statement2;\n break;\n .\n .\n case valueN:\n statementN;\n break;\n default:\n statementDefault;\n}" }, { "code": null, "e": 5214, "s": 5082, "text": "The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7, expression can also be of type String." }, { "code": null, "e": 5253, "s": 5214, "text": "Duplicate case values are not allowed." }, { "code": null, "e": 5288, "s": 5253, "text": "The default statement is optional." }, { "code": null, "e": 5369, "s": 5288, "text": "The break statement is used inside the switch to terminate a statement sequence." }, { "code": null, "e": 5461, "s": 5369, "text": "The break statement is optional. If omitted, execution will continue on into the next case." }, { "code": null, "e": 5608, "s": 5461, "text": "6. jump: Java supports three jump statements: break, continue and return. These three statements transfer control to another part of the program. " }, { "code": null, "e": 5765, "s": 5608, "text": "Break: In Java, a break is majorly used for: Terminate a sequence in a switch statement (discussed above).To exit a loop.Used as a “civilized” form of goto." }, { "code": null, "e": 5827, "s": 5765, "text": "Terminate a sequence in a switch statement (discussed above)." }, { "code": null, "e": 5843, "s": 5827, "text": "To exit a loop." }, { "code": null, "e": 5879, "s": 5843, "text": "Used as a “civilized” form of goto." }, { "code": null, "e": 6221, "s": 5879, "text": "Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action. " }, { "code": null, "e": 6230, "s": 6221, "text": "Example:" }, { "code": null, "e": 6235, "s": 6230, "text": "Java" }, { "code": "// Java program to illustrate using// continue in an if statementclass ContinueDemo { public static void main(String args[]) { for (int i = 0; i < 10; i++) { // If the number is even // skip and continue if (i % 2 == 0) continue; // If number is odd, print it System.out.print(i + \" \"); } }}", "e": 6621, "s": 6235, "text": null }, { "code": null, "e": 6632, "s": 6621, "text": "1 3 5 7 9 " }, { "code": null, "e": 6654, "s": 6632, "text": "Time Complexity: O(1)" }, { "code": null, "e": 6677, "s": 6654, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 6831, "s": 6677, "text": "Return: The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method." }, { "code": null, "e": 6840, "s": 6831, "text": "Example:" }, { "code": null, "e": 6845, "s": 6840, "text": "Java" }, { "code": "// Java program to illustrate using returnclass Return { public static void main(String args[]) { boolean t = true; System.out.println(\"Before the return.\"); if (t) return; // Compiler will bypass every statement // after return System.out.println(\"This won't execute.\"); }}", "e": 7184, "s": 6845, "text": null }, { "code": null, "e": 7203, "s": 7184, "text": "Before the return." }, { "code": null, "e": 7225, "s": 7203, "text": "Time Complexity: O(1)" }, { "code": null, "e": 7248, "s": 7225, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 7689, "s": 7248, "text": "This article is contributed by Anuj Chauhan and Harsh Aggarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7701, "s": 7689, "text": "sonamchawla" }, { "code": null, "e": 7708, "s": 7701, "text": "vrk-19" }, { "code": null, "e": 7724, "s": 7708, "text": "nishkarshgandhi" }, { "code": null, "e": 7736, "s": 7724, "text": "rishavnitro" }, { "code": null, "e": 7748, "s": 7736, "text": "java-basics" }, { "code": null, "e": 7753, "s": 7748, "text": "Java" }, { "code": null, "e": 7772, "s": 7753, "text": "School Programming" }, { "code": null, "e": 7777, "s": 7772, "text": "Java" }, { "code": null, "e": 7875, "s": 7777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7919, "s": 7875, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7955, "s": 7919, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7980, "s": 7955, "text": "Reverse a string in Java" }, { "code": null, "e": 8011, "s": 7980, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8026, "s": 8011, "text": "Stream In Java" }, { "code": null, "e": 8044, "s": 8026, "text": "Python Dictionary" }, { "code": null, "e": 8069, "s": 8044, "text": "Reverse a string in Java" }, { "code": null, "e": 8085, "s": 8069, "text": "Arrays in C/C++" }, { "code": null, "e": 8108, "s": 8085, "text": "Introduction To PYTHON" } ]
Python | Scipy integrate.cumtrapz() method
23 Jan, 2020 With the help of scipy.integrate.cumtrapz() method, we can get the cumulative integrated value of y(x) using composite trapezoidal rule by using scipy.integrate.cumtrapz() method. Syntax : scipy.integrate.cumtrapz()Return : Return the cumulative integrated value of y(x). Example #1 :In this example we can see that by using scipy.integrate.cumtrapz() method, we are able to get the cumulative integration of y(x) using trapezoidal rule by using this method. # import numpy and scipy.integrate.cumtrapzimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.arange(0, 10)# using scipy.integrate.cumtrapz() methodgfg = integrate.cumtrapz(y, x) print(gfg) Output : [0.5 2. 4.5 8. 12.5 18. 24.5 32. 40.5] Example #2 : # import numpy and scipy.integrate.cumtrapzimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.power(x, 2)# using scipy.integrate.cumtrapz() methodgfg = integrate.cumtrapz(y, x) print(gfg) Output : [0.5 3. 9.5 22. 42.5 73. 115.5 172. 244.5] Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2020" }, { "code": null, "e": 208, "s": 28, "text": "With the help of scipy.integrate.cumtrapz() method, we can get the cumulative integrated value of y(x) using composite trapezoidal rule by using scipy.integrate.cumtrapz() method." }, { "code": null, "e": 300, "s": 208, "text": "Syntax : scipy.integrate.cumtrapz()Return : Return the cumulative integrated value of y(x)." }, { "code": null, "e": 487, "s": 300, "text": "Example #1 :In this example we can see that by using scipy.integrate.cumtrapz() method, we are able to get the cumulative integration of y(x) using trapezoidal rule by using this method." }, { "code": "# import numpy and scipy.integrate.cumtrapzimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.arange(0, 10)# using scipy.integrate.cumtrapz() methodgfg = integrate.cumtrapz(y, x) print(gfg)", "e": 701, "s": 487, "text": null }, { "code": null, "e": 710, "s": 701, "text": "Output :" }, { "code": null, "e": 749, "s": 710, "text": "[0.5 2. 4.5 8. 12.5 18. 24.5 32. 40.5]" }, { "code": null, "e": 762, "s": 749, "text": "Example #2 :" }, { "code": "# import numpy and scipy.integrate.cumtrapzimport numpy as npfrom scipy import integrate x = np.arange(0, 10)y = np.power(x, 2)# using scipy.integrate.cumtrapz() methodgfg = integrate.cumtrapz(y, x) print(gfg)", "e": 974, "s": 762, "text": null }, { "code": null, "e": 983, "s": 974, "text": "Output :" }, { "code": null, "e": 1026, "s": 983, "text": "[0.5 3. 9.5 22. 42.5 73. 115.5 172. 244.5]" }, { "code": null, "e": 1039, "s": 1026, "text": "Python-scipy" }, { "code": null, "e": 1046, "s": 1039, "text": "Python" } ]
Graph measurements: length, distance, diameter, eccentricity, radius, center
31 May, 2021 Prerequisite – Graph Theory Basics – Set 1, Set 2 A graph is defined as set of points known as ‘Vertices’ and line joining these points is known as ‘Edges’. It is a set consisting of where ‘V’ is vertices and ‘E’ is edge. Vertices: {A, B, C, D, E, F} Edges: {{A, B}, {A, D}, {A, E}, {B, C}, {C, E}, {C, F}, {D, E}, {E, F}} Graph Measurements: There are few graph measurement methods available: 1. Length – Length of the graph is defined as the number of edges contained in the graph. Length of the graph: 8 AB, BC, CD, DE, EF, FA, AC, CE 2. The distance between two Vertices – The distance between two vertices in a graph is the number of edges in a shortest or minimal path. It gives the available minimum distance between two edges. There can exist more than one shortest path between two vertices. Shortest Distance between 1 - 5 is 2 1 → 2 → 5 3. Diameter of graph – The diameter of graph is the maximum distance between the pair of vertices. It can also be defined as the maximal distance between the pair of vertices. Way to solve it is to find all the paths and then find the maximum of all. Diameter: 3 BC → CF → FG 4. Radius of graph –A radius of the graph exists only if it has the diameter. The minimum among all the maximum distances between a vertex to all other vertices is considered as the radius of the Graph G.It is denoted as r(G). Radius: 2 All available minimum radius: BC → CF, BC → CE, BC → CD, BC → CA 5. Centre of graph – It consists of all the vertices whose eccentricity is minimum. Here the eccentricity is equal to the radius. For example, if the school is at the centre of town it will reduce the distance buses has to travel. Centre: A 6. Eccentricity of graph – It is defined as the maximum distance of one vertex from other vertex.The maximum distance between a vertex to all other vertices is considered as the eccentricity of the vertex. It is denoted by e(V). Eccentricity from: (A, A) = 0 (A, B) = 1 (A, C) = 2 (A, D) = 1 Maximum value is 2, So Eccentricity is 2 VaibhavRai3 ysachin2314 Discrete Mathematics Picked Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2021" }, { "code": null, "e": 275, "s": 52, "text": "Prerequisite – Graph Theory Basics – Set 1, Set 2 A graph is defined as set of points known as ‘Vertices’ and line joining these points is known as ‘Edges’. It is a set consisting of where ‘V’ is vertices and ‘E’ is edge. " }, { "code": null, "e": 379, "s": 277, "text": "Vertices: {A, B, C, D, E, F} Edges: {{A, B}, {A, D}, {A, E}, {B, C}, {C, E}, {C, F}, {D, E}, {E, F}} " }, { "code": null, "e": 451, "s": 379, "text": "Graph Measurements: There are few graph measurement methods available: " }, { "code": null, "e": 542, "s": 451, "text": "1. Length – Length of the graph is defined as the number of edges contained in the graph. " }, { "code": null, "e": 601, "s": 546, "text": "Length of the graph: 8\nAB, BC, CD, DE, EF, FA, AC, CE " }, { "code": null, "e": 865, "s": 601, "text": "2. The distance between two Vertices – The distance between two vertices in a graph is the number of edges in a shortest or minimal path. It gives the available minimum distance between two edges. There can exist more than one shortest path between two vertices. " }, { "code": null, "e": 917, "s": 869, "text": "Shortest Distance between 1 - 5 is 2\n1 → 2 → 5 " }, { "code": null, "e": 1169, "s": 917, "text": "3. Diameter of graph – The diameter of graph is the maximum distance between the pair of vertices. It can also be defined as the maximal distance between the pair of vertices. Way to solve it is to find all the paths and then find the maximum of all. " }, { "code": null, "e": 1200, "s": 1173, "text": "Diameter: 3\nBC → CF → FG " }, { "code": null, "e": 1428, "s": 1200, "text": "4. Radius of graph –A radius of the graph exists only if it has the diameter. The minimum among all the maximum distances between a vertex to all other vertices is considered as the radius of the Graph G.It is denoted as r(G). " }, { "code": null, "e": 1508, "s": 1432, "text": "Radius: 2\nAll available minimum radius: \nBC → CF,\nBC → CE,\nBC → CD,\nBC → CA" }, { "code": null, "e": 1740, "s": 1508, "text": "5. Centre of graph – It consists of all the vertices whose eccentricity is minimum. Here the eccentricity is equal to the radius. For example, if the school is at the centre of town it will reduce the distance buses has to travel. " }, { "code": null, "e": 1756, "s": 1744, "text": "Centre: A " }, { "code": null, "e": 1986, "s": 1756, "text": "6. Eccentricity of graph – It is defined as the maximum distance of one vertex from other vertex.The maximum distance between a vertex to all other vertices is considered as the eccentricity of the vertex. It is denoted by e(V). " }, { "code": null, "e": 2095, "s": 1990, "text": "Eccentricity from:\n(A, A) = 0\n(A, B) = 1\n(A, C) = 2\n(A, D) = 1\nMaximum value is 2, So Eccentricity is 2" }, { "code": null, "e": 2109, "s": 2097, "text": "VaibhavRai3" }, { "code": null, "e": 2121, "s": 2109, "text": "ysachin2314" }, { "code": null, "e": 2142, "s": 2121, "text": "Discrete Mathematics" }, { "code": null, "e": 2149, "s": 2142, "text": "Picked" }, { "code": null, "e": 2173, "s": 2149, "text": "Engineering Mathematics" }, { "code": null, "e": 2181, "s": 2173, "text": "GATE CS" }, { "code": null, "e": 2279, "s": 2181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2301, "s": 2279, "text": "Inequalities in LaTeX" }, { "code": null, "e": 2360, "s": 2301, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 2383, "s": 2360, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 2406, "s": 2383, "text": "Set Notations in LaTeX" }, { "code": null, "e": 2427, "s": 2406, "text": "Activation Functions" }, { "code": null, "e": 2447, "s": 2427, "text": "Layers of OSI Model" }, { "code": null, "e": 2471, "s": 2447, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2484, "s": 2471, "text": "TCP/IP Model" }, { "code": null, "e": 2511, "s": 2484, "text": "Types of Operating Systems" } ]
Python Program For Rearranging An Array In Maximum Minimum Form – Set 2 (O(1) extra space)
31 May, 2022 Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3} We have discussed a solution in below post: Rearrange an array in maximum minimum form | Set 1 : The solution discussed here requires extra space, how to solve this problem with O(1) extra space. In this post a solution that requires O(n) time and O(1) extra space is discussed. The idea is to use multiplication and modular trick to store two elements at an index. even index : remaining maximum element. odd index : remaining minimum element. max_index : Index of remaining maximum element (Moves from right to left) min_index : Index of remaining minimum element (Moves from left to right) Initialize: max_index = 'n-1' min_index = 0 // Can be any element which is more than // the maximum value in array max_element = arr[max_index] + 1 For i = 0 to n-1 If 'i' is even arr[i] += (arr[max_index] % max_element * max_element) max_index-- // if 'i' is odd ELSE arr[i] += (arr[min_index] % max_element * max_element) min_index++ How does expression “arr[i] += arr[max_index] % max_element * max_element” work ? The purpose of this expression is to store two elements at index arr[i]. arr[max_index] is stored as multiplier and “arr[i]” is stored as remainder. For example in {1 2 3 4 5 6 7 8 9}, max_element is 10 and we store 91 at index 0. With 91, we can get original element as 91%10 and new element as 91/10.Below implementation of above idea: Python3 # Python3 program to rearrange an# array in minimum maximum form # Prints max at first position, min at# second position second max at third# position, second min at fourth# position and so on.def rearrange(arr, n): # Initialize index of first minimum # and first maximum element max_idx = n - 1 min_idx = 0 # Store maximum element of array max_elem = arr[n-1] + 1 # Traverse array elements for i in range(0, n) : # At even index : we have to put # maximum element if i % 2 == 0 : arr[i] += ((arr[max_idx] % max_elem ) * max_elem) max_idx -= 1 # At odd index : we have to put # minimum element else : arr[i] += ((arr[min_idx] % max_elem ) * max_elem) min_idx += 1 # Array elements back to it's original form for i in range(0, n) : arr[i] = arr[i] / max_elem # Driver Codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr) print ("Original Array") for i in range(0, n): print (arr[i], end = " ") rearrange(arr, n) print ("Modified Array")for i in range(0, n): print (int(arr[i]), end = " ")# This code is contributed by Shreyanshi Arun. Output : Original Array 1 2 3 4 5 6 7 8 9 Modified Array 9 1 8 2 7 3 6 4 5 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach. Another Approach: A simpler approach will be to observe indexing positioning of maximum elements and minimum elements. The even index stores maximum elements and the odd index stores the minimum elements. With every increasing index, the maximum element decreases by one and the minimum element increases by one. A simple traversal can be done and arr[] can be filled in again.Note: This approach is only valid when elements of given sorted array are consecutive i.e., vary by one unit.Below is the implementation of the above approach: Python3 # Python 3 program to rearrange an# array in minimum maximum form # Prints max at first position, min# at second position second max at# third position, second min at# fourth position and so on.def rearrange(arr, n): # initialize index of first minimum # and first maximum element max_ele = arr[n - 1] min_ele = arr[0] # traverse array elements for i in range(n): # at even index : we have to # put maximum element if i % 2 == 0: arr[i] = max_ele max_ele -= 1 # at odd index : we have to # put minimum element else: arr[i] = min_ele min_ele += 1 # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr)print("Original Array")for i in range(n): print(arr[i], end = " ") rearrange(arr, n)print("Modified Array")for i in range(n): print(arr[i], end = " ")# This code is contributed by Shrikant13 Output : Original Array 1 2 3 4 5 6 7 8 9 Modified Array 9 1 8 2 7 3 6 4 5 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. Please refer complete article on Rearrange an array in maximum minimum form | Set 2 (O(1) extra space) for more details! rohitsingh07052 array-rearrange Modular Arithmetic Zoho Arrays Python Programs Sorting Zoho Arrays Sorting Modular Arithmetic 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 What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 229, "s": 28, "text": "Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:" }, { "code": null, "e": 373, "s": 229, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3} " }, { "code": null, "e": 569, "s": 373, "text": "We have discussed a solution in below post: Rearrange an array in maximum minimum form | Set 1 : The solution discussed here requires extra space, how to solve this problem with O(1) extra space." }, { "code": null, "e": 739, "s": 569, "text": "In this post a solution that requires O(n) time and O(1) extra space is discussed. The idea is to use multiplication and modular trick to store two elements at an index." }, { "code": null, "e": 1483, "s": 739, "text": "even index : remaining maximum element.\nodd index : remaining minimum element.\n \nmax_index : Index of remaining maximum element\n (Moves from right to left)\nmin_index : Index of remaining minimum element\n (Moves from left to right)\n\nInitialize: max_index = 'n-1'\n min_index = 0 \n\n // Can be any element which is more than\n // the maximum value in array\n max_element = arr[max_index] + 1 \n\nFor i = 0 to n-1 \n If 'i' is even\n arr[i] += (arr[max_index] % max_element * \n max_element) \n max_index-- \n\n // if 'i' is odd \n ELSE \n arr[i] += (arr[min_index] % max_element * \n max_element)\n min_index++" }, { "code": null, "e": 1903, "s": 1483, "text": "How does expression “arr[i] += arr[max_index] % max_element * max_element” work ? The purpose of this expression is to store two elements at index arr[i]. arr[max_index] is stored as multiplier and “arr[i]” is stored as remainder. For example in {1 2 3 4 5 6 7 8 9}, max_element is 10 and we store 91 at index 0. With 91, we can get original element as 91%10 and new element as 91/10.Below implementation of above idea:" }, { "code": null, "e": 1911, "s": 1903, "text": "Python3" }, { "code": "# Python3 program to rearrange an# array in minimum maximum form # Prints max at first position, min at# second position second max at third# position, second min at fourth# position and so on.def rearrange(arr, n): # Initialize index of first minimum # and first maximum element max_idx = n - 1 min_idx = 0 # Store maximum element of array max_elem = arr[n-1] + 1 # Traverse array elements for i in range(0, n) : # At even index : we have to put # maximum element if i % 2 == 0 : arr[i] += ((arr[max_idx] % max_elem ) * max_elem) max_idx -= 1 # At odd index : we have to put # minimum element else : arr[i] += ((arr[min_idx] % max_elem ) * max_elem) min_idx += 1 # Array elements back to it's original form for i in range(0, n) : arr[i] = arr[i] / max_elem # Driver Codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr) print (\"Original Array\") for i in range(0, n): print (arr[i], end = \" \") rearrange(arr, n) print (\"Modified Array\")for i in range(0, n): print (int(arr[i]), end = \" \")# This code is contributed by Shreyanshi Arun.", "e": 3127, "s": 1911, "text": null }, { "code": null, "e": 3137, "s": 3127, "text": "Output : " }, { "code": null, "e": 3205, "s": 3137, "text": "Original Array\n1 2 3 4 5 6 7 8 9 \nModified Array\n9 1 8 2 7 3 6 4 5 " }, { "code": null, "e": 3272, "s": 3205, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 3332, "s": 3272, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 3944, "s": 3332, "text": "Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach. Another Approach: A simpler approach will be to observe indexing positioning of maximum elements and minimum elements. The even index stores maximum elements and the odd index stores the minimum elements. With every increasing index, the maximum element decreases by one and the minimum element increases by one. A simple traversal can be done and arr[] can be filled in again.Note: This approach is only valid when elements of given sorted array are consecutive i.e., vary by one unit.Below is the implementation of the above approach:" }, { "code": null, "e": 3952, "s": 3944, "text": "Python3" }, { "code": "# Python 3 program to rearrange an# array in minimum maximum form # Prints max at first position, min# at second position second max at# third position, second min at# fourth position and so on.def rearrange(arr, n): # initialize index of first minimum # and first maximum element max_ele = arr[n - 1] min_ele = arr[0] # traverse array elements for i in range(n): # at even index : we have to # put maximum element if i % 2 == 0: arr[i] = max_ele max_ele -= 1 # at odd index : we have to # put minimum element else: arr[i] = min_ele min_ele += 1 # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr)print(\"Original Array\")for i in range(n): print(arr[i], end = \" \") rearrange(arr, n)print(\"Modified Array\")for i in range(n): print(arr[i], end = \" \")# This code is contributed by Shrikant13", "e": 4869, "s": 3952, "text": null }, { "code": null, "e": 4879, "s": 4869, "text": "Output : " }, { "code": null, "e": 4947, "s": 4879, "text": "Original Array\n1 2 3 4 5 6 7 8 9 \nModified Array\n9 1 8 2 7 3 6 4 5 " }, { "code": null, "e": 5014, "s": 4947, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 5074, "s": 5014, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 5195, "s": 5074, "text": "Please refer complete article on Rearrange an array in maximum minimum form | Set 2 (O(1) extra space) for more details!" }, { "code": null, "e": 5211, "s": 5195, "text": "rohitsingh07052" }, { "code": null, "e": 5227, "s": 5211, "text": "array-rearrange" }, { "code": null, "e": 5246, "s": 5227, "text": "Modular Arithmetic" }, { "code": null, "e": 5251, "s": 5246, "text": "Zoho" }, { "code": null, "e": 5258, "s": 5251, "text": "Arrays" }, { "code": null, "e": 5274, "s": 5258, "text": "Python Programs" }, { "code": null, "e": 5282, "s": 5274, "text": "Sorting" }, { "code": null, "e": 5287, "s": 5282, "text": "Zoho" }, { "code": null, "e": 5294, "s": 5287, "text": "Arrays" }, { "code": null, "e": 5302, "s": 5294, "text": "Sorting" }, { "code": null, "e": 5321, "s": 5302, "text": "Modular Arithmetic" }, { "code": null, "e": 5419, "s": 5321, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5451, "s": 5419, "text": "Introduction to Data Structures" }, { "code": null, "e": 5476, "s": 5451, "text": "Window Sliding Technique" }, { "code": null, "e": 5523, "s": 5476, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 5587, "s": 5523, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 5618, "s": 5587, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 5661, "s": 5618, "text": "Python program to convert a list to string" }, { "code": null, "e": 5683, "s": 5661, "text": "Defaultdict in Python" }, { "code": null, "e": 5722, "s": 5683, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 5760, "s": 5722, "text": "Python | Convert a list to dictionary" } ]
Convert Ternary Expression to a Binary Tree
12 Jul, 2022 Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree. Examples: Input : string expression = a?b:c Output : a / \ b c Input : expression = a?b?c:d:e Output : a / \ b e / \ c d Asked In : Facebook Interview Idea is that we traverse a string make first character as root and do following step recursively . If we see Symbol ‘?’ then we add next character as the left child of root. If we see Symbol ‘:’ then we add it as the right child of current root. If we see Symbol ‘?’ then we add next character as the left child of root. then we add next character as the left child of root. If we see Symbol ‘:’ then we add it as the right child of current root. then we add it as the right child of current root. do this process until we traverse all element of “String”. Below is the implementation of above idea C++ Java Python3 C# Javascript // C++ program to convert a ternary expression to// a tree.#include<bits/stdc++.h>using namespace std; // tree structurestruct Node{ char data; Node *left, *right;}; // function create a new nodeNode *newNode(char Data){ Node *new_node = new Node; new_node->data = Data; new_node->left = new_node->right = NULL; return new_node;} // Function to convert Ternary Expression to a Binary// Tree. It return the root of tree// Notice that we pass index i by reference because we // want to skip the characters in the subtreeNode *convertExpression(string str, int & i){ // store current character of expression_string // [ 'a' to 'z'] Node * root =newNode(str[i]); //If it was last character return //Base Case if(i==str.length()-1) return root; // Move ahead in str i++; //If the next character is '?'.Then there will be subtree for the current node if(str[i]=='?') { //skip the '?' i++; // construct the left subtree // Notice after the below recursive call i will point to ':' // just before the right child of current node since we pass i by reference root->left = convertExpression(str,i); //skip the ':' character i++; //construct the right subtree root->right = convertExpression(str,i); return root; } //If the next character is not '?' no subtree just return it else return root;} // function print treevoid printTree( Node *root){ if (!root) return ; cout << root->data <<" "; printTree(root->left); printTree(root->right);} // Driver program to test above functionint main(){ string expression = "a?b?c:d:e"; int i=0; Node *root = convertExpression(expression, i); printTree(root) ; return 0;} // Java program to convert a ternary // expression to a tree.import java.util.Queue;import java.util.LinkedList; // Class to represent Tree node class Node { char data; Node left, right; public Node(char item) { data = item; left = null; right = null; }} // Class to convert a ternary expression to a Tree class BinaryTree { // Function to convert Ternary Expression to a Binary // Tree. It return the root of tree Node convertExpression(char[] expression, int i) { // Base case if (i >= expression.length) return null; // store current character of expression_string // [ 'a' to 'z'] Node root = new Node(expression[i]); // Move ahead in str ++i; // if current character of ternary expression is '?' // then we add next character as a left child of // current node if (i < expression.length && expression[i]=='?') root.left = convertExpression(expression, i+1); // else we have to add it as a right child of // current node expression.at(0) == ':' else if (i < expression.length) root.right = convertExpression(expression, i+1); return root; } // function print tree public void printTree( Node root) { if (root == null) return; System.out.print(root.data +" "); printTree(root.left); printTree(root.right); } // Driver program to test above function public static void main(String args[]) { String exp = "a?b?c:d:e"; BinaryTree tree = new BinaryTree(); char[] expression=exp.toCharArray(); Node root = tree.convertExpression(expression, 0); tree.printTree(root) ; }} /* This code is contributed by Mr. Somesh Awasthi */ # Class to define a node # structure of the treeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to convert ternary # expression to a Binary tree# It returns the root node # of the treedef convert_expression(expression, i): if i >= len(expression): return None # Create a new node object # for the expression at # ith index root = Node(expression[i]) i += 1 # if current character of # ternary expression is '?' # then we add next character # as a left child of # current node if (i < len(expression) and expression[i] is "?"): root.left = convert_expression(expression, i + 1) # else we have to add it # as a right child of # current node expression[0] == ':' elif i < len(expression): root.right = convert_expression(expression, i + 1) return root # Function to print the tree# in a pre-order traversal patterndef print_tree(root): if not root: return print(root.data, end=' ') print_tree(root.left) print_tree(root.right) # Driver Codeif __name__ == "__main__": string_expression = "a?b?c:d:e" root_node = convert_expression(string_expression, 0) print_tree(root_node) # This code is contributed# by Kanav Malhotra // C# program to convert a ternary // expression to a tree. using System; // Class to represent Tree node public class Node{ public char data; public Node left, right; public Node(char item) { data = item; left = null; right = null; }} // Class to convert a ternary // expression to a Tree public class BinaryTree{ // Function to convert Ternary Expression // to a Binary Tree. It return the root of tree public virtual Node convertExpression(char[] expression, int i) { // Base case if (i >= expression.Length) { return null; } // store current character of // expression_string [ 'a' to 'z'] Node root = new Node(expression[i]); // Move ahead in str ++i; // if current character of ternary expression // is '?' then we add next character as a // left child of current node if (i < expression.Length && expression[i] == '?') { root.left = convertExpression(expression, i + 1); } // else we have to add it as a right child // of current node expression.at(0) == ':' else if (i < expression.Length) { root.right = convertExpression(expression, i + 1); } return root; } // function print tree public virtual void printTree(Node root) { if (root == null) { return; } Console.Write(root.data + " "); printTree(root.left); printTree(root.right); } // Driver Codepublic static void Main(string[] args){ string exp = "a?b?c:d:e"; BinaryTree tree = new BinaryTree(); char[] expression = exp.ToCharArray(); Node root = tree.convertExpression(expression, 0); tree.printTree(root);}} // This code is contributed by Shrikant13 <script> // Javascript program to convert a ternary // expreesion to a tree. // Class to represent Tree node class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} // Function to convert Ternary Expression // to a Binary Tree. It return the root of tree function convertExpression(expression, i){ // Base case if (i >= expression.length) { return null; } // Store current character of // expression_string [ 'a' to 'z'] var root = new Node(expression[i]); // Move ahead in str ++i; // If current character of ternary expression // is '?' then we add next character as a // left child of current node if (i < expression.length && expression[i] == '?') { root.left = convertExpression(expression, i + 1); } // Else we have to add it as a right child // of current node expression.at(0) == ':' else if (i < expression.length) { root.right = convertExpression(expression, i + 1); } return root;} // Function print tree function printTree(root){ if (root == null) { return; } document.write(root.data + " "); printTree(root.left); printTree(root.right);} // Driver codevar exp = "a?b?c:d:e";var expression = exp.split('');var root = convertExpression(expression, 0);printTree(root); // This code is contributed by noob2000 </script> a b c d e Time Complexity : O(n) [ here n is length of String ]Auxiliary Space: O(n) This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. kanavMalhotra shrikanth13 satish_kumar nidhi_biet noob2000 simmytarika5 mailaruyashaswi Facebook Strings Tree Facebook Strings Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2022" }, { "code": null, "e": 199, "s": 54, "text": "Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree. " }, { "code": null, "e": 210, "s": 199, "text": "Examples: " }, { "code": null, "e": 413, "s": 210, "text": "Input : string expression = a?b:c \nOutput : a\n / \\\n b c\n\nInput : expression = a?b?c:d:e\nOutput : a\n / \\\n b e\n / \\\n c d" }, { "code": null, "e": 443, "s": 413, "text": "Asked In : Facebook Interview" }, { "code": null, "e": 543, "s": 443, "text": "Idea is that we traverse a string make first character as root and do following step recursively . " }, { "code": null, "e": 691, "s": 543, "text": "If we see Symbol ‘?’ then we add next character as the left child of root. If we see Symbol ‘:’ then we add it as the right child of current root. " }, { "code": null, "e": 767, "s": 691, "text": "If we see Symbol ‘?’ then we add next character as the left child of root. " }, { "code": null, "e": 822, "s": 767, "text": "then we add next character as the left child of root. " }, { "code": null, "e": 895, "s": 822, "text": "If we see Symbol ‘:’ then we add it as the right child of current root. " }, { "code": null, "e": 947, "s": 895, "text": "then we add it as the right child of current root. " }, { "code": null, "e": 1007, "s": 947, "text": "do this process until we traverse all element of “String”. " }, { "code": null, "e": 1051, "s": 1007, "text": "Below is the implementation of above idea " }, { "code": null, "e": 1055, "s": 1051, "text": "C++" }, { "code": null, "e": 1060, "s": 1055, "text": "Java" }, { "code": null, "e": 1068, "s": 1060, "text": "Python3" }, { "code": null, "e": 1071, "s": 1068, "text": "C#" }, { "code": null, "e": 1082, "s": 1071, "text": "Javascript" }, { "code": "// C++ program to convert a ternary expression to// a tree.#include<bits/stdc++.h>using namespace std; // tree structurestruct Node{ char data; Node *left, *right;}; // function create a new nodeNode *newNode(char Data){ Node *new_node = new Node; new_node->data = Data; new_node->left = new_node->right = NULL; return new_node;} // Function to convert Ternary Expression to a Binary// Tree. It return the root of tree// Notice that we pass index i by reference because we // want to skip the characters in the subtreeNode *convertExpression(string str, int & i){ // store current character of expression_string // [ 'a' to 'z'] Node * root =newNode(str[i]); //If it was last character return //Base Case if(i==str.length()-1) return root; // Move ahead in str i++; //If the next character is '?'.Then there will be subtree for the current node if(str[i]=='?') { //skip the '?' i++; // construct the left subtree // Notice after the below recursive call i will point to ':' // just before the right child of current node since we pass i by reference root->left = convertExpression(str,i); //skip the ':' character i++; //construct the right subtree root->right = convertExpression(str,i); return root; } //If the next character is not '?' no subtree just return it else return root;} // function print treevoid printTree( Node *root){ if (!root) return ; cout << root->data <<\" \"; printTree(root->left); printTree(root->right);} // Driver program to test above functionint main(){ string expression = \"a?b?c:d:e\"; int i=0; Node *root = convertExpression(expression, i); printTree(root) ; return 0;}", "e": 2879, "s": 1082, "text": null }, { "code": "// Java program to convert a ternary // expression to a tree.import java.util.Queue;import java.util.LinkedList; // Class to represent Tree node class Node { char data; Node left, right; public Node(char item) { data = item; left = null; right = null; }} // Class to convert a ternary expression to a Tree class BinaryTree { // Function to convert Ternary Expression to a Binary // Tree. It return the root of tree Node convertExpression(char[] expression, int i) { // Base case if (i >= expression.length) return null; // store current character of expression_string // [ 'a' to 'z'] Node root = new Node(expression[i]); // Move ahead in str ++i; // if current character of ternary expression is '?' // then we add next character as a left child of // current node if (i < expression.length && expression[i]=='?') root.left = convertExpression(expression, i+1); // else we have to add it as a right child of // current node expression.at(0) == ':' else if (i < expression.length) root.right = convertExpression(expression, i+1); return root; } // function print tree public void printTree( Node root) { if (root == null) return; System.out.print(root.data +\" \"); printTree(root.left); printTree(root.right); } // Driver program to test above function public static void main(String args[]) { String exp = \"a?b?c:d:e\"; BinaryTree tree = new BinaryTree(); char[] expression=exp.toCharArray(); Node root = tree.convertExpression(expression, 0); tree.printTree(root) ; }} /* This code is contributed by Mr. Somesh Awasthi */", "e": 4760, "s": 2879, "text": null }, { "code": "# Class to define a node # structure of the treeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to convert ternary # expression to a Binary tree# It returns the root node # of the treedef convert_expression(expression, i): if i >= len(expression): return None # Create a new node object # for the expression at # ith index root = Node(expression[i]) i += 1 # if current character of # ternary expression is '?' # then we add next character # as a left child of # current node if (i < len(expression) and expression[i] is \"?\"): root.left = convert_expression(expression, i + 1) # else we have to add it # as a right child of # current node expression[0] == ':' elif i < len(expression): root.right = convert_expression(expression, i + 1) return root # Function to print the tree# in a pre-order traversal patterndef print_tree(root): if not root: return print(root.data, end=' ') print_tree(root.left) print_tree(root.right) # Driver Codeif __name__ == \"__main__\": string_expression = \"a?b?c:d:e\" root_node = convert_expression(string_expression, 0) print_tree(root_node) # This code is contributed# by Kanav Malhotra", "e": 6091, "s": 4760, "text": null }, { "code": "// C# program to convert a ternary // expression to a tree. using System; // Class to represent Tree node public class Node{ public char data; public Node left, right; public Node(char item) { data = item; left = null; right = null; }} // Class to convert a ternary // expression to a Tree public class BinaryTree{ // Function to convert Ternary Expression // to a Binary Tree. It return the root of tree public virtual Node convertExpression(char[] expression, int i) { // Base case if (i >= expression.Length) { return null; } // store current character of // expression_string [ 'a' to 'z'] Node root = new Node(expression[i]); // Move ahead in str ++i; // if current character of ternary expression // is '?' then we add next character as a // left child of current node if (i < expression.Length && expression[i] == '?') { root.left = convertExpression(expression, i + 1); } // else we have to add it as a right child // of current node expression.at(0) == ':' else if (i < expression.Length) { root.right = convertExpression(expression, i + 1); } return root; } // function print tree public virtual void printTree(Node root) { if (root == null) { return; } Console.Write(root.data + \" \"); printTree(root.left); printTree(root.right); } // Driver Codepublic static void Main(string[] args){ string exp = \"a?b?c:d:e\"; BinaryTree tree = new BinaryTree(); char[] expression = exp.ToCharArray(); Node root = tree.convertExpression(expression, 0); tree.printTree(root);}} // This code is contributed by Shrikant13", "e": 7990, "s": 6091, "text": null }, { "code": "<script> // Javascript program to convert a ternary // expreesion to a tree. // Class to represent Tree node class Node{ constructor(item) { this.data = item; this.left = null; this.right = null; }} // Function to convert Ternary Expression // to a Binary Tree. It return the root of tree function convertExpression(expression, i){ // Base case if (i >= expression.length) { return null; } // Store current character of // expression_string [ 'a' to 'z'] var root = new Node(expression[i]); // Move ahead in str ++i; // If current character of ternary expression // is '?' then we add next character as a // left child of current node if (i < expression.length && expression[i] == '?') { root.left = convertExpression(expression, i + 1); } // Else we have to add it as a right child // of current node expression.at(0) == ':' else if (i < expression.length) { root.right = convertExpression(expression, i + 1); } return root;} // Function print tree function printTree(root){ if (root == null) { return; } document.write(root.data + \" \"); printTree(root.left); printTree(root.right);} // Driver codevar exp = \"a?b?c:d:e\";var expression = exp.split('');var root = convertExpression(expression, 0);printTree(root); // This code is contributed by noob2000 </script>", "e": 9440, "s": 7990, "text": null }, { "code": null, "e": 9451, "s": 9440, "text": "a b c d e " }, { "code": null, "e": 9526, "s": 9451, "text": "Time Complexity : O(n) [ here n is length of String ]Auxiliary Space: O(n)" }, { "code": null, "e": 9824, "s": 9526, "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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9838, "s": 9824, "text": "kanavMalhotra" }, { "code": null, "e": 9850, "s": 9838, "text": "shrikanth13" }, { "code": null, "e": 9863, "s": 9850, "text": "satish_kumar" }, { "code": null, "e": 9874, "s": 9863, "text": "nidhi_biet" }, { "code": null, "e": 9883, "s": 9874, "text": "noob2000" }, { "code": null, "e": 9896, "s": 9883, "text": "simmytarika5" }, { "code": null, "e": 9912, "s": 9896, "text": "mailaruyashaswi" }, { "code": null, "e": 9921, "s": 9912, "text": "Facebook" }, { "code": null, "e": 9929, "s": 9921, "text": "Strings" }, { "code": null, "e": 9934, "s": 9929, "text": "Tree" }, { "code": null, "e": 9943, "s": 9934, "text": "Facebook" }, { "code": null, "e": 9951, "s": 9943, "text": "Strings" }, { "code": null, "e": 9956, "s": 9951, "text": "Tree" } ]
Closures in Java with Examples
26 Jul, 2021 A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python. In this article, we will understand one type of functions named closures. Before getting into the closures, lets first understand what a lambda expression is. A lambda expression basically expresses instances of the functional interfaces(An interface with a single abstract method is called a functional interface). An example is java.lang.Runnable. Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide below functionalities: Enable to treat functionality as a method argument, or code as data.A function that can be created without belonging to any class.A lambda expression can be passed around as if it was an object and executed on demand. Enable to treat functionality as a method argument, or code as data. A function that can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand. The main limitation of the lambda expression is that the scope for the lambda expressions will only be final. That is, we cant change the value of the variables in the lambda expressions. Suppose we define a lambda expression in which we increment the value of a variable, it simply throws an error. In order to solve this error, the closures have been defined. Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function. But as of Java 1.6, Java does not rely on closures or java does not have closures. Also, anonymous inner classes are not closures in Java. Using closures helps in data privacy and currying (currying means breaking a function with many parameters as a number of functions in a single argument). Though the concept of closure is much more well defined in Javascript, the closures can still be implemented using lambda expressions. The syntax to implement a closure is: (argument_list) -> {func_body} Now, let’s understand how to implement the closures with examples: Example 1: In this example, we will first implement a lambda expression without a parameter or an argument. Java // Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface SalutationInterface { public String salHello();} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression SalutationInterface obj = () -> { return "Hello, GFGians!"; }; // Calling the above interface System.out.println(obj.salHello()); }} Hello, GFGians! Example 2: In this example, we will understand how to implement the lambda expression which takes multiple parameters. Java // Java program to demonstrate// how a closure is implemented// using lambda expressionsimport java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface concatStrings { public String concat(String a, String b);} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression concatStrings s = (s1, s2) -> s1 + s2; System.out.println( s.concat("Hello, ", "GFGians!")); }} Hello, GFGians! Example 3: In this example, we are going to use a custom functional interface to display the month from the number provided. Java // Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface NumToMonth { public String convertToMonth(int x);} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression NumToMonth obj = new NumToMonth() { String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; public String convertToMonth(int n) { return (n > 0 && n <= months.length) ? months[n - 1] : null; }; }; System.out.println(obj.convertToMonth(8)); }} Aug rolf6 Functions Java 8 java-lambda Java Java Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2021" }, { "code": null, "e": 903, "s": 28, "text": "A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python. In this article, we will understand one type of functions named closures. Before getting into the closures, lets first understand what a lambda expression is. A lambda expression basically expresses instances of the functional interfaces(An interface with a single abstract method is called a functional interface). An example is java.lang.Runnable. Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide below functionalities: " }, { "code": null, "e": 1121, "s": 903, "text": "Enable to treat functionality as a method argument, or code as data.A function that can be created without belonging to any class.A lambda expression can be passed around as if it was an object and executed on demand." }, { "code": null, "e": 1190, "s": 1121, "text": "Enable to treat functionality as a method argument, or code as data." }, { "code": null, "e": 1253, "s": 1190, "text": "A function that can be created without belonging to any class." }, { "code": null, "e": 1341, "s": 1253, "text": "A lambda expression can be passed around as if it was an object and executed on demand." }, { "code": null, "e": 2425, "s": 1341, "text": "The main limitation of the lambda expression is that the scope for the lambda expressions will only be final. That is, we cant change the value of the variables in the lambda expressions. Suppose we define a lambda expression in which we increment the value of a variable, it simply throws an error. In order to solve this error, the closures have been defined. Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function. But as of Java 1.6, Java does not rely on closures or java does not have closures. Also, anonymous inner classes are not closures in Java. Using closures helps in data privacy and currying (currying means breaking a function with many parameters as a number of functions in a single argument). Though the concept of closure is much more well defined in Javascript, the closures can still be implemented using lambda expressions. The syntax to implement a closure is: " }, { "code": null, "e": 2456, "s": 2425, "text": "(argument_list) -> {func_body}" }, { "code": null, "e": 2524, "s": 2456, "text": "Now, let’s understand how to implement the closures with examples: " }, { "code": null, "e": 2636, "s": 2526, "text": "Example 1: In this example, we will first implement a lambda expression without a parameter or an argument. " }, { "code": null, "e": 2641, "s": 2636, "text": "Java" }, { "code": "// Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface SalutationInterface { public String salHello();} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression SalutationInterface obj = () -> { return \"Hello, GFGians!\"; }; // Calling the above interface System.out.println(obj.salHello()); }}", "e": 3221, "s": 2641, "text": null }, { "code": null, "e": 3237, "s": 3221, "text": "Hello, GFGians!" }, { "code": null, "e": 3360, "s": 3239, "text": "Example 2: In this example, we will understand how to implement the lambda expression which takes multiple parameters. " }, { "code": null, "e": 3365, "s": 3360, "text": "Java" }, { "code": "// Java program to demonstrate// how a closure is implemented// using lambda expressionsimport java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface concatStrings { public String concat(String a, String b);} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression concatStrings s = (s1, s2) -> s1 + s2; System.out.println( s.concat(\"Hello, \", \"GFGians!\")); }}", "e": 3951, "s": 3365, "text": null }, { "code": null, "e": 3967, "s": 3951, "text": "Hello, GFGians!" }, { "code": null, "e": 4095, "s": 3969, "text": "Example 3: In this example, we are going to use a custom functional interface to display the month from the number provided. " }, { "code": null, "e": 4100, "s": 4095, "text": "Java" }, { "code": "// Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface NumToMonth { public String convertToMonth(int x);} class GFG { // Driver code public static void main(String[] args) { // Lambda Expression NumToMonth obj = new NumToMonth() { String[] months = { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" }; public String convertToMonth(int n) { return (n > 0 && n <= months.length) ? months[n - 1] : null; }; }; System.out.println(obj.convertToMonth(8)); }}", "e": 5009, "s": 4100, "text": null }, { "code": null, "e": 5013, "s": 5009, "text": "Aug" }, { "code": null, "e": 5023, "s": 5017, "text": "rolf6" }, { "code": null, "e": 5033, "s": 5023, "text": "Functions" }, { "code": null, "e": 5040, "s": 5033, "text": "Java 8" }, { "code": null, "e": 5052, "s": 5040, "text": "java-lambda" }, { "code": null, "e": 5057, "s": 5052, "text": "Java" }, { "code": null, "e": 5062, "s": 5057, "text": "Java" }, { "code": null, "e": 5072, "s": 5062, "text": "Functions" }, { "code": null, "e": 5170, "s": 5072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5185, "s": 5170, "text": "Stream In Java" }, { "code": null, "e": 5206, "s": 5185, "text": "Introduction to Java" }, { "code": null, "e": 5227, "s": 5206, "text": "Constructors in Java" }, { "code": null, "e": 5246, "s": 5227, "text": "Exceptions in Java" }, { "code": null, "e": 5263, "s": 5246, "text": "Generics in Java" }, { "code": null, "e": 5293, "s": 5263, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5319, "s": 5293, "text": "Java Programming Examples" }, { "code": null, "e": 5335, "s": 5319, "text": "Strings in Java" }, { "code": null, "e": 5372, "s": 5335, "text": "Differences between JDK, JRE and JVM" } ]
Spring Data JPA – @Table Annotation
29 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss how to add table names to Spring Boot Project. @Table(), the JPA annotation is used for adding the table name in the particular MySQL database. Syntax: @Entity @Table(name=”Student”) public class Student { ... } Attribute: Name: The name of the table. It is an optional attribute. The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table. For now, we are using just the table name which is EMPLOYEE. @Entity @Table(name = "EMPLOYEE") public class Employee { @Id @GeneratedValue @Column(name = "id") private int id; } Step 1: Go to this link. Fill in the details as per the requirements. For this application: Project: Maven Language: Java Spring Boot: 2.5.6 Packaging: JAR Java: 11 Dependencies: Spring Web,Spring Data JPA, MySql Driver Click on Generate which will download the starter project. Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Mapping and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows: Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name) spring.datasource.username=root spring.datasource.password=Aayush spring.datasource.url=jdbc:mysql://localhost:3306/mapping spring.jpa.hibernate.ddl-auto=update Step 4: Create a model folder in the project folder and make a StudentInformation class. ProjectStrucuture: StudentInformation.java Java package com.example.Mapping.Models; import java.util.*;import javax.persistence.*; @Entity// Adding the table name@Table(name = "Student")public class StudentInformation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }} Run the main application: Database output: Java-Spring-Data-JPA Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Abstraction in Java HashSet in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 629, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss how to add table names to Spring Boot Project. @Table(), the JPA annotation is used for adding the table name in the particular MySQL database. " }, { "code": null, "e": 637, "s": 629, "text": "Syntax:" }, { "code": null, "e": 645, "s": 637, "text": "@Entity" }, { "code": null, "e": 668, "s": 645, "text": "@Table(name=”Student”)" }, { "code": null, "e": 693, "s": 668, "text": "public class Student { " }, { "code": null, "e": 699, "s": 693, "text": "... " }, { "code": null, "e": 701, "s": 699, "text": "}" }, { "code": null, "e": 712, "s": 701, "text": "Attribute:" }, { "code": null, "e": 770, "s": 712, "text": "Name: The name of the table. It is an optional attribute." }, { "code": null, "e": 1138, "s": 770, "text": "The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table. For now, we are using just the table name which is EMPLOYEE." }, { "code": null, "e": 1264, "s": 1138, "text": "@Entity\n@Table(name = \"EMPLOYEE\")\npublic class Employee {\n @Id @GeneratedValue\n @Column(name = \"id\")\n private int id;\n}" }, { "code": null, "e": 1356, "s": 1264, "text": "Step 1: Go to this link. Fill in the details as per the requirements. For this application:" }, { "code": null, "e": 1484, "s": 1356, "text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.5.6\nPackaging: JAR\nJava: 11\nDependencies: Spring Web,Spring Data JPA, MySql Driver" }, { "code": null, "e": 1543, "s": 1484, "text": "Click on Generate which will download the starter project." }, { "code": null, "e": 1794, "s": 1543, "text": "Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Mapping and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:" }, { "code": null, "e": 1901, "s": 1794, "text": "Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name)" }, { "code": null, "e": 2062, "s": 1901, "text": "spring.datasource.username=root\nspring.datasource.password=Aayush\nspring.datasource.url=jdbc:mysql://localhost:3306/mapping\nspring.jpa.hibernate.ddl-auto=update" }, { "code": null, "e": 2151, "s": 2062, "text": "Step 4: Create a model folder in the project folder and make a StudentInformation class." }, { "code": null, "e": 2170, "s": 2151, "text": "ProjectStrucuture:" }, { "code": null, "e": 2194, "s": 2170, "text": "StudentInformation.java" }, { "code": null, "e": 2199, "s": 2194, "text": "Java" }, { "code": "package com.example.Mapping.Models; import java.util.*;import javax.persistence.*; @Entity// Adding the table name@Table(name = \"Student\")public class StudentInformation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int rollno; private String name; public int getRollno() { return rollno; } public StudentInformation() {} public StudentInformation(int rollno, String name) { this.rollno = rollno; this.name = name; } public void setRollno(int rollno) { this.rollno = rollno; } public String getName() { return name; } public void setName(String name) { this.name = name; }}", "e": 2874, "s": 2199, "text": null }, { "code": null, "e": 2900, "s": 2874, "text": "Run the main application:" }, { "code": null, "e": 2917, "s": 2900, "text": "Database output:" }, { "code": null, "e": 2938, "s": 2917, "text": "Java-Spring-Data-JPA" }, { "code": null, "e": 2943, "s": 2938, "text": "Java" }, { "code": null, "e": 2948, "s": 2943, "text": "Java" }, { "code": null, "e": 3046, "s": 2948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3061, "s": 3046, "text": "Stream In Java" }, { "code": null, "e": 3082, "s": 3061, "text": "Introduction to Java" }, { "code": null, "e": 3103, "s": 3082, "text": "Constructors in Java" }, { "code": null, "e": 3122, "s": 3103, "text": "Exceptions in Java" }, { "code": null, "e": 3139, "s": 3122, "text": "Generics in Java" }, { "code": null, "e": 3169, "s": 3139, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3195, "s": 3169, "text": "Java Programming Examples" }, { "code": null, "e": 3211, "s": 3195, "text": "Strings in Java" }, { "code": null, "e": 3231, "s": 3211, "text": "Abstraction in Java" } ]
C | Dynamic Memory Allocation | Question 7
28 Jun, 2021 What is the problem with following code? #include<stdio.h>int main(){ int *p = (int *)malloc(sizeof(int)); p = NULL; free(p);} (A) Compiler Error: free can’t be applied on NULL pointer(B) Memory Leak(C) Dangling Pointer(D) The program may crash as free() is called for NULL pointer.Answer: (B)Explanation: free() can be called for NULL pointer, so no problem with free function call. The problem is memory leak, p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be following: free(p); p = NULL; Quiz of this Question C-Dynamic Memory Allocation Dynamic Memory Allocation C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Storage Classes and Type Qualifiers | Question 1 Output of C programs | Set 64 (Pointers) C | File Handling | Question 1
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2021" }, { "code": null, "e": 94, "s": 53, "text": "What is the problem with following code?" }, { "code": "#include<stdio.h>int main(){ int *p = (int *)malloc(sizeof(int)); p = NULL; free(p);}", "e": 193, "s": 94, "text": null }, { "code": null, "e": 450, "s": 193, "text": "(A) Compiler Error: free can’t be applied on NULL pointer(B) Memory Leak(C) Dangling Pointer(D) The program may crash as free() is called for NULL pointer.Answer: (B)Explanation: free() can be called for NULL pointer, so no problem with free function call." }, { "code": null, "e": 604, "s": 450, "text": "The problem is memory leak, p is allocated some memory which is not freed, but the pointer is assigned as NULL. The correct sequence should be following:" }, { "code": null, "e": 632, "s": 604, "text": " free(p);\n p = NULL;\n" }, { "code": null, "e": 654, "s": 632, "text": "Quiz of this Question" }, { "code": null, "e": 682, "s": 654, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 708, "s": 682, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 719, "s": 708, "text": "C Language" }, { "code": null, "e": 726, "s": 719, "text": "C Quiz" }, { "code": null, "e": 824, "s": 726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 841, "s": 824, "text": "Substring in C++" }, { "code": null, "e": 863, "s": 841, "text": "Function Pointer in C" }, { "code": null, "e": 909, "s": 863, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 954, "s": 909, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 979, "s": 954, "text": "std::string class in C++" }, { "code": null, "e": 1021, "s": 979, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 1064, "s": 1021, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 1117, "s": 1064, "text": "C | Storage Classes and Type Qualifiers | Question 1" }, { "code": null, "e": 1158, "s": 1117, "text": "Output of C programs | Set 64 (Pointers)" } ]
HTTP headers | Date
18 Oct, 2019 Description:HTTP headers are used to pass additional information with HTTP response or HTTP request. Date HTTP header contains the date and time at which the message was generated. It is supported by all the browsers. Syntax: Date: day-name, day month year hour:minute:second GMT Directives: day-name: It is case sensitive directive and specifies the day name when message was generated. The values it can have “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, or “Sun” as value. day: It specifies the day of month in 2 digit format. It can have values ranging from ’00’ to ’31’. For ex. 01, 21, 29 month: It specifies the month name and is case sensitive. It can have “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec” as value. year: It specifies the year in 4 digit format. For ex 2019, 2018. hour: It specifies hour in 24 hour, 2 digit format. It can have values ranging from ’00’ to ’23’. For ex. 10, 21 minute: It specifies minute in 2 digit format. It can have values ranging from ’00’ to ’59’. For ex. 05, 21 second: It specifies second in 2 digit format. It can have values ranging from ’00’ to ’59’. For ex. 05, 21 GMT: GMT stands for Greenwich mean time. Example: Date: Wed, 16 Oct 2019 07:28:00 GMT Supported Browsers: The browsers compatible with HTTP headers date are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 246, "s": 28, "text": "Description:HTTP headers are used to pass additional information with HTTP response or HTTP request. Date HTTP header contains the date and time at which the message was generated. It is supported by all the browsers." }, { "code": null, "e": 254, "s": 246, "text": "Syntax:" }, { "code": null, "e": 308, "s": 254, "text": "Date: day-name, day month year hour:minute:second GMT" }, { "code": null, "e": 320, "s": 308, "text": "Directives:" }, { "code": null, "e": 500, "s": 320, "text": "day-name: It is case sensitive directive and specifies the day name when message was generated. The values it can have “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, or “Sun” as value." }, { "code": null, "e": 619, "s": 500, "text": "day: It specifies the day of month in 2 digit format. It can have values ranging from ’00’ to ’31’. For ex. 01, 21, 29" }, { "code": null, "e": 782, "s": 619, "text": "month: It specifies the month name and is case sensitive. It can have “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec” as value." }, { "code": null, "e": 848, "s": 782, "text": "year: It specifies the year in 4 digit format. For ex 2019, 2018." }, { "code": null, "e": 961, "s": 848, "text": "hour: It specifies hour in 24 hour, 2 digit format. It can have values ranging from ’00’ to ’23’. For ex. 10, 21" }, { "code": null, "e": 1069, "s": 961, "text": "minute: It specifies minute in 2 digit format. It can have values ranging from ’00’ to ’59’. For ex. 05, 21" }, { "code": null, "e": 1177, "s": 1069, "text": "second: It specifies second in 2 digit format. It can have values ranging from ’00’ to ’59’. For ex. 05, 21" }, { "code": null, "e": 1218, "s": 1177, "text": "GMT: GMT stands for Greenwich mean time." }, { "code": null, "e": 1227, "s": 1218, "text": "Example:" }, { "code": null, "e": 1264, "s": 1227, "text": "Date: Wed, 16 Oct 2019 07:28:00 GMT " }, { "code": null, "e": 1349, "s": 1264, "text": "Supported Browsers: The browsers compatible with HTTP headers date are listed below:" }, { "code": null, "e": 1363, "s": 1349, "text": "Google Chrome" }, { "code": null, "e": 1381, "s": 1363, "text": "Internet Explorer" }, { "code": null, "e": 1389, "s": 1381, "text": "Firefox" }, { "code": null, "e": 1396, "s": 1389, "text": "Safari" }, { "code": null, "e": 1402, "s": 1396, "text": "Opera" }, { "code": null, "e": 1415, "s": 1402, "text": "HTTP-headers" }, { "code": null, "e": 1422, "s": 1415, "text": "Picked" }, { "code": null, "e": 1439, "s": 1422, "text": "Web Technologies" }, { "code": null, "e": 1537, "s": 1439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1598, "s": 1537, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1641, "s": 1598, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1713, "s": 1641, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1753, "s": 1713, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1777, "s": 1753, "text": "REST API (Introduction)" }, { "code": null, "e": 1810, "s": 1777, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1868, "s": 1810, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 1928, "s": 1868, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1989, "s": 1928, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Top 50 Software Engineering Interview Questions and Answers
11 Nov, 2021 Software Engineering is indeed a must-to-go field for every individual who aspires to make a successful career as a Software Engineer, Software Developer, etc. in the IT industry. In simple words, it is concerned with the systematic and comprehensive study of designing, development, operations, and maintenance of a software system. In tech interviews of almost every renowned tech company, recruiters asked various questions from Software Engineering concepts such as Software Development Models & Architecture, Software Project Management (SPM), Testing and Debugging, etc. to assess the candidates. Hence, you must be prepared for all such Software Engineering Interview Questions to ace the interview. We know that Software Engineering is a vast field in itself and to find out & prepare for all the important concepts or questions for interviews is not an easy job. So, to make it easier and convenient for you, here, we’re providing you with an extensive list of Commonly Asked Software Engineering Interview Questions that are often asked by the recruiters. Do check out all these questions from below: 1. What is software re-engineering? Software reengineering is the process of scanning, modifying, and reconfiguring a system in a new way. The principle of reengineering applied to the software development process is called software reengineering. It has a positive impact on software cost, quality, customer service, and shipping speed. Software reengineering improves software to create it more efficiently and effectively. For more details please refer to What Is Software Re-Engineering?. 2. What are the characteristics of Software? There are various characteristics of software: Software is developed or engineered; it is not manufactured in the classical sense:Although some similarities exist between software development and hardware manufacturing, few activities are fundamentally different.In both activities, high quality is achieved through good design, but the manufacturing phase for hardware can introduce quality problems than software. Although some similarities exist between software development and hardware manufacturing, few activities are fundamentally different. In both activities, high quality is achieved through good design, but the manufacturing phase for hardware can introduce quality problems than software. The software doesn’t “wear out.”:Hardware components suffer from the growing effects of many other environmental factors. Stated simply, the hardware begins to wear out.Software is not susceptible to the environmental maladies that cause hardware to wear out.When a hardware component wears out, it is replaced by a spare part.There are no software spare parts.Every software failure indicates an error in design or in the process through which design was translated into machine-executable code. Therefore, the software maintenance tasks that accommodate requests for change involve considerably more complexity than hardware maintenance. However, the implication is clear—the software doesn’t wear out. But it does deteriorate. Hardware components suffer from the growing effects of many other environmental factors. Stated simply, the hardware begins to wear out. Software is not susceptible to the environmental maladies that cause hardware to wear out. When a hardware component wears out, it is replaced by a spare part. There are no software spare parts. Every software failure indicates an error in design or in the process through which design was translated into machine-executable code. Therefore, the software maintenance tasks that accommodate requests for change involve considerably more complexity than hardware maintenance. However, the implication is clear—the software doesn’t wear out. But it does deteriorate. The software continues to be custom-built:A software part should be planned and carried out with the goal that it tends to be reused in various projects.Current reusable segments encapsulate the two information and the preparation that is applied to the information, empowering the programmer to make new applications from reusable parts.In the hardware world, component reuse is a natural part of the engineering process A software part should be planned and carried out with the goal that it tends to be reused in various projects. Current reusable segments encapsulate the two information and the preparation that is applied to the information, empowering the programmer to make new applications from reusable parts. In the hardware world, component reuse is a natural part of the engineering process For more details please refer to the following article Software Engineering Characteristics. 3. What activities come under the umbrella activities? The activities of the software engineering process framework are complemented by a variety of higher-level activities. Umbrella activities typically apply to the entire software project and help the software team manage and control progress, quality, changes, and risks. Common top activities include Software Project Tracking and Control Risk Management, Software Quality Assurance Technical Review Measurement Software Configuration Management Reusability Management Work Product Preparation and Production, etc. 4. What is Cohesion and Coupling? Cohesion indicates the relative functional capacity of the module. Aggregation modules need to interact less with other sections of other parts of the program to perform a single task. It can be said that only one coagulation module (ideally) needs to be run. Cohesion is a measurement of the functional strength of a module. A module with high cohesion and low coupling is functionally independent of other modules. Here, functional independence means that a cohesive module performs a single operation or function. The coupling means the overall association between the modules. Coupling relies on the information delivered through the interface with the complexity of the interface between the modules in which the reference to the section or module was created. High coupling support Low coupling modules assume that there are virtually no other modules. It is exceptionally relevant when both modules exchange a lot of information. The level of coupling between two modules depends on the complexity of the interface. For more details, please refer to the following article Coupling and cohesion. 5. What are the various phases of SDLC? SDLC phases: Requirement gathering & analysis Design Implementation & coding Testing Deployment Maintenance For more details, please refer to the following article Software Development Life Cycle. 6. What is the name of various CASE tools? Requirement Analysis Tool Structure Analysis Tool Software Design Tool Code Generation Tool Test Case Generation Tool Document Production Tool Reverse Engineering Tool For more details, please refer to the following article Computer-Aided Software Engineering(CASE). 7. What is Black box testing? The black box test (also known as the conducted test closed box test opaque box test) is centered around software useful prerequisites. In other words, it is possible to guess a set of information conditions that help the program through an attempt to discover and fulfill all the necessities perfectly. There is no choice of black-box testing white box procedures. Maybe it’s a complementary methodology, perhaps the white box method will reveal the errors of other classes. For more details, please refer to the following article Software Engineering – Black Box Testing. 8. What is White box testing? White Box Testing is a method of analyzing the internal structure, data structures used, internal design, code structure, and behavior of software, as well as functions such as black-box testing. Also called glass-box test or clear box test or structural test. For more details, please refer to the following article Software Engineering – White Box Testing. 9. What is a Feasibility Study? The Feasibility Study in Software Engineering is a study to assess the adequacy of proposed projects and systems. A feasibility study is a measure of a software product on how product development can benefit an organization from a validity analysis or practical point of view. Feasibility studies are conducted for multiple purposes to analyze the correctness of a software product in terms of development, porting, the contribution of an organization’s projects, and so on. For more details, please refer to the following article Types of Feasibility Study in Software Project Development article. 10. What is the Difference Between Quality Assurance and Quality Control? Quality Assurance (QA) Quality Control (QC) 11. What is the difference between Verification and Validation? Verification Validation For more details, please refer to the following article Software Engineering – Verification and Validation. 12. What is reverse engineering? Software Reverse Engineering is a process of recovering the design, requirement specifications, and functions of a product from an analysis of its code. It builds a program database and generates information from this. The purpose of reverse engineering is to facilitate maintenance work by improving the understandability of a system and producing the necessary documents for a legacy system. Reverse Engineering Goals: Cope with Complexity. Recover lost information. Detect side effects. Synthesize higher abstraction. Facilitate Reuse. For more details, please refer to the following article Software Engineering – Reverse Engineering. 13. What is SRS? Software Requirement Specification (SRS) Format is a complete specification and description of requirements of the software that needs to be fulfilled for successful development of software system. These requirements can be functional as well as non-requirements depending upon the type of requirement. The interaction between different customers and contractors is done because it’s necessary to fully understand the needs of customers. For more details please refer software requirement specification format article. 14. Distinguish between Alpha and Beta testing. Alpha Testing Beta Testing For more details, please refer to the following article Alpha Testing and Beta Testing. 15. What are the elements to be considered in the System Model Construction? 16. What are CASE tools? CASE stands for Computer-Aided Software Engineering. CASE tools are a set of automated software application programs, which are used to support, accelerate and smoothen the SDLC activities. 17. What is the limitation of the RAD Model? For large but scalable projects RAD requires sufficient human resources. Projects fail if developers and customers are not committed in a much-shortened time frame. Problematic if a system cannot be modularized For more details, please refer to the following article Software Engineering – Rapid Application Development Model (RAD). 18. What is the disadvantage of the spiral model? Can be a costly model to use. Risk analysis requires highly specific expertise. The project’s success is highly dependent on the risk analysis phase. Doesn’t work well for smaller projects For more details, please refer to the following article Software Engineering – Spiral Model. 19. What is COCOMO model? A COCOMO model stands for Constructive Cost Model. As with all estimation models, it requires sizing information and accepts it in three forms: Object points Function points Lines of source code For more details, please refer to the following article Software Engineering – COCOMO Model. 20. Define an estimation of software development effort for organic software in the basic COCOMO model? Estimation of software development effort for organic software in the basic COCOMO model is defined as Organic: Effort = 2.4(KLOC) 1.05 PM 21. What is the Agile software development model? The agile SDLC model is a combination of iterative and incremental process models with a focus on process adaptability and customer satisfaction by rapid delivery of working software products. Agile Methods break the product into small incremental builds. Every iteration involves cross-functional teams working simultaneously on various areas like planning, requirements analysis, design, coding, unit testing, and acceptance testing. Advantages: Customer satisfaction by rapid, continuous delivery of useful software. Customers, developers, and testers constantly interact with each other. Close, daily cooperation between business people and developers. Continuous attention to technical excellence and good design. Regular adaptation to changing circumstances. Even late changes in requirements are welcomed. For more details, please refer to the following article Software Engineering – Agile Development Models. 22. Which model can be selected if the user is involved in all the phases of SDLC? RAD model can be selected if the user is involved in all the phases of SDLC. 23. What are software project estimation techniques available? There are some software project estimation techniques available: PERT WBS Delphi method User case point 24. What is level-0 DFD? The highest abstraction level is called Level 0 of DFD. It is also called context-level DFD. It portrays the entire information system as one diagram. For more details, please refer to the following article DFD. 25. What is physical DFD? Physical DFD focuses on how the system is implemented. The next diagram to draw after creating a logical DFD is physical DFD. It explains the best method to implement the business activities of the system. Moreover, it involves the physical implementation of devices and files required for the business processes. In other words, physical DFD contains the implantation-related details such as hardware, people, and other external components required to run the business processes. 26. What is the black hole concept in DFD? A block hole concept in the data flow diagram can be defined as “A processing step may have input flows but no output flows”.In a black hole, data can only store inbound flows. 27. Mention the formula to calculate the Cyclomatic complexity of a program? The formula to calculate the cyclomatic complexity of a program is: e = number of edges n = number of vertices p = predicates For more details, please refer to the following article Cyclomatic Complexity. 28. What is software re-engineering? It is a process of software development that is done to improve the maintainability of a software system. 29. How to find the size of a software product? Estimation of the size of the software is an essential part of Software Project Management. It helps the project manager to further predict the effort and time which will be needed to build the project. Various measures are used in project size estimation. Some of these are: Lines of Code Number of entities in ER diagram Total number of processes in detailed data flow diagram Function points 30. Mentions some software analysis & design tools? Data Flow Diagrams Structured Charts Structured English Data Dictionary Hierarchical Input Process Output diagrams Entity Relationship Diagrams and Decision tables 31. What is the difference between Bug and Error? Bug: An Error found in the development environment before the product is shipped to the customer.Error: Deviation for actual and the expected/theoretical value. 32. What is the difference between Risk and Uncertainty? Risk is able to be measured while uncertainty is not able to be measured. Risk can be calculated while uncertainty can never be counted. You are capable of make earlier plans in order to avoid risk. It is impossible to make prior plans for the uncertainty. Certain sorts of empirical observations can help to understand the risk but on the other hand, the uncertainty can never be based on empirical observations. After making efforts, the risk is able to be converted into certainty. On the contrary, you can’t convert uncertainty into certainty. After making an estimate of the risk factor, a decision can be made but as the calculation of the uncertainty is not possible, hence no decision can be made. 33. What is a use case diagram? A use case diagram is a behavior diagram and visualizes the observable interactions between actors and the system under development. The diagram consists of the system, the related use cases, and actors and relates these to each other: System: What is being described? Actor: Who is using the system? Use Case: What are the actors doing? 34. Which model is used to check software reliability? A Rayleigh model is used to check software reliability. The Rayleigh model is a parametric model in the sense that it is based on a specific statistical distribution. When the parameters of the statistical distribution are estimated based on the data from a software project, projections about the defect rate of the project can be made based on the model. 35. What is CMM? To determine an organization’s current state of process maturity, the SEI uses an assessment that results in a five-point grading scheme. The grading scheme determines compliance with a capability maturity model (CMM) that defines key activities required at different levels of process maturity. The SEI approach provides a measure of the global effectiveness of a company’s software engineering practices and establishes five process maturity levels that are defined in the following manner: Level 1: Initial Level 2: Repeatable Level 3: Defined Level 4: Managed Level 5: Optimizing 36. Define adaptive maintenance? Adaptive maintenance defines as modifications and updations when the customers need the product to run on new platforms, on new operating systems, or when they need the product to interface with new hardware and software. 37. In the context of modular software design, which of the combination is considered for cohesion and coupling? In the context of modular software design, high cohesion, and low coupling is considered. 38. What is regression testing? Regression testing is defined as a type of software testing that is used to confirm that recent changes to the program or code have not adversely affected existing functionality. Regression testing is just a selection of all or part of the test cases that have been run. These test cases are rerun to ensure that the existing functions work correctly. This test is performed to ensure that new code changes do not have side effects on existing functions. Ensures that after the last code changes are completed, the above code is still valid. 39. Black box testing always focuses on which requirement of software? Black box testing always focuses on the functional requirements of the software. 40. Which of the testing is used for fault simulation? With increased expectations for software component quality and the complexity of components, software developers are expected to perform effective testing. In today’s scenario, mutation testing has been used as a fault injection technique to measure test adequacy. Mutation Testing adopts “fault simulation mode”. 41. What is a function point? Function point metrics provide a standardized method for measuring the various functions of a software application. Function point metrics, measure functionality from the user’s point of view, that is, on the basis of what the user requests and receives in return. 42. What is a baseline? A baseline is a measurement that defines the completeness of a phase. After all activities associated with a particular phase are accomplished, the phase is complete and acts as a baseline for next phase. 43. What is the cyclomatic complexity of a module that has 17 edges and 13 nodes? The cyclomatic complexity of a module that has seventeen edges and thirteen nodes = E – N + 2 E = Number of edges, N = Number of nodes Cyclometic complexity = 17 – 13 + 2 = 6 44. A software does not wear out in the traditional sense of the term, but the software does tend to deteriorate as it evolves, why? The software does not wear out in the traditional sense of the term, but the software does tend to deteriorate as it evolves because Multiple change requests introduce errors in component interactions. 45. A cohesion is an extension of which concept? Cohesion refers to the degree to which Cohesion the elements inside a module belong together. is an extension of the information hiding concept. 46. What are the three essential components of a software project plan? Team structure, Quality assurance plans, Cost estimation. 47. The testing of software against SRS is known as ....? The testing of software against SRS is known as acceptance testing. 48. How to measure the complexity of software? To measure the complexity of software there are some methods in software engineering: Line of codes Cyclomatic complexity Class coupling Depth of inheritance 49. Define the term WBS? The full form of WBS is Work Breakdown Structure. Its Work Breakdown Structure includes dividing a large and complex project into simpler, manageable, and independent tasks. For constructing a work breakdown structure, each node is recursively decomposed into smaller sub-activities, until at the leaf level, the activities become undividable and independent. A WBS works on a top-down approach. For more detail please refer Work breakdown structure article. 50. A regression testing primarily related to which testing? Regression testing is primarily related to Maintenance testing. Computer Subject Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Checking in Compiler Design Difference Between Edge Computing and Fog Computing OSI Security Architecture Optimization of Basic Blocks Token, Patterns, and Lexems Types of Software Testing Differences between Black Box Testing vs White Box Testing Functional vs Non Functional Requirements Software Engineering | COCOMO Model Differences between Verification and Validation
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2021" }, { "code": null, "e": 763, "s": 54, "text": "Software Engineering is indeed a must-to-go field for every individual who aspires to make a successful career as a Software Engineer, Software Developer, etc. in the IT industry. In simple words, it is concerned with the systematic and comprehensive study of designing, development, operations, and maintenance of a software system. In tech interviews of almost every renowned tech company, recruiters asked various questions from Software Engineering concepts such as Software Development Models & Architecture, Software Project Management (SPM), Testing and Debugging, etc. to assess the candidates. Hence, you must be prepared for all such Software Engineering Interview Questions to ace the interview. " }, { "code": null, "e": 1167, "s": 763, "text": "We know that Software Engineering is a vast field in itself and to find out & prepare for all the important concepts or questions for interviews is not an easy job. So, to make it easier and convenient for you, here, we’re providing you with an extensive list of Commonly Asked Software Engineering Interview Questions that are often asked by the recruiters. Do check out all these questions from below:" }, { "code": null, "e": 1203, "s": 1167, "text": "1. What is software re-engineering?" }, { "code": null, "e": 1593, "s": 1203, "text": "Software reengineering is the process of scanning, modifying, and reconfiguring a system in a new way. The principle of reengineering applied to the software development process is called software reengineering. It has a positive impact on software cost, quality, customer service, and shipping speed. Software reengineering improves software to create it more efficiently and effectively." }, { "code": null, "e": 1660, "s": 1593, "text": "For more details please refer to What Is Software Re-Engineering?." }, { "code": null, "e": 1705, "s": 1660, "text": "2. What are the characteristics of Software?" }, { "code": null, "e": 1752, "s": 1705, "text": "There are various characteristics of software:" }, { "code": null, "e": 2122, "s": 1752, "text": "Software is developed or engineered; it is not manufactured in the classical sense:Although some similarities exist between software development and hardware manufacturing, few activities are fundamentally different.In both activities, high quality is achieved through good design, but the manufacturing phase for hardware can introduce quality problems than software. " }, { "code": null, "e": 2256, "s": 2122, "text": "Although some similarities exist between software development and hardware manufacturing, few activities are fundamentally different." }, { "code": null, "e": 2410, "s": 2256, "text": "In both activities, high quality is achieved through good design, but the manufacturing phase for hardware can introduce quality problems than software. " }, { "code": null, "e": 3141, "s": 2410, "text": "The software doesn’t “wear out.”:Hardware components suffer from the growing effects of many other environmental factors. Stated simply, the hardware begins to wear out.Software is not susceptible to the environmental maladies that cause hardware to wear out.When a hardware component wears out, it is replaced by a spare part.There are no software spare parts.Every software failure indicates an error in design or in the process through which design was translated into machine-executable code. Therefore, the software maintenance tasks that accommodate requests for change involve considerably more complexity than hardware maintenance. However, the implication is clear—the software doesn’t wear out. But it does deteriorate. " }, { "code": null, "e": 3278, "s": 3141, "text": "Hardware components suffer from the growing effects of many other environmental factors. Stated simply, the hardware begins to wear out." }, { "code": null, "e": 3369, "s": 3278, "text": "Software is not susceptible to the environmental maladies that cause hardware to wear out." }, { "code": null, "e": 3438, "s": 3369, "text": "When a hardware component wears out, it is replaced by a spare part." }, { "code": null, "e": 3473, "s": 3438, "text": "There are no software spare parts." }, { "code": null, "e": 3843, "s": 3473, "text": "Every software failure indicates an error in design or in the process through which design was translated into machine-executable code. Therefore, the software maintenance tasks that accommodate requests for change involve considerably more complexity than hardware maintenance. However, the implication is clear—the software doesn’t wear out. But it does deteriorate. " }, { "code": null, "e": 4265, "s": 3843, "text": "The software continues to be custom-built:A software part should be planned and carried out with the goal that it tends to be reused in various projects.Current reusable segments encapsulate the two information and the preparation that is applied to the information, empowering the programmer to make new applications from reusable parts.In the hardware world, component reuse is a natural part of the engineering process" }, { "code": null, "e": 4377, "s": 4265, "text": "A software part should be planned and carried out with the goal that it tends to be reused in various projects." }, { "code": null, "e": 4563, "s": 4377, "text": "Current reusable segments encapsulate the two information and the preparation that is applied to the information, empowering the programmer to make new applications from reusable parts." }, { "code": null, "e": 4647, "s": 4563, "text": "In the hardware world, component reuse is a natural part of the engineering process" }, { "code": null, "e": 4740, "s": 4647, "text": "For more details please refer to the following article Software Engineering Characteristics." }, { "code": null, "e": 4795, "s": 4740, "text": "3. What activities come under the umbrella activities?" }, { "code": null, "e": 5310, "s": 4795, "text": "The activities of the software engineering process framework are complemented by a variety of higher-level activities. Umbrella activities typically apply to the entire software project and help the software team manage and control progress, quality, changes, and risks. Common top activities include Software Project Tracking and Control Risk Management, Software Quality Assurance Technical Review Measurement Software Configuration Management Reusability Management Work Product Preparation and Production, etc." }, { "code": null, "e": 5344, "s": 5310, "text": "4. What is Cohesion and Coupling?" }, { "code": null, "e": 5926, "s": 5344, "text": "Cohesion indicates the relative functional capacity of the module. Aggregation modules need to interact less with other sections of other parts of the program to perform a single task. It can be said that only one coagulation module (ideally) needs to be run. Cohesion is a measurement of the functional strength of a module. A module with high cohesion and low coupling is functionally independent of other modules. Here, functional independence means that a cohesive module performs a single operation or function. The coupling means the overall association between the modules. " }, { "code": null, "e": 6368, "s": 5926, "text": "Coupling relies on the information delivered through the interface with the complexity of the interface between the modules in which the reference to the section or module was created. High coupling support Low coupling modules assume that there are virtually no other modules. It is exceptionally relevant when both modules exchange a lot of information. The level of coupling between two modules depends on the complexity of the interface." }, { "code": null, "e": 6447, "s": 6368, "text": "For more details, please refer to the following article Coupling and cohesion." }, { "code": null, "e": 6487, "s": 6447, "text": "5. What are the various phases of SDLC?" }, { "code": null, "e": 6500, "s": 6487, "text": "SDLC phases:" }, { "code": null, "e": 6533, "s": 6500, "text": "Requirement gathering & analysis" }, { "code": null, "e": 6540, "s": 6533, "text": "Design" }, { "code": null, "e": 6564, "s": 6540, "text": "Implementation & coding" }, { "code": null, "e": 6572, "s": 6564, "text": "Testing" }, { "code": null, "e": 6584, "s": 6572, "text": "Deployment " }, { "code": null, "e": 6597, "s": 6584, "text": "Maintenance " }, { "code": null, "e": 6687, "s": 6597, "text": "For more details, please refer to the following article Software Development Life Cycle. " }, { "code": null, "e": 6730, "s": 6687, "text": "6. What is the name of various CASE tools?" }, { "code": null, "e": 6756, "s": 6730, "text": "Requirement Analysis Tool" }, { "code": null, "e": 6780, "s": 6756, "text": "Structure Analysis Tool" }, { "code": null, "e": 6801, "s": 6780, "text": "Software Design Tool" }, { "code": null, "e": 6822, "s": 6801, "text": "Code Generation Tool" }, { "code": null, "e": 6848, "s": 6822, "text": "Test Case Generation Tool" }, { "code": null, "e": 6873, "s": 6848, "text": "Document Production Tool" }, { "code": null, "e": 6898, "s": 6873, "text": "Reverse Engineering Tool" }, { "code": null, "e": 6997, "s": 6898, "text": "For more details, please refer to the following article Computer-Aided Software Engineering(CASE)." }, { "code": null, "e": 7027, "s": 6997, "text": "7. What is Black box testing?" }, { "code": null, "e": 7504, "s": 7027, "text": "The black box test (also known as the conducted test closed box test opaque box test) is centered around software useful prerequisites. In other words, it is possible to guess a set of information conditions that help the program through an attempt to discover and fulfill all the necessities perfectly. There is no choice of black-box testing white box procedures. Maybe it’s a complementary methodology, perhaps the white box method will reveal the errors of other classes. " }, { "code": null, "e": 7602, "s": 7504, "text": "For more details, please refer to the following article Software Engineering – Black Box Testing." }, { "code": null, "e": 7633, "s": 7602, "text": "8. What is White box testing?" }, { "code": null, "e": 7895, "s": 7633, "text": "White Box Testing is a method of analyzing the internal structure, data structures used, internal design, code structure, and behavior of software, as well as functions such as black-box testing. Also called glass-box test or clear box test or structural test. " }, { "code": null, "e": 7993, "s": 7895, "text": "For more details, please refer to the following article Software Engineering – White Box Testing." }, { "code": null, "e": 8026, "s": 7993, "text": "9. What is a Feasibility Study?" }, { "code": null, "e": 8502, "s": 8026, "text": "The Feasibility Study in Software Engineering is a study to assess the adequacy of proposed projects and systems. A feasibility study is a measure of a software product on how product development can benefit an organization from a validity analysis or practical point of view. Feasibility studies are conducted for multiple purposes to analyze the correctness of a software product in terms of development, porting, the contribution of an organization’s projects, and so on. " }, { "code": null, "e": 8626, "s": 8502, "text": "For more details, please refer to the following article Types of Feasibility Study in Software Project Development article." }, { "code": null, "e": 8701, "s": 8626, "text": "10. What is the Difference Between Quality Assurance and Quality Control?" }, { "code": null, "e": 8724, "s": 8701, "text": "Quality Assurance (QA)" }, { "code": null, "e": 8745, "s": 8724, "text": "Quality Control (QC)" }, { "code": null, "e": 8810, "s": 8745, "text": "11. What is the difference between Verification and Validation?" }, { "code": null, "e": 8823, "s": 8810, "text": "Verification" }, { "code": null, "e": 8834, "s": 8823, "text": "Validation" }, { "code": null, "e": 8942, "s": 8834, "text": "For more details, please refer to the following article Software Engineering – Verification and Validation." }, { "code": null, "e": 8975, "s": 8942, "text": "12. What is reverse engineering?" }, { "code": null, "e": 9370, "s": 8975, "text": "Software Reverse Engineering is a process of recovering the design, requirement specifications, and functions of a product from an analysis of its code. It builds a program database and generates information from this. The purpose of reverse engineering is to facilitate maintenance work by improving the understandability of a system and producing the necessary documents for a legacy system. " }, { "code": null, "e": 9399, "s": 9370, "text": "Reverse Engineering Goals: " }, { "code": null, "e": 9421, "s": 9399, "text": "Cope with Complexity." }, { "code": null, "e": 9447, "s": 9421, "text": "Recover lost information." }, { "code": null, "e": 9468, "s": 9447, "text": "Detect side effects." }, { "code": null, "e": 9499, "s": 9468, "text": "Synthesize higher abstraction." }, { "code": null, "e": 9517, "s": 9499, "text": "Facilitate Reuse." }, { "code": null, "e": 9617, "s": 9517, "text": "For more details, please refer to the following article Software Engineering – Reverse Engineering." }, { "code": null, "e": 9634, "s": 9617, "text": "13. What is SRS?" }, { "code": null, "e": 10153, "s": 9634, "text": "Software Requirement Specification (SRS) Format is a complete specification and description of requirements of the software that needs to be fulfilled for successful development of software system. These requirements can be functional as well as non-requirements depending upon the type of requirement. The interaction between different customers and contractors is done because it’s necessary to fully understand the needs of customers. For more details please refer software requirement specification format article." }, { "code": null, "e": 10201, "s": 10153, "text": "14. Distinguish between Alpha and Beta testing." }, { "code": null, "e": 10215, "s": 10201, "text": "Alpha Testing" }, { "code": null, "e": 10228, "s": 10215, "text": "Beta Testing" }, { "code": null, "e": 10316, "s": 10228, "text": "For more details, please refer to the following article Alpha Testing and Beta Testing." }, { "code": null, "e": 10394, "s": 10316, "text": "15. What are the elements to be considered in the System Model Construction?" }, { "code": null, "e": 10419, "s": 10394, "text": "16. What are CASE tools?" }, { "code": null, "e": 10610, "s": 10419, "text": "CASE stands for Computer-Aided Software Engineering. CASE tools are a set of automated software application programs, which are used to support, accelerate and smoothen the SDLC activities. " }, { "code": null, "e": 10656, "s": 10610, "text": "17. What is the limitation of the RAD Model?" }, { "code": null, "e": 10729, "s": 10656, "text": "For large but scalable projects RAD requires sufficient human resources." }, { "code": null, "e": 10821, "s": 10729, "text": "Projects fail if developers and customers are not committed in a much-shortened time frame." }, { "code": null, "e": 10867, "s": 10821, "text": "Problematic if a system cannot be modularized" }, { "code": null, "e": 10989, "s": 10867, "text": "For more details, please refer to the following article Software Engineering – Rapid Application Development Model (RAD)." }, { "code": null, "e": 11040, "s": 10989, "text": "18. What is the disadvantage of the spiral model?" }, { "code": null, "e": 11070, "s": 11040, "text": "Can be a costly model to use." }, { "code": null, "e": 11120, "s": 11070, "text": "Risk analysis requires highly specific expertise." }, { "code": null, "e": 11190, "s": 11120, "text": "The project’s success is highly dependent on the risk analysis phase." }, { "code": null, "e": 11229, "s": 11190, "text": "Doesn’t work well for smaller projects" }, { "code": null, "e": 11322, "s": 11229, "text": "For more details, please refer to the following article Software Engineering – Spiral Model." }, { "code": null, "e": 11349, "s": 11322, "text": "19. What is COCOMO model?" }, { "code": null, "e": 11494, "s": 11349, "text": "A COCOMO model stands for Constructive Cost Model. As with all estimation models, it requires sizing information and accepts it in three forms: " }, { "code": null, "e": 11508, "s": 11494, "text": "Object points" }, { "code": null, "e": 11524, "s": 11508, "text": "Function points" }, { "code": null, "e": 11545, "s": 11524, "text": "Lines of source code" }, { "code": null, "e": 11638, "s": 11545, "text": "For more details, please refer to the following article Software Engineering – COCOMO Model." }, { "code": null, "e": 11742, "s": 11638, "text": "20. Define an estimation of software development effort for organic software in the basic COCOMO model?" }, { "code": null, "e": 11846, "s": 11742, "text": "Estimation of software development effort for organic software in the basic COCOMO model is defined as " }, { "code": null, "e": 11882, "s": 11846, "text": "Organic: Effort = 2.4(KLOC) 1.05 PM" }, { "code": null, "e": 11932, "s": 11882, "text": "21. What is the Agile software development model?" }, { "code": null, "e": 12368, "s": 11932, "text": "The agile SDLC model is a combination of iterative and incremental process models with a focus on process adaptability and customer satisfaction by rapid delivery of working software products. Agile Methods break the product into small incremental builds. Every iteration involves cross-functional teams working simultaneously on various areas like planning, requirements analysis, design, coding, unit testing, and acceptance testing." }, { "code": null, "e": 12380, "s": 12368, "text": "Advantages:" }, { "code": null, "e": 12452, "s": 12380, "text": "Customer satisfaction by rapid, continuous delivery of useful software." }, { "code": null, "e": 12524, "s": 12452, "text": "Customers, developers, and testers constantly interact with each other." }, { "code": null, "e": 12589, "s": 12524, "text": "Close, daily cooperation between business people and developers." }, { "code": null, "e": 12651, "s": 12589, "text": "Continuous attention to technical excellence and good design." }, { "code": null, "e": 12697, "s": 12651, "text": "Regular adaptation to changing circumstances." }, { "code": null, "e": 12745, "s": 12697, "text": "Even late changes in requirements are welcomed." }, { "code": null, "e": 12850, "s": 12745, "text": "For more details, please refer to the following article Software Engineering – Agile Development Models." }, { "code": null, "e": 12933, "s": 12850, "text": "22. Which model can be selected if the user is involved in all the phases of SDLC?" }, { "code": null, "e": 13010, "s": 12933, "text": "RAD model can be selected if the user is involved in all the phases of SDLC." }, { "code": null, "e": 13073, "s": 13010, "text": "23. What are software project estimation techniques available?" }, { "code": null, "e": 13138, "s": 13073, "text": "There are some software project estimation techniques available:" }, { "code": null, "e": 13143, "s": 13138, "text": "PERT" }, { "code": null, "e": 13147, "s": 13143, "text": "WBS" }, { "code": null, "e": 13161, "s": 13147, "text": "Delphi method" }, { "code": null, "e": 13177, "s": 13161, "text": "User case point" }, { "code": null, "e": 13202, "s": 13177, "text": "24. What is level-0 DFD?" }, { "code": null, "e": 13353, "s": 13202, "text": "The highest abstraction level is called Level 0 of DFD. It is also called context-level DFD. It portrays the entire information system as one diagram." }, { "code": null, "e": 13414, "s": 13353, "text": "For more details, please refer to the following article DFD." }, { "code": null, "e": 13440, "s": 13414, "text": "25. What is physical DFD?" }, { "code": null, "e": 13922, "s": 13440, "text": "Physical DFD focuses on how the system is implemented. The next diagram to draw after creating a logical DFD is physical DFD. It explains the best method to implement the business activities of the system. Moreover, it involves the physical implementation of devices and files required for the business processes. In other words, physical DFD contains the implantation-related details such as hardware, people, and other external components required to run the business processes. " }, { "code": null, "e": 13965, "s": 13922, "text": "26. What is the black hole concept in DFD?" }, { "code": null, "e": 14142, "s": 13965, "text": "A block hole concept in the data flow diagram can be defined as “A processing step may have input flows but no output flows”.In a black hole, data can only store inbound flows." }, { "code": null, "e": 14219, "s": 14142, "text": "27. Mention the formula to calculate the Cyclomatic complexity of a program?" }, { "code": null, "e": 14287, "s": 14219, "text": "The formula to calculate the cyclomatic complexity of a program is:" }, { "code": null, "e": 14347, "s": 14289, "text": "e = number of edges\nn = number of vertices\np = predicates" }, { "code": null, "e": 14426, "s": 14347, "text": "For more details, please refer to the following article Cyclomatic Complexity." }, { "code": null, "e": 14463, "s": 14426, "text": "28. What is software re-engineering?" }, { "code": null, "e": 14569, "s": 14463, "text": "It is a process of software development that is done to improve the maintainability of a software system." }, { "code": null, "e": 14617, "s": 14569, "text": "29. How to find the size of a software product?" }, { "code": null, "e": 14893, "s": 14617, "text": "Estimation of the size of the software is an essential part of Software Project Management. It helps the project manager to further predict the effort and time which will be needed to build the project. Various measures are used in project size estimation. Some of these are:" }, { "code": null, "e": 14907, "s": 14893, "text": "Lines of Code" }, { "code": null, "e": 14940, "s": 14907, "text": "Number of entities in ER diagram" }, { "code": null, "e": 14996, "s": 14940, "text": "Total number of processes in detailed data flow diagram" }, { "code": null, "e": 15012, "s": 14996, "text": "Function points" }, { "code": null, "e": 15064, "s": 15012, "text": "30. Mentions some software analysis & design tools?" }, { "code": null, "e": 15083, "s": 15064, "text": "Data Flow Diagrams" }, { "code": null, "e": 15101, "s": 15083, "text": "Structured Charts" }, { "code": null, "e": 15120, "s": 15101, "text": "Structured English" }, { "code": null, "e": 15136, "s": 15120, "text": "Data Dictionary" }, { "code": null, "e": 15179, "s": 15136, "text": "Hierarchical Input Process Output diagrams" }, { "code": null, "e": 15228, "s": 15179, "text": "Entity Relationship Diagrams and Decision tables" }, { "code": null, "e": 15278, "s": 15228, "text": "31. What is the difference between Bug and Error?" }, { "code": null, "e": 15440, "s": 15278, "text": "Bug: An Error found in the development environment before the product is shipped to the customer.Error: Deviation for actual and the expected/theoretical value. " }, { "code": null, "e": 15497, "s": 15440, "text": "32. What is the difference between Risk and Uncertainty?" }, { "code": null, "e": 15571, "s": 15497, "text": "Risk is able to be measured while uncertainty is not able to be measured." }, { "code": null, "e": 15634, "s": 15571, "text": "Risk can be calculated while uncertainty can never be counted." }, { "code": null, "e": 15754, "s": 15634, "text": "You are capable of make earlier plans in order to avoid risk. It is impossible to make prior plans for the uncertainty." }, { "code": null, "e": 15911, "s": 15754, "text": "Certain sorts of empirical observations can help to understand the risk but on the other hand, the uncertainty can never be based on empirical observations." }, { "code": null, "e": 16045, "s": 15911, "text": "After making efforts, the risk is able to be converted into certainty. On the contrary, you can’t convert uncertainty into certainty." }, { "code": null, "e": 16203, "s": 16045, "text": "After making an estimate of the risk factor, a decision can be made but as the calculation of the uncertainty is not possible, hence no decision can be made." }, { "code": null, "e": 16235, "s": 16203, "text": "33. What is a use case diagram?" }, { "code": null, "e": 16471, "s": 16235, "text": "A use case diagram is a behavior diagram and visualizes the observable interactions between actors and the system under development. The diagram consists of the system, the related use cases, and actors and relates these to each other:" }, { "code": null, "e": 16504, "s": 16471, "text": "System: What is being described?" }, { "code": null, "e": 16536, "s": 16504, "text": "Actor: Who is using the system?" }, { "code": null, "e": 16573, "s": 16536, "text": "Use Case: What are the actors doing?" }, { "code": null, "e": 16628, "s": 16573, "text": "34. Which model is used to check software reliability?" }, { "code": null, "e": 16985, "s": 16628, "text": "A Rayleigh model is used to check software reliability. The Rayleigh model is a parametric model in the sense that it is based on a specific statistical distribution. When the parameters of the statistical distribution are estimated based on the data from a software project, projections about the defect rate of the project can be made based on the model." }, { "code": null, "e": 17002, "s": 16985, "text": "35. What is CMM?" }, { "code": null, "e": 17495, "s": 17002, "text": "To determine an organization’s current state of process maturity, the SEI uses an assessment that results in a five-point grading scheme. The grading scheme determines compliance with a capability maturity model (CMM) that defines key activities required at different levels of process maturity. The SEI approach provides a measure of the global effectiveness of a company’s software engineering practices and establishes five process maturity levels that are defined in the following manner:" }, { "code": null, "e": 17512, "s": 17495, "text": "Level 1: Initial" }, { "code": null, "e": 17532, "s": 17512, "text": "Level 2: Repeatable" }, { "code": null, "e": 17549, "s": 17532, "text": "Level 3: Defined" }, { "code": null, "e": 17566, "s": 17549, "text": "Level 4: Managed" }, { "code": null, "e": 17586, "s": 17566, "text": "Level 5: Optimizing" }, { "code": null, "e": 17619, "s": 17586, "text": "36. Define adaptive maintenance?" }, { "code": null, "e": 17842, "s": 17619, "text": "Adaptive maintenance defines as modifications and updations when the customers need the product to run on new platforms, on new operating systems, or when they need the product to interface with new hardware and software. " }, { "code": null, "e": 17955, "s": 17842, "text": "37. In the context of modular software design, which of the combination is considered for cohesion and coupling?" }, { "code": null, "e": 18045, "s": 17955, "text": "In the context of modular software design, high cohesion, and low coupling is considered." }, { "code": null, "e": 18077, "s": 18045, "text": "38. What is regression testing?" }, { "code": null, "e": 18619, "s": 18077, "text": "Regression testing is defined as a type of software testing that is used to confirm that recent changes to the program or code have not adversely affected existing functionality. Regression testing is just a selection of all or part of the test cases that have been run. These test cases are rerun to ensure that the existing functions work correctly. This test is performed to ensure that new code changes do not have side effects on existing functions. Ensures that after the last code changes are completed, the above code is still valid." }, { "code": null, "e": 18690, "s": 18619, "text": "39. Black box testing always focuses on which requirement of software?" }, { "code": null, "e": 18771, "s": 18690, "text": "Black box testing always focuses on the functional requirements of the software." }, { "code": null, "e": 18826, "s": 18771, "text": "40. Which of the testing is used for fault simulation?" }, { "code": null, "e": 19140, "s": 18826, "text": "With increased expectations for software component quality and the complexity of components, software developers are expected to perform effective testing. In today’s scenario, mutation testing has been used as a fault injection technique to measure test adequacy. Mutation Testing adopts “fault simulation mode”." }, { "code": null, "e": 19170, "s": 19140, "text": "41. What is a function point?" }, { "code": null, "e": 19435, "s": 19170, "text": "Function point metrics provide a standardized method for measuring the various functions of a software application. Function point metrics, measure functionality from the user’s point of view, that is, on the basis of what the user requests and receives in return." }, { "code": null, "e": 19459, "s": 19435, "text": "42. What is a baseline?" }, { "code": null, "e": 19664, "s": 19459, "text": "A baseline is a measurement that defines the completeness of a phase. After all activities associated with a particular phase are accomplished, the phase is complete and acts as a baseline for next phase." }, { "code": null, "e": 19746, "s": 19664, "text": "43. What is the cyclomatic complexity of a module that has 17 edges and 13 nodes?" }, { "code": null, "e": 19840, "s": 19746, "text": "The cyclomatic complexity of a module that has seventeen edges and thirteen nodes = E – N + 2" }, { "code": null, "e": 19921, "s": 19840, "text": "E = Number of edges, N = Number of nodes\nCyclometic complexity = 17 – 13 + 2 = 6" }, { "code": null, "e": 20055, "s": 19921, "text": "44. A software does not wear out in the traditional sense of the term, but the software does tend to deteriorate as it evolves, why? " }, { "code": null, "e": 20258, "s": 20055, "text": "The software does not wear out in the traditional sense of the term, but the software does tend to deteriorate as it evolves because Multiple change requests introduce errors in component interactions." }, { "code": null, "e": 20307, "s": 20258, "text": "45. A cohesion is an extension of which concept?" }, { "code": null, "e": 20453, "s": 20307, "text": "Cohesion refers to the degree to which Cohesion the elements inside a module belong together. is an extension of the information hiding concept. " }, { "code": null, "e": 20525, "s": 20453, "text": "46. What are the three essential components of a software project plan?" }, { "code": null, "e": 20541, "s": 20525, "text": "Team structure," }, { "code": null, "e": 20566, "s": 20541, "text": "Quality assurance plans," }, { "code": null, "e": 20583, "s": 20566, "text": "Cost estimation." }, { "code": null, "e": 20641, "s": 20583, "text": "47. The testing of software against SRS is known as ....?" }, { "code": null, "e": 20709, "s": 20641, "text": "The testing of software against SRS is known as acceptance testing." }, { "code": null, "e": 20756, "s": 20709, "text": "48. How to measure the complexity of software?" }, { "code": null, "e": 20842, "s": 20756, "text": "To measure the complexity of software there are some methods in software engineering:" }, { "code": null, "e": 20856, "s": 20842, "text": "Line of codes" }, { "code": null, "e": 20879, "s": 20856, "text": "Cyclomatic complexity " }, { "code": null, "e": 20894, "s": 20879, "text": "Class coupling" }, { "code": null, "e": 20915, "s": 20894, "text": "Depth of inheritance" }, { "code": null, "e": 20940, "s": 20915, "text": "49. Define the term WBS?" }, { "code": null, "e": 21399, "s": 20940, "text": "The full form of WBS is Work Breakdown Structure. Its Work Breakdown Structure includes dividing a large and complex project into simpler, manageable, and independent tasks. For constructing a work breakdown structure, each node is recursively decomposed into smaller sub-activities, until at the leaf level, the activities become undividable and independent. A WBS works on a top-down approach. For more detail please refer Work breakdown structure article." }, { "code": null, "e": 21460, "s": 21399, "text": "50. A regression testing primarily related to which testing?" }, { "code": null, "e": 21524, "s": 21460, "text": "Regression testing is primarily related to Maintenance testing." }, { "code": null, "e": 21541, "s": 21524, "text": "Computer Subject" }, { "code": null, "e": 21562, "s": 21541, "text": "Software Engineering" }, { "code": null, "e": 21660, "s": 21562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21693, "s": 21660, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 21745, "s": 21693, "text": "Difference Between Edge Computing and Fog Computing" }, { "code": null, "e": 21771, "s": 21745, "text": "OSI Security Architecture" }, { "code": null, "e": 21800, "s": 21771, "text": "Optimization of Basic Blocks" }, { "code": null, "e": 21828, "s": 21800, "text": "Token, Patterns, and Lexems" }, { "code": null, "e": 21854, "s": 21828, "text": "Types of Software Testing" }, { "code": null, "e": 21913, "s": 21854, "text": "Differences between Black Box Testing vs White Box Testing" }, { "code": null, "e": 21955, "s": 21913, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 21991, "s": 21955, "text": "Software Engineering | COCOMO Model" } ]
Print calendar for a given year in C++
21 Jun, 2021 Prerequisite : Find day of the week for given dateProblem: To print the calendar of any given year. The program should be such that it can prints the calendar of any input year.Implementation: CPP // A C++ Program to Implement a Calendar// of an year#include<bits/stdc++.h>using namespace std; /*A Function that returns the index of the day of the date- day/month/year For e.g- Index Day 0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday*/int dayNumber(int day, int month, int year){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; year -= month < 3; return ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7;} /* A Function that returns the name of the month with a given month number Month Number Name 0 January 1 February 2 March 3 April 4 May 5 June 6 July 7 August 8 September 9 October 10 November 11 December */string getMonthName(int monthNumber){ string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (months[monthNumber]);} /* A Function to return the number of days in a month Month Number Name Number of Days 0 January 31 1 February 28 (non-leap) / 29 (leap) 2 March 31 3 April 30 4 May 31 5 June 30 6 July 31 7 August 31 8 September 30 9 October 31 10 November 30 11 December 31 */int numberOfDays (int monthNumber, int year){ // January if (monthNumber == 0) return (31); // February if (monthNumber == 1) { // If the year is leap then February has // 29 days if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return (29); else return (28); } // March if (monthNumber == 2) return (31); // April if (monthNumber == 3) return (30); // May if (monthNumber == 4) return (31); // June if (monthNumber == 5) return (30); // July if (monthNumber == 6) return (31); // August if (monthNumber == 7) return (31); // September if (monthNumber == 8) return (30); // October if (monthNumber == 9) return (31); // November if (monthNumber == 10) return (30); // December if (monthNumber == 11) return (31);} // Function to print the calendar of the given yearvoid printCalendar(int year){ printf (" Calendar - %d\n\n", year); int days; // Index of the day from 0 to 6 int current = dayNumber (1, 1, year); // i --> Iterate through all the months // j --> Iterate through all the days of the // month - i for (int i = 0; i < 12; i++) { days = numberOfDays (i, year); // Print the current month name printf("\n ------------%s-------------\n", getMonthName (i).c_str()); // Print the columns printf(" Sun Mon Tue Wed Thu Fri Sat\n"); // Print appropriate spaces int k; for (k = 0; k < current; k++) printf(" "); for (int j = 1; j <= days; j++) { printf("%5d", j); if (++k > 6) { k = 0; printf("\n"); } } if (k) printf("\n"); current = k; } return;} // Driver Program to check above functionsint main(){ int year = 2016; printCalendar(year); return (0);} Output: Calendar - 2016 ------------January------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------February------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ------------March------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------April------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------May------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------June------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------July------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------August------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------September------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------October------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ------------November------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ------------December------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Time Complexity– O(1) . The time taken doesn’t depends on the input year. It is same for any given year. Auxiliary Space – O(1)This article is contributed by Rachit Balweriar .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sagar0719kumar CPP-Library date-time-program C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2021" }, { "code": null, "e": 249, "s": 54, "text": "Prerequisite : Find day of the week for given dateProblem: To print the calendar of any given year. The program should be such that it can prints the calendar of any input year.Implementation: " }, { "code": null, "e": 253, "s": 249, "text": "CPP" }, { "code": "// A C++ Program to Implement a Calendar// of an year#include<bits/stdc++.h>using namespace std; /*A Function that returns the index of the day of the date- day/month/year For e.g- Index Day 0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday*/int dayNumber(int day, int month, int year){ static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; year -= month < 3; return ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7;} /* A Function that returns the name of the month with a given month number Month Number Name 0 January 1 February 2 March 3 April 4 May 5 June 6 July 7 August 8 September 9 October 10 November 11 December */string getMonthName(int monthNumber){ string months[] = {\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\" }; return (months[monthNumber]);} /* A Function to return the number of days in a month Month Number Name Number of Days 0 January 31 1 February 28 (non-leap) / 29 (leap) 2 March 31 3 April 30 4 May 31 5 June 30 6 July 31 7 August 31 8 September 30 9 October 31 10 November 30 11 December 31 */int numberOfDays (int monthNumber, int year){ // January if (monthNumber == 0) return (31); // February if (monthNumber == 1) { // If the year is leap then February has // 29 days if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return (29); else return (28); } // March if (monthNumber == 2) return (31); // April if (monthNumber == 3) return (30); // May if (monthNumber == 4) return (31); // June if (monthNumber == 5) return (30); // July if (monthNumber == 6) return (31); // August if (monthNumber == 7) return (31); // September if (monthNumber == 8) return (30); // October if (monthNumber == 9) return (31); // November if (monthNumber == 10) return (30); // December if (monthNumber == 11) return (31);} // Function to print the calendar of the given yearvoid printCalendar(int year){ printf (\" Calendar - %d\\n\\n\", year); int days; // Index of the day from 0 to 6 int current = dayNumber (1, 1, year); // i --> Iterate through all the months // j --> Iterate through all the days of the // month - i for (int i = 0; i < 12; i++) { days = numberOfDays (i, year); // Print the current month name printf(\"\\n ------------%s-------------\\n\", getMonthName (i).c_str()); // Print the columns printf(\" Sun Mon Tue Wed Thu Fri Sat\\n\"); // Print appropriate spaces int k; for (k = 0; k < current; k++) printf(\" \"); for (int j = 1; j <= days; j++) { printf(\"%5d\", j); if (++k > 6) { k = 0; printf(\"\\n\"); } } if (k) printf(\"\\n\"); current = k; } return;} // Driver Program to check above functionsint main(){ int year = 2016; printCalendar(year); return (0);}", "e": 4135, "s": 253, "text": null }, { "code": null, "e": 4145, "s": 4135, "text": "Output: " }, { "code": null, "e": 7100, "s": 4145, "text": " Calendar - 2016\n\n\n ------------January-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n 31\n\n ------------February-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20\n 21 22 23 24 25 26 27\n 28 29\n\n ------------March-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n 13 14 15 16 17 18 19\n 20 21 22 23 24 25 26\n 27 28 29 30 31\n\n ------------April-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n\n ------------May-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6 7\n 8 9 10 11 12 13 14\n 15 16 17 18 19 20 21\n 22 23 24 25 26 27 28\n 29 30 31\n\n ------------June-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4\n 5 6 7 8 9 10 11\n 12 13 14 15 16 17 18\n 19 20 21 22 23 24 25\n 26 27 28 29 30\n\n ------------July-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30\n 31\n\n ------------August-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5 6\n 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20\n 21 22 23 24 25 26 27\n 28 29 30 31\n\n ------------September-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30\n\n ------------October-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1\n 2 3 4 5 6 7 8\n 9 10 11 12 13 14 15\n 16 17 18 19 20 21 22\n 23 24 25 26 27 28 29\n 30 31\n\n ------------November-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n 13 14 15 16 17 18 19\n 20 21 22 23 24 25 26\n 27 28 29 30\n\n ------------December-------------\n Sun Mon Tue Wed Thu Fri Sat\n 1 2 3\n 4 5 6 7 8 9 10\n 11 12 13 14 15 16 17\n 18 19 20 21 22 23 24\n 25 26 27 28 29 30 31" }, { "code": null, "e": 7652, "s": 7100, "text": "Time Complexity– O(1) . The time taken doesn’t depends on the input year. It is same for any given year. Auxiliary Space – O(1)This article is contributed by Rachit Balweriar .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7667, "s": 7652, "text": "sagar0719kumar" }, { "code": null, "e": 7679, "s": 7667, "text": "CPP-Library" }, { "code": null, "e": 7697, "s": 7679, "text": "date-time-program" }, { "code": null, "e": 7708, "s": 7697, "text": "C Language" }, { "code": null, "e": 7712, "s": 7708, "text": "C++" }, { "code": null, "e": 7716, "s": 7712, "text": "CPP" } ]
HTML5 Game Development | Infinitely Scrolling Background
31 May, 2022 Game Design and Development is an emerging industry. Although making AAA titles will require advanced knowledge of game engines, DirectX, OpenGL, etc. small HTML5 video game projects is a good place to start. HTML5 canvas and javascript can be used to make small games while learning the fundamentals of game development like Collision-Detection, Object Pools, etc. Infinitely Scrolling Background An infinitely scrolling background is an important tool that is essential when making endless arcade games like flappy bird or in a normal platformer where you do not have the time or resources to hand-craft the entire level. The idea is to draw the same image twice consecutively and replace the second image with the first when it occupies the entire screen effectively restarting the process. Drawing an Image The image should be such that the intermediate frames with parts of the 2 images are proper backgrounds and the separating line should not be visible. The same logic can be applied to create an infinite side scrolling background.Here we will use this space background image as an example: spacebg.png It was made using MS Paint. Any other software like Photoshop or Gimp can be used. Writing the Code HTML: <!DOCTYPE html><html><head> <title>Infinitely Scrolling Background</title></head><body style="background-color: black;"> <canvas id="canvas1" style="border: 1px solid black;"></canvas></body></html> <script src="main_javascript.js"></script> JavaScript: // inside main_javascript.js var can = document.getElementById('canvas1'); // The 2D Context for the HTML canvas element. It// provides objects, methods, and properties to draw and// manipulate graphics on a canvas drawing surface.var ctx = can.getContext('2d'); // canvas width and heightcan.width = 600;can.height = 600; // create an image elementvar img = new Image(); // specify the image source relative to the html or js file// when the image is in the same directory as the file// only the file name is required:img.src = "spacebg.png"; // window.onload is an event that occurs when all the assets// have been successfully loaded( in this case only the spacebg.png)window.onload = function() { // the initial image height var imgHeight = 0; // the scroll speed // an important thing to ensure here is that can.height // is divisible by scrollSpeed var scrollSpeed = 10; // this is the primary animation loop that is called 60 times // per second function loop() { // draw image 1 ctx.drawImage(img, 0, imgHeight); // draw image 2 ctx.drawImage(img, 0, imgHeight - can.height); // update image height imgHeight += scrollSpeed; //resetting the images when the first image entirely exits the screen if (imgHeight == can.height) imgHeight = 0; // this function creates a 60fps animation by scheduling a // loop function call before the // next redraw every time it is called window.requestAnimationFrame(loop); } // this initiates the animation by calling the loop function // for the first time loop(); } Methods and Events getContext(‘2d’) : The HTML5 canvas tag is used to draw graphics via scripting (usually JavaScript).However, the canvas element has no drawing abilities of its own (it is only a container for graphics) – you must use a script to actually draw the graphics.The getContext() method returns an object that provides methods and properties for drawing on the canvas.Syntax:var ctx = document.getElementbyId("canvasid").getContext('2d');The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas.window.onload : The onload event occurs when an object has been loaded. It is commonly used in javascript to trigger a function once an asset has been loaded.Syntax:object.onload = function() { /*myScript*/ };window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.window.requestAnimationFrame() : The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.Syntax:window.requestAnimationFrame(callback_function);The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire. getContext(‘2d’) : The HTML5 canvas tag is used to draw graphics via scripting (usually JavaScript).However, the canvas element has no drawing abilities of its own (it is only a container for graphics) – you must use a script to actually draw the graphics.The getContext() method returns an object that provides methods and properties for drawing on the canvas.Syntax:var ctx = document.getElementbyId("canvasid").getContext('2d');The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas. var ctx = document.getElementbyId("canvasid").getContext('2d'); The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas. window.onload : The onload event occurs when an object has been loaded. It is commonly used in javascript to trigger a function once an asset has been loaded.Syntax:object.onload = function() { /*myScript*/ };window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information. object.onload = function() { /*myScript*/ }; window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} ) It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information. window.requestAnimationFrame() : The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.Syntax:window.requestAnimationFrame(callback_function);The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire. window.requestAnimationFrame(callback_function); The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire. Note: Your callback routine must itself call requestAnimationFrame() if you want to animate another frame at the next repaint. Final AnimationThe final canvas animation should look like this when the html file is opened : Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/2018-05-14-12-03-12.mp400:0000:0000:06Use Up/Down Arrow keys to increase or decrease volume. nidhi_biet surinderdawra388 HTML5 HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 261, "s": 52, "text": "Game Design and Development is an emerging industry. Although making AAA titles will require advanced knowledge of game engines, DirectX, OpenGL, etc. small HTML5 video game projects is a good place to start." }, { "code": null, "e": 418, "s": 261, "text": "HTML5 canvas and javascript can be used to make small games while learning the fundamentals of game development like Collision-Detection, Object Pools, etc." }, { "code": null, "e": 450, "s": 418, "text": "Infinitely Scrolling Background" }, { "code": null, "e": 676, "s": 450, "text": "An infinitely scrolling background is an important tool that is essential when making endless arcade games like flappy bird or in a normal platformer where you do not have the time or resources to hand-craft the entire level." }, { "code": null, "e": 846, "s": 676, "text": "The idea is to draw the same image twice consecutively and replace the second image with the first when it occupies the entire screen effectively restarting the process." }, { "code": null, "e": 865, "s": 848, "text": "Drawing an Image" }, { "code": null, "e": 1154, "s": 865, "text": "The image should be such that the intermediate frames with parts of the 2 images are proper backgrounds and the separating line should not be visible. The same logic can be applied to create an infinite side scrolling background.Here we will use this space background image as an example:" }, { "code": null, "e": 1169, "s": 1154, "text": "\n spacebg.png\n" }, { "code": null, "e": 1252, "s": 1169, "text": "It was made using MS Paint. Any other software like Photoshop or Gimp can be used." }, { "code": null, "e": 1269, "s": 1252, "text": "Writing the Code" }, { "code": null, "e": 1275, "s": 1269, "text": "HTML:" }, { "code": "<!DOCTYPE html><html><head> <title>Infinitely Scrolling Background</title></head><body style=\"background-color: black;\"> <canvas id=\"canvas1\" style=\"border: 1px solid black;\"></canvas></body></html> <script src=\"main_javascript.js\"></script>", "e": 1524, "s": 1275, "text": null }, { "code": null, "e": 1536, "s": 1524, "text": "JavaScript:" }, { "code": "// inside main_javascript.js var can = document.getElementById('canvas1'); // The 2D Context for the HTML canvas element. It// provides objects, methods, and properties to draw and// manipulate graphics on a canvas drawing surface.var ctx = can.getContext('2d'); // canvas width and heightcan.width = 600;can.height = 600; // create an image elementvar img = new Image(); // specify the image source relative to the html or js file// when the image is in the same directory as the file// only the file name is required:img.src = \"spacebg.png\"; // window.onload is an event that occurs when all the assets// have been successfully loaded( in this case only the spacebg.png)window.onload = function() { // the initial image height var imgHeight = 0; // the scroll speed // an important thing to ensure here is that can.height // is divisible by scrollSpeed var scrollSpeed = 10; // this is the primary animation loop that is called 60 times // per second function loop() { // draw image 1 ctx.drawImage(img, 0, imgHeight); // draw image 2 ctx.drawImage(img, 0, imgHeight - can.height); // update image height imgHeight += scrollSpeed; //resetting the images when the first image entirely exits the screen if (imgHeight == can.height) imgHeight = 0; // this function creates a 60fps animation by scheduling a // loop function call before the // next redraw every time it is called window.requestAnimationFrame(loop); } // this initiates the animation by calling the loop function // for the first time loop(); }", "e": 3189, "s": 1536, "text": null }, { "code": null, "e": 3208, "s": 3189, "text": "Methods and Events" }, { "code": null, "e": 5385, "s": 3208, "text": "getContext(‘2d’) : The HTML5 canvas tag is used to draw graphics via scripting (usually JavaScript).However, the canvas element has no drawing abilities of its own (it is only a container for graphics) – you must use a script to actually draw the graphics.The getContext() method returns an object that provides methods and properties for drawing on the canvas.Syntax:var ctx = document.getElementbyId(\"canvasid\").getContext('2d');The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas.window.onload : The onload event occurs when an object has been loaded. It is commonly used in javascript to trigger a function once an asset has been loaded.Syntax:object.onload = function() { /*myScript*/ };window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.window.requestAnimationFrame() : The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.Syntax:window.requestAnimationFrame(callback_function);The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire." }, { "code": null, "e": 5919, "s": 5385, "text": "getContext(‘2d’) : The HTML5 canvas tag is used to draw graphics via scripting (usually JavaScript).However, the canvas element has no drawing abilities of its own (it is only a container for graphics) – you must use a script to actually draw the graphics.The getContext() method returns an object that provides methods and properties for drawing on the canvas.Syntax:var ctx = document.getElementbyId(\"canvasid\").getContext('2d');The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas." }, { "code": "var ctx = document.getElementbyId(\"canvasid\").getContext('2d');", "e": 5983, "s": 5919, "text": null }, { "code": null, "e": 6086, "s": 5983, "text": "The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas." }, { "code": null, "e": 6854, "s": 6086, "text": "window.onload : The onload event occurs when an object has been loaded. It is commonly used in javascript to trigger a function once an asset has been loaded.Syntax:object.onload = function() { /*myScript*/ };window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information." }, { "code": "object.onload = function() { /*myScript*/ };", "e": 6899, "s": 6854, "text": null }, { "code": null, "e": 7312, "s": 6899, "text": "window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.(try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )" }, { "code": null, "e": 7459, "s": 7312, "text": "It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information." }, { "code": null, "e": 8336, "s": 7459, "text": "window.requestAnimationFrame() : The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.Syntax:window.requestAnimationFrame(callback_function);The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire." }, { "code": "window.requestAnimationFrame(callback_function);", "e": 8385, "s": 8336, "text": null }, { "code": null, "e": 8555, "s": 8385, "text": "The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire." }, { "code": null, "e": 8682, "s": 8555, "text": "Note: Your callback routine must itself call requestAnimationFrame() if you want to animate another frame at the next repaint." }, { "code": null, "e": 8777, "s": 8682, "text": "Final AnimationThe final canvas animation should look like this when the html file is opened :" }, { "code": null, "e": 8935, "s": 8777, "text": "\nVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/2018-05-14-12-03-12.mp400:0000:0000:06Use Up/Down Arrow keys to increase or decrease volume.\n" }, { "code": null, "e": 8946, "s": 8935, "text": "nidhi_biet" }, { "code": null, "e": 8963, "s": 8946, "text": "surinderdawra388" }, { "code": null, "e": 8969, "s": 8963, "text": "HTML5" }, { "code": null, "e": 8974, "s": 8969, "text": "HTML" }, { "code": null, "e": 8991, "s": 8974, "text": "Web Technologies" }, { "code": null, "e": 8996, "s": 8991, "text": "HTML" }, { "code": null, "e": 9094, "s": 8996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9142, "s": 9094, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 9204, "s": 9142, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9254, "s": 9204, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 9278, "s": 9254, "text": "REST API (Introduction)" }, { "code": null, "e": 9331, "s": 9278, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 9364, "s": 9331, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 9426, "s": 9364, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9487, "s": 9426, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9537, "s": 9487, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | PRAW – Python Reddit API Wrapper
09 Aug, 2021 PRAW (Python Reddit API Wrapper) is a Python module that provides a simple access to Reddit’s API. PRAW is easy to use and follows all of Reddit’s API rules.The documentation regarding PRAW is located here.Prerequisites: Basic Python Programming Skills Basic Reddit Knowledge : Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them. A Reddit Account To install PRAW, we run the following pip script on the terminal / command prompt. pip install praw After installing PRAW, we need to import it: Python3 import praw After importing PRAW, we need to instantiate it. There are 2 types of PRAW instances: Read-only Instance: With read-only instance we can only retrieve public information from Reddit. Information like top 10 posts from a certain subreddit. We can’t post material from this. Authorized Instance: With authorized instance we can do whatever a normal reddit account can do. Actions like comment, post, repost, upvote etc. can be performed. Creating a read-only instance: Python3 reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent') # to verify whether the instance is read-only instance or notprint(reddit.read_only) Output: True Creating an authorized instance: Python3 reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent', username ='my username', password ='my password') # to verify whether the instance is authorized instance or notprint(reddit.read_only) Output: False To switch back to read-only mode: Python3 reddit.read_only = True Now let us see some of the operations we can achieve using PRAW: Access a Subreddit: In reddit there are multiple communities known as subreddits. We can obtain a subreddit instance using the method subreddit. Python3 subreddit = reddit.subreddit('GRE') # display the subreddit nameprint(subreddit.display_name) # display the subreddit titleprint(subreddit.title) # display the subreddit descriptionprint(subreddit.description) Output : GRE GRE #/r/GRE This subreddit is for discussion of the GRE (Graduate Record Examination). If you're studying for the GRE, or can help people who are studying for the GRE, you're in the right place! ----- #Rules - You must read and follow the rules! https://www.reddit.com/r/gre/about/rules ----- Access a Submission: Within a subreddit there are multiple post submissions. We can iterate through the submissions in the submission instance. Reddit provides us multiple ways to sort submissions: risingnewhotgildedcontroversialtop rising new hot gilded controversial top Access a Redditor: In Reddit, the user is called a Redditor. We can obtain the redditor instance using the method redditor. In the method we pass the username of the redditor. Python3 # let the redditor be "AutoModerator"redditor = reddit.redditor('AutoModerator') # display AutoModerator's karmaprint(redditor.link_karma) Output: 6554 varshagumber28 abhishek0719kadiyan Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 251, "s": 28, "text": "PRAW (Python Reddit API Wrapper) is a Python module that provides a simple access to Reddit’s API. PRAW is easy to use and follows all of Reddit’s API rules.The documentation regarding PRAW is located here.Prerequisites: " }, { "code": null, "e": 283, "s": 251, "text": "Basic Python Programming Skills" }, { "code": null, "e": 505, "s": 283, "text": "Basic Reddit Knowledge : Reddit is a network of communities based on people’s interests. Each of these communities is called a subreddit. Users can subscribe to multiple subreddits to post, comment and interact with them." }, { "code": null, "e": 522, "s": 505, "text": "A Reddit Account" }, { "code": null, "e": 606, "s": 522, "text": "To install PRAW, we run the following pip script on the terminal / command prompt. " }, { "code": null, "e": 623, "s": 606, "text": "pip install praw" }, { "code": null, "e": 669, "s": 623, "text": "After installing PRAW, we need to import it: " }, { "code": null, "e": 677, "s": 669, "text": "Python3" }, { "code": "import praw", "e": 689, "s": 677, "text": null }, { "code": null, "e": 777, "s": 689, "text": "After importing PRAW, we need to instantiate it. There are 2 types of PRAW instances: " }, { "code": null, "e": 964, "s": 777, "text": "Read-only Instance: With read-only instance we can only retrieve public information from Reddit. Information like top 10 posts from a certain subreddit. We can’t post material from this." }, { "code": null, "e": 1127, "s": 964, "text": "Authorized Instance: With authorized instance we can do whatever a normal reddit account can do. Actions like comment, post, repost, upvote etc. can be performed." }, { "code": null, "e": 1160, "s": 1127, "text": "Creating a read-only instance: " }, { "code": null, "e": 1168, "s": 1160, "text": "Python3" }, { "code": "reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent') # to verify whether the instance is read-only instance or notprint(reddit.read_only)", "e": 1405, "s": 1168, "text": null }, { "code": null, "e": 1415, "s": 1405, "text": "Output: " }, { "code": null, "e": 1420, "s": 1415, "text": "True" }, { "code": null, "e": 1454, "s": 1420, "text": "Creating an authorized instance: " }, { "code": null, "e": 1462, "s": 1454, "text": "Python3" }, { "code": "reddit = praw.Reddit(client_id ='my client id', client_secret ='my client secret', user_agent ='my user agent', username ='my username', password ='my password') # to verify whether the instance is authorized instance or notprint(reddit.read_only)", "e": 1790, "s": 1462, "text": null }, { "code": null, "e": 1800, "s": 1790, "text": "Output: " }, { "code": null, "e": 1806, "s": 1800, "text": "False" }, { "code": null, "e": 1842, "s": 1806, "text": "To switch back to read-only mode: " }, { "code": null, "e": 1850, "s": 1842, "text": "Python3" }, { "code": "reddit.read_only = True", "e": 1874, "s": 1850, "text": null }, { "code": null, "e": 1940, "s": 1874, "text": "Now let us see some of the operations we can achieve using PRAW: " }, { "code": null, "e": 2086, "s": 1940, "text": "Access a Subreddit: In reddit there are multiple communities known as subreddits. We can obtain a subreddit instance using the method subreddit. " }, { "code": null, "e": 2094, "s": 2086, "text": "Python3" }, { "code": "subreddit = reddit.subreddit('GRE') # display the subreddit nameprint(subreddit.display_name) # display the subreddit titleprint(subreddit.title) # display the subreddit descriptionprint(subreddit.description)", "e": 2310, "s": 2094, "text": null }, { "code": null, "e": 2321, "s": 2310, "text": "Output : " }, { "code": null, "e": 2630, "s": 2321, "text": "GRE\nGRE\n#/r/GRE \n\nThis subreddit is for discussion of the GRE (Graduate Record Examination). If you're studying for the GRE, or can help people who are studying for the GRE, you're in the right place!\n\n \n\n-----\n\n#Rules\n\n- You must read and follow the rules! \nhttps://www.reddit.com/r/gre/about/rules\n\n-----" }, { "code": null, "e": 2863, "s": 2630, "text": "Access a Submission: Within a subreddit there are multiple post submissions. We can iterate through the submissions in the submission instance. Reddit provides us multiple ways to sort submissions: risingnewhotgildedcontroversialtop" }, { "code": null, "e": 2870, "s": 2863, "text": "rising" }, { "code": null, "e": 2874, "s": 2870, "text": "new" }, { "code": null, "e": 2878, "s": 2874, "text": "hot" }, { "code": null, "e": 2885, "s": 2878, "text": "gilded" }, { "code": null, "e": 2899, "s": 2885, "text": "controversial" }, { "code": null, "e": 2903, "s": 2899, "text": "top" }, { "code": null, "e": 3081, "s": 2903, "text": "Access a Redditor: In Reddit, the user is called a Redditor. We can obtain the redditor instance using the method redditor. In the method we pass the username of the redditor. " }, { "code": null, "e": 3089, "s": 3081, "text": "Python3" }, { "code": "# let the redditor be \"AutoModerator\"redditor = reddit.redditor('AutoModerator') # display AutoModerator's karmaprint(redditor.link_karma)", "e": 3228, "s": 3089, "text": null }, { "code": null, "e": 3237, "s": 3228, "text": "Output: " }, { "code": null, "e": 3242, "s": 3237, "text": "6554" }, { "code": null, "e": 3259, "s": 3244, "text": "varshagumber28" }, { "code": null, "e": 3279, "s": 3259, "text": "abhishek0719kadiyan" }, { "code": null, "e": 3286, "s": 3279, "text": "Python" }, { "code": null, "e": 3302, "s": 3286, "text": "Python Programs" } ]
Second largest element in BST
21 May, 2021 Given a Binary Search Tree(BST), find the second largest element. Examples: Input: Root of below BST 10 / 5 Output: 5 Input: Root of below BST 10 / \ 5 20 \ 30 Output: 20 Source: Microsoft Interview The idea is similar to below post. K’th Largest Element in BST when modification to BST is not allowedThe second largest element is second last element in inorder traversal and second element in reverse inorder traversal. We traverse given Binary Search Tree in reverse inorder and keep track of counts of nodes visited. Once the count becomes 2, we print the node.Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ program to find 2nd largest element in BST#include<bits/stdc++.h>using namespace std; struct Node{ int key; Node *left, *right;}; // 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 function to find 2nd largest element in a given tree.void secondLargestUtil(Node *root, int &c){ // Base cases, the second condition is important to // avoid unnecessary recursive calls if (root == NULL || c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first secondLargestUtil(root->right, c); // Increment count of visited nodes c++; // If c becomes k now, then this is the 2nd largest if (c == 2) { cout << "2nd largest element is " << root->key << endl; return; } // Recur for left subtree secondLargestUtil(root->left, c);} // Function to find 2nd largest elementvoid secondLargest(Node *root){ // Initialize count of nodes visited as 0 int c = 0; // Note that c is passed by reference secondLargestUtil(root, c);} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* 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); secondLargest(root); return 0;} // Java code to find second largest element in BST // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // function to insert new nodes public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { int c = 0; } // Function to find 2nd largest element void secondLargestUtil(Node node, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { System.out.print("2nd largest element is "+ node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element void secondLargest(Node node) { // object of class count count C = new count(); this.secondLargestUtil(this.root, C); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); tree.secondLargest(tree.root); }} // This code is contributed by Kamal Rawal # Python3 code to find second largest# element in BSTclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find 2nd largest# element in a given tree.def secondLargestUtil(root, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= 2: return # Follow reverse inorder traversal so that # the largest element is visited first secondLargestUtil(root.right, c) # Increment count of visited nodes c[0] += 1 # If c becomes k now, then this is # the 2nd largest if c[0] == 2: print("2nd largest element is", root.key) return # Recur for left subtree secondLargestUtil(root.left, c) # Function to find 2nd largest elementdef secondLargest(root): # Initialize count of nodes # visited as 0 c = [0] # Note that c is passed by reference secondLargestUtil(root, c) # A utility function to insert a new# node with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) secondLargest(root) # This code is contributed by PranchalK using System; // C# code to find second largest element in BST // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree{ // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // function to insert new nodes public virtual void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ public virtual Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { private readonly BinarySearchTree outerInstance; public count(BinarySearchTree outerInstance) { this.outerInstance = outerInstance; } public int c = 0; } // Function to find 2nd largest element public virtual void secondLargestUtil(Node node, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) { return; } // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { Console.Write("2nd largest element is " + node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element public virtual void secondLargest(Node node) { // object of class count count C = new count(this); this.secondLargestUtil(this.root, C); } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); tree.secondLargest(tree.root); }} // This code is contributed by Shrikant13 <script> // JavaScript code to find second largest// element in BST // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // function to insert new nodes function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ function insertRec(node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count class count { constructor(){ this.c = 0; } } // Function to find 2nd largest element function secondLargestUtil(node, C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { document.write("2nd largest element is "+ node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element function secondLargest(node) { // object of class count var C = new count(); this.secondLargestUtil(this.root, C); } // Driver function /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ insert(50); insert(30); insert(20); insert(40); insert(70); insert(60); insert(80); secondLargest(root); // This code contributed by aashish1995 </script> Output: 2nd largest element is 70 Time complexity of the above solution is O(h) where h is height of BST. Second largest element in BST | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSecond largest element 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 / 3:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OKAEDMCwhNI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 PranchalKatiyar megha92c aashish1995 Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Merge Two Balanced Binary Search Trees Convert a normal BST to Balanced BST Inorder predecessor and successor for a given key in BST set vs unordered_set in C++ STL Find the node with minimum value in a Binary Search Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n21 May, 2021" }, { "code": null, "e": 130, "s": 52, "text": "Given a Binary Search Tree(BST), find the second largest element. Examples: " }, { "code": null, "e": 294, "s": 130, "text": "Input: Root of below BST\n 10\n /\n 5\n\nOutput: 5\n\n\nInput: Root of below BST\n 10\n / \\\n 5 20\n \\ \n 30 \n\nOutput: 20" }, { "code": null, "e": 323, "s": 294, "text": "Source: Microsoft Interview " }, { "code": null, "e": 733, "s": 323, "text": "The idea is similar to below post. K’th Largest Element in BST when modification to BST is not allowedThe second largest element is second last element in inorder traversal and second element in reverse inorder traversal. We traverse given Binary Search Tree in reverse inorder and keep track of counts of nodes visited. Once the count becomes 2, we print the node.Below is the implementation of above idea. " }, { "code": null, "e": 737, "s": 733, "text": "C++" }, { "code": null, "e": 742, "s": 737, "text": "Java" }, { "code": null, "e": 750, "s": 742, "text": "Python3" }, { "code": null, "e": 753, "s": 750, "text": "C#" }, { "code": null, "e": 764, "s": 753, "text": "Javascript" }, { "code": "// C++ program to find 2nd largest element in BST#include<bits/stdc++.h>using namespace std; struct Node{ int key; Node *left, *right;}; // 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 function to find 2nd largest element in a given tree.void secondLargestUtil(Node *root, int &c){ // Base cases, the second condition is important to // avoid unnecessary recursive calls if (root == NULL || c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first secondLargestUtil(root->right, c); // Increment count of visited nodes c++; // If c becomes k now, then this is the 2nd largest if (c == 2) { cout << \"2nd largest element is \" << root->key << endl; return; } // Recur for left subtree secondLargestUtil(root->left, c);} // Function to find 2nd largest elementvoid secondLargest(Node *root){ // Initialize count of nodes visited as 0 int c = 0; // Note that c is passed by reference secondLargestUtil(root, c);} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* 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); secondLargest(root); return 0;}", "e": 2788, "s": 764, "text": null }, { "code": "// Java code to find second largest element in BST // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // function to insert new nodes public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { int c = 0; } // Function to find 2nd largest element void secondLargestUtil(Node node, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { System.out.print(\"2nd largest element is \"+ node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element void secondLargest(Node node) { // object of class count count C = new count(); this.secondLargestUtil(this.root, C); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); tree.secondLargest(tree.root); }} // This code is contributed by Kamal Rawal", "e": 5387, "s": 2788, "text": null }, { "code": "# Python3 code to find second largest# element in BSTclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find 2nd largest# element in a given tree.def secondLargestUtil(root, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= 2: return # Follow reverse inorder traversal so that # the largest element is visited first secondLargestUtil(root.right, c) # Increment count of visited nodes c[0] += 1 # If c becomes k now, then this is # the 2nd largest if c[0] == 2: print(\"2nd largest element is\", root.key) return # Recur for left subtree secondLargestUtil(root.left, c) # Function to find 2nd largest elementdef secondLargest(root): # Initialize count of nodes # visited as 0 c = [0] # Note that c is passed by reference secondLargestUtil(root, c) # A utility function to insert a new# node with given key in BSTdef insert(node, key): # If the tree is empty, return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \\ # 30 70 # / \\ / \\ # 20 40 60 80 root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) secondLargest(root) # This code is contributed by PranchalK", "e": 7246, "s": 5387, "text": null }, { "code": "using System; // C# code to find second largest element in BST // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree{ // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // function to insert new nodes public virtual void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ public virtual Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { private readonly BinarySearchTree outerInstance; public count(BinarySearchTree outerInstance) { this.outerInstance = outerInstance; } public int c = 0; } // Function to find 2nd largest element public virtual void secondLargestUtil(Node node, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) { return; } // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { Console.Write(\"2nd largest element is \" + node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element public virtual void secondLargest(Node node) { // object of class count count C = new count(this); this.secondLargestUtil(this.root, C); } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); tree.secondLargest(tree.root); }} // This code is contributed by Shrikant13", "e": 10093, "s": 7246, "text": null }, { "code": "<script> // JavaScript code to find second largest// element in BST // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // function to insert new nodes function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ function insertRec(node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count class count { constructor(){ this.c = 0; } } // Function to find 2nd largest element function secondLargestUtil(node, C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= 2) return; // Follow reverse inorder traversal so that the // largest element is visited first this.secondLargestUtil(node.right, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the 2nd largest if (C.c == 2) { document.write(\"2nd largest element is \"+ node.data); return; } // Recur for left subtree this.secondLargestUtil(node.left, C); } // Function to find 2nd largest element function secondLargest(node) { // object of class count var C = new count(); this.secondLargestUtil(this.root, C); } // Driver function /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ insert(50); insert(30); insert(20); insert(40); insert(70); insert(60); insert(80); secondLargest(root); // This code contributed by aashish1995 </script>", "e": 12467, "s": 10093, "text": null }, { "code": null, "e": 12476, "s": 12467, "text": "Output: " }, { "code": null, "e": 12502, "s": 12476, "text": "2nd largest element is 70" }, { "code": null, "e": 12576, "s": 12502, "text": "Time complexity of the above solution is O(h) where h is height of BST. " }, { "code": null, "e": 13452, "s": 12576, "text": "Second largest element in BST | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSecond largest element 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 / 3:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OKAEDMCwhNI\" 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": 13614, "s": 13452, "text": "This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 13626, "s": 13614, "text": "shrikanth13" }, { "code": null, "e": 13642, "s": 13626, "text": "PranchalKatiyar" }, { "code": null, "e": 13651, "s": 13642, "text": "megha92c" }, { "code": null, "e": 13663, "s": 13651, "text": "aashish1995" }, { "code": null, "e": 13682, "s": 13663, "text": "Binary Search Tree" }, { "code": null, "e": 13701, "s": 13682, "text": "Binary Search Tree" }, { "code": null, "e": 13799, "s": 13701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13855, "s": 13799, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 13925, "s": 13855, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 13954, "s": 13925, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 13989, "s": 13954, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 14029, "s": 13989, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 14068, "s": 14029, "text": "Merge Two Balanced Binary Search Trees" }, { "code": null, "e": 14105, "s": 14068, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 14162, "s": 14105, "text": "Inorder predecessor and successor for a given key in BST" }, { "code": null, "e": 14194, "s": 14162, "text": "set vs unordered_set in C++ STL" } ]
SWING - JLabel Class
The class JLabel can display either text, an image, or both. Label's contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default. Following is the declaration for javax.swing.JLabel class − public class JLabel extends JComponent implements SwingConstants, Accessible Following are the fields for javax.swing.JLabel class − protected Component labelFor JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(Icon image) Creates a JLabel instance with the specified image. JLabel(Icon image, int horizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(String text, Icon icon, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, int horizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. protected int checkHorizontalKey(int key, String message) Verify that key is a legal value for the horizontalAlignment properties. protected int checkVerticalKey(int key, String message) Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties. AccessibleContext getAccessibleContext() Get the AccessibleContext of this object. Icon getDisabledIcon() Returns the icon used by the label when it's disabled. int getDisplayedMnemonic() Return the keycode that indicates a mnemonic key. int getDisplayedMnemonicIndex() Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character. int getHorizontalAlignment() Returns the alignment of the label's contents along the X axis. int getHorizontalTextPosition() Returns the horizontal position of the label's text, relative to its image. Icon getIcon() Returns the graphic image (glyph, icon) that the label displays. int getIconTextGap() Returns the amount of space between the text and the icon displayed in this label. Component getLabelFor() Get the component this is labelling. String getText() Returns the text string that the label displays. LabelUI getUI() Returns the L&F object that renders this component. String getUIClassID() Returns a string that specifies the name of the l&f class which renders this component. int getVerticalAlignment() Returns the alignment of the label's contents along the Y axis. int getVerticalTextPosition() Returns the vertical position of the label's text, relative to its image. boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) This is overridden to return false if the current Icon's image is not equal to the passed in Image img. protected String paramString() Returns a string representation of this JLabel. void setDisabledIcon(Icon disabledIcon) Sets the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)). void setDisplayedMnemonic(char aChar) Specifies the displayedMnemonic as a char value. void setDisplayedMnemonic(int key) Specifies a keycode that indicates a mnemonic key. void setDisplayedMnemonicIndex(int index) Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic. void setHorizontalAlignment(int alignment) Sets the alignment of the label's contents along the X axis. void setHorizontalTextPosition(int textPosition) Sets the horizontal position of the label's text, relative to its image. void setIcon(Icon icon) Defines the icon this component will display. void setIconTextGap(int iconTextGap) If both the icon and text properties are set, this property defines the space between them. void setLabelFor(Component c) Sets the component, this is labelling. void setText(String text) Defines the single line of text this component will display. void setUI(LabelUI ui) Sets the L&F object that renders this component. void setVerticalAlignment(int alignment) Sets the alignment of the label's contents along the Y axis. void setVerticalTextPosition(int textPosition) Sets the vertical position of the label's text, relative to its image. void updateUI() Resets the UI property to a value from the current look and feel. This class inherits methods from the following classes − javax.swing.JComponent java.awt.Container java.awt.Component java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingControlDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingControlDemo(){ prepareGUI(); } public static void main(String[] args){ SwingControlDemo swingControlDemo = new SwingControlDemo(); swingControlDemo.showLabelDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showLabelDemo(){ headerLabel.setText("Control in action: JLabel"); JLabel label = new JLabel("", JLabel.CENTER); label.setText("Welcome to TutorialsPoint Swing Tutorial."); label.setOpaque(true); label.setBackground(Color.GRAY); label.setForeground(Color.WHITE); controlPanel.add(label); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingControlDemo Verify the following output.
[ { "code": null, "e": 2235, "s": 1897, "text": "The class JLabel can display either text, an image, or both. Label's contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default." }, { "code": null, "e": 2295, "s": 2235, "text": "Following is the declaration for javax.swing.JLabel class −" }, { "code": null, "e": 2382, "s": 2295, "text": "public class JLabel\n extends JComponent\n implements SwingConstants, Accessible\n" }, { "code": null, "e": 2438, "s": 2382, "text": "Following are the fields for javax.swing.JLabel class −" }, { "code": null, "e": 2467, "s": 2438, "text": "protected Component labelFor" }, { "code": null, "e": 2476, "s": 2467, "text": "JLabel()" }, { "code": null, "e": 2556, "s": 2476, "text": "Creates a JLabel instance with no image and with an empty string for the title." }, { "code": null, "e": 2575, "s": 2556, "text": "JLabel(Icon image)" }, { "code": null, "e": 2627, "s": 2575, "text": "Creates a JLabel instance with the specified image." }, { "code": null, "e": 2671, "s": 2627, "text": "JLabel(Icon image, int horizontalAlignment)" }, { "code": null, "e": 2748, "s": 2671, "text": "Creates a JLabel instance with the specified image and horizontal alignment." }, { "code": null, "e": 2768, "s": 2748, "text": "JLabel(String text)" }, { "code": null, "e": 2819, "s": 2768, "text": "Creates a JLabel instance with the specified text." }, { "code": null, "e": 2875, "s": 2819, "text": "JLabel(String text, Icon icon, int horizontalAlignment)" }, { "code": null, "e": 2959, "s": 2875, "text": "Creates a JLabel instance with the specified text, image, and horizontal alignment." }, { "code": null, "e": 3004, "s": 2959, "text": "JLabel(String text, int horizontalAlignment)" }, { "code": null, "e": 3080, "s": 3004, "text": "Creates a JLabel instance with the specified text and horizontal alignment." }, { "code": null, "e": 3138, "s": 3080, "text": "protected int checkHorizontalKey(int key, String message)" }, { "code": null, "e": 3211, "s": 3138, "text": "Verify that key is a legal value for the horizontalAlignment properties." }, { "code": null, "e": 3267, "s": 3211, "text": "protected int checkVerticalKey(int key, String message)" }, { "code": null, "e": 3362, "s": 3267, "text": "Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties." }, { "code": null, "e": 3403, "s": 3362, "text": "AccessibleContext\tgetAccessibleContext()" }, { "code": null, "e": 3445, "s": 3403, "text": "Get the AccessibleContext of this object." }, { "code": null, "e": 3468, "s": 3445, "text": "Icon getDisabledIcon()" }, { "code": null, "e": 3523, "s": 3468, "text": "Returns the icon used by the label when it's disabled." }, { "code": null, "e": 3550, "s": 3523, "text": "int getDisplayedMnemonic()" }, { "code": null, "e": 3600, "s": 3550, "text": "Return the keycode that indicates a mnemonic key." }, { "code": null, "e": 3632, "s": 3600, "text": "int getDisplayedMnemonicIndex()" }, { "code": null, "e": 3761, "s": 3632, "text": "Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character." }, { "code": null, "e": 3790, "s": 3761, "text": "int getHorizontalAlignment()" }, { "code": null, "e": 3854, "s": 3790, "text": "Returns the alignment of the label's contents along the X axis." }, { "code": null, "e": 3886, "s": 3854, "text": "int getHorizontalTextPosition()" }, { "code": null, "e": 3962, "s": 3886, "text": "Returns the horizontal position of the label's text, relative to its image." }, { "code": null, "e": 3977, "s": 3962, "text": "Icon getIcon()" }, { "code": null, "e": 4042, "s": 3977, "text": "Returns the graphic image (glyph, icon) that the label displays." }, { "code": null, "e": 4063, "s": 4042, "text": "int getIconTextGap()" }, { "code": null, "e": 4146, "s": 4063, "text": "Returns the amount of space between the text and the icon displayed in this label." }, { "code": null, "e": 4170, "s": 4146, "text": "Component\tgetLabelFor()" }, { "code": null, "e": 4207, "s": 4170, "text": "Get the component this is labelling." }, { "code": null, "e": 4224, "s": 4207, "text": "String getText()" }, { "code": null, "e": 4273, "s": 4224, "text": "Returns the text string that the label displays." }, { "code": null, "e": 4289, "s": 4273, "text": "LabelUI getUI()" }, { "code": null, "e": 4341, "s": 4289, "text": "Returns the L&F object that renders this component." }, { "code": null, "e": 4363, "s": 4341, "text": "String getUIClassID()" }, { "code": null, "e": 4451, "s": 4363, "text": "Returns a string that specifies the name of the l&f class which renders this component." }, { "code": null, "e": 4478, "s": 4451, "text": "int getVerticalAlignment()" }, { "code": null, "e": 4542, "s": 4478, "text": "Returns the alignment of the label's contents along the Y axis." }, { "code": null, "e": 4572, "s": 4542, "text": "int getVerticalTextPosition()" }, { "code": null, "e": 4646, "s": 4572, "text": "Returns the vertical position of the label's text, relative to its image." }, { "code": null, "e": 4720, "s": 4646, "text": "boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)" }, { "code": null, "e": 4824, "s": 4720, "text": "This is overridden to return false if the current Icon's image is not equal to the passed in Image img." }, { "code": null, "e": 4855, "s": 4824, "text": "protected String paramString()" }, { "code": null, "e": 4903, "s": 4855, "text": "Returns a string representation of this JLabel." }, { "code": null, "e": 4943, "s": 4903, "text": "void setDisabledIcon(Icon disabledIcon)" }, { "code": null, "e": 5030, "s": 4943, "text": "Sets the icon to be displayed if this JLabel is \"disabled\" (JLabel.setEnabled(false))." }, { "code": null, "e": 5068, "s": 5030, "text": "void setDisplayedMnemonic(char aChar)" }, { "code": null, "e": 5117, "s": 5068, "text": "Specifies the displayedMnemonic as a char value." }, { "code": null, "e": 5152, "s": 5117, "text": "void setDisplayedMnemonic(int key)" }, { "code": null, "e": 5203, "s": 5152, "text": "Specifies a keycode that indicates a mnemonic key." }, { "code": null, "e": 5245, "s": 5203, "text": "void setDisplayedMnemonicIndex(int index)" }, { "code": null, "e": 5363, "s": 5245, "text": "Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic." }, { "code": null, "e": 5406, "s": 5363, "text": "void setHorizontalAlignment(int alignment)" }, { "code": null, "e": 5467, "s": 5406, "text": "Sets the alignment of the label's contents along the X axis." }, { "code": null, "e": 5516, "s": 5467, "text": "void setHorizontalTextPosition(int textPosition)" }, { "code": null, "e": 5589, "s": 5516, "text": "Sets the horizontal position of the label's text, relative to its image." }, { "code": null, "e": 5613, "s": 5589, "text": "void setIcon(Icon icon)" }, { "code": null, "e": 5659, "s": 5613, "text": "Defines the icon this component will display." }, { "code": null, "e": 5696, "s": 5659, "text": "void setIconTextGap(int iconTextGap)" }, { "code": null, "e": 5788, "s": 5696, "text": "If both the icon and text properties are set, this property defines the space between them." }, { "code": null, "e": 5818, "s": 5788, "text": "void setLabelFor(Component c)" }, { "code": null, "e": 5857, "s": 5818, "text": "Sets the component, this is labelling." }, { "code": null, "e": 5883, "s": 5857, "text": "void setText(String text)" }, { "code": null, "e": 5944, "s": 5883, "text": "Defines the single line of text this component will display." }, { "code": null, "e": 5967, "s": 5944, "text": "void setUI(LabelUI ui)" }, { "code": null, "e": 6016, "s": 5967, "text": "Sets the L&F object that renders this component." }, { "code": null, "e": 6057, "s": 6016, "text": "void setVerticalAlignment(int alignment)" }, { "code": null, "e": 6118, "s": 6057, "text": "Sets the alignment of the label's contents along the Y axis." }, { "code": null, "e": 6165, "s": 6118, "text": "void setVerticalTextPosition(int textPosition)" }, { "code": null, "e": 6236, "s": 6165, "text": "Sets the vertical position of the label's text, relative to its image." }, { "code": null, "e": 6252, "s": 6236, "text": "void updateUI()" }, { "code": null, "e": 6318, "s": 6252, "text": "Resets the UI property to a value from the current look and feel." }, { "code": null, "e": 6375, "s": 6318, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 6398, "s": 6375, "text": "javax.swing.JComponent" }, { "code": null, "e": 6417, "s": 6398, "text": "java.awt.Container" }, { "code": null, "e": 6436, "s": 6417, "text": "java.awt.Component" }, { "code": null, "e": 6453, "s": 6436, "text": "java.lang.Object" }, { "code": null, "e": 6569, "s": 6453, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 8182, "s": 6569, "text": "package com.tutorialspoint.gui;\n \nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n \npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showLabelDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showLabelDemo(){\n headerLabel.setText(\"Control in action: JLabel\"); \n JLabel label = new JLabel(\"\", JLabel.CENTER); \n label.setText(\"Welcome to TutorialsPoint Swing Tutorial.\");\n label.setOpaque(true);\n label.setBackground(Color.GRAY);\n label.setForeground(Color.WHITE);\n controlPanel.add(label);\n \n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 8278, "s": 8182, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 8339, "s": 8278, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n" }, { "code": null, "e": 8444, "s": 8339, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 8499, "s": 8444, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingControlDemo\n" } ]
Python | sympy.Mod() method
02 Aug, 2019 With the help of sympy.Mod() method, we can find the modulus and can give the parameters separately by using sympy.Mod() method. Syntax : sympy.Mod(var1, var2)Return : Return a value of modulo. Example #1 :In this example we can see that by using sympy.Mod() method, we are able to find the modulus for a given parameters. # import sympyfrom sympy import * x, y = symbols('x y') # Using sympy.Mod() methodgfg = Mod(x, y).subs({x:7, y:2}) print(gfg) Output : 1 Example #2 : # import sympyfrom sympy import * x, y = symbols('x y') # Using sympy.Mod() methodgfg = Mod(x**2, y).subs({x:7, y:5}) print(gfg) Output : 4 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 157, "s": 28, "text": "With the help of sympy.Mod() method, we can find the modulus and can give the parameters separately by using sympy.Mod() method." }, { "code": null, "e": 222, "s": 157, "text": "Syntax : sympy.Mod(var1, var2)Return : Return a value of modulo." }, { "code": null, "e": 351, "s": 222, "text": "Example #1 :In this example we can see that by using sympy.Mod() method, we are able to find the modulus for a given parameters." }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y') # Using sympy.Mod() methodgfg = Mod(x, y).subs({x:7, y:2}) print(gfg)", "e": 481, "s": 351, "text": null }, { "code": null, "e": 490, "s": 481, "text": "Output :" }, { "code": null, "e": 492, "s": 490, "text": "1" }, { "code": null, "e": 505, "s": 492, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y') # Using sympy.Mod() methodgfg = Mod(x**2, y).subs({x:7, y:5}) print(gfg)", "e": 638, "s": 505, "text": null }, { "code": null, "e": 647, "s": 638, "text": "Output :" }, { "code": null, "e": 649, "s": 647, "text": "4" }, { "code": null, "e": 655, "s": 649, "text": "SymPy" }, { "code": null, "e": 662, "s": 655, "text": "Python" }, { "code": null, "e": 760, "s": 662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 805, "s": 760, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 855, "s": 805, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 871, "s": 855, "text": "Deque in Python" }, { "code": null, "e": 887, "s": 871, "text": "Queue in Python" }, { "code": null, "e": 909, "s": 887, "text": "Defaultdict in Python" }, { "code": null, "e": 951, "s": 909, "text": "Check if element exists in list in Python" }, { "code": null, "e": 978, "s": 951, "text": "Python Classes and Objects" }, { "code": null, "e": 1001, "s": 978, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 1020, "s": 1001, "text": "reduce() in Python" } ]
Backward iteration in Python
04 Jul, 2022 The iteration of numbers is done by looping techniques in Python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backward and having shorthands to do so can be quite useful. Let’s discuss certain ways in which this can be done. Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting. Python3 # Python3 code to demonstrate# backward iteration# using reversed() # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint ("The reversed numbers are : ", end = "")for num in reversed(range(N + 1)) : print(num, end = " ") The reversed numbers are : 6 5 4 3 2 1 0 Method #2 : Using range(N, -1, -1) This particular task can also be performed using the conventional range function which, if provided with the third argument performs the skip and second argument is used to start from backwards. Python3 # Python3 code to demonstrate# backward iteration# using range(N, -1, -1) # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint ("The reversed numbers are : ", end = "")for num in range(N, -1, -1) : print(num, end = " ") The reversed numbers are : 6 5 4 3 2 1 0 Method#3: Using slice syntax This particular task can also be performed using the slice syntax which, is used for reversing the list. We used it for reversing the range class in the for loop then we perform the backward iteration. Python3 # # Python3 code to demonstrate# # backward iteration# # using slice syntax # # Initializing number from which# # iteration beginsN = 6 # Using slice syntax perform the backward iterationk = range(N+1)[::-1]print("The reversed numbers are : ",end='')for i in k: print(i, end=' ') The reversed numbers are : 6 5 4 3 2 1 0 satyam00so shabankhn002 Python loop-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2022" }, { "code": null, "e": 339, "s": 52, "text": "The iteration of numbers is done by looping techniques in Python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backward and having shorthands to do so can be quite useful. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 541, "s": 339, "text": "Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting. " }, { "code": null, "e": 549, "s": 541, "text": "Python3" }, { "code": "# Python3 code to demonstrate# backward iteration# using reversed() # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint (\"The reversed numbers are : \", end = \"\")for num in reversed(range(N + 1)) : print(num, end = \" \")", "e": 829, "s": 549, "text": null }, { "code": null, "e": 871, "s": 829, "text": "The reversed numbers are : 6 5 4 3 2 1 0 " }, { "code": null, "e": 1103, "s": 871, "text": " Method #2 : Using range(N, -1, -1) This particular task can also be performed using the conventional range function which, if provided with the third argument performs the skip and second argument is used to start from backwards. " }, { "code": null, "e": 1111, "s": 1103, "text": "Python3" }, { "code": "# Python3 code to demonstrate# backward iteration# using range(N, -1, -1) # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint (\"The reversed numbers are : \", end = \"\")for num in range(N, -1, -1) : print(num, end = \" \")", "e": 1391, "s": 1111, "text": null }, { "code": null, "e": 1433, "s": 1391, "text": "The reversed numbers are : 6 5 4 3 2 1 0 " }, { "code": null, "e": 1664, "s": 1433, "text": "Method#3: Using slice syntax This particular task can also be performed using the slice syntax which, is used for reversing the list. We used it for reversing the range class in the for loop then we perform the backward iteration." }, { "code": null, "e": 1672, "s": 1664, "text": "Python3" }, { "code": "# # Python3 code to demonstrate# # backward iteration# # using slice syntax # # Initializing number from which# # iteration beginsN = 6 # Using slice syntax perform the backward iterationk = range(N+1)[::-1]print(\"The reversed numbers are : \",end='')for i in k: print(i, end=' ')", "e": 1956, "s": 1672, "text": null }, { "code": null, "e": 1998, "s": 1956, "text": "The reversed numbers are : 6 5 4 3 2 1 0 " }, { "code": null, "e": 2009, "s": 1998, "text": "satyam00so" }, { "code": null, "e": 2022, "s": 2009, "text": "shabankhn002" }, { "code": null, "e": 2043, "s": 2022, "text": "Python loop-programs" }, { "code": null, "e": 2050, "s": 2043, "text": "Python" }, { "code": null, "e": 2066, "s": 2050, "text": "Python Programs" }, { "code": null, "e": 2164, "s": 2066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2182, "s": 2164, "text": "Python Dictionary" }, { "code": null, "e": 2224, "s": 2182, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2246, "s": 2224, "text": "Enumerate() in Python" }, { "code": null, "e": 2272, "s": 2246, "text": "Python String | replace()" }, { "code": null, "e": 2304, "s": 2272, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2347, "s": 2304, "text": "Python program to convert a list to string" }, { "code": null, "e": 2369, "s": 2347, "text": "Defaultdict in Python" }, { "code": null, "e": 2408, "s": 2369, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2446, "s": 2408, "text": "Python | Convert a list to dictionary" } ]
Java Virtual Machine (JVM) Stack Area
20 Jun, 2021 For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Every method call performed by that thread is stored in the corresponding run-time stack including parameters, local variables, intermediate computations, and other data. After completing a method, the corresponding entry from the stack is removed. After completing all method calls the stack becomes empty and that empty stack is destroyed by the JVM just before terminating the thread. The data stored in the stack is available for the corresponding thread and not available to the remaining threads. Hence we can say local data thread-safe. Each entry in the stack is called Stack Frame or Activation Record. Stack Frame Structure The stack frame basically consists of three parts: Local Variable Array, Operand Stack & Frame Data. When JVM invokes a Java method, first it checks the class data to determine the number of words (size of the local variable array and operand stack, which is measured in words for each individual method) required by the method in the local variables array and operand stack. It creates a stack frame of the proper size for invoked method and pushes it onto the Java stack. 1. Local Variable Array (LVA): The local variables part of the stack frame is organized as a zero-based array of words. It contains all parameters and local variables of the method. Each slot or entry in the array is of 4 Bytes. Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4 bytes. Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes total. Byte, short, and char values will be converted to int type before storing and occupy 1 slot i.e. 4 Bytes. But the way of storing Boolean values is varied from JVM to JVM. But most of the JVM gives 1 slot for Boolean values in the local variable array. The parameters are placed into the local variable array first, in the order in which they are declared. For Example: Let us consider a class Example having a method bike() then the local variable array will be as shown in the below diagram: // Class Declaration class Example { public void bike(int i, long l, float f, double d, Object o, byte b) { } } 2. Operand Stack (OS): JVM uses operand stack as workspace like rough work or we can say for storing intermediate calculation’s result. The operand stack is organized as an array of words like a local variable array. But this is not accessed by using an index like local variable array rather it is accessed by some instructions that can push the value to the operand stack and some instructions that can pop values from the operand stack and some instructions that can perform required operations. For Example: Here is how a JVM will use this below code that would subtract two local variables that contain two ints and store the int result in a third local variable: So here first two instructions iload_0 and iload_1 will push the values in the operand stack from a local variable array. And instruction isub will subtract these two values and store the result back to the operand stack and after istore_2 the result will pop out from the operand stack and will store into a local variable array at position 2. 3. Frame Data (FD): It contains all symbolic references (constant pool resolution) and normal method returns related to that particular method. It also contains a reference to the Exception table which provides the corresponding catch block information in the case of exceptions. Manish Dhanuka sandeeprana1 vaibhavsinghtanwar java-basics java-JVM 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 How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2021" }, { "code": null, "e": 997, "s": 54, "text": "For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Every method call performed by that thread is stored in the corresponding run-time stack including parameters, local variables, intermediate computations, and other data. After completing a method, the corresponding entry from the stack is removed. After completing all method calls the stack becomes empty and that empty stack is destroyed by the JVM just before terminating the thread. The data stored in the stack is available for the corresponding thread and not available to the remaining threads. Hence we can say local data thread-safe. Each entry in the stack is called Stack Frame or Activation Record. " }, { "code": null, "e": 1496, "s": 999, "text": "Stack Frame Structure The stack frame basically consists of three parts: Local Variable Array, Operand Stack & Frame Data. When JVM invokes a Java method, first it checks the class data to determine the number of words (size of the local variable array and operand stack, which is measured in words for each individual method) required by the method in the local variables array and operand stack. It creates a stack frame of the proper size for invoked method and pushes it onto the Java stack. " }, { "code": null, "e": 1529, "s": 1496, "text": "1. Local Variable Array (LVA): " }, { "code": null, "e": 1618, "s": 1529, "text": "The local variables part of the stack frame is organized as a zero-based array of words." }, { "code": null, "e": 1680, "s": 1618, "text": "It contains all parameters and local variables of the method." }, { "code": null, "e": 1727, "s": 1680, "text": "Each slot or entry in the array is of 4 Bytes." }, { "code": null, "e": 1818, "s": 1727, "text": "Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4 bytes." }, { "code": null, "e": 1906, "s": 1818, "text": "Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes total." }, { "code": null, "e": 2012, "s": 1906, "text": "Byte, short, and char values will be converted to int type before storing and occupy 1 slot i.e. 4 Bytes." }, { "code": null, "e": 2158, "s": 2012, "text": "But the way of storing Boolean values is varied from JVM to JVM. But most of the JVM gives 1 slot for Boolean values in the local variable array." }, { "code": null, "e": 2262, "s": 2158, "text": "The parameters are placed into the local variable array first, in the order in which they are declared." }, { "code": null, "e": 2399, "s": 2262, "text": "For Example: Let us consider a class Example having a method bike() then the local variable array will be as shown in the below diagram:" }, { "code": null, "e": 2546, "s": 2401, "text": "// Class Declaration\nclass Example\n{\n public void bike(int i, long l, float f, \n double d, Object o, byte b)\n {\n \n } \n} " }, { "code": null, "e": 2573, "s": 2548, "text": "2. Operand Stack (OS): " }, { "code": null, "e": 2686, "s": 2573, "text": "JVM uses operand stack as workspace like rough work or we can say for storing intermediate calculation’s result." }, { "code": null, "e": 3049, "s": 2686, "text": "The operand stack is organized as an array of words like a local variable array. But this is not accessed by using an index like local variable array rather it is accessed by some instructions that can push the value to the operand stack and some instructions that can pop values from the operand stack and some instructions that can perform required operations." }, { "code": null, "e": 3219, "s": 3049, "text": "For Example: Here is how a JVM will use this below code that would subtract two local variables that contain two ints and store the int result in a third local variable:" }, { "code": null, "e": 3568, "s": 3223, "text": "So here first two instructions iload_0 and iload_1 will push the values in the operand stack from a local variable array. And instruction isub will subtract these two values and store the result back to the operand stack and after istore_2 the result will pop out from the operand stack and will store into a local variable array at position 2." }, { "code": null, "e": 3592, "s": 3570, "text": "3. Frame Data (FD): " }, { "code": null, "e": 3716, "s": 3592, "text": "It contains all symbolic references (constant pool resolution) and normal method returns related to that particular method." }, { "code": null, "e": 3852, "s": 3716, "text": "It also contains a reference to the Exception table which provides the corresponding catch block information in the case of exceptions." }, { "code": null, "e": 3869, "s": 3854, "text": "Manish Dhanuka" }, { "code": null, "e": 3882, "s": 3869, "text": "sandeeprana1" }, { "code": null, "e": 3901, "s": 3882, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 3913, "s": 3901, "text": "java-basics" }, { "code": null, "e": 3922, "s": 3913, "text": "java-JVM" }, { "code": null, "e": 3927, "s": 3922, "text": "Java" }, { "code": null, "e": 3932, "s": 3927, "text": "Java" }, { "code": null, "e": 4030, "s": 3932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4081, "s": 4030, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4112, "s": 4081, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4131, "s": 4112, "text": "Interfaces in Java" }, { "code": null, "e": 4161, "s": 4131, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4176, "s": 4161, "text": "Stream In Java" }, { "code": null, "e": 4194, "s": 4176, "text": "ArrayList in Java" }, { "code": null, "e": 4214, "s": 4194, "text": "Collections in Java" }, { "code": null, "e": 4238, "s": 4214, "text": "Singleton Class in Java" }, { "code": null, "e": 4270, "s": 4238, "text": "Multidimensional Arrays in Java" } ]
Bayesian logistic regression with PyMC3 | by Tung T. Nguyen | Towards Data Science
This is another article in a series of articles (see here and here for the other relevant articles) on probabilistic programming in general and PyMC3 in particular. In our previous articles, we explained how PyMC3 helps with statistical inference. In this article, we will solve a classification problem from end to end with PyMC3. More precisely, we will use PyMC3 to do Bayesian logistic regression using the following public dataset: https://archive.ics.uci.edu/ml/datasets/Occupancy+Detection+ The dataset contains several variables such as light, temperature, humidity, and CO2 levels. The goal is to detect a room’s occupancy from these variables. First, we will need to load several relevant packages. import arviz as azimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pymc3 as pmimport seabornimport theano.tensor as ttimport warningsfrom IPython.core.pylabtools import figsizeimport seaborn as snsfrom sklearn.metrics import (roc_curve, roc_auc_score, confusion_matrix, accuracy_score, f1_score, precision_recall_curve) from sklearn.metrics import confusion_matrix Next, we load the dataset. df=pd.read_csv('datatest.txt')df.sample(5) For convenience, we convert the date variable into a DateTime object. df['date']=pd.to_datetime(df['date']) First, let us take an overview of the dataset. df.describe() We see that there are 2655 samples in this dataset. Furthermore, there are no missing values. Let us also take a look at the timeframe of this dataset. df['date'].describe()count 2665unique 2665top 2015-02-03 07:25:59freq 1first 2015-02-02 14:19:00last 2015-02-04 10:43:00Name: date, dtype: object So our data are collected in only three days. Next, we will explore our variables and their relationship. First, let us plot the temperature variable. figsize(12.5, 4)plt.hist(df['Temperature'], bins=40, density=True, label='Temperature')plt.xlabel('Temperature')plt.title('Distribution of temperature')plt.show() The plot shows that the temperature has a heavy tail distribution. What about the Humidity variable? figsize(12.5, 4)plt.hist(df['Humidity'], bins=50, density=True, label='Humidity')plt.xlabel('Humidity')plt.title('Distribution of Humidity')plt.show() It is interesting to see that there are two peaks around 22.5 and 25. We are also interested in the Light variable during different days. figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['Light'], orient='v')plt.xlabel('Day')plt.title('Boxplot for Light during different days')plt.show() We see that the distributions of light are almost identical during these three days. Next, let us take a look at the CO2 level. figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['CO2'], orient='v')plt.xlabel('Day')plt.title('Boxplot for CO2 level during different days')plt.show() These distributions are significantly different. There are lots of outliers on 2/4/2015. Finally, we will dive into the Humidity Ratio variable. figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['HumidityRatio'], orient='v')plt.xlabel('Day')plt.title('Boxplot for Humidity Ratio level during different days')plt.show() This looks pretty much similar to the boxplot for the CO2 level. Maybe, there is a strong correlation between the CO2 level and Humidity Ratio. We can check that by using a scatter plot for these two variables. ax=sns.scatterplot(df['CO2'], df['HumidityRatio'], style=df['date'].dt.day) Indeed, there is a strong linear relationship between the CO2 level and the Humidity Ratio. Let us take an overview of the relation between our variables. This can be done by the pair plot function with seaborn. ax=seaborn.pairplot(df) This visually shows that there is a strong linear relationship between the following pairs: CO2 and temperature, CO2 and Humidity, Humidity and Humidity Ratio, Humidity Ration, and CO2. We can even quantify these relations by plotting the heatmap. corr=df.iloc[:, 1:-1].corr()# Generate a mask for the upper trianglemask = np.triu(np.ones_like(corr, dtype=np.bool))# Set up the matplotlib figuref, ax = plt.subplots(figsize=(11, 9))# Draw the heatmap with the mask and correct aspect ratioax=sns.heatmap(corr, mask=mask, square=True, linewidths=.5, cbar_kws={"shrink": .5}) It is clearly shown that the two pairs Humidity-Humidity Ration and Humidity Ratio-CO2 express the strongest linear relationship. We will build several machine learning models to classify Occupancy based on other variables. Recall that we have a binary decision problem. In other words, our target variable is assumed to follow a Bernoulli random variable with p given by: where var is the set of all variables that we use in our model and logit is the logistic function. To build a Bayesian logistic regression model, we first have to put a prior distribution on each parameter. The choice of these priors will affect the outcome (though with more data, they probably will “converge” to the same distribution.) Once our priors are specified, PyMC3 will numerically approximate the posterior distributions using Markov Chain Monte Carlo simulations and its generalizations. We can then use samples from these posteriors to make inferences. Since we have no prior knowledge about these parameters, we can assume that they could be anything. In other words, we assume that all β_var follows a uniform distribution with large lower and upper bounds. In order to catch a big net, we use big lower and upper bounds for our uniform distributions. lower=-10**6higher=10**6with pm.Model() as first_model: #priors on parameters beta_0=pm.Uniform('beta_0', lower=lower, upper= higher) beta_temp=pm.Uniform('beta_temp', lower, higher) beta_humid=pm.Uniform('beta_humid', lower, higher) beta_light=pm.Uniform('beta_light', lower, higher) beta_co2=pm.Uniform('beta_co2', lower, higher) beta_humid_ratio=pm.Uniform('beta_humid_ration', lower, higher) #the probability of belonging to class 1 p = pm.Deterministic('p', pm.math.sigmoid(beta_0+beta_temp*df['Temperature']+ beta_humid*df['Humidity']+ beta_light*df['Light']+ beta_co2*df['CO2']+ beta_humid_ratio*df['HumidityRatio']))with first_model: #fit the data observed=pm.Bernoulli("occupancy", p, observed=df['Occupancy']) start=pm.find_MAP() step=pm.Metropolis() #samples from posterior distribution trace=pm.sample(25000, step=step, start=start) burned_trace=trace[15000:] This might take a while to run. Once it is done, we can plot the samples. pm.traceplot(burned_trace)plt.show() We conclude that our algorithm does converge. We can compute the mean of these posterior distributions. coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[burned_trace[item].mean()] result_coeffs=pd.DataFrame.from_dict(d) result_coeffs#coeff_result=pd.DataFrame(d) #coeff_result An advantage of Bayesian statistics in comparison with frequentist statistics is that we have a lot more than just a mean value. In particular, we can compute the 95% High-Density Interval for those parameters. pm.stats.hpd(burned_trace['beta_0'])coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']interval=dict()for item in coeffs: interval[item]=pm.stats.hpd(burned_trace[item]) #compute 95% high density interval result_coeffs=pd.DataFrame.from_dict(interval).rename(index={0: 'lower', 1: 'upper'})result_coeffs Note that, the coefficients of the Humidity Ratio are significantly bigger than other coefficients. That does not necessarily mean that this variable is more important. If we take a close look at the data, we observe that this variable takes very small values. Furthermore, we can explore the relationship between different parameters. For example, let us take a look at the beta_co2 and beta_humid_ratio coefficients. figsize(12.5, 12.5)seaborn.jointplot(burned_trace['beta_co2'], burned_trace['beta_humid_ration'], kind="hex") #color="#4CB391")plt.xlabel("beta_co2")plt.ylabel("beta_humid_ratio"); The plots show that these two coefficients are negatively correlated. Note that the CO2 level and Humidity Ratio are positively correlated. Recall that in classical logistic regression, we find for the best parameters by maximum a posteriori estimation (MAP solution). In other words, the best-fitted parameters are given by where p(θ|D)p(θ|D) is the posterior distribution of θ given the data, p(D|θ) is the likelihood function, and p(θ) is the prior distribution of θ. Note that since we use uniform distributions on our first model, we can expect that our MAP solution should coincide with the MLE solution (maximum likelihood estimation) which corresponds to frequentist logistic regression. We can use the Scikit-Learn library to test this statement. First, we compute the coefficients using MAP. coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[float(start[item])] map_coeffs=pd.DataFrame.from_dict(d) map_coeffs Next, we compute the beta coefficients using classical logistic regression. from sklearn.linear_model import LogisticRegressionX=df.iloc[:, 1: -1]y=df['Occupancy']logit=LogisticRegression()logit_model=logit.fit(X,y)pd.DataFrame(logit_model.coef_, columns=X.columns) YES! The coefficients for the two methods are almost identical. Next, we discuss the prediction power of our model and compare it with the classical logistic regression. We record the prediction using the classical method. logit_prediction=logit_model.predict(X) To make predictions with our Bayesian logistic model, we compute the y_score by averaging over our sample values. #compute the average probability of predicting 1. y_score = np.mean(burned_trace['p'], axis=0)#histogram of the distributionfigsize(12.5,4)plt.hist(y_score, bins=40, density=True)plt.xlabel('Probability')plt.ylabel('Frequency')plt.title('Distribution of $y_score$')plt.show() It is interesting to see that the majority of p is concentrated near 0 and 1. We can use y_score to make a prediction as well. first_model_prediction=[1 if x >0.5 else 0 for x in y_score] Let us evaluate the performance of our model by computing the confusion matrix. first_model_confussion_matrix =confusion_matrix(df['Occupancy'], first_model_prediction)first_model_confussion_matrixarray([[1639, 54], [ 3, 969]]) This is pretty good. We can even quantify the performance by other metrics as well. import sklearnfrom sklearn.metrics import classification_reportprint(sklearn.metrics.classification_report(y, first_model_prediction))precision recall f1-score support 0 1.00 0.97 0.98 1693 1 0.95 1.00 0.97 972 accuracy 0.98 2665 macro avg 0.97 0.98 0.98 2665weighted avg 0.98 0.98 0.98 2665 We can also compute the area under the curve. pred_scores = dict(y_true=df['Occupancy'],y_score=y_score)roc_auc_score(**pred_scores)0.99358530283253 So, our model performs pretty well. Let’s compare it with the classical logistic regression. print(sklearn.metrics.classification_report(y, logit_prediction))precision recall f1-score support 0 1.00 0.97 0.98 1693 1 0.95 1.00 0.97 972 accuracy 0.98 2665 macro avg 0.97 0.98 0.98 2665weighted avg 0.98 0.98 0.98 2665 They are the same! However, with the Bayesian model, we gain more information and hence we are more confident about our estimations. Now, let us train our model using a different set of priors. For example, we can assume that the coefficients follow normal distributions. with pm.Model() as second_model: #priors with normal distribution beta_0=pm.Normal('beta_0', mu=0, sd=10**4) beta_temp=pm.Normal('beta_temp', mu=0, sd=10**4) beta_humid=pm.Normal('beta_humid', mu=0, sd=10**4) beta_light=pm.Normal('beta_light', mu=0, sd=10**4) beta_co2=pm.Normal('beta_co2', mu=0, sd=10**4) beta_humid_ratio=pm.Normal('beta_humid_ration', mu=0, sd=10**4) #probability of belonging to class 1 p = pm.Deterministic('p', pm.math.sigmoid(beta_0+beta_temp*df['Temperature']+ beta_humid*df['Humidity']+ beta_light*df['Light']+ beta_co2*df['CO2']+ beta_humid_ratio*df['HumidityRatio']))#fit observed data into the modelwith second_model: observed=pm.Bernoulli("occupancy", p, observed=df['Occupancy']) start=pm.find_MAP() step=pm.Metropolis() second_trace=pm.sample(25000, step=step, start=start) second_burned_trace=second_trace[15000:]pm.traceplot(second_burned_trace)plt.show() Again, we see that the algorithm does converge. Let us compute the beta coefficients for the MAP solution. coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[float(start[item])] second_map_coeffs=pd.DataFrame.from_dict(d) second_map_coeffs They are very closed to the ones that we got in the first model. To go further, as we are in a Bayesian framework, we can even compare the posterior distributions across the two models. For example, let take a look at the intercept variable. figsize(12.5,4)plt.hist(burned_trace['beta_0']-second_burned_trace['beta_0'], bins=40, density=True)plt.title('Distribution of the difference between beta_0')plt.legend()plt.show() While the MAP solutions give the same estimation for β_0, we see that the two posteriors are rather different. Let us also compare the posterior distributions of β_temp between these two models. figsize(12.5,4)plt.hist(burned_trace['beta_temp'], label='First model', bins=40, density=True)plt.hist(second_burned_trace['beta_temp'], bins=40, label='Second model', density=True)plt.title('Distribution of of beta_temp')plt.legend()plt.show() The difference is in fact small. Next, let us compute the prediction power of the second model. second_y_score = np.mean(second_burned_trace['p'], axis=0)second_model_prediction=[1 if x >0.5 else 0 for x in second_y_score]second_model_confussion_matrix =confusion_matrix(df['Occupancy'], second_model_prediction)second_model_confussion_matrixarray([[1639, 54], [ 3, 969]]) This is identical to the result that we got from the first model. We can check that the y_score and second_y_score are almost the same. figsize(12.5,4)plt.hist(y_score-second_y_score, bins=40)plt.title('Distribution of the difference between y_score and second_y_score')plt.ylabel('Frequency')plt.show() In the previous sections, we use a hands-on approach to build our models. This is rather easy because we only have a few variables. When the number of variables is very large, it will not be very practical. Fortunately, PyMC3 has a built-in generalized linear model in which everything will be automated. Let us use this built-in model to fit our data. with pm.Model() as third_model: pm.glm.GLM.from_formula('Occupancy ~ Temperature + Humidity + Light + CO2 + HumidityRatio', df, family=pm.glm.families.Binomial()) third_trace = pm.sample(25000, tune=10000, init='adapt_diag')pm.traceplot(third_trace)plt.show() Unlike the previous models, the posterior distributions of our parameters are unimodal in this case. Let us get a summary of these posterior distributions. pm.summary(third_trace) Instead of looking at summarized statistics, we can also look at the MAP solution. with third_model: map_solution=pm.find_MAP()d=dict()for item in map_solution.keys(): d[item]=[float(map_solution[item])] third_map_coeffs=pd.DataFrame.from_dict(d) third_map_coeffs We see that there is a significant difference between the MAP solutions between the second and the third model. What about prediction? with third_model: ppc = pm.sample_posterior_predictive(third_trace, samples=15000)#compute y_score with third_model: third_y_score = np.mean(ppc['y'], axis=0)#convert y_score into binary decisions third_model_prediction=[1 if x >0.5 else 0 for x in third_y_score]#compute confussion matrix third_model_confussion_matrix =confusion_matrix(df['Occupancy'], third_model_prediction)third_model_confussion_matrixarray([[1639, 54], [ 3, 969]]) This confusion matrix is identical to the ones from the first two models. What about the distributions of y_scores for the second and the third model? figsize(12.5,4)plt.hist(third_y_score-second_y_score, bins=40)plt.title('Distribution of the difference between y_score and second_y_score')plt.ylabel('Frequency')plt.show( This distribution concentrates around 0. In other words, the distribution of y_scores is almost the same across different models. What about the coefficients, for example, the coefficients for temperature? figsize(12.5,4)plt.hist(third_trace['Temperature'][-40000:]-second_burned_trace['beta_temp'], bins=40, density=True)plt.title('Difference between the temperature coefficients for the second and the third model')plt.show() The difference approximately follows a normal distribution with a small mean. Let us also check the difference between the humidity coefficients. figsize(12.5,4)plt.boxplot(third_trace['Humidity'][-40000:]-second_burned_trace['beta_humid'])plt.title('Difference between the humidity coefficients for the second and the third model')plt.show() Again, that difference is small. We see that even though our models use different priors, the prediction performances are similar. This confirms our belief that as our dataset gets bigger, they should converge to the same solution. We expect that our project will beginners to PyMC3 learn its syntaxes. We find PyMC3’s codes rather intuitive and we hope that our codes clearly demonstrate this point. [1] https://docs.pymc.io/notebooks/GLM-logistic.html Official PyMC3 documentation
[ { "code": null, "e": 608, "s": 171, "text": "This is another article in a series of articles (see here and here for the other relevant articles) on probabilistic programming in general and PyMC3 in particular. In our previous articles, we explained how PyMC3 helps with statistical inference. In this article, we will solve a classification problem from end to end with PyMC3. More precisely, we will use PyMC3 to do Bayesian logistic regression using the following public dataset:" }, { "code": null, "e": 669, "s": 608, "text": "https://archive.ics.uci.edu/ml/datasets/Occupancy+Detection+" }, { "code": null, "e": 825, "s": 669, "text": "The dataset contains several variables such as light, temperature, humidity, and CO2 levels. The goal is to detect a room’s occupancy from these variables." }, { "code": null, "e": 880, "s": 825, "text": "First, we will need to load several relevant packages." }, { "code": null, "e": 1300, "s": 880, "text": "import arviz as azimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pymc3 as pmimport seabornimport theano.tensor as ttimport warningsfrom IPython.core.pylabtools import figsizeimport seaborn as snsfrom sklearn.metrics import (roc_curve, roc_auc_score, confusion_matrix, accuracy_score, f1_score, precision_recall_curve) from sklearn.metrics import confusion_matrix" }, { "code": null, "e": 1327, "s": 1300, "text": "Next, we load the dataset." }, { "code": null, "e": 1370, "s": 1327, "text": "df=pd.read_csv('datatest.txt')df.sample(5)" }, { "code": null, "e": 1440, "s": 1370, "text": "For convenience, we convert the date variable into a DateTime object." }, { "code": null, "e": 1478, "s": 1440, "text": "df['date']=pd.to_datetime(df['date'])" }, { "code": null, "e": 1525, "s": 1478, "text": "First, let us take an overview of the dataset." }, { "code": null, "e": 1539, "s": 1525, "text": "df.describe()" }, { "code": null, "e": 1691, "s": 1539, "text": "We see that there are 2655 samples in this dataset. Furthermore, there are no missing values. Let us also take a look at the timeframe of this dataset." }, { "code": null, "e": 1912, "s": 1691, "text": "df['date'].describe()count 2665unique 2665top 2015-02-03 07:25:59freq 1first 2015-02-02 14:19:00last 2015-02-04 10:43:00Name: date, dtype: object" }, { "code": null, "e": 2063, "s": 1912, "text": "So our data are collected in only three days. Next, we will explore our variables and their relationship. First, let us plot the temperature variable." }, { "code": null, "e": 2226, "s": 2063, "text": "figsize(12.5, 4)plt.hist(df['Temperature'], bins=40, density=True, label='Temperature')plt.xlabel('Temperature')plt.title('Distribution of temperature')plt.show()" }, { "code": null, "e": 2327, "s": 2226, "text": "The plot shows that the temperature has a heavy tail distribution. What about the Humidity variable?" }, { "code": null, "e": 2478, "s": 2327, "text": "figsize(12.5, 4)plt.hist(df['Humidity'], bins=50, density=True, label='Humidity')plt.xlabel('Humidity')plt.title('Distribution of Humidity')plt.show()" }, { "code": null, "e": 2616, "s": 2478, "text": "It is interesting to see that there are two peaks around 22.5 and 25. We are also interested in the Light variable during different days." }, { "code": null, "e": 2770, "s": 2616, "text": "figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['Light'], orient='v')plt.xlabel('Day')plt.title('Boxplot for Light during different days')plt.show()" }, { "code": null, "e": 2898, "s": 2770, "text": "We see that the distributions of light are almost identical during these three days. Next, let us take a look at the CO2 level." }, { "code": null, "e": 3054, "s": 2898, "text": "figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['CO2'], orient='v')plt.xlabel('Day')plt.title('Boxplot for CO2 level during different days')plt.show()" }, { "code": null, "e": 3199, "s": 3054, "text": "These distributions are significantly different. There are lots of outliers on 2/4/2015. Finally, we will dive into the Humidity Ratio variable." }, { "code": null, "e": 3376, "s": 3199, "text": "figsize(12.5, 4)sns.boxplot(x=df['date'].dt.day,y=df['HumidityRatio'], orient='v')plt.xlabel('Day')plt.title('Boxplot for Humidity Ratio level during different days')plt.show()" }, { "code": null, "e": 3587, "s": 3376, "text": "This looks pretty much similar to the boxplot for the CO2 level. Maybe, there is a strong correlation between the CO2 level and Humidity Ratio. We can check that by using a scatter plot for these two variables." }, { "code": null, "e": 3663, "s": 3587, "text": "ax=sns.scatterplot(df['CO2'], df['HumidityRatio'], style=df['date'].dt.day)" }, { "code": null, "e": 3875, "s": 3663, "text": "Indeed, there is a strong linear relationship between the CO2 level and the Humidity Ratio. Let us take an overview of the relation between our variables. This can be done by the pair plot function with seaborn." }, { "code": null, "e": 3899, "s": 3875, "text": "ax=seaborn.pairplot(df)" }, { "code": null, "e": 4147, "s": 3899, "text": "This visually shows that there is a strong linear relationship between the following pairs: CO2 and temperature, CO2 and Humidity, Humidity and Humidity Ratio, Humidity Ration, and CO2. We can even quantify these relations by plotting the heatmap." }, { "code": null, "e": 4484, "s": 4147, "text": "corr=df.iloc[:, 1:-1].corr()# Generate a mask for the upper trianglemask = np.triu(np.ones_like(corr, dtype=np.bool))# Set up the matplotlib figuref, ax = plt.subplots(figsize=(11, 9))# Draw the heatmap with the mask and correct aspect ratioax=sns.heatmap(corr, mask=mask, square=True, linewidths=.5, cbar_kws={\"shrink\": .5})" }, { "code": null, "e": 4614, "s": 4484, "text": "It is clearly shown that the two pairs Humidity-Humidity Ration and Humidity Ratio-CO2 express the strongest linear relationship." }, { "code": null, "e": 4708, "s": 4614, "text": "We will build several machine learning models to classify Occupancy based on other variables." }, { "code": null, "e": 4857, "s": 4708, "text": "Recall that we have a binary decision problem. In other words, our target variable is assumed to follow a Bernoulli random variable with p given by:" }, { "code": null, "e": 4956, "s": 4857, "text": "where var is the set of all variables that we use in our model and logit is the logistic function." }, { "code": null, "e": 5196, "s": 4956, "text": "To build a Bayesian logistic regression model, we first have to put a prior distribution on each parameter. The choice of these priors will affect the outcome (though with more data, they probably will “converge” to the same distribution.)" }, { "code": null, "e": 5424, "s": 5196, "text": "Once our priors are specified, PyMC3 will numerically approximate the posterior distributions using Markov Chain Monte Carlo simulations and its generalizations. We can then use samples from these posteriors to make inferences." }, { "code": null, "e": 5725, "s": 5424, "text": "Since we have no prior knowledge about these parameters, we can assume that they could be anything. In other words, we assume that all β_var follows a uniform distribution with large lower and upper bounds. In order to catch a big net, we use big lower and upper bounds for our uniform distributions." }, { "code": null, "e": 6775, "s": 5725, "text": "lower=-10**6higher=10**6with pm.Model() as first_model: #priors on parameters beta_0=pm.Uniform('beta_0', lower=lower, upper= higher) beta_temp=pm.Uniform('beta_temp', lower, higher) beta_humid=pm.Uniform('beta_humid', lower, higher) beta_light=pm.Uniform('beta_light', lower, higher) beta_co2=pm.Uniform('beta_co2', lower, higher) beta_humid_ratio=pm.Uniform('beta_humid_ration', lower, higher) #the probability of belonging to class 1 p = pm.Deterministic('p', pm.math.sigmoid(beta_0+beta_temp*df['Temperature']+ beta_humid*df['Humidity']+ beta_light*df['Light']+ beta_co2*df['CO2']+ beta_humid_ratio*df['HumidityRatio']))with first_model: #fit the data observed=pm.Bernoulli(\"occupancy\", p, observed=df['Occupancy']) start=pm.find_MAP() step=pm.Metropolis() #samples from posterior distribution trace=pm.sample(25000, step=step, start=start) burned_trace=trace[15000:]" }, { "code": null, "e": 6849, "s": 6775, "text": "This might take a while to run. Once it is done, we can plot the samples." }, { "code": null, "e": 6886, "s": 6849, "text": "pm.traceplot(burned_trace)plt.show()" }, { "code": null, "e": 6990, "s": 6886, "text": "We conclude that our algorithm does converge. We can compute the mean of these posterior distributions." }, { "code": null, "e": 7254, "s": 6990, "text": "coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[burned_trace[item].mean()] result_coeffs=pd.DataFrame.from_dict(d) result_coeffs#coeff_result=pd.DataFrame(d) #coeff_result" }, { "code": null, "e": 7465, "s": 7254, "text": "An advantage of Bayesian statistics in comparison with frequentist statistics is that we have a lot more than just a mean value. In particular, we can compute the 95% High-Density Interval for those parameters." }, { "code": null, "e": 7815, "s": 7465, "text": "pm.stats.hpd(burned_trace['beta_0'])coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']interval=dict()for item in coeffs: interval[item]=pm.stats.hpd(burned_trace[item]) #compute 95% high density interval result_coeffs=pd.DataFrame.from_dict(interval).rename(index={0: 'lower', 1: 'upper'})result_coeffs" }, { "code": null, "e": 8076, "s": 7815, "text": "Note that, the coefficients of the Humidity Ratio are significantly bigger than other coefficients. That does not necessarily mean that this variable is more important. If we take a close look at the data, we observe that this variable takes very small values." }, { "code": null, "e": 8234, "s": 8076, "text": "Furthermore, we can explore the relationship between different parameters. For example, let us take a look at the beta_co2 and beta_humid_ratio coefficients." }, { "code": null, "e": 8415, "s": 8234, "text": "figsize(12.5, 12.5)seaborn.jointplot(burned_trace['beta_co2'], burned_trace['beta_humid_ration'], kind=\"hex\") #color=\"#4CB391\")plt.xlabel(\"beta_co2\")plt.ylabel(\"beta_humid_ratio\");" }, { "code": null, "e": 8555, "s": 8415, "text": "The plots show that these two coefficients are negatively correlated. Note that the CO2 level and Humidity Ratio are positively correlated." }, { "code": null, "e": 8740, "s": 8555, "text": "Recall that in classical logistic regression, we find for the best parameters by maximum a posteriori estimation (MAP solution). In other words, the best-fitted parameters are given by" }, { "code": null, "e": 8886, "s": 8740, "text": "where p(θ|D)p(θ|D) is the posterior distribution of θ given the data, p(D|θ) is the likelihood function, and p(θ) is the prior distribution of θ." }, { "code": null, "e": 9217, "s": 8886, "text": "Note that since we use uniform distributions on our first model, we can expect that our MAP solution should coincide with the MLE solution (maximum likelihood estimation) which corresponds to frequentist logistic regression. We can use the Scikit-Learn library to test this statement. First, we compute the coefficients using MAP." }, { "code": null, "e": 9422, "s": 9217, "text": "coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[float(start[item])] map_coeffs=pd.DataFrame.from_dict(d) map_coeffs" }, { "code": null, "e": 9498, "s": 9422, "text": "Next, we compute the beta coefficients using classical logistic regression." }, { "code": null, "e": 9688, "s": 9498, "text": "from sklearn.linear_model import LogisticRegressionX=df.iloc[:, 1: -1]y=df['Occupancy']logit=LogisticRegression()logit_model=logit.fit(X,y)pd.DataFrame(logit_model.coef_, columns=X.columns)" }, { "code": null, "e": 9752, "s": 9688, "text": "YES! The coefficients for the two methods are almost identical." }, { "code": null, "e": 9911, "s": 9752, "text": "Next, we discuss the prediction power of our model and compare it with the classical logistic regression. We record the prediction using the classical method." }, { "code": null, "e": 9951, "s": 9911, "text": "logit_prediction=logit_model.predict(X)" }, { "code": null, "e": 10065, "s": 9951, "text": "To make predictions with our Bayesian logistic model, we compute the y_score by averaging over our sample values." }, { "code": null, "e": 10341, "s": 10065, "text": "#compute the average probability of predicting 1. y_score = np.mean(burned_trace['p'], axis=0)#histogram of the distributionfigsize(12.5,4)plt.hist(y_score, bins=40, density=True)plt.xlabel('Probability')plt.ylabel('Frequency')plt.title('Distribution of $y_score$')plt.show()" }, { "code": null, "e": 10468, "s": 10341, "text": "It is interesting to see that the majority of p is concentrated near 0 and 1. We can use y_score to make a prediction as well." }, { "code": null, "e": 10529, "s": 10468, "text": "first_model_prediction=[1 if x >0.5 else 0 for x in y_score]" }, { "code": null, "e": 10609, "s": 10529, "text": "Let us evaluate the performance of our model by computing the confusion matrix." }, { "code": null, "e": 10768, "s": 10609, "text": "first_model_confussion_matrix =confusion_matrix(df['Occupancy'], first_model_prediction)first_model_confussion_matrixarray([[1639, 54], [ 3, 969]])" }, { "code": null, "e": 10852, "s": 10768, "text": "This is pretty good. We can even quantify the performance by other metrics as well." }, { "code": null, "e": 11291, "s": 10852, "text": "import sklearnfrom sklearn.metrics import classification_reportprint(sklearn.metrics.classification_report(y, first_model_prediction))precision recall f1-score support 0 1.00 0.97 0.98 1693 1 0.95 1.00 0.97 972 accuracy 0.98 2665 macro avg 0.97 0.98 0.98 2665weighted avg 0.98 0.98 0.98 2665" }, { "code": null, "e": 11337, "s": 11291, "text": "We can also compute the area under the curve." }, { "code": null, "e": 11440, "s": 11337, "text": "pred_scores = dict(y_true=df['Occupancy'],y_score=y_score)roc_auc_score(**pred_scores)0.99358530283253" }, { "code": null, "e": 11533, "s": 11440, "text": "So, our model performs pretty well. Let’s compare it with the classical logistic regression." }, { "code": null, "e": 11903, "s": 11533, "text": "print(sklearn.metrics.classification_report(y, logit_prediction))precision recall f1-score support 0 1.00 0.97 0.98 1693 1 0.95 1.00 0.97 972 accuracy 0.98 2665 macro avg 0.97 0.98 0.98 2665weighted avg 0.98 0.98 0.98 2665" }, { "code": null, "e": 12036, "s": 11903, "text": "They are the same! However, with the Bayesian model, we gain more information and hence we are more confident about our estimations." }, { "code": null, "e": 12175, "s": 12036, "text": "Now, let us train our model using a different set of priors. For example, we can assume that the coefficients follow normal distributions." }, { "code": null, "e": 13228, "s": 12175, "text": "with pm.Model() as second_model: #priors with normal distribution beta_0=pm.Normal('beta_0', mu=0, sd=10**4) beta_temp=pm.Normal('beta_temp', mu=0, sd=10**4) beta_humid=pm.Normal('beta_humid', mu=0, sd=10**4) beta_light=pm.Normal('beta_light', mu=0, sd=10**4) beta_co2=pm.Normal('beta_co2', mu=0, sd=10**4) beta_humid_ratio=pm.Normal('beta_humid_ration', mu=0, sd=10**4) #probability of belonging to class 1 p = pm.Deterministic('p', pm.math.sigmoid(beta_0+beta_temp*df['Temperature']+ beta_humid*df['Humidity']+ beta_light*df['Light']+ beta_co2*df['CO2']+ beta_humid_ratio*df['HumidityRatio']))#fit observed data into the modelwith second_model: observed=pm.Bernoulli(\"occupancy\", p, observed=df['Occupancy']) start=pm.find_MAP() step=pm.Metropolis() second_trace=pm.sample(25000, step=step, start=start) second_burned_trace=second_trace[15000:]pm.traceplot(second_burned_trace)plt.show()" }, { "code": null, "e": 13335, "s": 13228, "text": "Again, we see that the algorithm does converge. Let us compute the beta coefficients for the MAP solution." }, { "code": null, "e": 13554, "s": 13335, "text": "coeffs=['beta_0', 'beta_temp', 'beta_humid', 'beta_light', 'beta_co2', 'beta_humid_ration']d=dict()for item in coeffs: d[item]=[float(start[item])] second_map_coeffs=pd.DataFrame.from_dict(d) second_map_coeffs" }, { "code": null, "e": 13796, "s": 13554, "text": "They are very closed to the ones that we got in the first model. To go further, as we are in a Bayesian framework, we can even compare the posterior distributions across the two models. For example, let take a look at the intercept variable." }, { "code": null, "e": 13977, "s": 13796, "text": "figsize(12.5,4)plt.hist(burned_trace['beta_0']-second_burned_trace['beta_0'], bins=40, density=True)plt.title('Distribution of the difference between beta_0')plt.legend()plt.show()" }, { "code": null, "e": 14172, "s": 13977, "text": "While the MAP solutions give the same estimation for β_0, we see that the two posteriors are rather different. Let us also compare the posterior distributions of β_temp between these two models." }, { "code": null, "e": 14417, "s": 14172, "text": "figsize(12.5,4)plt.hist(burned_trace['beta_temp'], label='First model', bins=40, density=True)plt.hist(second_burned_trace['beta_temp'], bins=40, label='Second model', density=True)plt.title('Distribution of of beta_temp')plt.legend()plt.show()" }, { "code": null, "e": 14513, "s": 14417, "text": "The difference is in fact small. Next, let us compute the prediction power of the second model." }, { "code": null, "e": 14801, "s": 14513, "text": "second_y_score = np.mean(second_burned_trace['p'], axis=0)second_model_prediction=[1 if x >0.5 else 0 for x in second_y_score]second_model_confussion_matrix =confusion_matrix(df['Occupancy'], second_model_prediction)second_model_confussion_matrixarray([[1639, 54], [ 3, 969]])" }, { "code": null, "e": 14937, "s": 14801, "text": "This is identical to the result that we got from the first model. We can check that the y_score and second_y_score are almost the same." }, { "code": null, "e": 15105, "s": 14937, "text": "figsize(12.5,4)plt.hist(y_score-second_y_score, bins=40)plt.title('Distribution of the difference between y_score and second_y_score')plt.ylabel('Frequency')plt.show()" }, { "code": null, "e": 15458, "s": 15105, "text": "In the previous sections, we use a hands-on approach to build our models. This is rather easy because we only have a few variables. When the number of variables is very large, it will not be very practical. Fortunately, PyMC3 has a built-in generalized linear model in which everything will be automated. Let us use this built-in model to fit our data." }, { "code": null, "e": 15778, "s": 15458, "text": "with pm.Model() as third_model: pm.glm.GLM.from_formula('Occupancy ~ Temperature + Humidity + Light + CO2 + HumidityRatio', df, family=pm.glm.families.Binomial()) third_trace = pm.sample(25000, tune=10000, init='adapt_diag')pm.traceplot(third_trace)plt.show()" }, { "code": null, "e": 15879, "s": 15778, "text": "Unlike the previous models, the posterior distributions of our parameters are unimodal in this case." }, { "code": null, "e": 15934, "s": 15879, "text": "Let us get a summary of these posterior distributions." }, { "code": null, "e": 15958, "s": 15934, "text": "pm.summary(third_trace)" }, { "code": null, "e": 16041, "s": 15958, "text": "Instead of looking at summarized statistics, we can also look at the MAP solution." }, { "code": null, "e": 16234, "s": 16041, "text": "with third_model: map_solution=pm.find_MAP()d=dict()for item in map_solution.keys(): d[item]=[float(map_solution[item])] third_map_coeffs=pd.DataFrame.from_dict(d) third_map_coeffs" }, { "code": null, "e": 16369, "s": 16234, "text": "We see that there is a significant difference between the MAP solutions between the second and the third model. What about prediction?" }, { "code": null, "e": 16827, "s": 16369, "text": "with third_model: ppc = pm.sample_posterior_predictive(third_trace, samples=15000)#compute y_score with third_model: third_y_score = np.mean(ppc['y'], axis=0)#convert y_score into binary decisions third_model_prediction=[1 if x >0.5 else 0 for x in third_y_score]#compute confussion matrix third_model_confussion_matrix =confusion_matrix(df['Occupancy'], third_model_prediction)third_model_confussion_matrixarray([[1639, 54], [ 3, 969]])" }, { "code": null, "e": 16978, "s": 16827, "text": "This confusion matrix is identical to the ones from the first two models. What about the distributions of y_scores for the second and the third model?" }, { "code": null, "e": 17151, "s": 16978, "text": "figsize(12.5,4)plt.hist(third_y_score-second_y_score, bins=40)plt.title('Distribution of the difference between y_score and second_y_score')plt.ylabel('Frequency')plt.show(" }, { "code": null, "e": 17357, "s": 17151, "text": "This distribution concentrates around 0. In other words, the distribution of y_scores is almost the same across different models. What about the coefficients, for example, the coefficients for temperature?" }, { "code": null, "e": 17579, "s": 17357, "text": "figsize(12.5,4)plt.hist(third_trace['Temperature'][-40000:]-second_burned_trace['beta_temp'], bins=40, density=True)plt.title('Difference between the temperature coefficients for the second and the third model')plt.show()" }, { "code": null, "e": 17657, "s": 17579, "text": "The difference approximately follows a normal distribution with a small mean." }, { "code": null, "e": 17725, "s": 17657, "text": "Let us also check the difference between the humidity coefficients." }, { "code": null, "e": 17922, "s": 17725, "text": "figsize(12.5,4)plt.boxplot(third_trace['Humidity'][-40000:]-second_burned_trace['beta_humid'])plt.title('Difference between the humidity coefficients for the second and the third model')plt.show()" }, { "code": null, "e": 17955, "s": 17922, "text": "Again, that difference is small." }, { "code": null, "e": 18154, "s": 17955, "text": "We see that even though our models use different priors, the prediction performances are similar. This confirms our belief that as our dataset gets bigger, they should converge to the same solution." }, { "code": null, "e": 18323, "s": 18154, "text": "We expect that our project will beginners to PyMC3 learn its syntaxes. We find PyMC3’s codes rather intuitive and we hope that our codes clearly demonstrate this point." } ]
Asynchronous and Synchronous Callbacks in Java - GeeksforGeeks
13 Aug, 2019 A CallBack Function is a function that is passed into another function as an argument and is expected to execute after some kind of event. The purpose of the callback function is to inform a class Sync/Async if some work in another class is done. This is very useful when working with Asynchronous tasks. Suppose we want to perform some routine tasks like perform some operation or display content after clicking a button, or fetching data from internet. This is also used in event handling, as we get notified when a button is clicked via callback function. This type of design pattern is used in Observer Design Pattern.The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependent, called observers, and notifies them automatically of any state changes, usually by calling one of their methods( Source:wiki). In Java, Callbacks can be implemented using an interface. The general procedure for implementation is given below. 1. Define the methods in an interface that we want to invoke after callback. 2. Define a class that will implement the callback methods of the interface. 3. Define a reference in other class to register the callback interface. 4. Use that reference to invoke the callback method. Synchronous Callback The code execution will block or wait for the event before continuing. Until your event returns a response, your program will not execute any further. So Basically, the callback performs all its work before returning to the call statement. The problem with synchronous callbacks are that they appear to lag. Below is the simple implementation of this principle // Java program to illustrate synchronous callbackinterface OnGeekEventListener { // this can be any type of method void onGeekEvent();} class B { private OnGeekEventListener mListener; // listener field // setting the listener public void registerOnGeekEventListener(OnGeekEventListener mListener) { this.mListener = mListener; } // my synchronous task public void doGeekStuff() { // perform any operation System.out.println("Performing callback before synchronous Task"); // check if listener is registered. if (this.mListener != null) { // invoke the callback method of class A mListener.onGeekEvent(); } } // Driver Function public static void main(String[] args) { B obj = new B(); OnGeekEventListener mListener = new A(); obj.registerOnGeekEventListener(mListener); obj.doGeekStuff(); }} class A implements OnGeekEventListener { @Override public void onGeekEvent() { System.out.println("Performing callback after synchronous Task"); // perform some routine operation } // some class A methods} Output: Performing callback before synchronous Task Performing callback after synchronous Task Asynchronous Callback An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread. The callback function may be invoked from a thread but is not a requirement. A Callback may also start a new thread, thus making themselves asynchronous. Below is the simple implementation of this principle. // Java program to illustrate Asynchronous callback interface OnGeekEventListener { // this can be any type of method void onGeekEvent();} class B { private OnGeekEventListener mListener; // listener field // setting the listener public void registerOnGeekEventListener(OnGeekEventListener mListener) { this.mListener = mListener; } // My Asynchronous task public void doGeekStuff() { // An Async task always executes in new thread new Thread(new Runnable() { public void run() { // perform any operation System.out.println("Performing operation in Asynchronous Task"); // check if listener is registered. if (mListener != null) { // invoke the callback method of class A mListener.onGeekEvent(); } } }).start(); } // Driver Program public static void main(String[] args) { B obj = new B(); OnGeekEventListener mListener = new A(); obj.registerOnGeekEventListener(mListener); obj.doGeekStuff(); }} class A implements OnGeekEventListener { @Override public void onGeekEvent() { System.out.println("Performing callback after Asynchronous Task"); // perform some routine operation } // some class A methods} Output: Performing operation in Asynchronous Task Performing callback after Asynchronous Task When To Use What Synchronous Callback : Any process having multiple tasks where the tasks must be executed in sequence and doesn’t occupy much time should use synchronous Callbacks.For example : You’re in a movie queue for ticket you can’t get one until everyone in front of you gets one. Asynchronous Callback : When the tasks are not dependent on each other and may take some time for execution we should use Asynchronous callbacks.For example : When you order your food other people can also order their food in the restaurant. They don’t have to wait for your order to finish, If you’re downloading a song from internet, Getting an API response. References:https://www.javaworld.com/article/2077462/learn-java/java-tip-10–implement-callback-routines-in-java.htmlhttps://en.wikipedia.org/wiki/Callback_(computer_programming) Akanksha_Rai AshaIvey Java-Multithreading Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 24560, "s": 24532, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25119, "s": 24560, "text": "A CallBack Function is a function that is passed into another function as an argument and is expected to execute after some kind of event. The purpose of the callback function is to inform a class Sync/Async if some work in another class is done. This is very useful when working with Asynchronous tasks. Suppose we want to perform some routine tasks like perform some operation or display content after clicking a button, or fetching data from internet. This is also used in event handling, as we get notified when a button is clicked via callback function." }, { "code": null, "e": 25434, "s": 25119, "text": "This type of design pattern is used in Observer Design Pattern.The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependent, called observers, and notifies them automatically of any state changes, usually by calling one of their methods( Source:wiki)." }, { "code": null, "e": 25549, "s": 25434, "text": "In Java, Callbacks can be implemented using an interface. The general procedure for implementation is given below." }, { "code": null, "e": 25838, "s": 25549, "text": " 1. Define the methods in an interface that we want to invoke after callback.\n 2. Define a class that will implement the callback methods of the interface.\n 3. Define a reference in other class to register the callback interface.\n 4. Use that reference to invoke the callback method.\n" }, { "code": null, "e": 25859, "s": 25838, "text": "Synchronous Callback" }, { "code": null, "e": 26167, "s": 25859, "text": "The code execution will block or wait for the event before continuing. Until your event returns a response, your program will not execute any further. So Basically, the callback performs all its work before returning to the call statement. The problem with synchronous callbacks are that they appear to lag." }, { "code": null, "e": 26220, "s": 26167, "text": "Below is the simple implementation of this principle" }, { "code": "// Java program to illustrate synchronous callbackinterface OnGeekEventListener { // this can be any type of method void onGeekEvent();} class B { private OnGeekEventListener mListener; // listener field // setting the listener public void registerOnGeekEventListener(OnGeekEventListener mListener) { this.mListener = mListener; } // my synchronous task public void doGeekStuff() { // perform any operation System.out.println(\"Performing callback before synchronous Task\"); // check if listener is registered. if (this.mListener != null) { // invoke the callback method of class A mListener.onGeekEvent(); } } // Driver Function public static void main(String[] args) { B obj = new B(); OnGeekEventListener mListener = new A(); obj.registerOnGeekEventListener(mListener); obj.doGeekStuff(); }} class A implements OnGeekEventListener { @Override public void onGeekEvent() { System.out.println(\"Performing callback after synchronous Task\"); // perform some routine operation } // some class A methods}", "e": 27406, "s": 26220, "text": null }, { "code": null, "e": 27414, "s": 27406, "text": "Output:" }, { "code": null, "e": 27502, "s": 27414, "text": "Performing callback before synchronous Task\nPerforming callback after synchronous Task\n" }, { "code": null, "e": 27524, "s": 27502, "text": "Asynchronous Callback" }, { "code": null, "e": 27946, "s": 27524, "text": "An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread. The callback function may be invoked from a thread but is not a requirement. A Callback may also start a new thread, thus making themselves asynchronous." }, { "code": null, "e": 28000, "s": 27946, "text": "Below is the simple implementation of this principle." }, { "code": "// Java program to illustrate Asynchronous callback interface OnGeekEventListener { // this can be any type of method void onGeekEvent();} class B { private OnGeekEventListener mListener; // listener field // setting the listener public void registerOnGeekEventListener(OnGeekEventListener mListener) { this.mListener = mListener; } // My Asynchronous task public void doGeekStuff() { // An Async task always executes in new thread new Thread(new Runnable() { public void run() { // perform any operation System.out.println(\"Performing operation in Asynchronous Task\"); // check if listener is registered. if (mListener != null) { // invoke the callback method of class A mListener.onGeekEvent(); } } }).start(); } // Driver Program public static void main(String[] args) { B obj = new B(); OnGeekEventListener mListener = new A(); obj.registerOnGeekEventListener(mListener); obj.doGeekStuff(); }} class A implements OnGeekEventListener { @Override public void onGeekEvent() { System.out.println(\"Performing callback after Asynchronous Task\"); // perform some routine operation } // some class A methods}", "e": 29406, "s": 28000, "text": null }, { "code": null, "e": 29414, "s": 29406, "text": "Output:" }, { "code": null, "e": 29501, "s": 29414, "text": "Performing operation in Asynchronous Task\nPerforming callback after Asynchronous Task\n" }, { "code": null, "e": 29518, "s": 29501, "text": "When To Use What" }, { "code": null, "e": 29790, "s": 29518, "text": "Synchronous Callback : Any process having multiple tasks where the tasks must be executed in sequence and doesn’t occupy much time should use synchronous Callbacks.For example : You’re in a movie queue for ticket you can’t get one until everyone in front of you gets one." }, { "code": null, "e": 30151, "s": 29790, "text": "Asynchronous Callback : When the tasks are not dependent on each other and may take some time for execution we should use Asynchronous callbacks.For example : When you order your food other people can also order their food in the restaurant. They don’t have to wait for your order to finish, If you’re downloading a song from internet, Getting an API response." }, { "code": null, "e": 30329, "s": 30151, "text": "References:https://www.javaworld.com/article/2077462/learn-java/java-tip-10–implement-callback-routines-in-java.htmlhttps://en.wikipedia.org/wiki/Callback_(computer_programming)" }, { "code": null, "e": 30342, "s": 30329, "text": "Akanksha_Rai" }, { "code": null, "e": 30351, "s": 30342, "text": "AshaIvey" }, { "code": null, "e": 30371, "s": 30351, "text": "Java-Multithreading" }, { "code": null, "e": 30376, "s": 30371, "text": "Java" }, { "code": null, "e": 30395, "s": 30376, "text": "Technical Scripter" }, { "code": null, "e": 30400, "s": 30395, "text": "Java" }, { "code": null, "e": 30498, "s": 30400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30513, "s": 30498, "text": "Stream In Java" }, { "code": null, "e": 30564, "s": 30513, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30594, "s": 30564, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30613, "s": 30594, "text": "Interfaces in Java" }, { "code": null, "e": 30644, "s": 30613, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30662, "s": 30644, "text": "ArrayList in Java" }, { "code": null, "e": 30694, "s": 30662, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30714, "s": 30694, "text": "Stack Class in Java" }, { "code": null, "e": 30738, "s": 30714, "text": "Singleton Class in Java" } ]
Maximum sum rectangle in a 2D matrix
A matrix is given. We need to find a rectangle (sometimes square) matrix, whose sum is maximum. The idea behind this algorithm is to fix the left and right columns and try to find the sum of the element from the left column to right column for each row, and store it temporarily. We will try to find top and bottom row numbers. After getting the temporary array, we can apply the Kadane’s Algorithm to get maximum sum sub-array. With it, the total rectangle will be formed. Input: The matrix of integers. 1 2 -1 -4 -20 -8 -3 4 2 1 3 8 10 1 3 -4 -1 1 7 -6 Output: The top left point and bottom right point of the submatrix, and the total sum of the submatrix. (Top, Left) (1, 1) (Bottom, Right) (3, 3) The max sum is: 29 kadaneAlgorithm(array, start, end, n) Input: The array will hold sums, start and end points, number of elements. Output − Find the starting and ending point. Begin sum := 0 and maxSum := - ∞ end := -1 tempStart := 0 for each element i in the array, do sum := sum + array[i] if sum < 0, then sum := 0 tempStart := i + 1 else if sum > maxSum, then maxSum := sum start := tempStart end := i done if end ≠ -1, then return maxSum maxSum := array[0], start := 0 and end := 0 for each element i from 1 to n of array, do if array[i] > maxSum, then maxSum := array[i] start := i and end := i done return maxSum End maxSumRect(Matrix) Input: The given matrix. Output: the Maximum sum of the rectangle. Begin maxSum := - ∞ define temp array, whose size is same as row of matrix for left := 0 to number of columns in the Matrix, do till temp array with 0s for right := left to column of matrix -1, do for each row i, do temp[i] := matrix[i, right] done sum := kadaneAlgorithm(temp, start, end, number of rows) if sum > maxSum, then maxSum := sum endLeft := left endRight := right endTop := start endBottom := end done done display top left and bottom right corner and the maxSum End #include<iostream> #define ROW 4 #define COL 5 using namespace std; int M[ROW][COL] = { {1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 10, 1, 3}, {-4, -1, 1, 7, -6} }; int kadaneAlgo(int arr[], int &start, int &end, int n) { //find max sum and starting and ending location int sum = 0, maxSum = INT_MIN; end = -1; //at first no place is selected int tempStart = 0; //starting from 0 for (int i = 0; i < n; i++) { sum += arr[i]; if (sum < 0) { sum = 0; tempStart = i+1; }else if (sum > maxSum) { //get maximum sum, and update start and end index maxSum = sum; start = tempStart; end = i; } } if (end != -1) return maxSum; //when all elements are negative in the array maxSum = arr[0]; start = end = 0; // Find the maximum element in array for (int i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; start = end = i; } } return maxSum; } void maxSumRect() { int maxSum = INT_MIN, endLeft, endRight, endTop, endBottom; int left, right; int temp[ROW], sum, start, end; for (left = 0; left < COL; left++) { for(int i = 0; i<ROW; i++)//temp initially holds all 0 temp[i] = 0; for (right = left; right < COL; ++right) { for (int i = 0; i < ROW; ++i) //for each row, find the sum temp[i] += M[i][right]; sum = kadaneAlgo(temp, start, end, ROW); //find sum of rectangle (top, left) and (bottom right) if (sum > maxSum) { //find maximum value of sum, then update corner points maxSum = sum; endLeft = left; endRight = right; endTop = start; endBottom = end; } } } cout << "(Top, Left) ("<<endTop<<", "<<endLeft<<")"<<endl; cout << "(Bottom, Right) ("<<endBottom<<", "<<endRight<<")"<<endl; cout << "The max sum is: "<< maxSum; } int main() { maxSumRect(); } (Top, Left) (1, 1) (Bottom, Right) (3, 3) The max sum is: 29
[ { "code": null, "e": 1158, "s": 1062, "text": "A matrix is given. We need to find a rectangle (sometimes square) matrix, whose sum is maximum." }, { "code": null, "e": 1536, "s": 1158, "text": "The idea behind this algorithm is to fix the left and right columns and try to find the sum of the element from the left column to right column for each row, and store it temporarily. We will try to find top and bottom row numbers. After getting the temporary array, we can apply the Kadane’s Algorithm to get maximum sum sub-array. With it, the total rectangle will be formed." }, { "code": null, "e": 1798, "s": 1536, "text": "Input:\nThe matrix of integers.\n 1 2 -1 -4 -20\n-8 -3 4 2 1\n 3 8 10 1 3\n-4 -1 1 7 -6\n\nOutput:\nThe top left point and bottom right point of the submatrix, and the total sum of the submatrix.\n(Top, Left) (1, 1)\n(Bottom, Right) (3, 3)\nThe max sum is: 29\n" }, { "code": null, "e": 1836, "s": 1798, "text": "kadaneAlgorithm(array, start, end, n)" }, { "code": null, "e": 1911, "s": 1836, "text": "Input: The array will hold sums, start and end points, number of elements." }, { "code": null, "e": 1956, "s": 1911, "text": "Output − Find the starting and ending point." }, { "code": null, "e": 2532, "s": 1956, "text": "Begin\n sum := 0 and maxSum := - ∞\n end := -1\n tempStart := 0\n\n for each element i in the array, do\n sum := sum + array[i]\n if sum < 0, then\n sum := 0\n tempStart := i + 1\n else if sum > maxSum, then\n maxSum := sum\n start := tempStart\n end := i\n done\n\n if end ≠ -1, then\n return maxSum\n maxSum := array[0], start := 0 and end := 0\n\n for each element i from 1 to n of array, do\n if array[i] > maxSum, then\n maxSum := array[i]\n start := i and end := i\n done\n\n return maxSum\nEnd" }, { "code": null, "e": 2551, "s": 2532, "text": "maxSumRect(Matrix)" }, { "code": null, "e": 2576, "s": 2551, "text": "Input: The given matrix." }, { "code": null, "e": 2618, "s": 2576, "text": "Output: the Maximum sum of the rectangle." }, { "code": null, "e": 3259, "s": 2618, "text": "Begin\n maxSum := - ∞\n define temp array, whose size is same as row of matrix\n\n for left := 0 to number of columns in the Matrix, do\n till temp array with 0s\n for right := left to column of matrix -1, do\n for each row i, do\n temp[i] := matrix[i, right]\n done\n\n sum := kadaneAlgorithm(temp, start, end, number of rows)\n if sum > maxSum, then\n maxSum := sum\n endLeft := left\n endRight := right\n endTop := start\n endBottom := end\n done\n done\n\n display top left and bottom right corner and the maxSum\nEnd" }, { "code": null, "e": 5272, "s": 3259, "text": "#include<iostream>\n#define ROW 4\n#define COL 5\nusing namespace std;\n\nint M[ROW][COL] = {\n {1, 2, -1, -4, -20},\n {-8, -3, 4, 2, 1},\n {3, 8, 10, 1, 3},\n {-4, -1, 1, 7, -6}\n };\n\nint kadaneAlgo(int arr[], int &start, int &end, int n) { //find max sum and starting and ending location\n int sum = 0, maxSum = INT_MIN;\n\n end = -1; //at first no place is selected\n\n int tempStart = 0; //starting from 0\n\n for (int i = 0; i < n; i++) {\n sum += arr[i];\n if (sum < 0) {\n sum = 0;\n tempStart = i+1;\n }else if (sum > maxSum) { //get maximum sum, and update start and end index\n maxSum = sum;\n start = tempStart;\n end = i;\n }\n }\n\n if (end != -1)\n return maxSum;\n //when all elements are negative in the array\n maxSum = arr[0];\n start = end = 0;\n\n // Find the maximum element in array\n for (int i = 1; i < n; i++) {\n if (arr[i] > maxSum) {\n maxSum = arr[i];\n start = end = i;\n }\n }\n return maxSum;\n}\n\nvoid maxSumRect() {\n int maxSum = INT_MIN, endLeft, endRight, endTop, endBottom;\n\n int left, right;\n int temp[ROW], sum, start, end;\n\n for (left = 0; left < COL; left++) {\n for(int i = 0; i<ROW; i++)//temp initially holds all 0\n temp[i] = 0;\n\n for (right = left; right < COL; ++right) {\n for (int i = 0; i < ROW; ++i) //for each row, find the sum\n temp[i] += M[i][right];\n sum = kadaneAlgo(temp, start, end, ROW); //find sum of rectangle (top, left) and (bottom right)\n\n if (sum > maxSum) { //find maximum value of sum, then update corner points\n maxSum = sum;\n endLeft = left;\n endRight = right;\n endTop = start;\n endBottom = end;\n }\n }\n }\n\n cout << \"(Top, Left) (\"<<endTop<<\", \"<<endLeft<<\")\"<<endl;\n cout << \"(Bottom, Right) (\"<<endBottom<<\", \"<<endRight<<\")\"<<endl;\n cout << \"The max sum is: \"<< maxSum;\n}\n\nint main() {\n maxSumRect();\n}" }, { "code": null, "e": 5333, "s": 5272, "text": "(Top, Left) (1, 1)\n(Bottom, Right) (3, 3)\nThe max sum is: 29" } ]
ViewPager2 in Android with Example - GeeksforGeeks
15 May, 2021 Before going to Viewpager2 let us know about Viewpager. Most of you have used WhatsApp, when you open WhatsApp you can see at the top, there are four sections Camera, Chats, Status, Calls these are the Viewpager. So a Viewpager is an android widget that is used to navigate from one page to another page by swiping left or right using the same activity. So when we use Viewpager, we can add different layouts in one activity and this can be done by using the fragments. Famous applications like WhatsApp, Snapchat uses Viewpager. Viewpager2 is an updated or enhanced version of Viewpager released by Google on 7th Feb 2009. It comes with a variety of new features. The most important feature of viewpager2 that is not present in Viewpager is, the Recyclerview which makes Viewpager2 more efficient than Viewpager. By using the Recyclerview, we can add items dynamically. If you know how to implement a RecyclerView then you can easily implement ViewPager2. It uses Recyclerview implicitly and is the most important feature. Supports Right to Left layout. Supports Vertical orientation. CompositePageTransformer is introduced to combine multiple page transformers notifyDataSetChanged() fully functional. View Group: Just like ViewPager the ViewPager2 extends from the ViewGroup. A ViewGroup is a view that can contain other views. It is a subclass of the View class. It is the base class for the layouts, like LinearLayout, RelativeLayout, etc. LayoutManager: The LayoutManager is the same that you have been used in RecyclerView. The LayoutManager is managed by the Viewpager and it manages the views and is used to set the orientation of the ViewPager2. RecyclerView: The Recyclerview is used to handle to components provided to it. It will show the data to the user that is assigned to it and makes ViewPager2 more efficient. onPageScrolled(): This method is triggered when there is any scrolling activity for the current page. onPageSelected(): triggered when you select a new page. onPageScrollStateChanged(): triggered when there is scroll state will be changed. Setting Orientation By default the orientation of viewpager2 is Horizontal. We can set the orientation of viewpager2 to Vertical by calling the setOrientation() method and passing ORIENTATION_VERTICAL to it. For Horizontal Orientation use YourViewPager2Object.orientation = ViewPager2.ORIENTATION_VERTICAL To use ViewPager2, you have to first add the dependency in your Build.gradle file: To do this. Go to app > Gradle Scripts > build.gradle (Module: app) and then write the following dependency ” implementation ‘androidx.viewpager2:viewpager2:1.0.0’ ” into dependencies section as shown below and then click on Sync now. dependencies { implementation 'androidx.viewpager2:viewpager2:1.0.0' } After doing all these steps let’s now build an application. So we are going to build the below application. Step 1: Create a New Project On the Welcome screen of Android Studio, click on Create New Project. If you have a project already opened, Go to File > New > New Project. Select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field. Select Java from the Language drop-down menu. Step 2: Add Vector Assets to show on the screen Go to the app > res > drawable > right-click > new > Vector Asset and select any vector asset of your choice Step 3: Go to activity_main.xml and add the ViewPager2 widget to it Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" /> </LinearLayout> Step 4: Create a new Layout Resource file Go to app > res > layout > right-click > New > Layout Resource File and name that file as “images_holder.xml”. Inside that file insert an ImageView widget and provide an id to it. This layout file will hold our images. Below is the code for the images_holder.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/images" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 5: Create an Adapter class Go to the app > java > right click on first package name > new > java class name that class as ViewPager2Adapter. An adapter is an important class to work with Recyclerview. Because it contains all the important methods dealing with RecyclerView. Below is the implementation of the Adapter class. For better understanding comments are added inside the code. Below is the code for the ViewPager2Adapter.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; class ViewPager2Adapter extends RecyclerView.Adapter<ViewPager2Adapter.ViewHolder> { // Array of images // Adding images from drawable folder private int[] images = {R.drawable.ic_baseline_looks_one_24, R.drawable.ic_baseline_looks_two_24, R.drawable.ic_baseline_looks_3_24, R.drawable.ic_baseline_looks_4_24, R.drawable.ic_baseline_looks_5_24}; private Context ctx; // Constructor of our ViewPager2Adapter class ViewPager2Adapter(Context ctx) { this.ctx = ctx; } // This method returns our layout @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(ctx).inflate(R.layout.images_holder, parent, false); return new ViewHolder(view); } // This method binds the screen with the view @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // This will set the images in imageview holder.images.setImageResource(images[position]); } // This Method returns the size of the Array @Override public int getItemCount() { return images.length; } // The ViewHolder class holds the view public static class ViewHolder extends RecyclerView.ViewHolder { ImageView images; public ViewHolder(@NonNull View itemView) { super(itemView); images = itemView.findViewById(R.id.images); } }} Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager2.widget.ViewPager2; public class MainActivity extends AppCompatActivity { // Create object of ViewPager2 private ViewPager2 viewPager2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing the viewpager2 object // It will find the view by its id which // you have provided into XML file viewPager2 = findViewById(R.id.viewpager); // Object of ViewPager2Adapter // this will passes the // context to the constructor // of ViewPager2Adapter ViewPager2Adapter viewPager2Adapter = new ViewPager2Adapter(this); // adding the adapter to viewPager2 // to show the views in recyclerview viewPager2.setAdapter(viewPager2Adapter); // To get swipe event of viewpager2 viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override // This method is triggered when there is any scrolling activity for the current page public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { super.onPageScrolled(position, positionOffset, positionOffsetPixels); } // triggered when you select a new page @Override public void onPageSelected(int position) { super.onPageSelected(position); } // triggered when there is // scroll state will be changed @Override public void onPageScrollStateChanged(int state) { super.onPageScrollStateChanged(state); } }); }} Output: Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java
[ { "code": null, "e": 25939, "s": 25911, "text": "\n15 May, 2021" }, { "code": null, "e": 26469, "s": 25939, "text": "Before going to Viewpager2 let us know about Viewpager. Most of you have used WhatsApp, when you open WhatsApp you can see at the top, there are four sections Camera, Chats, Status, Calls these are the Viewpager. So a Viewpager is an android widget that is used to navigate from one page to another page by swiping left or right using the same activity. So when we use Viewpager, we can add different layouts in one activity and this can be done by using the fragments. Famous applications like WhatsApp, Snapchat uses Viewpager." }, { "code": null, "e": 26896, "s": 26469, "text": "Viewpager2 is an updated or enhanced version of Viewpager released by Google on 7th Feb 2009. It comes with a variety of new features. The most important feature of viewpager2 that is not present in Viewpager is, the Recyclerview which makes Viewpager2 more efficient than Viewpager. By using the Recyclerview, we can add items dynamically. If you know how to implement a RecyclerView then you can easily implement ViewPager2." }, { "code": null, "e": 26963, "s": 26896, "text": "It uses Recyclerview implicitly and is the most important feature." }, { "code": null, "e": 26994, "s": 26963, "text": "Supports Right to Left layout." }, { "code": null, "e": 27025, "s": 26994, "text": "Supports Vertical orientation." }, { "code": null, "e": 27103, "s": 27025, "text": "CompositePageTransformer is introduced to combine multiple page transformers" }, { "code": null, "e": 27144, "s": 27103, "text": "notifyDataSetChanged() fully functional." }, { "code": null, "e": 27385, "s": 27144, "text": "View Group: Just like ViewPager the ViewPager2 extends from the ViewGroup. A ViewGroup is a view that can contain other views. It is a subclass of the View class. It is the base class for the layouts, like LinearLayout, RelativeLayout, etc." }, { "code": null, "e": 27596, "s": 27385, "text": "LayoutManager: The LayoutManager is the same that you have been used in RecyclerView. The LayoutManager is managed by the Viewpager and it manages the views and is used to set the orientation of the ViewPager2." }, { "code": null, "e": 27771, "s": 27596, "text": "RecyclerView: The Recyclerview is used to handle to components provided to it. It will show the data to the user that is assigned to it and makes ViewPager2 more efficient. " }, { "code": null, "e": 27873, "s": 27771, "text": "onPageScrolled(): This method is triggered when there is any scrolling activity for the current page." }, { "code": null, "e": 27929, "s": 27873, "text": "onPageSelected(): triggered when you select a new page." }, { "code": null, "e": 28011, "s": 27929, "text": "onPageScrollStateChanged(): triggered when there is scroll state will be changed." }, { "code": null, "e": 28031, "s": 28011, "text": "Setting Orientation" }, { "code": null, "e": 28251, "s": 28031, "text": "By default the orientation of viewpager2 is Horizontal. We can set the orientation of viewpager2 to Vertical by calling the setOrientation() method and passing ORIENTATION_VERTICAL to it. For Horizontal Orientation use " }, { "code": null, "e": 28319, "s": 28251, "text": "YourViewPager2Object.orientation = ViewPager2.ORIENTATION_VERTICAL " }, { "code": null, "e": 28402, "s": 28319, "text": "To use ViewPager2, you have to first add the dependency in your Build.gradle file:" }, { "code": null, "e": 28637, "s": 28402, "text": "To do this. Go to app > Gradle Scripts > build.gradle (Module: app) and then write the following dependency ” implementation ‘androidx.viewpager2:viewpager2:1.0.0’ ” into dependencies section as shown below and then click on Sync now." }, { "code": null, "e": 28714, "s": 28637, "text": "dependencies {\n implementation 'androidx.viewpager2:viewpager2:1.0.0'\n}" }, { "code": null, "e": 28823, "s": 28714, "text": "After doing all these steps let’s now build an application. So we are going to build the below application. " }, { "code": null, "e": 28852, "s": 28823, "text": "Step 1: Create a New Project" }, { "code": null, "e": 29149, "s": 28852, "text": "On the Welcome screen of Android Studio, click on Create New Project. If you have a project already opened, Go to File > New > New Project. Select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field. Select Java from the Language drop-down menu." }, { "code": null, "e": 29197, "s": 29149, "text": "Step 2: Add Vector Assets to show on the screen" }, { "code": null, "e": 29306, "s": 29197, "text": "Go to the app > res > drawable > right-click > new > Vector Asset and select any vector asset of your choice" }, { "code": null, "e": 29375, "s": 29306, "text": "Step 3: Go to activity_main.xml and add the ViewPager2 widget to it " }, { "code": null, "e": 29518, "s": 29375, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 29522, "s": 29518, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.viewpager2.widget.ViewPager2 android:id=\"@+id/viewpager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" /> </LinearLayout>", "e": 30024, "s": 29522, "text": null }, { "code": null, "e": 30067, "s": 30024, "text": "Step 4: Create a new Layout Resource file " }, { "code": null, "e": 30337, "s": 30067, "text": "Go to app > res > layout > right-click > New > Layout Resource File and name that file as “images_holder.xml”. Inside that file insert an ImageView widget and provide an id to it. This layout file will hold our images. Below is the code for the images_holder.xml file. " }, { "code": null, "e": 30341, "s": 30337, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <ImageView android:id=\"@+id/images\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </LinearLayout>", "e": 30691, "s": 30341, "text": null }, { "code": null, "e": 30723, "s": 30691, "text": "Step 5: Create an Adapter class" }, { "code": null, "e": 31211, "s": 30723, "text": "Go to the app > java > right click on first package name > new > java class name that class as ViewPager2Adapter. An adapter is an important class to work with Recyclerview. Because it contains all the important methods dealing with RecyclerView. Below is the implementation of the Adapter class. For better understanding comments are added inside the code. Below is the code for the ViewPager2Adapter.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 31216, "s": 31211, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; class ViewPager2Adapter extends RecyclerView.Adapter<ViewPager2Adapter.ViewHolder> { // Array of images // Adding images from drawable folder private int[] images = {R.drawable.ic_baseline_looks_one_24, R.drawable.ic_baseline_looks_two_24, R.drawable.ic_baseline_looks_3_24, R.drawable.ic_baseline_looks_4_24, R.drawable.ic_baseline_looks_5_24}; private Context ctx; // Constructor of our ViewPager2Adapter class ViewPager2Adapter(Context ctx) { this.ctx = ctx; } // This method returns our layout @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(ctx).inflate(R.layout.images_holder, parent, false); return new ViewHolder(view); } // This method binds the screen with the view @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // This will set the images in imageview holder.images.setImageResource(images[position]); } // This Method returns the size of the Array @Override public int getItemCount() { return images.length; } // The ViewHolder class holds the view public static class ViewHolder extends RecyclerView.ViewHolder { ImageView images; public ViewHolder(@NonNull View itemView) { super(itemView); images = itemView.findViewById(R.id.images); } }}", "e": 32914, "s": 31216, "text": null }, { "code": null, "e": 32962, "s": 32914, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 33152, "s": 32962, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 33157, "s": 33152, "text": "Java" }, { "code": "import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager2.widget.ViewPager2; public class MainActivity extends AppCompatActivity { // Create object of ViewPager2 private ViewPager2 viewPager2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing the viewpager2 object // It will find the view by its id which // you have provided into XML file viewPager2 = findViewById(R.id.viewpager); // Object of ViewPager2Adapter // this will passes the // context to the constructor // of ViewPager2Adapter ViewPager2Adapter viewPager2Adapter = new ViewPager2Adapter(this); // adding the adapter to viewPager2 // to show the views in recyclerview viewPager2.setAdapter(viewPager2Adapter); // To get swipe event of viewpager2 viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() { @Override // This method is triggered when there is any scrolling activity for the current page public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { super.onPageScrolled(position, positionOffset, positionOffsetPixels); } // triggered when you select a new page @Override public void onPageSelected(int position) { super.onPageSelected(position); } // triggered when there is // scroll state will be changed @Override public void onPageScrollStateChanged(int state) { super.onPageScrollStateChanged(state); } }); }}", "e": 35025, "s": 33157, "text": null }, { "code": null, "e": 35033, "s": 35025, "text": "Output:" }, { "code": null, "e": 35040, "s": 35033, "text": "Picked" }, { "code": null, "e": 35048, "s": 35040, "text": "Android" }, { "code": null, "e": 35053, "s": 35048, "text": "Java" }, { "code": null, "e": 35058, "s": 35053, "text": "Java" }, { "code": null, "e": 35066, "s": 35058, "text": "Android" }, { "code": null, "e": 35164, "s": 35066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35222, "s": 35164, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 35265, "s": 35222, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 35303, "s": 35265, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35336, "s": 35303, "text": "Services in Android with Example" }, { "code": null, "e": 35367, "s": 35336, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 35382, "s": 35367, "text": "Arrays in Java" }, { "code": null, "e": 35426, "s": 35382, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35448, "s": 35426, "text": "For-each loop in Java" }, { "code": null, "e": 35499, "s": 35448, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
JavaScript Number toPrecision( ) Method - GeeksforGeeks
22 Dec, 2021 Below is the example of the Number toPrecision( ) Method. Example: <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(3)); </script> <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(3)); </script> Output:213 213 The toPrecision() method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length. Syntax: number.toPrecision(value) The toPrecision() method is used with a number as shown in above syntax using the ‘.’ operator. This method will format a number to a specified length. Parameters: This method accepts a single parameter value. This parameter is also optional and it represents the value of the number of significant digits the user wants in the formatted number. Return Value: The toPrecision() method in JavaScript returns a string in which the number is formatted to the specified precision. Below are some examples to illustrates toPrecision() method: Passing no arguments in the toPrecision() method: If no arguments is passed to the toPrecision() method then the formatted number will be exactly the same as input number. Though, it will be represented as a string rather than a number.Code# 1: <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision()); </script>Output:213.45689Passing an argument in the toPrecision() method: If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision.Code# 2:<script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(4)); </script>Output:213.5Passing an argument which results in addition of null in the output: If the length of precision passed to the toPrecision() method is greater than the original number then zero’s are appended to the input number to meet the specified precision.Code# 3:<script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script>Output:213.456890000 123.00 Passing no arguments in the toPrecision() method: If no arguments is passed to the toPrecision() method then the formatted number will be exactly the same as input number. Though, it will be represented as a string rather than a number.Code# 1: <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision()); </script>Output:213.45689 <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision()); </script> Output: 213.45689 Passing an argument in the toPrecision() method: If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision.Code# 2:<script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(4)); </script>Output:213.5 <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(4)); </script> Output: 213.5 Passing an argument which results in addition of null in the output: If the length of precision passed to the toPrecision() method is greater than the original number then zero’s are appended to the input number to meet the specified precision.Code# 3:<script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script>Output:213.456890000 123.00 <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script> Output: 213.456890000 123.00 Note: If the precision specified is not in between 1 and 100 (inclusive), it results in a RangeError. Supported Browsers: Google Chrome 1 and above Internet Explorer 5.5 and above Firefox 1 and above Apple Safari 2 and above Opera 7 and above shubham_singh ysachin2314 JavaScript-Methods JavaScript-Numbers JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Set the value of an input field in JavaScript How to read a local text file using JavaScript? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24850, "s": 24822, "text": "\n22 Dec, 2021" }, { "code": null, "e": 24908, "s": 24850, "text": "Below is the example of the Number toPrecision( ) Method." }, { "code": null, "e": 25036, "s": 24908, "text": "Example: <script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(3)); </script>" }, { "code": " <script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(3)); </script>", "e": 25156, "s": 25036, "text": null }, { "code": null, "e": 25167, "s": 25156, "text": "Output:213" }, { "code": null, "e": 25171, "s": 25167, "text": "213" }, { "code": null, "e": 25413, "s": 25171, "text": "The toPrecision() method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length." }, { "code": null, "e": 25421, "s": 25413, "text": "Syntax:" }, { "code": null, "e": 25447, "s": 25421, "text": "number.toPrecision(value)" }, { "code": null, "e": 25599, "s": 25447, "text": "The toPrecision() method is used with a number as shown in above syntax using the ‘.’ operator. This method will format a number to a specified length." }, { "code": null, "e": 25793, "s": 25599, "text": "Parameters: This method accepts a single parameter value. This parameter is also optional and it represents the value of the number of significant digits the user wants in the formatted number." }, { "code": null, "e": 25924, "s": 25793, "text": "Return Value: The toPrecision() method in JavaScript returns a string in which the number is formatted to the specified precision." }, { "code": null, "e": 25985, "s": 25924, "text": "Below are some examples to illustrates toPrecision() method:" }, { "code": null, "e": 27144, "s": 25985, "text": "Passing no arguments in the toPrecision() method: If no arguments is passed to the toPrecision() method then the formatted number will be exactly the same as input number. Though, it will be represented as a string rather than a number.Code# 1: <script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision()); </script>Output:213.45689Passing an argument in the toPrecision() method: If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision.Code# 2:<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(4)); </script>Output:213.5Passing an argument which results in addition of null in the output: If the length of precision passed to the toPrecision() method is greater than the original number then zero’s are appended to the input number to meet the specified precision.Code# 3:<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script>Output:213.456890000\n123.00\n" }, { "code": null, "e": 27523, "s": 27144, "text": "Passing no arguments in the toPrecision() method: If no arguments is passed to the toPrecision() method then the formatted number will be exactly the same as input number. Though, it will be represented as a string rather than a number.Code# 1: <script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision()); </script>Output:213.45689" }, { "code": " <script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision()); </script>", "e": 27642, "s": 27523, "text": null }, { "code": null, "e": 27650, "s": 27642, "text": "Output:" }, { "code": null, "e": 27660, "s": 27650, "text": "213.45689" }, { "code": null, "e": 27988, "s": 27660, "text": "Passing an argument in the toPrecision() method: If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision.Code# 2:<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(4)); </script>Output:213.5" }, { "code": "<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(4)); </script>", "e": 28100, "s": 27988, "text": null }, { "code": null, "e": 28108, "s": 28100, "text": "Output:" }, { "code": null, "e": 28114, "s": 28108, "text": "213.5" }, { "code": null, "e": 28568, "s": 28114, "text": "Passing an argument which results in addition of null in the output: If the length of precision passed to the toPrecision() method is greater than the original number then zero’s are appended to the input number to meet the specified precision.Code# 3:<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script>Output:213.456890000\n123.00\n" }, { "code": "<script type=\"text/javascript\"> var num=213.45689; document.write(num.toPrecision(12)); var num2 = 123; document.write(num2.toPrecision(5)); </script>", "e": 28742, "s": 28568, "text": null }, { "code": null, "e": 28750, "s": 28742, "text": "Output:" }, { "code": null, "e": 28772, "s": 28750, "text": "213.456890000\n123.00\n" }, { "code": null, "e": 28874, "s": 28772, "text": "Note: If the precision specified is not in between 1 and 100 (inclusive), it results in a RangeError." }, { "code": null, "e": 28894, "s": 28874, "text": "Supported Browsers:" }, { "code": null, "e": 28920, "s": 28894, "text": "Google Chrome 1 and above" }, { "code": null, "e": 28952, "s": 28920, "text": "Internet Explorer 5.5 and above" }, { "code": null, "e": 28972, "s": 28952, "text": "Firefox 1 and above" }, { "code": null, "e": 28997, "s": 28972, "text": "Apple Safari 2 and above" }, { "code": null, "e": 29015, "s": 28997, "text": "Opera 7 and above" }, { "code": null, "e": 29029, "s": 29015, "text": "shubham_singh" }, { "code": null, "e": 29041, "s": 29029, "text": "ysachin2314" }, { "code": null, "e": 29060, "s": 29041, "text": "JavaScript-Methods" }, { "code": null, "e": 29079, "s": 29060, "text": "JavaScript-Numbers" }, { "code": null, "e": 29090, "s": 29079, "text": "JavaScript" }, { "code": null, "e": 29107, "s": 29090, "text": "Web Technologies" }, { "code": null, "e": 29205, "s": 29107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29214, "s": 29205, "text": "Comments" }, { "code": null, "e": 29227, "s": 29214, "text": "Old Comments" }, { "code": null, "e": 29272, "s": 29227, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29333, "s": 29272, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29405, "s": 29333, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29451, "s": 29405, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 29499, "s": 29451, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 29541, "s": 29499, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29574, "s": 29541, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29636, "s": 29574, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29679, "s": 29636, "text": "How to fetch data from an API in ReactJS ?" } ]
GATE | GATE-CS-2003 | Question 21 - GeeksforGeeks
15 Nov, 2018 Consider the following graph, Among the following sequences: (I) a b e g h f (II) a b f e h g (III) a b f h g e (IV) a f g h b e Which are depth first traversals of the above graph?(A) I, II and IV only(B) I and IV only(C) II, III and IV only(D) I, III and IV onlyAnswer: (D)Explanation: DFS of a graph 1) Visits a node. 2) Do following for every unvisited adjacent. a) Completely explores all vertices through current adjacent using recursive call to DFS. There can be any DFS possible as we may pick different vertices as starting points and we may pick adjacents in different orders. (i) a b e g h f [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent e is picked first(iii) a b f h g e [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent f is picked first(iv) a f g h b e [Visit a, explore all adjacents through f, and so on..]. In this f’s adjacent g is picked first (ii) a b f e h g can not be an answer as e is visited after f [e is not an adjacent of f and all adjcents of f are not explored yet]Quiz of this Question clintra GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25885, "s": 25857, "text": "\n15 Nov, 2018" }, { "code": null, "e": 25915, "s": 25885, "text": "Consider the following graph," }, { "code": null, "e": 25946, "s": 25915, "text": "Among the following sequences:" }, { "code": null, "e": 26018, "s": 25946, "text": "(I) a b e g h f \n(II) a b f e h g\n(III) a b f h g e \n(IV) a f g h b e " }, { "code": null, "e": 26192, "s": 26018, "text": "Which are depth first traversals of the above graph?(A) I, II and IV only(B) I and IV only(C) II, III and IV only(D) I, III and IV onlyAnswer: (D)Explanation: DFS of a graph" }, { "code": null, "e": 26358, "s": 26192, "text": "1) Visits a node. \n2) Do following for every unvisited adjacent.\n a) Completely explores all vertices through current \n adjacent using recursive call to DFS.\n" }, { "code": null, "e": 26488, "s": 26358, "text": "There can be any DFS possible as we may pick different vertices as starting points and we may pick adjacents in different orders." }, { "code": null, "e": 26825, "s": 26488, "text": "(i) a b e g h f [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent e is picked first(iii) a b f h g e [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent f is picked first(iv) a f g h b e [Visit a, explore all adjacents through f, and so on..]. In this f’s adjacent g is picked first" }, { "code": null, "e": 26979, "s": 26825, "text": "(ii) a b f e h g can not be an answer as e is visited after f [e is not an adjacent of f and all adjcents of f are not explored yet]Quiz of this Question" }, { "code": null, "e": 26987, "s": 26979, "text": "clintra" }, { "code": null, "e": 27000, "s": 26987, "text": "GATE-CS-2003" }, { "code": null, "e": 27018, "s": 27000, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 27023, "s": 27018, "text": "GATE" }, { "code": null, "e": 27121, "s": 27023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27155, "s": 27121, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27189, "s": 27155, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27223, "s": 27189, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27256, "s": 27223, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27292, "s": 27256, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27326, "s": 27292, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27362, "s": 27326, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27396, "s": 27362, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27430, "s": 27396, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Hexadecimal Number System
Hexadecimal Number System is one the type of Number Representation techniques, in which there value of base is 16. That means there are only 16 symbols or possible digit values, there are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Where A, B, C, D, E and F are single bit representations of decimal value 10, 11, 12, 13, 14 and 15 respectively. It requires only 4 bits to represent value of any digit. Hexadecimal numbers are indicated by the addition of either an 0x prefix or an h suffix. Position of every digit has a weight which is a power of 16. Each position in the Hexadecimal system is 16 times more significant than the previous position, that means numeric value of an hexadecimal number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system. Each Hexadecimal number can be represented using only 4 bits, with each group of bits having a distich values between 0000 (for 0) and 1111 (for F = 15 = 8+4+2+1). The equivalent binary number of Hexadecimal number are as given below. Hexadecimal number system is similar to Octal number system. Hexadecimal number system provides convenient way of converting large binary numbers into more compact and smaller groups. Since base value of Hexadecimal number system is 16, so there maximum value of digit is 15 and it can not be more than 15. In this number system, the successive positions to the left of the hexadecimal point having weights of 160, 161, 162, 163and so on. Similarly, the successive positions to the right of the hexadecimal point having weights of 16-1, 16-2, 16-3and so on. This is called base power of 16. The decimal value of any hexadecimal number can be determined using sum of product of each digit with its positional value. Example-1 − The number 512 is interpreted as 512=2x162+0x161+0x160=200 Here, right most bit 0 is the least significant bit (LSB) and left most bit 2 is the most significant bit (MSB). Example-2 − The number 2015.0625 is interpreted as 2015.0625=7x162+13x161+15x160+1x16-1=7DF.10 Here, right most bit 0 is the least significant bit (LSB) and left most bit 7 is the most significant bit (MSB). Example-3 A a decimal number 21 to represent in Hexadecimal representation (21)10=1x161+5x160=(15)16 So, decimal value 21 is equivalent to 15 in Hexadecimal Number System. Hexadecimal Number System is commonly used in Computer programming and Microprocessors. It is also helpful to describe colors on web pages. Each of the three primary colors (i.e., red, green and blue) is represented by two hexadecimal digits to create 255 possible values, thus resulting in more than 16 million possible colors. Hexadecimal number system is used to describe locations in memory for every byte. These hexadecimal numbers are also easier to read and write than binary or decimal numbers for Computer Professionals. The main advantage of using Hexadecimal numbers is that it uses less memory to store more numbers, for example it store 256 numbers in two digits whereas decimal number stores 100 numbers in two digits. This number system is also used to represent Computer memory addresses. It uses only 4 bits to represent any digit in binary and easy to convert from hexadecimal to binary and vice-versa. It is easier to handle input and output in the hexadecimal form. There is wide number of advantages in data science field, artificial intelligence and machine learning. The major disadvantage of Hexadecimal number system is that it may not an easy to read and write for people, and also difficult to perform operations like multiplications, divisions using hexadecimal number system. Hexadecimal numbers is most difficult number system for dealing with Computer’s data. Simply, 15’s complement of a hexadecimal number is the subtraction of it’s each digits from F(=15). For example, 15’s complement of hexadecimal number 2030 is FFFF - 2030 = DFCF. 16’s complement of hexadecimal number is 15’s complement of given number plus 1 to the least significant bit (LSB). For example 8’s complement of hexadecimal number 2020 is (FFFF - 2030) + 1 = DFDF + 1 = DFE0. Please note that maximum digit of hexadecimal number system is F(=15), so addition of F+1 will be 0 with carry 1.
[ { "code": null, "e": 1558, "s": 1062, "text": "Hexadecimal Number System is one the type of Number Representation techniques, in which there value of base is 16. That means there are only 16 symbols or possible digit values, there are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Where A, B, C, D, E and F are single bit representations of decimal value 10, 11, 12, 13, 14 and 15 respectively. It requires only 4 bits to represent value of any digit. Hexadecimal numbers are indicated by the addition of either an 0x prefix or an h suffix." }, { "code": null, "e": 1963, "s": 1558, "text": "Position of every digit has a weight which is a power of 16. Each position in the Hexadecimal system is 16 times more significant than the previous position, that means numeric value of an hexadecimal number is determined by multiplying each digit of the number by the value of the position in which the digit appears and then adding the products. So, it is also a positional (or weighted) number system." }, { "code": null, "e": 2198, "s": 1963, "text": "Each Hexadecimal number can be represented using only 4 bits, with each group of bits having a distich values between 0000 (for 0) and 1111 (for F = 15 = 8+4+2+1). The equivalent binary number of Hexadecimal number are as given below." }, { "code": null, "e": 2382, "s": 2198, "text": "Hexadecimal number system is similar to Octal number system. Hexadecimal number system provides convenient way of converting large binary numbers into more compact and smaller groups." }, { "code": null, "e": 2913, "s": 2382, "text": "Since base value of Hexadecimal number system is 16, so there maximum value of digit is 15 and it can not be more than 15. In this number system, the successive positions to the left of the hexadecimal point having weights of 160, 161, 162, 163and so on. Similarly, the successive positions to the right of the hexadecimal point having weights of 16-1, 16-2, 16-3and so on. This is called base power of 16. The decimal value of any hexadecimal number can be determined using sum of product of each digit with its positional value." }, { "code": null, "e": 2958, "s": 2913, "text": "Example-1 − The number 512 is interpreted as" }, { "code": null, "e": 2984, "s": 2958, "text": "512=2x162+0x161+0x160=200" }, { "code": null, "e": 3097, "s": 2984, "text": "Here, right most bit 0 is the least significant bit (LSB) and left most bit 2 is the most significant bit (MSB)." }, { "code": null, "e": 3148, "s": 3097, "text": "Example-2 − The number 2015.0625 is interpreted as" }, { "code": null, "e": 3192, "s": 3148, "text": "2015.0625=7x162+13x161+15x160+1x16-1=7DF.10" }, { "code": null, "e": 3305, "s": 3192, "text": "Here, right most bit 0 is the least significant bit (LSB) and left most bit 7 is the most significant bit (MSB)." }, { "code": null, "e": 3380, "s": 3305, "text": "Example-3 A a decimal number 21 to represent in Hexadecimal representation" }, { "code": null, "e": 3477, "s": 3380, "text": "(21)10=1x161+5x160=(15)16\nSo, decimal value 21 is equivalent to 15 in Hexadecimal Number System." }, { "code": null, "e": 4007, "s": 3477, "text": "Hexadecimal Number System is commonly used in Computer programming and Microprocessors. It is also helpful to describe colors on web pages. Each of the three primary colors (i.e., red, green and blue) is represented by two hexadecimal digits to create 255 possible values, thus resulting in more than 16 million possible colors. Hexadecimal number system is used to describe locations in memory for every byte. These hexadecimal numbers are also easier to read and write than binary or decimal numbers for Computer Professionals." }, { "code": null, "e": 4567, "s": 4007, "text": "The main advantage of using Hexadecimal numbers is that it uses less memory to store more numbers, for example it store 256 numbers in two digits whereas decimal number stores 100 numbers in two digits. This number system is also used to represent Computer memory addresses. It uses only 4 bits to represent any digit in binary and easy to convert from hexadecimal to binary and vice-versa. It is easier to handle input and output in the hexadecimal form. There is wide number of advantages in data science field, artificial intelligence and machine learning." }, { "code": null, "e": 4868, "s": 4567, "text": "The major disadvantage of Hexadecimal number system is that it may not an easy to read and write for people, and also difficult to perform operations like multiplications, divisions using hexadecimal number system. Hexadecimal numbers is most difficult number system for dealing with Computer’s data." }, { "code": null, "e": 5047, "s": 4868, "text": "Simply, 15’s complement of a hexadecimal number is the subtraction of it’s each digits from F(=15). For example, 15’s complement of hexadecimal number 2030 is FFFF - 2030 = DFCF." }, { "code": null, "e": 5371, "s": 5047, "text": "16’s complement of hexadecimal number is 15’s complement of given number plus 1 to the least significant bit (LSB). For example 8’s complement of hexadecimal number 2020 is (FFFF - 2030) + 1 = DFDF + 1 = DFE0. Please note that maximum digit of hexadecimal number system is F(=15), so addition of F+1 will be 0 with carry 1." } ]
Create a Bar chart using Recharts in ReactJS - GeeksforGeeks
27 Jul, 2021 Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save recharts Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save recharts Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'; import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts'; const App = () => { // Sample data const data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000} ]; return ( <BarChart width={600} height={600} data={data}> <Bar dataKey="students" fill="green" /> <CartesianGrid stroke="#ccc" /> <XAxis dataKey="name" /> <YAxis /> </BarChart> ); } export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output React-Questions Recharts JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? How to Use the JavaScript Fetch API to Get Data? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 24379, "s": 24348, "text": " \n27 Jul, 2021\n" }, { "code": null, "e": 24597, "s": 24379, "text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). " }, { "code": null, "e": 24872, "s": 24597, "text": "To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates." }, { "code": null, "e": 24922, "s": 24872, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25020, "s": 24922, "text": "\nStep 1: Create a React application using the following command.\nnpx create-react-app foldername\n" }, { "code": null, "e": 25084, "s": 25020, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 25116, "s": 25084, "text": "npx create-react-app foldername" }, { "code": null, "e": 25232, "s": 25116, "text": "\nStep 2: After creating your project folder i.e. foldername, move to it using the following command.\ncd foldername\n" }, { "code": null, "e": 25332, "s": 25232, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 25346, "s": 25332, "text": "cd foldername" }, { "code": null, "e": 25482, "s": 25346, "text": "\nStep 3: After creating the ReactJS application, Install the required modules using the following command.\nnpm install --save recharts\n" }, { "code": null, "e": 25588, "s": 25482, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command." }, { "code": null, "e": 25616, "s": 25588, "text": "npm install --save recharts" }, { "code": null, "e": 25668, "s": 25616, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25798, "s": 25668, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25805, "s": 25798, "text": "App.js" }, { "code": "\n\n\n\n\n\n\nimport React from 'react'; \nimport { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts'; \n \n \nconst App = () => { \n \n// Sample data \nconst data = [ \n {name: 'Geeksforgeeks', students: 400}, \n {name: 'Technical scripter', students: 700}, \n {name: 'Geek-i-knack', students: 200}, \n {name: 'Geek-o-mania', students: 1000} \n]; \n \n \nreturn ( \n<BarChart width={600} height={600} data={data}> \n <Bar dataKey=\"students\" fill=\"green\" /> \n <CartesianGrid stroke=\"#ccc\" /> \n <XAxis dataKey=\"name\" /> \n <YAxis /> \n </BarChart> \n); \n} \n \nexport default App; \n\n\n\n\n\n", "e": 26407, "s": 25815, "text": null }, { "code": null, "e": 26520, "s": 26407, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26530, "s": 26520, "text": "npm start" }, { "code": null, "e": 26629, "s": 26530, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26636, "s": 26629, "text": "Output" }, { "code": null, "e": 26654, "s": 26636, "text": "\nReact-Questions\n" }, { "code": null, "e": 26665, "s": 26654, "text": "\nRecharts\n" }, { "code": null, "e": 26678, "s": 26665, "text": "\nJavaScript\n" }, { "code": null, "e": 26688, "s": 26678, "text": "\nReactJS\n" }, { "code": null, "e": 26707, "s": 26688, "text": "\nWeb Technologies\n" }, { "code": null, "e": 26912, "s": 26707, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26973, "s": 26912, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27018, "s": 26973, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27090, "s": 27018, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27136, "s": 27090, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27185, "s": 27136, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 27228, "s": 27185, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27273, "s": 27228, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27338, "s": 27273, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27379, "s": 27338, "text": "Create a Responsive Navbar using ReactJS" } ]
Fibonacci Iterative Program in C
RecursionDemo.c #include <stdio.h> int factorial(int n) { //base case if(n == 0) { return 1; } else { return n * factorial(n-1); } } int fibbonacci(int n) { if(n == 0) { return 0; } else if(n == 1) { return 1; } else { return (fibbonacci(n-1) + fibbonacci(n-2)); } } int main() { int n = 5; int i; printf("Factorial of %d: %d\n" , n , factorial(n)); printf("Fibbonacci of %d: " , n); for(i = 0;i < n;i++) { printf("%d ",fibbonacci(i)); } } If we compile and run the above program, it will produce the following result − Factorial of 5: 120 Fibbonacci of 5: 0 1 1 2 3 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2596, "s": 2580, "text": "RecursionDemo.c" }, { "code": null, "e": 3105, "s": 2596, "text": "#include <stdio.h>\n\nint factorial(int n) {\n //base case\n if(n == 0) {\n return 1;\n } else {\n return n * factorial(n-1);\n }\n}\n\nint fibbonacci(int n) {\n if(n == 0) {\n return 0;\n } else if(n == 1) {\n return 1;\n } else {\n return (fibbonacci(n-1) + fibbonacci(n-2));\n }\n}\n\nint main() {\n int n = 5;\n int i;\n\t\n printf(\"Factorial of %d: %d\\n\" , n , factorial(n));\n printf(\"Fibbonacci of %d: \" , n);\n\t\n for(i = 0;i < n;i++) {\n printf(\"%d \",fibbonacci(i));\n }\n}" }, { "code": null, "e": 3185, "s": 3105, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 3233, "s": 3185, "text": "Factorial of 5: 120\nFibbonacci of 5: 0 1 1 2 3\n" }, { "code": null, "e": 3268, "s": 3233, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3280, "s": 3268, "text": " Ravi Kiran" }, { "code": null, "e": 3315, "s": 3280, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 3334, "s": 3315, "text": " Arnab Chakraborty" }, { "code": null, "e": 3369, "s": 3334, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3384, "s": 3369, "text": " Parth Panjabi" }, { "code": null, "e": 3417, "s": 3384, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 3436, "s": 3417, "text": " Arnab Chakraborty" }, { "code": null, "e": 3470, "s": 3436, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3498, "s": 3470, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3534, "s": 3498, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3562, "s": 3534, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3569, "s": 3562, "text": " Print" }, { "code": null, "e": 3580, "s": 3569, "text": " Add Notes" } ]
How to Deploy your Dash App on Heroku | by François St-Amant | Towards Data Science
You just spent weeks developing your Dash app. It now looks great and you want the world to see it? This tutorial will show you how to do just that using Heroku. Heroku is a cloud application platform that allows you to run your apps, completely free of charge. For this tutorial, you will need to install a few things: Heroku account: https://id.heroku.com/login Git Bash: https://git-scm.com/download/win Virtualenv, which can be installed with pip: pip install virtualenv. You should also download 4 files, all available right here: https://github.com/francoisstamant/dash_heroku_deployment. App.py is the file that contains your Dash appplication. That’s the file that you should be changing if you want to update/improve the app. requirements.txt contains the Python dependencies needed to run the app itself. Alright, now that you got everything needed, here is the step-by-step tutorial that will get you to deploy your Dash app for everyone else to see! Open Git. From there, type the following code to create a folder for the project and make that folder the current directory. Open Git. From there, type the following code to create a folder for the project and make that folder the current directory. $mkdir dash_app_deployment$cd dash_app_deployment 2. Initialize the folder with an empty Git repository with $ git init . 3. Create a virtual environment called venv with $ virtualenv venv . 4. If you are using Git Bash In order to activate the environment, you need to make the Scripts folder the current directory first. Then, you can activate the environment. Here are the commands: 5. Then, install Dash and Gunicorn in the virtual environment: $ pip install dash$ pip install gunicorn Just a heads up, it can take a while to install dash (took about 4 minutes for me). 5. Then, make sure to change the directory back to the repository, using in this case $ cd ~/dash_app_deployment. 6. Now, make sure the 4 files from earlier are actually copied in the current location and once they are, initialize the folder by adding them one by one, like this: $ git add app.py$ git add Procfile$ git add requirements.txt$ git add .gitignore 7. You can now create the heroku app with the name you want for it. That name needs to be unique. It will let you know if the name is not available. Then, you can deploy your code to heroku. $ heroku create francois-st-amant-app $ git add . $ git commit -m 'Initial app template'$ git push heroku master 8. Finally, run the app on one dyno by doing $ heroku ps:scale web=1. Dynos are “containers” for running apps/code. Assuming you want to keep everything free, you are allowed 2 running dynos, each with 512MB of RAM. The URL of your app should be visible after step 7. Basically, it will be https://name-of-your-app.herokuapp.com. Here is my app: https://francois-st-amant-app.herokuapp.com/ You will notice that if you go on your Heroku account now, you will see your app page. From there, you can manage the app settings, add collaborators, etc. To change the app, simply modify the app.py file. Then, the following 4 commands will allow you to push the changes to your Heroku app. I hope this helped. Feel free to reach out should you have any questions. Thanks for reading!
[ { "code": null, "e": 333, "s": 171, "text": "You just spent weeks developing your Dash app. It now looks great and you want the world to see it? This tutorial will show you how to do just that using Heroku." }, { "code": null, "e": 433, "s": 333, "text": "Heroku is a cloud application platform that allows you to run your apps, completely free of charge." }, { "code": null, "e": 491, "s": 433, "text": "For this tutorial, you will need to install a few things:" }, { "code": null, "e": 535, "s": 491, "text": "Heroku account: https://id.heroku.com/login" }, { "code": null, "e": 578, "s": 535, "text": "Git Bash: https://git-scm.com/download/win" }, { "code": null, "e": 647, "s": 578, "text": "Virtualenv, which can be installed with pip: pip install virtualenv." }, { "code": null, "e": 766, "s": 647, "text": "You should also download 4 files, all available right here: https://github.com/francoisstamant/dash_heroku_deployment." }, { "code": null, "e": 906, "s": 766, "text": "App.py is the file that contains your Dash appplication. That’s the file that you should be changing if you want to update/improve the app." }, { "code": null, "e": 986, "s": 906, "text": "requirements.txt contains the Python dependencies needed to run the app itself." }, { "code": null, "e": 1133, "s": 986, "text": "Alright, now that you got everything needed, here is the step-by-step tutorial that will get you to deploy your Dash app for everyone else to see!" }, { "code": null, "e": 1258, "s": 1133, "text": "Open Git. From there, type the following code to create a folder for the project and make that folder the current directory." }, { "code": null, "e": 1383, "s": 1258, "text": "Open Git. From there, type the following code to create a folder for the project and make that folder the current directory." }, { "code": null, "e": 1433, "s": 1383, "text": "$mkdir dash_app_deployment$cd dash_app_deployment" }, { "code": null, "e": 1505, "s": 1433, "text": "2. Initialize the folder with an empty Git repository with $ git init ." }, { "code": null, "e": 1574, "s": 1505, "text": "3. Create a virtual environment called venv with $ virtualenv venv ." }, { "code": null, "e": 1769, "s": 1574, "text": "4. If you are using Git Bash In order to activate the environment, you need to make the Scripts folder the current directory first. Then, you can activate the environment. Here are the commands:" }, { "code": null, "e": 1832, "s": 1769, "text": "5. Then, install Dash and Gunicorn in the virtual environment:" }, { "code": null, "e": 1873, "s": 1832, "text": "$ pip install dash$ pip install gunicorn" }, { "code": null, "e": 1957, "s": 1873, "text": "Just a heads up, it can take a while to install dash (took about 4 minutes for me)." }, { "code": null, "e": 2071, "s": 1957, "text": "5. Then, make sure to change the directory back to the repository, using in this case $ cd ~/dash_app_deployment." }, { "code": null, "e": 2237, "s": 2071, "text": "6. Now, make sure the 4 files from earlier are actually copied in the current location and once they are, initialize the folder by adding them one by one, like this:" }, { "code": null, "e": 2318, "s": 2237, "text": "$ git add app.py$ git add Procfile$ git add requirements.txt$ git add .gitignore" }, { "code": null, "e": 2509, "s": 2318, "text": "7. You can now create the heroku app with the name you want for it. That name needs to be unique. It will let you know if the name is not available. Then, you can deploy your code to heroku." }, { "code": null, "e": 2654, "s": 2509, "text": "$ heroku create francois-st-amant-app $ git add . $ git commit -m 'Initial app template'$ git push heroku master" }, { "code": null, "e": 2870, "s": 2654, "text": "8. Finally, run the app on one dyno by doing $ heroku ps:scale web=1. Dynos are “containers” for running apps/code. Assuming you want to keep everything free, you are allowed 2 running dynos, each with 512MB of RAM." }, { "code": null, "e": 2984, "s": 2870, "text": "The URL of your app should be visible after step 7. Basically, it will be https://name-of-your-app.herokuapp.com." }, { "code": null, "e": 3045, "s": 2984, "text": "Here is my app: https://francois-st-amant-app.herokuapp.com/" }, { "code": null, "e": 3201, "s": 3045, "text": "You will notice that if you go on your Heroku account now, you will see your app page. From there, you can manage the app settings, add collaborators, etc." }, { "code": null, "e": 3337, "s": 3201, "text": "To change the app, simply modify the app.py file. Then, the following 4 commands will allow you to push the changes to your Heroku app." } ]
iOS - Labels
Labels are used for displaying static content, which consists of a single line or multiple lines. textAlignment textColor text numberOflines lineBreakMode -(void)addLabel { UILabel *aLabel = [[UILabel alloc]initWithFrame: CGRectMake(20, 200, 280, 80)]; aLabel.numberOfLines = 0; aLabel.textColor = [UIColor blueColor]; aLabel.backgroundColor = [UIColor clearColor]; aLabel.textAlignment = UITextAlignmentCenter; aLabel.text = @"This is a sample text\n of multiple lines. here number of lines is not limited."; [self.view addSubview:aLabel]; } Update viewDidLoad in ViewController.m as follows − - (void)viewDidLoad { [super viewDidLoad]; //The custom method to create our label is called [self addLabel]; // Do any additional setup after loading the view, typically from a nib. } When we run the application we'll get the following output − 23 Lectures 1.5 hours Ashish Sharma 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson 69 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2189, "s": 2091, "text": "Labels are used for displaying static content, which consists of a single line or multiple lines." }, { "code": null, "e": 2203, "s": 2189, "text": "textAlignment" }, { "code": null, "e": 2213, "s": 2203, "text": "textColor" }, { "code": null, "e": 2218, "s": 2213, "text": "text" }, { "code": null, "e": 2232, "s": 2218, "text": "numberOflines" }, { "code": null, "e": 2246, "s": 2232, "text": "lineBreakMode" }, { "code": null, "e": 2661, "s": 2246, "text": "-(void)addLabel {\n UILabel *aLabel = [[UILabel alloc]initWithFrame:\n CGRectMake(20, 200, 280, 80)];\n aLabel.numberOfLines = 0;\n aLabel.textColor = [UIColor blueColor];\n aLabel.backgroundColor = [UIColor clearColor];\n aLabel.textAlignment = UITextAlignmentCenter;\n aLabel.text = @\"This is a sample text\\n of multiple lines.\n here number of lines is not limited.\";\n [self.view addSubview:aLabel];\n}" }, { "code": null, "e": 2713, "s": 2661, "text": "Update viewDidLoad in ViewController.m as follows −" }, { "code": null, "e": 2914, "s": 2713, "text": "- (void)viewDidLoad {\n [super viewDidLoad];\n \n //The custom method to create our label is called\n [self addLabel];\n // Do any additional setup after loading the view, typically from a nib.\n}" }, { "code": null, "e": 2975, "s": 2914, "text": "When we run the application we'll get the following output −" }, { "code": null, "e": 3010, "s": 2975, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3025, "s": 3010, "text": " Ashish Sharma" }, { "code": null, "e": 3057, "s": 3025, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 3074, "s": 3057, "text": " Abhilash Nelson" }, { "code": null, "e": 3109, "s": 3074, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3126, "s": 3109, "text": " Abhilash Nelson" }, { "code": null, "e": 3161, "s": 3126, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3178, "s": 3161, "text": " Abhilash Nelson" }, { "code": null, "e": 3211, "s": 3178, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 3228, "s": 3211, "text": " Abhilash Nelson" }, { "code": null, "e": 3261, "s": 3228, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3278, "s": 3261, "text": " Frahaan Hussain" }, { "code": null, "e": 3285, "s": 3278, "text": " Print" }, { "code": null, "e": 3296, "s": 3285, "text": " Add Notes" } ]
Check loop in array according to given constraints - GeeksforGeeks
07 Mar, 2022 Given an array arr[0..n-1] of positive and negative numbers we need to find if there is a cycle in array with given rules of movements. If a number at an i index is positive, then move arr[i]%n forward steps, i.e., next index to visit is (i + arr[i])%n. Conversely, if it’s negative, move backward arr[i]%n steps i.e., next index to visit is (i – arr[i])%n. Here n is size of array. If value of arr[i]%n is zero, then it means no move from index i.Examples: Input: arr[] = {2, -1, 1, 2, 2} Output: Yes Explanation: There is a loop in this array because 0 moves to 2, 2 moves to 3, and 3 moves to 0. Input : arr[] = {1, 1, 1, 1, 1, 1} Output : Yes Whole array forms a loop. Input : arr[] = {1, 2} Output : No We move from 0 to index 1. From index 1, there is no move as 2%n is 0. Note that n is 2. Note that self loops are not considered a cycle. For example {0} is not cyclic. The idea is to form a directed graph of array elements using given set of rules. While forming the graph we don’t make self loops as value arr[i]%n equals to 0 means no moves. Finally our task reduces to detecting cycle in a directed graph. For detecting cycle, we use DFS and in DFS if reach a node which is visited and recursion call stack, we say there is a cycle. C++ Java Python3 C# Javascript // C++ program to check if a given array is cyclic or not#include<bits/stdc++.h>using namespace std; // A simple Graph DFS based recursive function to check if// there is cycle in graph with vertex v as root of DFS.// Refer below article for details.// https://www.geeksforgeeks.org/detect-cycle-in-a-graph/bool isCycleRec(int v, vector<int>adj[], vector<bool> &visited, vector<bool> &recur){ visited[v] = true; recur[v] = true; for (int i=0; i<adj[v].size(); i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false;} // Returns true if arr[] has cyclebool isCycle(int arr[], int n){ // Create a graph using given moves in arr[] vector<int>adj[n]; for (int i=0; i<n; i++) if (i != (i+arr[i]+n)%n) adj[i].push_back((i+arr[i]+n)%n); // Do DFS traversal of graph to detect cycle vector<bool> visited(n, false); vector<bool> recur(n, false); for (int i=0; i<n; i++) if (visited[i]==false) if (isCycleRec(i, adj, visited, recur)) return true; return true;} // Driver codeint main(void){ int arr[] = {2, -1, 1, 2, 2}; int n = sizeof(arr)/sizeof(arr[0]); if (isCycle(arr, n)) cout << "Yes"<<endl; else cout << "No"<<endl; return 0;} // Java program to check if// a given array is cyclic or notimport java.util.Vector; class GFG{ // A simple Graph DFS based recursive function // to check if there is cycle in graph with // vertex v as root of DFS. Refer below article for details. // https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ static boolean isCycleRec(int v, Vector<Integer>[] adj, Vector<Boolean> visited, Vector<Boolean> recur) { visited.set(v, true); recur.set(v, true); for (int i = 0; i < adj[v].size(); i++) { if (visited.elementAt(adj[v].elementAt(i)) == false) { if (isCycleRec(adj[v].elementAt(i), adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited.elementAt(adj[v].elementAt(i)) == true && recur.elementAt(adj[v].elementAt(i)) == true) return true; } recur.set(v, false); return false; } // Returns true if arr[] has cycle @SuppressWarnings("unchecked") static boolean isCycle(int[] arr, int n) { // Create a graph using given moves in arr[] Vector<Integer>[] adj = new Vector[n]; for (int i = 0; i < n; i++) if (i != (i + arr[i] + n) % n && adj[i] != null) adj[i].add((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle Vector<Boolean> visited = new Vector<>(); for (int i = 0; i < n; i++) visited.add(true); Vector<Boolean> recur = new Vector<>(); for (int i = 0; i < n; i++) recur.add(true); for (int i = 0; i < n; i++) if (visited.elementAt(i) == false) if (isCycleRec(i, adj, visited, recur)) return true; return true; } // Driver Code public static void main(String[] args) { int[] arr = { 2, -1, 1, 2, 2 }; int n = arr.length; if (isCycle(arr, n) == true) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by sanjeev2552 # Python3 program to check if a# given array is cyclic or not # A simple Graph DFS based recursive# function to check if there is cycle# in graph with vertex v as root of DFS.# Refer below article for details.# https:#www.geeksforgeeks.org/detect-cycle-in-a-graph/def isCycleRec(v, adj, visited, recur): visited[v] = True recur[v] = True for i in range(len(adj[v])): if (visited[adj[v][i]] == False): if (isCycleRec(adj[v][i], adj, visited, recur)): return True # There is a cycle if an adjacent is visited # and present in recursion call stack recur[] else if (visited[adj[v][i]] == True and recur[adj[v][i]] == True): return True recur[v] = False return False # Returns true if arr[] has cycledef isCycle(arr, n): # Create a graph using given # moves in arr[] adj = [[] for i in range(n)] for i in range(n): if (i != (i + arr[i] + n) % n): adj[i].append((i + arr[i] + n) % n) # Do DFS traversal of graph # to detect cycle visited = [False] * n recur = [False] * n for i in range(n): if (visited[i] == False): if (isCycleRec(i, adj, visited, recur)): return True return True # Driver codeif __name__ == '__main__': arr = [2, -1, 1, 2, 2] n = len(arr) if (isCycle(arr, n)): print("Yes") else: print("No") # This code is contributed by PranchalK // C# program to check if// a given array is cyclic or notusing System;using System.Collections.Generic;public class GFG{ // A simple Graph DFS based recursive function // to check if there is cycle in graph with // vertex v as root of DFS. Refer below article for details. // https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ static bool isCycleRec(int v, List<int>[] adj, List<Boolean> visited, List<Boolean> recur) { visited[v] = true; recur[v] = true; for (int i = 0; i < adj[v].Count; i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false; } // Returns true if []arr has cycle static bool isCycle(int[] arr, int n) { // Create a graph using given moves in []arr List<int>[] adj = new List<int>[n]; for (int i = 0; i < n; i++) if (i != (i + arr[i] + n) % n && adj[i] != null) adj[i].Add((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle List<Boolean> visited = new List<Boolean>(); for (int i = 0; i < n; i++) visited.Add(true); List<Boolean> recur = new List<Boolean>(); for (int i = 0; i < n; i++) recur.Add(true); for (int i = 0; i < n; i++) if (visited[i] == false) if (isCycleRec(i, adj, visited, recur)) return true; return true; } // Driver Code public static void Main(String[] args) { int[] arr = { 2, -1, 1, 2, 2 }; int n = arr.Length; if (isCycle(arr, n) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by aashish1995 <script> // JavaScript program to check if a given array is cyclic or not // A simple Graph DFS based recursive function to check if// there is cycle in graph with vertex v as root of DFS.// Refer below article for details.// https://www.geeksforgeeks.org/detect-cycle-in-a-graph/function isCycleRec(v, adj, visited, recur) { visited[v] = true; recur[v] = true; for (let i = 0; i < adj[v].length; i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false;} // Returns true if arr[] has cyclefunction isCycle(arr, n) { // Create a graph using given moves in arr[] let adj = new Array(n).fill(0).map(() => []); for (let i = 0; i < n; i++) if (i != (i + arr[i] + n) % n) adj[i].push((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle let visited = new Array(n).fill(false); let recur = new Array(n).fill(false); for (let i = 0; i < n; i++) if (visited[i] == false) if (isCycleRec(i, adj, visited, recur)) return true; return true;} // Driver code let arr = [2, -1, 1, 2, 2];let n = arr.length;if (isCycle(arr, n)) document.write("Yes" + "<br>");else document.write("No" + "<br>"); </script> Output: Yes This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PranchalKatiyar sanjeev2552 aashish1995 _saurabh_jaiswal surinderdawra388 Arrays Graph Arrays Graph 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 Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Graph and its representations Topological Sorting Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 26671, "s": 26643, "text": "\n07 Mar, 2022" }, { "code": null, "e": 27131, "s": 26671, "text": "Given an array arr[0..n-1] of positive and negative numbers we need to find if there is a cycle in array with given rules of movements. If a number at an i index is positive, then move arr[i]%n forward steps, i.e., next index to visit is (i + arr[i])%n. Conversely, if it’s negative, move backward arr[i]%n steps i.e., next index to visit is (i – arr[i])%n. Here n is size of array. If value of arr[i]%n is zero, then it means no move from index i.Examples: " }, { "code": null, "e": 27475, "s": 27131, "text": "Input: arr[] = {2, -1, 1, 2, 2}\nOutput: Yes\nExplanation: There is a loop in this array\nbecause 0 moves to 2, 2 moves to 3, and 3 \nmoves to 0.\n\nInput : arr[] = {1, 1, 1, 1, 1, 1}\nOutput : Yes\nWhole array forms a loop.\n\nInput : arr[] = {1, 2}\nOutput : No\nWe move from 0 to index 1. From index\n1, there is no move as 2%n is 0. Note that\nn is 2." }, { "code": null, "e": 27556, "s": 27475, "text": "Note that self loops are not considered a cycle. For example {0} is not cyclic. " }, { "code": null, "e": 27925, "s": 27556, "text": "The idea is to form a directed graph of array elements using given set of rules. While forming the graph we don’t make self loops as value arr[i]%n equals to 0 means no moves. Finally our task reduces to detecting cycle in a directed graph. For detecting cycle, we use DFS and in DFS if reach a node which is visited and recursion call stack, we say there is a cycle. " }, { "code": null, "e": 27929, "s": 27925, "text": "C++" }, { "code": null, "e": 27934, "s": 27929, "text": "Java" }, { "code": null, "e": 27942, "s": 27934, "text": "Python3" }, { "code": null, "e": 27945, "s": 27942, "text": "C#" }, { "code": null, "e": 27956, "s": 27945, "text": "Javascript" }, { "code": "// C++ program to check if a given array is cyclic or not#include<bits/stdc++.h>using namespace std; // A simple Graph DFS based recursive function to check if// there is cycle in graph with vertex v as root of DFS.// Refer below article for details.// https://www.geeksforgeeks.org/detect-cycle-in-a-graph/bool isCycleRec(int v, vector<int>adj[], vector<bool> &visited, vector<bool> &recur){ visited[v] = true; recur[v] = true; for (int i=0; i<adj[v].size(); i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false;} // Returns true if arr[] has cyclebool isCycle(int arr[], int n){ // Create a graph using given moves in arr[] vector<int>adj[n]; for (int i=0; i<n; i++) if (i != (i+arr[i]+n)%n) adj[i].push_back((i+arr[i]+n)%n); // Do DFS traversal of graph to detect cycle vector<bool> visited(n, false); vector<bool> recur(n, false); for (int i=0; i<n; i++) if (visited[i]==false) if (isCycleRec(i, adj, visited, recur)) return true; return true;} // Driver codeint main(void){ int arr[] = {2, -1, 1, 2, 2}; int n = sizeof(arr)/sizeof(arr[0]); if (isCycle(arr, n)) cout << \"Yes\"<<endl; else cout << \"No\"<<endl; return 0;}", "e": 29566, "s": 27956, "text": null }, { "code": "// Java program to check if// a given array is cyclic or notimport java.util.Vector; class GFG{ // A simple Graph DFS based recursive function // to check if there is cycle in graph with // vertex v as root of DFS. Refer below article for details. // https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ static boolean isCycleRec(int v, Vector<Integer>[] adj, Vector<Boolean> visited, Vector<Boolean> recur) { visited.set(v, true); recur.set(v, true); for (int i = 0; i < adj[v].size(); i++) { if (visited.elementAt(adj[v].elementAt(i)) == false) { if (isCycleRec(adj[v].elementAt(i), adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited.elementAt(adj[v].elementAt(i)) == true && recur.elementAt(adj[v].elementAt(i)) == true) return true; } recur.set(v, false); return false; } // Returns true if arr[] has cycle @SuppressWarnings(\"unchecked\") static boolean isCycle(int[] arr, int n) { // Create a graph using given moves in arr[] Vector<Integer>[] adj = new Vector[n]; for (int i = 0; i < n; i++) if (i != (i + arr[i] + n) % n && adj[i] != null) adj[i].add((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle Vector<Boolean> visited = new Vector<>(); for (int i = 0; i < n; i++) visited.add(true); Vector<Boolean> recur = new Vector<>(); for (int i = 0; i < n; i++) recur.add(true); for (int i = 0; i < n; i++) if (visited.elementAt(i) == false) if (isCycleRec(i, adj, visited, recur)) return true; return true; } // Driver Code public static void main(String[] args) { int[] arr = { 2, -1, 1, 2, 2 }; int n = arr.length; if (isCycle(arr, n) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by sanjeev2552", "e": 31917, "s": 29566, "text": null }, { "code": "# Python3 program to check if a# given array is cyclic or not # A simple Graph DFS based recursive# function to check if there is cycle# in graph with vertex v as root of DFS.# Refer below article for details.# https:#www.geeksforgeeks.org/detect-cycle-in-a-graph/def isCycleRec(v, adj, visited, recur): visited[v] = True recur[v] = True for i in range(len(adj[v])): if (visited[adj[v][i]] == False): if (isCycleRec(adj[v][i], adj, visited, recur)): return True # There is a cycle if an adjacent is visited # and present in recursion call stack recur[] else if (visited[adj[v][i]] == True and recur[adj[v][i]] == True): return True recur[v] = False return False # Returns true if arr[] has cycledef isCycle(arr, n): # Create a graph using given # moves in arr[] adj = [[] for i in range(n)] for i in range(n): if (i != (i + arr[i] + n) % n): adj[i].append((i + arr[i] + n) % n) # Do DFS traversal of graph # to detect cycle visited = [False] * n recur = [False] * n for i in range(n): if (visited[i] == False): if (isCycleRec(i, adj, visited, recur)): return True return True # Driver codeif __name__ == '__main__': arr = [2, -1, 1, 2, 2] n = len(arr) if (isCycle(arr, n)): print(\"Yes\") else: print(\"No\") # This code is contributed by PranchalK", "e": 33431, "s": 31917, "text": null }, { "code": "// C# program to check if// a given array is cyclic or notusing System;using System.Collections.Generic;public class GFG{ // A simple Graph DFS based recursive function // to check if there is cycle in graph with // vertex v as root of DFS. Refer below article for details. // https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ static bool isCycleRec(int v, List<int>[] adj, List<Boolean> visited, List<Boolean> recur) { visited[v] = true; recur[v] = true; for (int i = 0; i < adj[v].Count; i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false; } // Returns true if []arr has cycle static bool isCycle(int[] arr, int n) { // Create a graph using given moves in []arr List<int>[] adj = new List<int>[n]; for (int i = 0; i < n; i++) if (i != (i + arr[i] + n) % n && adj[i] != null) adj[i].Add((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle List<Boolean> visited = new List<Boolean>(); for (int i = 0; i < n; i++) visited.Add(true); List<Boolean> recur = new List<Boolean>(); for (int i = 0; i < n; i++) recur.Add(true); for (int i = 0; i < n; i++) if (visited[i] == false) if (isCycleRec(i, adj, visited, recur)) return true; return true; } // Driver Code public static void Main(String[] args) { int[] arr = { 2, -1, 1, 2, 2 }; int n = arr.Length; if (isCycle(arr, n) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by aashish1995", "e": 35376, "s": 33431, "text": null }, { "code": "<script> // JavaScript program to check if a given array is cyclic or not // A simple Graph DFS based recursive function to check if// there is cycle in graph with vertex v as root of DFS.// Refer below article for details.// https://www.geeksforgeeks.org/detect-cycle-in-a-graph/function isCycleRec(v, adj, visited, recur) { visited[v] = true; recur[v] = true; for (let i = 0; i < adj[v].length; i++) { if (visited[adj[v][i]] == false) { if (isCycleRec(adj[v][i], adj, visited, recur)) return true; } // There is a cycle if an adjacent is visited // and present in recursion call stack recur[] else if (visited[adj[v][i]] == true && recur[adj[v][i]] == true) return true; } recur[v] = false; return false;} // Returns true if arr[] has cyclefunction isCycle(arr, n) { // Create a graph using given moves in arr[] let adj = new Array(n).fill(0).map(() => []); for (let i = 0; i < n; i++) if (i != (i + arr[i] + n) % n) adj[i].push((i + arr[i] + n) % n); // Do DFS traversal of graph to detect cycle let visited = new Array(n).fill(false); let recur = new Array(n).fill(false); for (let i = 0; i < n; i++) if (visited[i] == false) if (isCycleRec(i, adj, visited, recur)) return true; return true;} // Driver code let arr = [2, -1, 1, 2, 2];let n = arr.length;if (isCycle(arr, n)) document.write(\"Yes\" + \"<br>\");else document.write(\"No\" + \"<br>\"); </script>", "e": 36922, "s": 35376, "text": null }, { "code": null, "e": 36931, "s": 36922, "text": "Output: " }, { "code": null, "e": 36936, "s": 36931, "text": " Yes" }, { "code": null, "e": 37359, "s": 36936, "text": "This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37375, "s": 37359, "text": "PranchalKatiyar" }, { "code": null, "e": 37387, "s": 37375, "text": "sanjeev2552" }, { "code": null, "e": 37399, "s": 37387, "text": "aashish1995" }, { "code": null, "e": 37416, "s": 37399, "text": "_saurabh_jaiswal" }, { "code": null, "e": 37433, "s": 37416, "text": "surinderdawra388" }, { "code": null, "e": 37440, "s": 37433, "text": "Arrays" }, { "code": null, "e": 37446, "s": 37440, "text": "Graph" }, { "code": null, "e": 37453, "s": 37446, "text": "Arrays" }, { "code": null, "e": 37459, "s": 37453, "text": "Graph" }, { "code": null, "e": 37557, "s": 37459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37625, "s": 37557, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37669, "s": 37625, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37717, "s": 37669, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37740, "s": 37717, "text": "Introduction to Arrays" }, { "code": null, "e": 37772, "s": 37740, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37812, "s": 37772, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 37850, "s": 37812, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 37880, "s": 37850, "text": "Graph and its representations" }, { "code": null, "e": 37900, "s": 37880, "text": "Topological Sorting" } ]
Energy consumption time series forecasting with python and LSTM deep learning model | by Eligijus Bujokas | Towards Data Science
The objective of this article is to present the reader with a class in python that has a very intuitive and easy input to model and predict time series data using deep learning. Ideally, the reader should be able to copy the code presented in this article or the GitHub repository, tailor it to his needs (add more layers to the model for example) and use it his/her work. All the code that is used in this article can be found here: https://github.com/Eligijus112/deep-learning-ts The data for this article can be found here: https://www.kaggle.com/robikscube/hourly-energy-consumption The packages that are used for deep modeling are TensorFlow and Keras. A time series is a sequence of numerical data points in successive order. These points are often measured at regular intervals (every month, every day, every hour, etc.). The data frequency used in this article is hourly and it was measured from 2004–10–01 to 2018–08–03. The total number of raw data points is 121271. Visualization of the time series: The main objective of the deep learning algorithm for a given time series is to find a function f such that: Yt = f(Yt−1, Yt−2, ..., Yt−p) In other words, we want to estimate a function that explains the current values of energy consumption based on p lags of the same energy consumption. This article is not about explaining why long short-term memory (LSTM) deep learning networks are good for time series modeling or how it works. For resources on that check great articles like: pathmind.com towardsdatascience.com For the implementation of LSTM (or any RNN layer) in Keras see the official documentation: keras.io Firstly, we need to read the data : We then need a function that converts the time series into an X and Y matrices for the deep learning model to start learning. Let us say that we want to create a function that explains current time series values using 3 lags: And we have this data: ts = [1621.0, 1536.0, 1500.0, 1434.0, 1489.0, 1620.0] What we would like is to create two matrices: X = [[1621.0, 1536.0, 1500.0], # First three lags[1536.0, 1500.0, 1434.0], # Second three lags[1500.0, 1434.0, 1489.0], # Third three lags]Y = [1434.0, 1489.0, 1620.0] This is the most important trick when using deep learning with time series. You can feed these X and Y matrices not only to a recurrent neural network system (like LSTM) but to any vanilla deep learning algorithm. The deep learning model has an LSTM layer (that serves as the input layer as well) and an output layer. During my searches on the internet for an easy to use deep learning model with time series I came across various articles that picked apart several parts of modeling like how to define a model, how to create the matrix for the models, etc. I did not find a package or a class that wrapped everything up into one easy to use entity. So I decided to do that myself: Initiating the class: # Initiating the classdeep_learner = DeepModelTS(data = d,Y_var = 'DAYTON_MW',lag = 6,LSTM_layer_depth = 50,epochs = 10,batch_size = 256,train_test_split = 0.15) The parameters for the class are: data - the data used for modeling. Y_var - the variable name we want to model/forecast. lag - the number of lags used for modeling. LSTM_layer_depth - number of neurons in the LSTM layer. epochs - number of training loops (forward propagation to backward propagation cycles). batch_size - the size of the data sample for the gradient descent used in the finding of the parameters by the deep learning model. All the data is divided into chunks of batch_size sizes and fed through the network. The internal parameters of the model are updated after each batch_size of data goes forward and backward in the model. To read more about epochs and batch sizes visit: machinelearningmastery.com train_test_split - the share of the data that is used for testing. 1 - train_test_split is used for the training of the model. Fitting the model: # Fitting the modelmodel = deep_learner.LSTModel() After the above command, you can witness the fan-favorite training screen: Training the model with more lags (hence, a larger X matrix) increases the training time: deep_learner = DeepModelTS(data = d,Y_var = 'DAYTON_MW',lag = 24, # 24 past hours are usedLSTM_layer_depth = 50,epochs = 10,batch_size = 256,train_test_split = 0.15)model = deep_learner.LSTModel() Now that we have a created model we can start forecasting. The formula for the forecasts with a model trained with p lags: # Defining the lag that we used for training of the model lag_model = 24# Getting the last periodts = d['DAYTON_MW'].tail(lag_model).values.tolist()# Creating the X matrix for the modelX, _ = deep_learner.create_X_Y(ts, lag=lag_model)# Getting the forecastyhat = model.predict(X) If the data was split into training and test sets then the deep_learner.predict() method will predict the points which are in the test set to see how our model performs out of sample. yhat = deep_learner.predict()# Constructing the forecast dataframefc = d.tail(len(yhat)).copy()fc.reset_index(inplace=True)fc['forecast'] = yhat# Ploting the forecastsplt.figure(figsize=(12, 8))for dtype in ['DAYTON_MW', 'forecast']: plt.plot( 'Datetime', dtype, data=fc, label=dtype, alpha=0.8 )plt.legend()plt.grid()plt.show() As we can see, the forecasts for 15 percent of the data that was hidden from model creation are close to the real values. We usually want to forecast ahead of the last original time series data. The class DeepModelTS has the method predict_n_ahead(n_ahead) which forecasts n_ahead time steps. # Creating the model using full data and forecasting n steps aheaddeep_learner = DeepModelTS(data=d,Y_var='DAYTON_MW',lag=48,LSTM_layer_depth=64,epochs=10,train_test_split=0)# Fitting the modeldeep_learner.LSTModel()# Forecasting n steps aheadn_ahead = 168yhat = deep_learner.predict_n_ahead(n_ahead)yhat = [y[0][0] for y in yhat] The above code forecasts one week's worth of steps ahead (168 hours). Comparing it with the previous 400 hours: In conclusion, this article presented a simple pipeline example when working with modeling and forecasting of the time series data: Reading and cleaning the data (1 row for 1 time step) Selecting the number of lags and model depth Initiating the DeepModelTS() class Fitting the model Forecasting n_steps ahead I hope that the reader can use the code showcased in this article in his/her professional and academic work.
[ { "code": null, "e": 545, "s": 172, "text": "The objective of this article is to present the reader with a class in python that has a very intuitive and easy input to model and predict time series data using deep learning. Ideally, the reader should be able to copy the code presented in this article or the GitHub repository, tailor it to his needs (add more layers to the model for example) and use it his/her work." }, { "code": null, "e": 606, "s": 545, "text": "All the code that is used in this article can be found here:" }, { "code": null, "e": 654, "s": 606, "text": "https://github.com/Eligijus112/deep-learning-ts" }, { "code": null, "e": 699, "s": 654, "text": "The data for this article can be found here:" }, { "code": null, "e": 759, "s": 699, "text": "https://www.kaggle.com/robikscube/hourly-energy-consumption" }, { "code": null, "e": 830, "s": 759, "text": "The packages that are used for deep modeling are TensorFlow and Keras." }, { "code": null, "e": 1149, "s": 830, "text": "A time series is a sequence of numerical data points in successive order. These points are often measured at regular intervals (every month, every day, every hour, etc.). The data frequency used in this article is hourly and it was measured from 2004–10–01 to 2018–08–03. The total number of raw data points is 121271." }, { "code": null, "e": 1183, "s": 1149, "text": "Visualization of the time series:" }, { "code": null, "e": 1292, "s": 1183, "text": "The main objective of the deep learning algorithm for a given time series is to find a function f such that:" }, { "code": null, "e": 1322, "s": 1292, "text": "Yt = f(Yt−1, Yt−2, ..., Yt−p)" }, { "code": null, "e": 1472, "s": 1322, "text": "In other words, we want to estimate a function that explains the current values of energy consumption based on p lags of the same energy consumption." }, { "code": null, "e": 1666, "s": 1472, "text": "This article is not about explaining why long short-term memory (LSTM) deep learning networks are good for time series modeling or how it works. For resources on that check great articles like:" }, { "code": null, "e": 1679, "s": 1666, "text": "pathmind.com" }, { "code": null, "e": 1702, "s": 1679, "text": "towardsdatascience.com" }, { "code": null, "e": 1793, "s": 1702, "text": "For the implementation of LSTM (or any RNN layer) in Keras see the official documentation:" }, { "code": null, "e": 1802, "s": 1793, "text": "keras.io" }, { "code": null, "e": 1838, "s": 1802, "text": "Firstly, we need to read the data :" }, { "code": null, "e": 2064, "s": 1838, "text": "We then need a function that converts the time series into an X and Y matrices for the deep learning model to start learning. Let us say that we want to create a function that explains current time series values using 3 lags:" }, { "code": null, "e": 2087, "s": 2064, "text": "And we have this data:" }, { "code": null, "e": 2141, "s": 2087, "text": "ts = [1621.0, 1536.0, 1500.0, 1434.0, 1489.0, 1620.0]" }, { "code": null, "e": 2187, "s": 2141, "text": "What we would like is to create two matrices:" }, { "code": null, "e": 2355, "s": 2187, "text": "X = [[1621.0, 1536.0, 1500.0], # First three lags[1536.0, 1500.0, 1434.0], # Second three lags[1500.0, 1434.0, 1489.0], # Third three lags]Y = [1434.0, 1489.0, 1620.0]" }, { "code": null, "e": 2569, "s": 2355, "text": "This is the most important trick when using deep learning with time series. You can feed these X and Y matrices not only to a recurrent neural network system (like LSTM) but to any vanilla deep learning algorithm." }, { "code": null, "e": 2673, "s": 2569, "text": "The deep learning model has an LSTM layer (that serves as the input layer as well) and an output layer." }, { "code": null, "e": 3037, "s": 2673, "text": "During my searches on the internet for an easy to use deep learning model with time series I came across various articles that picked apart several parts of modeling like how to define a model, how to create the matrix for the models, etc. I did not find a package or a class that wrapped everything up into one easy to use entity. So I decided to do that myself:" }, { "code": null, "e": 3059, "s": 3037, "text": "Initiating the class:" }, { "code": null, "e": 3221, "s": 3059, "text": "# Initiating the classdeep_learner = DeepModelTS(data = d,Y_var = 'DAYTON_MW',lag = 6,LSTM_layer_depth = 50,epochs = 10,batch_size = 256,train_test_split = 0.15)" }, { "code": null, "e": 3255, "s": 3221, "text": "The parameters for the class are:" }, { "code": null, "e": 3290, "s": 3255, "text": "data - the data used for modeling." }, { "code": null, "e": 3343, "s": 3290, "text": "Y_var - the variable name we want to model/forecast." }, { "code": null, "e": 3387, "s": 3343, "text": "lag - the number of lags used for modeling." }, { "code": null, "e": 3443, "s": 3387, "text": "LSTM_layer_depth - number of neurons in the LSTM layer." }, { "code": null, "e": 3531, "s": 3443, "text": "epochs - number of training loops (forward propagation to backward propagation cycles)." }, { "code": null, "e": 3867, "s": 3531, "text": "batch_size - the size of the data sample for the gradient descent used in the finding of the parameters by the deep learning model. All the data is divided into chunks of batch_size sizes and fed through the network. The internal parameters of the model are updated after each batch_size of data goes forward and backward in the model." }, { "code": null, "e": 3916, "s": 3867, "text": "To read more about epochs and batch sizes visit:" }, { "code": null, "e": 3943, "s": 3916, "text": "machinelearningmastery.com" }, { "code": null, "e": 4070, "s": 3943, "text": "train_test_split - the share of the data that is used for testing. 1 - train_test_split is used for the training of the model." }, { "code": null, "e": 4089, "s": 4070, "text": "Fitting the model:" }, { "code": null, "e": 4140, "s": 4089, "text": "# Fitting the modelmodel = deep_learner.LSTModel()" }, { "code": null, "e": 4215, "s": 4140, "text": "After the above command, you can witness the fan-favorite training screen:" }, { "code": null, "e": 4305, "s": 4215, "text": "Training the model with more lags (hence, a larger X matrix) increases the training time:" }, { "code": null, "e": 4502, "s": 4305, "text": "deep_learner = DeepModelTS(data = d,Y_var = 'DAYTON_MW',lag = 24, # 24 past hours are usedLSTM_layer_depth = 50,epochs = 10,batch_size = 256,train_test_split = 0.15)model = deep_learner.LSTModel()" }, { "code": null, "e": 4625, "s": 4502, "text": "Now that we have a created model we can start forecasting. The formula for the forecasts with a model trained with p lags:" }, { "code": null, "e": 4905, "s": 4625, "text": "# Defining the lag that we used for training of the model lag_model = 24# Getting the last periodts = d['DAYTON_MW'].tail(lag_model).values.tolist()# Creating the X matrix for the modelX, _ = deep_learner.create_X_Y(ts, lag=lag_model)# Getting the forecastyhat = model.predict(X)" }, { "code": null, "e": 5089, "s": 4905, "text": "If the data was split into training and test sets then the deep_learner.predict() method will predict the points which are in the test set to see how our model performs out of sample." }, { "code": null, "e": 5435, "s": 5089, "text": "yhat = deep_learner.predict()# Constructing the forecast dataframefc = d.tail(len(yhat)).copy()fc.reset_index(inplace=True)fc['forecast'] = yhat# Ploting the forecastsplt.figure(figsize=(12, 8))for dtype in ['DAYTON_MW', 'forecast']: plt.plot( 'Datetime', dtype, data=fc, label=dtype, alpha=0.8 )plt.legend()plt.grid()plt.show()" }, { "code": null, "e": 5557, "s": 5435, "text": "As we can see, the forecasts for 15 percent of the data that was hidden from model creation are close to the real values." }, { "code": null, "e": 5728, "s": 5557, "text": "We usually want to forecast ahead of the last original time series data. The class DeepModelTS has the method predict_n_ahead(n_ahead) which forecasts n_ahead time steps." }, { "code": null, "e": 6059, "s": 5728, "text": "# Creating the model using full data and forecasting n steps aheaddeep_learner = DeepModelTS(data=d,Y_var='DAYTON_MW',lag=48,LSTM_layer_depth=64,epochs=10,train_test_split=0)# Fitting the modeldeep_learner.LSTModel()# Forecasting n steps aheadn_ahead = 168yhat = deep_learner.predict_n_ahead(n_ahead)yhat = [y[0][0] for y in yhat]" }, { "code": null, "e": 6171, "s": 6059, "text": "The above code forecasts one week's worth of steps ahead (168 hours). Comparing it with the previous 400 hours:" }, { "code": null, "e": 6303, "s": 6171, "text": "In conclusion, this article presented a simple pipeline example when working with modeling and forecasting of the time series data:" }, { "code": null, "e": 6357, "s": 6303, "text": "Reading and cleaning the data (1 row for 1 time step)" }, { "code": null, "e": 6402, "s": 6357, "text": "Selecting the number of lags and model depth" }, { "code": null, "e": 6437, "s": 6402, "text": "Initiating the DeepModelTS() class" }, { "code": null, "e": 6455, "s": 6437, "text": "Fitting the model" }, { "code": null, "e": 6481, "s": 6455, "text": "Forecasting n_steps ahead" } ]
What is Memory Leak? How can we avoid? - GeeksforGeeks
01 Aug, 2021 Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly . Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate. c /* Function with memory leak */#include <stdlib.h> void f(){ int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/} To avoid memory leaks, memory allocated on heap should always be freed when no longer needed. c /* Function without memory leak */#include <stdlib.h>; void f(){ int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ free(ptr); return;} arora_hritik C-Dynamic Memory Allocation Articles C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Mutex vs Semaphore Time Complexity and Space Complexity SQL | GROUP BY SQL | Views Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 26497, "s": 26469, "text": "\n01 Aug, 2021" }, { "code": null, "e": 26583, "s": 26497, "text": "Memory leak occurs when programmers create a memory in heap and forget to delete it. " }, { "code": null, "e": 26917, "s": 26583, "text": "The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly ." }, { "code": null, "e": 27038, "s": 26917, "text": "Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate. " }, { "code": null, "e": 27040, "s": 27038, "text": "c" }, { "code": "/* Function with memory leak */#include <stdlib.h> void f(){ int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ return; /* Return without freeing ptr*/}", "e": 27209, "s": 27040, "text": null }, { "code": null, "e": 27304, "s": 27209, "text": "To avoid memory leaks, memory allocated on heap should always be freed when no longer needed. " }, { "code": null, "e": 27306, "s": 27304, "text": "c" }, { "code": "/* Function without memory leak */#include <stdlib.h>; void f(){ int *ptr = (int *) malloc(sizeof(int)); /* Do some work */ free(ptr); return;}", "e": 27460, "s": 27306, "text": null }, { "code": null, "e": 27473, "s": 27460, "text": "arora_hritik" }, { "code": null, "e": 27501, "s": 27473, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 27510, "s": 27501, "text": "Articles" }, { "code": null, "e": 27521, "s": 27510, "text": "C Language" }, { "code": null, "e": 27619, "s": 27521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27643, "s": 27619, "text": "SQL Interview Questions" }, { "code": null, "e": 27662, "s": 27643, "text": "Mutex vs Semaphore" }, { "code": null, "e": 27699, "s": 27662, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 27714, "s": 27699, "text": "SQL | GROUP BY" }, { "code": null, "e": 27726, "s": 27714, "text": "SQL | Views" }, { "code": null, "e": 27742, "s": 27726, "text": "Arrays in C/C++" }, { "code": null, "e": 27820, "s": 27742, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 27843, "s": 27820, "text": "std::sort() in C++ STL" }, { "code": null, "e": 27870, "s": 27843, "text": "Bitwise Operators in C/C++" } ]
Data Binding with ViewModel in Android - GeeksforGeeks
27 Sep, 2021 Prerequisite: ViewModel DataBinding What is the benefit of integrating data binding in ViewModel? Simply we can say, It provides easy communication between VIEW and its data (or can say View’s Data). As we know the Views are defined in XML files and the XML file are linked with their activity or fragment file, but their data are stored in ViewModel objects. So if the data wants to communicate with the Views, the Activity or Fragment file will act as an intermediator. This will also increase the productivity of developers as it reduces boilerplate codes. So, In this article will we get to how to connect the Views and their Data directly which is there in ViewModel objects. We will learn this by creating a simple app using Kotlin. Create an app with an empty activity. As we are using Data binding we need to enable Data Binding in build.gradle file Create a ViewModel class Kotlin class MainViewModel : ViewModel() { var text = " Welcome to my application " fun updateText() { text = " Text is Updated " }} Now we need to create a layout in XML and create a variable in the XML layout. Using data tag we declare a variable. XML <?xml version="1.0" encoding="utf-8"?><layout 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"> <data> <variable name="mainViewModel" type="com.ayush.databinding.MainViewModel" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="50dp" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center_horizontal" android:text="@{ mainViewModel.text }" android:textSize="24sp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Update text" android:onClick="@{ ()-> mainViewModel.updateText() }"/> </LinearLayout> </layout> Now, we need to create a binding object in Activity, to pass the data to the variable which we defined in XML layout and MainViewModel object as a data source for the Views. Kotlin class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) mainViewModel = MainViewModel() binding.mainViewModel = mainViewModel }} Output: Our app is ready and it’s also working as we can see the data in form of text which was stored in the ViewModel object. So, we got to know how we directly communicate the View with its Data without taking the help of any intermediate. But, in this app, there is one issue as if we click the UPDATE TEXT button the text won’t be updated as expected, but it will remain the same. This is because we need to set the change text ( Data ) again to the View for any new data changes, so we need to define a function in the Activity file to Update the view. But we don’t want the communicate the View with Activity. So here we can use Live Data, Simply we can say, Live data is observer data holder class. If we declare any data as LiveData, then the data can be observed by Android components like Activity, Fragments, etc. Therefore, if we declare any data as Live Data and bind it using view binding to a View, then whenever the data changes the View gets automatically gets updated. In this article, we have discussed only Data binding with ViewModel and in the next article, we will also see Data Binding with LiveData. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Kotlin Array Android UI Layouts Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26405, "s": 26377, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26419, "s": 26405, "text": "Prerequisite:" }, { "code": null, "e": 26429, "s": 26419, "text": "ViewModel" }, { "code": null, "e": 26441, "s": 26429, "text": "DataBinding" }, { "code": null, "e": 27086, "s": 26441, "text": "What is the benefit of integrating data binding in ViewModel? Simply we can say, It provides easy communication between VIEW and its data (or can say View’s Data). As we know the Views are defined in XML files and the XML file are linked with their activity or fragment file, but their data are stored in ViewModel objects. So if the data wants to communicate with the Views, the Activity or Fragment file will act as an intermediator. This will also increase the productivity of developers as it reduces boilerplate codes. So, In this article will we get to how to connect the Views and their Data directly which is there in ViewModel objects." }, { "code": null, "e": 27145, "s": 27086, "text": "We will learn this by creating a simple app using Kotlin. " }, { "code": null, "e": 27264, "s": 27145, "text": "Create an app with an empty activity. As we are using Data binding we need to enable Data Binding in build.gradle file" }, { "code": null, "e": 27289, "s": 27264, "text": "Create a ViewModel class" }, { "code": null, "e": 27296, "s": 27289, "text": "Kotlin" }, { "code": "class MainViewModel : ViewModel() { var text = \" Welcome to my application \" fun updateText() { text = \" Text is Updated \" }}", "e": 27440, "s": 27296, "text": null }, { "code": null, "e": 27558, "s": 27440, "text": "Now we need to create a layout in XML and create a variable in the XML layout. Using data tag we declare a variable. " }, { "code": null, "e": 27562, "s": 27558, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layout 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\"> <data> <variable name=\"mainViewModel\" type=\"com.ayush.databinding.MainViewModel\" /> </data> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"50dp\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:gravity=\"center_horizontal\" android:text=\"@{ mainViewModel.text }\" android:textSize=\"24sp\" /> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Update text\" android:onClick=\"@{ ()-> mainViewModel.updateText() }\"/> </LinearLayout> </layout>", "e": 28697, "s": 27562, "text": null }, { "code": null, "e": 28871, "s": 28697, "text": "Now, we need to create a binding object in Activity, to pass the data to the variable which we defined in XML layout and MainViewModel object as a data source for the Views." }, { "code": null, "e": 28878, "s": 28871, "text": "Kotlin" }, { "code": "class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) mainViewModel = MainViewModel() binding.mainViewModel = mainViewModel }}", "e": 29285, "s": 28878, "text": null }, { "code": null, "e": 29293, "s": 29285, "text": "Output:" }, { "code": null, "e": 29903, "s": 29293, "text": "Our app is ready and it’s also working as we can see the data in form of text which was stored in the ViewModel object. So, we got to know how we directly communicate the View with its Data without taking the help of any intermediate. But, in this app, there is one issue as if we click the UPDATE TEXT button the text won’t be updated as expected, but it will remain the same. This is because we need to set the change text ( Data ) again to the View for any new data changes, so we need to define a function in the Activity file to Update the view. But we don’t want the communicate the View with Activity. " }, { "code": null, "e": 30412, "s": 29903, "text": "So here we can use Live Data, Simply we can say, Live data is observer data holder class. If we declare any data as LiveData, then the data can be observed by Android components like Activity, Fragments, etc. Therefore, if we declare any data as Live Data and bind it using view binding to a View, then whenever the data changes the View gets automatically gets updated. In this article, we have discussed only Data binding with ViewModel and in the next article, we will also see Data Binding with LiveData." }, { "code": null, "e": 30420, "s": 30412, "text": "Android" }, { "code": null, "e": 30427, "s": 30420, "text": "Kotlin" }, { "code": null, "e": 30435, "s": 30427, "text": "Android" }, { "code": null, "e": 30533, "s": 30435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30571, "s": 30533, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30610, "s": 30571, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30660, "s": 30610, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30702, "s": 30660, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30753, "s": 30702, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30766, "s": 30753, "text": "Kotlin Array" }, { "code": null, "e": 30785, "s": 30766, "text": "Android UI Layouts" }, { "code": null, "e": 30827, "s": 30785, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30867, "s": 30827, "text": "How to Get Current Location in Android?" } ]
jQuery | addClass() with Examples - GeeksforGeeks
13 Feb, 2019 The addClass is an inbuilt method in jQuery which is used to add more property to each selected element. It can also be used to change the property of the selected element. This method can be used in two different ways: 1) By adding Class name directly:Here, Class name can be used directly with the element which are going to be selected.Syntax: $(selector).addClass(className); Parameters: It accepts a parameter “className” which is the name of the class that are going to be added.Return Value: It returns the selected elements with added new class. <html> <head> <meta charset="utf-8"> <title>addClass demo</title> <style> p { margin: 8px; font-size: 35px; } .selected { color: ; display: block; border: 2px solid green; width: 160px; height: 60px; background-color: lightgreen; padding: 20px; } .highlight { background: yellow; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <p>GeeksforGeeks</p> <p>gfg</p> <p>CSE</p> <script> $("p").last().addClass("selected"); </script></body> </html> In the above code, “p” element is selected and “selected” class is applied only on last “p” element with the help of .last() method and .addClass() method of jQuery.Output: 2) By passing a function to add new class:Here, A function can be passed to the .addClass() for the selected element.Syntax: $(selector).addClass(function); Parameters: It accepts a parameter “function”.Return Value: It returns the selected element with added function. Code #2: <html> <head> <meta charset="utf-8"> <style> div { background: white; margin: 20px; } .red { background: red; width: 300px; margin: 20px; } .red.green { background: lightgreen; margin: 20px; border: 2px solid green; } body { border: 2px solid green; width: 350px; height: 200px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script></head> <body> <div>This div should be white</div> <div class="red">This div will be green because now it has the both "green" and "red" classes. </div> <div>This div should be white</div> <script> $("div").addClass(function(index, currentClass) { var addedClass; if (currentClass === "red") { addedClass = "green"; $("p").text("There is one green div"); } return addedClass; }); </script></body> </html> In the above code,The “div” element is selected and with the help of a function a new class is added to the selected div element.Output: jQuery-HTML/CSS JavaScript JQuery 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 calculate the number of days between two dates in javascript? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 41992, "s": 41964, "text": "\n13 Feb, 2019" }, { "code": null, "e": 42212, "s": 41992, "text": "The addClass is an inbuilt method in jQuery which is used to add more property to each selected element. It can also be used to change the property of the selected element. This method can be used in two different ways:" }, { "code": null, "e": 42339, "s": 42212, "text": "1) By adding Class name directly:Here, Class name can be used directly with the element which are going to be selected.Syntax:" }, { "code": null, "e": 42373, "s": 42339, "text": "$(selector).addClass(className);\n" }, { "code": null, "e": 42547, "s": 42373, "text": "Parameters: It accepts a parameter “className” which is the name of the class that are going to be added.Return Value: It returns the selected elements with added new class." }, { "code": "<html> <head> <meta charset=\"utf-8\"> <title>addClass demo</title> <style> p { margin: 8px; font-size: 35px; } .selected { color: ; display: block; border: 2px solid green; width: 160px; height: 60px; background-color: lightgreen; padding: 20px; } .highlight { background: yellow; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <p>GeeksforGeeks</p> <p>gfg</p> <p>CSE</p> <script> $(\"p\").last().addClass(\"selected\"); </script></body> </html>", "e": 43246, "s": 42547, "text": null }, { "code": null, "e": 43419, "s": 43246, "text": "In the above code, “p” element is selected and “selected” class is applied only on last “p” element with the help of .last() method and .addClass() method of jQuery.Output:" }, { "code": null, "e": 43544, "s": 43419, "text": "2) By passing a function to add new class:Here, A function can be passed to the .addClass() for the selected element.Syntax:" }, { "code": null, "e": 43577, "s": 43544, "text": "$(selector).addClass(function);\n" }, { "code": null, "e": 43690, "s": 43577, "text": "Parameters: It accepts a parameter “function”.Return Value: It returns the selected element with added function." }, { "code": null, "e": 43699, "s": 43690, "text": "Code #2:" }, { "code": "<html> <head> <meta charset=\"utf-8\"> <style> div { background: white; margin: 20px; } .red { background: red; width: 300px; margin: 20px; } .red.green { background: lightgreen; margin: 20px; border: 2px solid green; } body { border: 2px solid green; width: 350px; height: 200px; } </style> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script></head> <body> <div>This div should be white</div> <div class=\"red\">This div will be green because now it has the both \"green\" and \"red\" classes. </div> <div>This div should be white</div> <script> $(\"div\").addClass(function(index, currentClass) { var addedClass; if (currentClass === \"red\") { addedClass = \"green\"; $(\"p\").text(\"There is one green div\"); } return addedClass; }); </script></body> </html>", "e": 44804, "s": 43699, "text": null }, { "code": null, "e": 44941, "s": 44804, "text": "In the above code,The “div” element is selected and with the help of a function a new class is added to the selected div element.Output:" }, { "code": null, "e": 44957, "s": 44941, "text": "jQuery-HTML/CSS" }, { "code": null, "e": 44968, "s": 44957, "text": "JavaScript" }, { "code": null, "e": 44975, "s": 44968, "text": "JQuery" }, { "code": null, "e": 45073, "s": 44975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45113, "s": 45073, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 45158, "s": 45113, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45219, "s": 45158, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45291, "s": 45219, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45360, "s": 45291, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 45406, "s": 45360, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 45435, "s": 45406, "text": "Form validation using jQuery" }, { "code": null, "e": 45498, "s": 45435, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 45575, "s": 45498, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
How to Merge DataFrames Based on Multiple Columns in R? - GeeksforGeeks
28 Nov, 2021 In this article, we will discuss how to merge dataframes based on multiple columns in R Programming Language. We can merge two dataframes based on multiple columns by using merge() function Syntax: merge(dataframe1, dataframe2, by.x=c(‘column1’, ‘column2’...........,’column n’), by.y=c(‘column1’, ‘column2’...........,’column n’)) where dataframe1 is the first dataframe dataframe2 is the second dataframe by.x represents first dataframe columns by.y represents second dataframe columns Let create two dataframes and display Example: R program to create two dataframes with 4 columns of student data R # create dataframe1data1 = data.frame(name=c("manoj", "manoja", "saroja", "ramya"), subjects=c("java", "c/cpp", "python", "R"), city=c("ponnur", "tenali", "hyd", "guntur"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(name=c("manoj", "sravya", "saroja", "pavani"), subjects=c("java", "c/html", "python", "php/css"), city=c("ponnur", "hyd", "hyd", "guntur"), marks=c(89, 78, 78, 81)) # displayprint(data1)print(data2) Output: Example 1 : Merge dataframes on 2 columns R # create dataframe1data1 = data.frame(name=c("manoj", "manoja", "saroja", "ramya"), subjects=c("java", "c/cpp", "python", "R"), city=c("ponnur", "tenali", "hyd", "guntur"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(student=c("manoj", "sravya", "saroja", "pavani"), subjects=c("java", "c/html", "python", "php/css"), city=c("ponnur", "hyd", "hyd", "guntur"), exams=c(89, 78, 78, 81)) # merge dataframes based on name and subjects from data1# with student and subjects from data2merge(data1, data2, by.x=c('name', 'subjects'), by.y=c('student', 'subjects')) Output: Example 2: Merge the dataframes based on three columns. R # create dataframe1data1 = data.frame(name=c("manoj", "manoja", "saroja", "ramya"), subjects=c("java", "c/cpp", "python", "R"), city=c("ponnur", "tenali", "hyd", "guntur"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(student=c("manoj", "sravya", "saroja", "pavani"), subjects=c("java", "c/html", "python", "php/css"), city=c("ponnur", "hyd", "hyd", "guntur"), exams=c(89, 78, 78, 81)) # merge dataframes based on name,city and subjects from data1# with student,city and subjects from data2merge(data1, data2, by.x=c('name', 'subjects', 'city'), by.y=c('student', 'subjects', 'city')) Output: Picked R DataFrame-Programs R-DataFrame 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to import an Excel File into R ? How to filter R DataFrame by values in a column? Time Series Analysis in R R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 26487, "s": 26459, "text": "\n28 Nov, 2021" }, { "code": null, "e": 26597, "s": 26487, "text": "In this article, we will discuss how to merge dataframes based on multiple columns in R Programming Language." }, { "code": null, "e": 26679, "s": 26597, "text": "We can merge two dataframes based on multiple columns by using merge() function" }, { "code": null, "e": 26687, "s": 26679, "text": "Syntax:" }, { "code": null, "e": 26821, "s": 26687, "text": "merge(dataframe1, dataframe2, by.x=c(‘column1’, ‘column2’...........,’column n’), by.y=c(‘column1’, ‘column2’...........,’column n’))" }, { "code": null, "e": 26827, "s": 26821, "text": "where" }, { "code": null, "e": 26861, "s": 26827, "text": "dataframe1 is the first dataframe" }, { "code": null, "e": 26896, "s": 26861, "text": "dataframe2 is the second dataframe" }, { "code": null, "e": 26936, "s": 26896, "text": "by.x represents first dataframe columns" }, { "code": null, "e": 26977, "s": 26936, "text": "by.y represents second dataframe columns" }, { "code": null, "e": 27015, "s": 26977, "text": "Let create two dataframes and display" }, { "code": null, "e": 27090, "s": 27015, "text": "Example: R program to create two dataframes with 4 columns of student data" }, { "code": null, "e": 27092, "s": 27090, "text": "R" }, { "code": "# create dataframe1data1 = data.frame(name=c(\"manoj\", \"manoja\", \"saroja\", \"ramya\"), subjects=c(\"java\", \"c/cpp\", \"python\", \"R\"), city=c(\"ponnur\", \"tenali\", \"hyd\", \"guntur\"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(name=c(\"manoj\", \"sravya\", \"saroja\", \"pavani\"), subjects=c(\"java\", \"c/html\", \"python\", \"php/css\"), city=c(\"ponnur\", \"hyd\", \"hyd\", \"guntur\"), marks=c(89, 78, 78, 81)) # displayprint(data1)print(data2)", "e": 27637, "s": 27092, "text": null }, { "code": null, "e": 27645, "s": 27637, "text": "Output:" }, { "code": null, "e": 27687, "s": 27645, "text": "Example 1 : Merge dataframes on 2 columns" }, { "code": null, "e": 27689, "s": 27687, "text": "R" }, { "code": "# create dataframe1data1 = data.frame(name=c(\"manoj\", \"manoja\", \"saroja\", \"ramya\"), subjects=c(\"java\", \"c/cpp\", \"python\", \"R\"), city=c(\"ponnur\", \"tenali\", \"hyd\", \"guntur\"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(student=c(\"manoj\", \"sravya\", \"saroja\", \"pavani\"), subjects=c(\"java\", \"c/html\", \"python\", \"php/css\"), city=c(\"ponnur\", \"hyd\", \"hyd\", \"guntur\"), exams=c(89, 78, 78, 81)) # merge dataframes based on name and subjects from data1# with student and subjects from data2merge(data1, data2, by.x=c('name', 'subjects'), by.y=c('student', 'subjects'))", "e": 28381, "s": 27689, "text": null }, { "code": null, "e": 28389, "s": 28381, "text": "Output:" }, { "code": null, "e": 28445, "s": 28389, "text": "Example 2: Merge the dataframes based on three columns." }, { "code": null, "e": 28447, "s": 28445, "text": "R" }, { "code": "# create dataframe1data1 = data.frame(name=c(\"manoj\", \"manoja\", \"saroja\", \"ramya\"), subjects=c(\"java\", \"c/cpp\", \"python\", \"R\"), city=c(\"ponnur\", \"tenali\", \"hyd\", \"guntur\"), marks=c(89, 90, 78, 89)) # create dataframe2data2 = data.frame(student=c(\"manoj\", \"sravya\", \"saroja\", \"pavani\"), subjects=c(\"java\", \"c/html\", \"python\", \"php/css\"), city=c(\"ponnur\", \"hyd\", \"hyd\", \"guntur\"), exams=c(89, 78, 78, 81)) # merge dataframes based on name,city and subjects from data1# with student,city and subjects from data2merge(data1, data2, by.x=c('name', 'subjects', 'city'), by.y=c('student', 'subjects', 'city'))", "e": 29165, "s": 28447, "text": null }, { "code": null, "e": 29173, "s": 29165, "text": "Output:" }, { "code": null, "e": 29180, "s": 29173, "text": "Picked" }, { "code": null, "e": 29201, "s": 29180, "text": "R DataFrame-Programs" }, { "code": null, "e": 29213, "s": 29201, "text": "R-DataFrame" }, { "code": null, "e": 29224, "s": 29213, "text": "R Language" }, { "code": null, "e": 29322, "s": 29224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29374, "s": 29322, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29409, "s": 29374, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29447, "s": 29409, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29505, "s": 29447, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29548, "s": 29505, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29585, "s": 29548, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29634, "s": 29585, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29660, "s": 29634, "text": "Time Series Analysis in R" }, { "code": null, "e": 29677, "s": 29660, "text": "R - if statement" } ]
Nutanix Interview Experience | Set 1 (On-Campus for Internship) - GeeksforGeeks
14 May, 2017 Nutanix visited my campus. There were 3 rounds in total: Round 1 (coding round) :2 questions were to be solved in 1hr 15min.Question 1:Given a string determine whether it is a ‘sum-string’. A string is called a sum-string if it satisfies the following properties:len(s)>3sub-string(i,x) + sub-string(x+1,j) = sub-string(j,l)example:“12358” is a sum string. Explanation : 1+2 = 3 ; 2+3 = 5 ; 3+5 = 8“199100199” is a sum string. Explanation: 1+99 = 100 ; 99+100 = 199“2368” is not a sum string. Question 2:Given 2 strings s1 and s2 determine whether s2 is a shuffle of s1. Where shuffle is defined as an operation that switches 2 children of a node in a binary tree. Example: s1 = great s2 = taerg binary tree for s1 great / \ gr eat / \ / \ g r e at after shuffle we obtain, great / \ eat gr (shuffle gr and eat as they are children of great node) / \ / \ at e r g / \ t a so taerg is a shuffel string of s1.This was a tricky question of the 2.12 students qualified for the next round. I solved all the test cases of the 1st question and 5 test cases of question 2. So I was selected for 2nd round. Round 2:I was asked to solve a Dynamic Programming problem. Given a string of digits separated by operators ( + and *) only. Then parenthesize the string in such a way that first we get the max value possible and then we get the least value possible from the string. Return the difference of the two values calculated. I had to solve this problem on a paper sheet and explain the whole approach. I took 30 min to complete the code on paper along with the explanation. Then the interviewer tested my code for some simple cases : 2*2+2 => max is 2*(2+2) = 8 and min is (2*2)+2 = 6.Then he asked me if I had any questions for him.He was impressed by my solution and coding style, clean and neat with comments and camel case of variables.In total 6 students were shortlisted for the 3rd round including me. Round 3:Interviewer asked me to debug a code involving reader – writer locks. It was an OS question, modified version of readers-writers problem. I pointed out 5 problems with the code, syntactical and logical both. There was a deadlock condition, write after write inconsistency, read after write inconsistency, wrong if then else and a syntax error. I took 10 min to do point out all the problems and write the correct code. The interviewer had a stopwatch running on his phone, which I only got to know about after 5 mins. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Nutanix Internship Interview Experiences Nutanix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Zoho Interview Experience (Off-Campus ) 2022 Resume Writing For Internship Difference Between ON Page and OFF Page SEO Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26315, "s": 26287, "text": "\n14 May, 2017" }, { "code": null, "e": 26372, "s": 26315, "text": "Nutanix visited my campus. There were 3 rounds in total:" }, { "code": null, "e": 26808, "s": 26372, "text": "Round 1 (coding round) :2 questions were to be solved in 1hr 15min.Question 1:Given a string determine whether it is a ‘sum-string’. A string is called a sum-string if it satisfies the following properties:len(s)>3sub-string(i,x) + sub-string(x+1,j) = sub-string(j,l)example:“12358” is a sum string. Explanation : 1+2 = 3 ; 2+3 = 5 ; 3+5 = 8“199100199” is a sum string. Explanation: 1+99 = 100 ; 99+100 = 199“2368” is not a sum string." }, { "code": null, "e": 26980, "s": 26808, "text": "Question 2:Given 2 strings s1 and s2 determine whether s2 is a shuffle of s1. Where shuffle is defined as an operation that switches 2 children of a node in a binary tree." }, { "code": null, "e": 27273, "s": 26980, "text": "Example:\ns1 = great\ns2 = taerg\n\nbinary tree for s1\n great\n / \\\n gr eat\n / \\ / \\\n g r e at\n\nafter shuffle we obtain,\n great\n / \\\n eat gr (shuffle gr and eat as they are children of great node)\n / \\ / \\\n at e r g\n / \\\nt a" }, { "code": null, "e": 27499, "s": 27273, "text": "so taerg is a shuffel string of s1.This was a tricky question of the 2.12 students qualified for the next round. I solved all the test cases of the 1st question and 5 test cases of question 2. So I was selected for 2nd round." }, { "code": null, "e": 28302, "s": 27499, "text": "Round 2:I was asked to solve a Dynamic Programming problem. Given a string of digits separated by operators ( + and *) only. Then parenthesize the string in such a way that first we get the max value possible and then we get the least value possible from the string. Return the difference of the two values calculated. I had to solve this problem on a paper sheet and explain the whole approach. I took 30 min to complete the code on paper along with the explanation. Then the interviewer tested my code for some simple cases : 2*2+2 => max is 2*(2+2) = 8 and min is (2*2)+2 = 6.Then he asked me if I had any questions for him.He was impressed by my solution and coding style, clean and neat with comments and camel case of variables.In total 6 students were shortlisted for the 3rd round including me." }, { "code": null, "e": 28828, "s": 28302, "text": "Round 3:Interviewer asked me to debug a code involving reader – writer locks. It was an OS question, modified version of readers-writers problem. I pointed out 5 problems with the code, syntactical and logical both. There was a deadlock condition, write after write inconsistency, read after write inconsistency, wrong if then else and a syntax error. I took 10 min to do point out all the problems and write the correct code. The interviewer had a stopwatch running on his phone, which I only got to know about after 5 mins." }, { "code": null, "e": 29049, "s": 28828, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29057, "s": 29049, "text": "Nutanix" }, { "code": null, "e": 29068, "s": 29057, "text": "Internship" }, { "code": null, "e": 29090, "s": 29068, "text": "Interview Experiences" }, { "code": null, "e": 29098, "s": 29090, "text": "Nutanix" }, { "code": null, "e": 29196, "s": 29098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29273, "s": 29196, "text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)" }, { "code": null, "e": 29345, "s": 29273, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 29390, "s": 29345, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 29420, "s": 29390, "text": "Resume Writing For Internship" }, { "code": null, "e": 29464, "s": 29420, "text": "Difference Between ON Page and OFF Page SEO" }, { "code": null, "e": 29491, "s": 29464, "text": "Amazon Interview Questions" }, { "code": null, "e": 29551, "s": 29491, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 29602, "s": 29551, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 29644, "s": 29602, "text": "Amazon AWS Interview Experience for SDE-1" } ]
Hashmap vs WeakHashMap in Java - GeeksforGeeks
29 Sep, 2021 HashMap Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates over Garbage Collector. Java // Java program to illustrate// Hashmapimport java.util.*;class HashMapDemo{ public static void main(String args[])throws Exception { HashMap m = new HashMap(); Demo d = new Demo(); // puts an entry into HashMap m.put(d," Hi "); System.out.println(m); d = null; // garbage collector is called System.gc(); //thread sleeps for 4 sec Thread.sleep(4000); System.out.println(m); } } class Demo { public String toString() { return "demo"; } // finalize method public void finalize() { System.out.println("Finalize method is called"); }} Output: {demo=Hi} {demo=Hi} WeakHashMap WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap. Java // Java program to illustrate// WeakHashmapimport java.util.*;class WeakHashMapDemo{ public static void main(String args[])throws Exception { WeakHashMap m = new WeakHashMap(); Demo d = new Demo(); // puts an entry into WeakHashMap m.put(d," Hi "); System.out.println(m); d = null; // garbage collector is called System.gc(); // thread sleeps for 4 sec Thread.sleep(4000); . System.out.println(m); }} class Demo{ public String toString() { return "demo"; } // finalize method public void finalize() { System.out.println("finalize method is called"); }} Output: {demo = Hi} finalize method is called { } Some more important differences between Hashmap and WeakHashmap: Strong vs Weak References: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. This type of reference is used in WeakHashMap to reference the entry objects. Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. In HashMap, key objects have strong references. Role of Garbage Collector: Garbage Collected : In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection i.e Hashmap is dominant over Garbage Collector. In WeakHashmap, When a key is discarded then its entry is automatically removed from the map, in other words, garbage collected.Clone method Implementation: HashMap implements Cloneable interface. WeakHashMap does not implement Cloneable interface, it only implements Map interface. Hence, there is no clone() method in the WeakHashMap class. Strong vs Weak References: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. This type of reference is used in WeakHashMap to reference the entry objects. Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. In HashMap, key objects have strong references. Role of Garbage Collector: Garbage Collected : In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection i.e Hashmap is dominant over Garbage Collector. In WeakHashmap, When a key is discarded then its entry is automatically removed from the map, in other words, garbage collected. Clone method Implementation: HashMap implements Cloneable interface. WeakHashMap does not implement Cloneable interface, it only implements Map interface. Hence, there is no clone() method in the WeakHashMap class. This article is contributed by Rishabh Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surindertarika1234 Java-Collections Java-Map-Programs Java 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 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": 26235, "s": 26207, "text": "\n29 Sep, 2021" }, { "code": null, "e": 26243, "s": 26235, "text": "HashMap" }, { "code": null, "e": 26558, "s": 26243, "text": "Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates over Garbage Collector." }, { "code": null, "e": 26563, "s": 26558, "text": "Java" }, { "code": "// Java program to illustrate// Hashmapimport java.util.*;class HashMapDemo{ public static void main(String args[])throws Exception { HashMap m = new HashMap(); Demo d = new Demo(); // puts an entry into HashMap m.put(d,\" Hi \"); System.out.println(m); d = null; // garbage collector is called System.gc(); //thread sleeps for 4 sec Thread.sleep(4000); System.out.println(m); } } class Demo { public String toString() { return \"demo\"; } // finalize method public void finalize() { System.out.println(\"Finalize method is called\"); }}", "e": 27319, "s": 26563, "text": null }, { "code": null, "e": 27328, "s": 27319, "text": "Output: " }, { "code": null, "e": 27348, "s": 27328, "text": "{demo=Hi}\n{demo=Hi}" }, { "code": null, "e": 27360, "s": 27348, "text": "WeakHashMap" }, { "code": null, "e": 27681, "s": 27360, "text": "WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap." }, { "code": null, "e": 27686, "s": 27681, "text": "Java" }, { "code": "// Java program to illustrate// WeakHashmapimport java.util.*;class WeakHashMapDemo{ public static void main(String args[])throws Exception { WeakHashMap m = new WeakHashMap(); Demo d = new Demo(); // puts an entry into WeakHashMap m.put(d,\" Hi \"); System.out.println(m); d = null; // garbage collector is called System.gc(); // thread sleeps for 4 sec Thread.sleep(4000); . System.out.println(m); }} class Demo{ public String toString() { return \"demo\"; } // finalize method public void finalize() { System.out.println(\"finalize method is called\"); }}", "e": 28410, "s": 27686, "text": null }, { "code": null, "e": 28419, "s": 28410, "text": "Output: " }, { "code": null, "e": 28461, "s": 28419, "text": "{demo = Hi}\nfinalize method is called\n{ }" }, { "code": null, "e": 28527, "s": 28461, "text": "Some more important differences between Hashmap and WeakHashmap: " }, { "code": null, "e": 29512, "s": 28527, "text": "Strong vs Weak References: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. This type of reference is used in WeakHashMap to reference the entry objects. Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. In HashMap, key objects have strong references. Role of Garbage Collector: Garbage Collected : In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection i.e Hashmap is dominant over Garbage Collector. In WeakHashmap, When a key is discarded then its entry is automatically removed from the map, in other words, garbage collected.Clone method Implementation: HashMap implements Cloneable interface. WeakHashMap does not implement Cloneable interface, it only implements Map interface. Hence, there is no clone() method in the WeakHashMap class." }, { "code": null, "e": 29958, "s": 29512, "text": "Strong vs Weak References: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. This type of reference is used in WeakHashMap to reference the entry objects. Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. In HashMap, key objects have strong references. " }, { "code": null, "e": 30284, "s": 29958, "text": "Role of Garbage Collector: Garbage Collected : In HashMap , entry object(entry object stores key-value pairs) is not eligible for garbage collection i.e Hashmap is dominant over Garbage Collector. In WeakHashmap, When a key is discarded then its entry is automatically removed from the map, in other words, garbage collected." }, { "code": null, "e": 30499, "s": 30284, "text": "Clone method Implementation: HashMap implements Cloneable interface. WeakHashMap does not implement Cloneable interface, it only implements Map interface. Hence, there is no clone() method in the WeakHashMap class." }, { "code": null, "e": 30921, "s": 30499, "text": "This article is contributed by Rishabh Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30940, "s": 30921, "text": "surindertarika1234" }, { "code": null, "e": 30957, "s": 30940, "text": "Java-Collections" }, { "code": null, "e": 30975, "s": 30957, "text": "Java-Map-Programs" }, { "code": null, "e": 30980, "s": 30975, "text": "Java" }, { "code": null, "e": 30985, "s": 30980, "text": "Java" }, { "code": null, "e": 31002, "s": 30985, "text": "Java-Collections" }, { "code": null, "e": 31100, "s": 31002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31151, "s": 31100, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31181, "s": 31151, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31196, "s": 31181, "text": "Stream In Java" }, { "code": null, "e": 31215, "s": 31196, "text": "Interfaces in Java" }, { "code": null, "e": 31246, "s": 31215, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31264, "s": 31246, "text": "ArrayList in Java" }, { "code": null, "e": 31296, "s": 31264, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31316, "s": 31296, "text": "Stack Class in Java" }, { "code": null, "e": 31340, "s": 31316, "text": "Singleton Class in Java" } ]
Creating A Range Slider in HTML using JavaScript - GeeksforGeeks
03 Dec, 2018 Range Sliders are used on web pages to allow the user specify a numeric value which must be no less than a given value, and no more than another given value. That is, it allows to choose value from a range which is represented as a slider.A Range slider is typically represented using a slider or dial control rather than a text entry box like the “number” input type. It is used when the exact numeric value isn’t required to input. For example, the price slider in the filter menu of products list at flipkart.com Creating a Range Slider We can create a Range Slider using simple HTML and JavaScript by following the below steps:Step 1:Creating an HTML element.The slider element is defined in this step using the “div” element under which is a input field whose range is defined between 1 and 100. <div class="rangeslider"> <input type="range" min="1" max="100" value="10" class="myslider" id="sliderRange"></div> Step 2:Adding CSS to the slider element. Define the width of the outside container..rangeslider{ width: 50%; } Define CSS for the slider like height, width, background, opacity etc for the slider..myslider { -webkit-appearance: none; background: #FCF3CF ; width: 50%; height: 20px; opacity: 2; } Add Mouse hovering effects..myslider:hover { opacity: 1; } Add WebKit for browsers to change the default look of range sliders..myslider::-webkit-slider-thumb { -webkit-appearance: none; cursor: pointer; background: #34495E ; width: 5%; height: 20px; } Define the width of the outside container..rangeslider{ width: 50%; } .rangeslider{ width: 50%; } Define CSS for the slider like height, width, background, opacity etc for the slider..myslider { -webkit-appearance: none; background: #FCF3CF ; width: 50%; height: 20px; opacity: 2; } .myslider { -webkit-appearance: none; background: #FCF3CF ; width: 50%; height: 20px; opacity: 2; } Add Mouse hovering effects..myslider:hover { opacity: 1; } .myslider:hover { opacity: 1; } Add WebKit for browsers to change the default look of range sliders..myslider::-webkit-slider-thumb { -webkit-appearance: none; cursor: pointer; background: #34495E ; width: 5%; height: 20px; } .myslider::-webkit-slider-thumb { -webkit-appearance: none; cursor: pointer; background: #34495E ; width: 5%; height: 20px; } Step 3:Addition of JavaScript to the slider element.Add the below JavaScript code to display the default slider value. var rangeslider = document.getElementById("sliderRange"); var output = document.getElementById("demo"); output.innerHTML = rangeslider.value; rangeslider.oninput = function() { output.innerHTML = this.value; } Step 4:Combine the above elements. <!DOCTYPE html><html><style> .rangeslider{ width: 50%;} .myslider { -webkit-appearance: none; background: #FCF3CF ; width: 50%; height: 20px; opacity: 2; } .myslider::-webkit-slider-thumb { -webkit-appearance: none; cursor: pointer; background: #34495E ; width: 5%; height: 20px;} .myslider:hover { opacity: 1;} </style><body> <h1>Example of Range Slider Using Javascript</h1><p>Use the slider to increment or decrement value.</p> <div class="rangeslider"> <input type="range" min="1" max="100" value="10" class="myslider" id="sliderRange"> <p>Value: <span id="demo"></span></p></div> <script>var rangeslider = document.getElementById("sliderRange");var output = document.getElementById("demo");output.innerHTML = rangeslider.value; rangeslider.oninput = function() { output.innerHTML = this.value;}</script> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? 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": 25185, "s": 25157, "text": "\n03 Dec, 2018" }, { "code": null, "e": 25701, "s": 25185, "text": "Range Sliders are used on web pages to allow the user specify a numeric value which must be no less than a given value, and no more than another given value. That is, it allows to choose value from a range which is represented as a slider.A Range slider is typically represented using a slider or dial control rather than a text entry box like the “number” input type. It is used when the exact numeric value isn’t required to input. For example, the price slider in the filter menu of products list at flipkart.com" }, { "code": null, "e": 25725, "s": 25701, "text": "Creating a Range Slider" }, { "code": null, "e": 25986, "s": 25725, "text": "We can create a Range Slider using simple HTML and JavaScript by following the below steps:Step 1:Creating an HTML element.The slider element is defined in this step using the “div” element under which is a input field whose range is defined between 1 and 100." }, { "code": "<div class=\"rangeslider\"> <input type=\"range\" min=\"1\" max=\"100\" value=\"10\" class=\"myslider\" id=\"sliderRange\"></div>", "e": 26119, "s": 25986, "text": null }, { "code": null, "e": 26160, "s": 26119, "text": "Step 2:Adding CSS to the slider element." }, { "code": null, "e": 26726, "s": 26160, "text": "Define the width of the outside container..rangeslider{\n width: 50%;\n }\nDefine CSS for the slider like height, width, background, opacity etc for the slider..myslider {\n -webkit-appearance: none;\n background: #FCF3CF ;\n width: 50%;\n height: 20px;\n opacity: 2;\n }\nAdd Mouse hovering effects..myslider:hover {\n opacity: 1;\n}\nAdd WebKit for browsers to change the default look of range sliders..myslider::-webkit-slider-thumb {\n -webkit-appearance: none;\n cursor: pointer;\n background: #34495E ;\n width: 5%;\n height: 20px;\n}\n" }, { "code": null, "e": 26805, "s": 26726, "text": "Define the width of the outside container..rangeslider{\n width: 50%;\n }\n" }, { "code": null, "e": 26842, "s": 26805, "text": ".rangeslider{\n width: 50%;\n }\n" }, { "code": null, "e": 27052, "s": 26842, "text": "Define CSS for the slider like height, width, background, opacity etc for the slider..myslider {\n -webkit-appearance: none;\n background: #FCF3CF ;\n width: 50%;\n height: 20px;\n opacity: 2;\n }\n" }, { "code": null, "e": 27177, "s": 27052, "text": ".myslider {\n -webkit-appearance: none;\n background: #FCF3CF ;\n width: 50%;\n height: 20px;\n opacity: 2;\n }\n" }, { "code": null, "e": 27241, "s": 27177, "text": "Add Mouse hovering effects..myslider:hover {\n opacity: 1;\n}\n" }, { "code": null, "e": 27278, "s": 27241, "text": ".myslider:hover {\n opacity: 1;\n}\n" }, { "code": null, "e": 27494, "s": 27278, "text": "Add WebKit for browsers to change the default look of range sliders..myslider::-webkit-slider-thumb {\n -webkit-appearance: none;\n cursor: pointer;\n background: #34495E ;\n width: 5%;\n height: 20px;\n}\n" }, { "code": null, "e": 27642, "s": 27494, "text": ".myslider::-webkit-slider-thumb {\n -webkit-appearance: none;\n cursor: pointer;\n background: #34495E ;\n width: 5%;\n height: 20px;\n}\n" }, { "code": null, "e": 27761, "s": 27642, "text": "Step 3:Addition of JavaScript to the slider element.Add the below JavaScript code to display the default slider value." }, { "code": null, "e": 27975, "s": 27761, "text": "var rangeslider = document.getElementById(\"sliderRange\");\nvar output = document.getElementById(\"demo\");\noutput.innerHTML = rangeslider.value;\n\nrangeslider.oninput = function() {\n output.innerHTML = this.value;\n}\n" }, { "code": null, "e": 28010, "s": 27975, "text": "Step 4:Combine the above elements." }, { "code": "<!DOCTYPE html><html><style> .rangeslider{ width: 50%;} .myslider { -webkit-appearance: none; background: #FCF3CF ; width: 50%; height: 20px; opacity: 2; } .myslider::-webkit-slider-thumb { -webkit-appearance: none; cursor: pointer; background: #34495E ; width: 5%; height: 20px;} .myslider:hover { opacity: 1;} </style><body> <h1>Example of Range Slider Using Javascript</h1><p>Use the slider to increment or decrement value.</p> <div class=\"rangeslider\"> <input type=\"range\" min=\"1\" max=\"100\" value=\"10\" class=\"myslider\" id=\"sliderRange\"> <p>Value: <span id=\"demo\"></span></p></div> <script>var rangeslider = document.getElementById(\"sliderRange\");var output = document.getElementById(\"demo\");output.innerHTML = rangeslider.value; rangeslider.oninput = function() { output.innerHTML = this.value;}</script> </body></html>", "e": 28908, "s": 28010, "text": null }, { "code": null, "e": 28916, "s": 28908, "text": "Output:" }, { "code": null, "e": 29053, "s": 28916, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29063, "s": 29053, "text": "HTML-Misc" }, { "code": null, "e": 29068, "s": 29063, "text": "HTML" }, { "code": null, "e": 29085, "s": 29068, "text": "Web Technologies" }, { "code": null, "e": 29090, "s": 29085, "text": "HTML" }, { "code": null, "e": 29188, "s": 29090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29238, "s": 29188, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29300, "s": 29238, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29348, "s": 29300, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29408, "s": 29348, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29469, "s": 29408, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29509, "s": 29469, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29542, "s": 29509, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29587, "s": 29542, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29630, "s": 29587, "text": "How to fetch data from an API in ReactJS ?" } ]
Swapping two numbers using template function in C++ - GeeksforGeeks
27 Dec, 2021 A significant benefit of object-oriented programming is the reusability of code which eliminates redundant coding. An important feature of C++ is called templates. Templates support generic programming, which allows to development of reusable software components such as functions, classes, etc., supporting different data types in a single framework. A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. The templates declared for functions are called function templates and those declared for classes are called class templates. This article focuses on discussing how to use a function template to swap two numbers in C++. Function Templates There are several functions of considerable importance which have to be used frequently with different data types. The limitation of such functions is that they operate only on a particular data type. It can be overcome by defining that function as a function template or a generic function. A function template specifies how an individual function can be constructed. Syntax: template <class T, ...... >returntype FuncName (arguments){ // body of template function ........... ............} Below is the C++ program to implement the function templates to swap two numbers. C++ // C++ program to implement// function templates#include <iostream>using namespace std; // Function template to swap// two numberstemplate <class T>int swap_numbers(T& x, T& y){ T t; t = x; x = y; y = t; return 0;} // Driver codeint main(){ int a, b; a = 10, b = 20; // Invoking the swap() swap_numbers(a, b); cout << a << " " << b << endl; return 0;} 20 10 CPP-Functions Swap-Program C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Iterative Letter Combinations of a Phone Number Return by reference in C++ with Examples How to sort an Array in descending order using STL in C++? Setting up Sublime Text for C++ Competitive Programming Environment Why it is important to write "using namespace std" in C++ program?
[ { "code": null, "e": 25773, "s": 25745, "text": "\n27 Dec, 2021" }, { "code": null, "e": 26125, "s": 25773, "text": "A significant benefit of object-oriented programming is the reusability of code which eliminates redundant coding. An important feature of C++ is called templates. Templates support generic programming, which allows to development of reusable software components such as functions, classes, etc., supporting different data types in a single framework." }, { "code": null, "e": 26621, "s": 26125, "text": "A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. The templates declared for functions are called function templates and those declared for classes are called class templates." }, { "code": null, "e": 26715, "s": 26621, "text": "This article focuses on discussing how to use a function template to swap two numbers in C++." }, { "code": null, "e": 26734, "s": 26715, "text": "Function Templates" }, { "code": null, "e": 27103, "s": 26734, "text": "There are several functions of considerable importance which have to be used frequently with different data types. The limitation of such functions is that they operate only on a particular data type. It can be overcome by defining that function as a function template or a generic function. A function template specifies how an individual function can be constructed." }, { "code": null, "e": 27111, "s": 27103, "text": "Syntax:" }, { "code": null, "e": 27240, "s": 27111, "text": "template <class T, ...... >returntype FuncName (arguments){ // body of template function ........... ............}" }, { "code": null, "e": 27322, "s": 27240, "text": "Below is the C++ program to implement the function templates to swap two numbers." }, { "code": null, "e": 27326, "s": 27322, "text": "C++" }, { "code": "// C++ program to implement// function templates#include <iostream>using namespace std; // Function template to swap// two numberstemplate <class T>int swap_numbers(T& x, T& y){ T t; t = x; x = y; y = t; return 0;} // Driver codeint main(){ int a, b; a = 10, b = 20; // Invoking the swap() swap_numbers(a, b); cout << a << \" \" << b << endl; return 0;}", "e": 27715, "s": 27326, "text": null }, { "code": null, "e": 27721, "s": 27715, "text": "20 10" }, { "code": null, "e": 27735, "s": 27721, "text": "CPP-Functions" }, { "code": null, "e": 27748, "s": 27735, "text": "Swap-Program" }, { "code": null, "e": 27761, "s": 27748, "text": "C++ Programs" }, { "code": null, "e": 27859, "s": 27761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27900, "s": 27859, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27959, "s": 27900, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27980, "s": 27959, "text": "Const keyword in C++" }, { "code": null, "e": 27992, "s": 27980, "text": "cout in C++" }, { "code": null, "e": 28013, "s": 27992, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 28061, "s": 28013, "text": "Iterative Letter Combinations of a Phone Number" }, { "code": null, "e": 28102, "s": 28061, "text": "Return by reference in C++ with Examples" }, { "code": null, "e": 28161, "s": 28102, "text": "How to sort an Array in descending order using STL in C++?" }, { "code": null, "e": 28229, "s": 28161, "text": "Setting up Sublime Text for C++ Competitive Programming Environment" } ]
Merge k sorted linked lists | Set 2 (Using Min Heap) - GeeksforGeeks
28 Mar, 2022 Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10->11 Merged lists in a sorted order where every element is greater than the previous element. Input: k = 3, n = 3 list1 = 1->3->7->NULL list2 = 2->4->8->NULL list3 = 9->10->11->NULL Output: 1->2->3->4->7->8->9->10->11 Merged lists in a sorted order where every element is greater than the previous element. Source: Merge K sorted Linked Lists | Method 2 An efficient solution for the problem has been discussed in Method 3 of this post. Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here.MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2. Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps: Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list. Create a min-heap and insert the first element of all the ‘k’ linked lists. As long as the min-heap is not empty, perform the following steps: Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap. Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list. If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap. Return the head node address of the merged list. Below is the implementation of the above approach: C++ C++ Java // C++ implementation to merge k// sorted linked lists// | Using MIN HEAP method#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* next;}; // Utility function to create// a new nodestruct Node* newNode(int data){ // Allocate node struct Node* new_node = new Node(); // Put in the data new_node->data = data; new_node->next = NULL; return new_node;} // 'compare' function used to build// up the priority queuestruct compare{ bool operator()( struct Node* a, struct Node* b) { return a->data > b->data; }}; // Function to merge k sorted linked listsstruct Node* mergeKSortedLists( struct Node* arr[], int k){ // Priority_queue 'pq' implemented // as min heap with the help of // 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; // Push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != NULL) pq.push(arr[i]); // Handles the case when k = 0 // or lists have no elements in them if (pq.empty()) return NULL; struct Node *dummy = newNode(0); struct Node *last = dummy; // Loop till 'pq' is not empty while (!pq.empty()) { // Get the top element of 'pq' struct Node* curr = pq.top(); pq.pop(); // Add the top element of 'pq' // to the resultant merged list last->next = curr; last = last->next; // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr->next != NULL) // Push the next node of top node // in 'pq' pq.push(curr->next); } // Address of head node of the required // merged list return dummy->next;} // Function to print the singly// linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // An array of pointers storing the // head nodes of the linked lists Node* arr[k]; // Creating k = 3 sorted lists arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge the k sorted lists struct Node* head = mergeKSortedLists(arr, k); // Print the merged list printList(head); return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*; class Node { int data; Node next; Node(int key) { data = key; next = null; }}// Class implements Comparator to compare Node dataclass NodeComparator implements Comparator<Node> { public int compare(Node k1, Node k2) { if (k1.data > k2.data) return 1; else if (k1.data < k2.data) return -1; return 0; }}class GFG { // Function to merge k sorted linked lists static Node mergeKList(Node[] arr, int K) { // Priority_queue 'queue' implemented // as min heap with the help of // 'compare' function PriorityQueue<Node> queue = new PriorityQueue<>(new NodeComparator()); Node at[] = new Node[K]; Node head = new Node(0); Node last = head; // Push the head nodes of all // the k lists in 'queue' for (int i = 0; i < K; i++) { if (arr[i] != null) { queue.add(arr[i]); } } // Handles the case when k = 0 // or lists have no elements in them if (queue.isEmpty()) return null; // Loop till 'queue' is not empty while (!queue.isEmpty()) { // Get the top element of 'queue' Node curr = queue.poll(); // Add the top element of 'queue' // to the resultant merged list last.next = curr; last = last.next; // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr.next != null) { // Push the next node of top node // in 'queue' queue.add(curr.next); } } // Address of head node of the required // merged list return head.next; } // Print linked list public static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { int N = 4; // array to store head of linkedlist Node[] a = new Node[N]; // Linkedlist1 Node head1 = new Node(1); a[0] = head1; head1.next = new Node(2); head1.next.next = new Node(3); // Limkedlist2 Node head2 = new Node(4); a[1] = head2; head2.next = new Node(5); // Linkedlist3 Node head3 = new Node(5); a[2] = head3; head3.next = new Node(6); // Linkedlist4 Node head4 = new Node(7); a[3] = head4; head4.next = new Node(8); Node res = mergeKList(a, N); if (res != null) printList(res); System.out.println(); }} Output: 0 1 2 3 4 5 6 7 8 9 10 11 Complexity Analysis: Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time. Auxiliary Space: O(k).The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k). This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari AdarshTadwai andrew1234 tridib_samanta mittulmandhan avanitrachhadiya2155 pratikpatle varshagumber28 Amazon VMWare Heap Linked List VMWare Amazon Linked List Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Insertion and Deletion in Heaps Max Heap in Java Priority Queue in Python Priority Queue using Binary Heap Median in a stream of integers (running integers) Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 25837, "s": 25809, "text": "\n28 Mar, 2022" }, { "code": null, "e": 26042, "s": 25837, "text": "Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples:" }, { "code": null, "e": 26495, "s": 26042, "text": "Input: k = 3, n = 4\nlist1 = 1->3->5->7->NULL\nlist2 = 2->4->6->8->NULL\nlist3 = 0->9->10->11->NULL\n\nOutput: 0->1->2->3->4->5->6->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element.\n\nInput: k = 3, n = 3\nlist1 = 1->3->7->NULL\nlist2 = 2->4->8->NULL\nlist3 = 9->10->11->NULL\n\nOutput: 1->2->3->4->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element." }, { "code": null, "e": 26542, "s": 26495, "text": "Source: Merge K sorted Linked Lists | Method 2" }, { "code": null, "e": 26625, "s": 26542, "text": "An efficient solution for the problem has been discussed in Method 3 of this post." }, { "code": null, "e": 27085, "s": 26625, "text": "Approach: This solution is based on the MIN HEAP approach used to solve the problem ‘merge k sorted arrays’ which is discussed here.MinHeap: A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2." }, { "code": null, "e": 27545, "s": 27085, "text": "Create a min-heap and insert the first element of all the ‘k’ linked lists.As long as the min-heap is not empty, perform the following steps: Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap.Return the head node address of the merged list." }, { "code": null, "e": 27621, "s": 27545, "text": "Create a min-heap and insert the first element of all the ‘k’ linked lists." }, { "code": null, "e": 27958, "s": 27621, "text": "As long as the min-heap is not empty, perform the following steps: Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list.If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap." }, { "code": null, "e": 28098, "s": 27958, "text": "Remove the top element of the min-heap (which is the current minimum among all the elements in the min-heap) and add it to the result list." }, { "code": null, "e": 28229, "s": 28098, "text": "If there exists an element (in the same linked list) next to the element popped out in previous step, insert it into the min-heap." }, { "code": null, "e": 28278, "s": 28229, "text": "Return the head node address of the merged list." }, { "code": null, "e": 28329, "s": 28278, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28333, "s": 28329, "text": "C++" }, { "code": null, "e": 28337, "s": 28333, "text": "C++" }, { "code": null, "e": 28342, "s": 28337, "text": "Java" }, { "code": "// C++ implementation to merge k// sorted linked lists// | Using MIN HEAP method#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node* next;}; // Utility function to create// a new nodestruct Node* newNode(int data){ // Allocate node struct Node* new_node = new Node(); // Put in the data new_node->data = data; new_node->next = NULL; return new_node;} // 'compare' function used to build// up the priority queuestruct compare{ bool operator()( struct Node* a, struct Node* b) { return a->data > b->data; }}; // Function to merge k sorted linked listsstruct Node* mergeKSortedLists( struct Node* arr[], int k){ // Priority_queue 'pq' implemented // as min heap with the help of // 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; // Push the head nodes of all // the k lists in 'pq' for (int i = 0; i < k; i++) if (arr[i] != NULL) pq.push(arr[i]); // Handles the case when k = 0 // or lists have no elements in them if (pq.empty()) return NULL; struct Node *dummy = newNode(0); struct Node *last = dummy; // Loop till 'pq' is not empty while (!pq.empty()) { // Get the top element of 'pq' struct Node* curr = pq.top(); pq.pop(); // Add the top element of 'pq' // to the resultant merged list last->next = curr; last = last->next; // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr->next != NULL) // Push the next node of top node // in 'pq' pq.push(curr->next); } // Address of head node of the required // merged list return dummy->next;} // Function to print the singly// linked listvoid printList(struct Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // An array of pointers storing the // head nodes of the linked lists Node* arr[k]; // Creating k = 3 sorted lists arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge the k sorted lists struct Node* head = mergeKSortedLists(arr, k); // Print the merged list printList(head); return 0;}", "e": 31161, "s": 28342, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class Node { int data; Node next; Node(int key) { data = key; next = null; }}// Class implements Comparator to compare Node dataclass NodeComparator implements Comparator<Node> { public int compare(Node k1, Node k2) { if (k1.data > k2.data) return 1; else if (k1.data < k2.data) return -1; return 0; }}class GFG { // Function to merge k sorted linked lists static Node mergeKList(Node[] arr, int K) { // Priority_queue 'queue' implemented // as min heap with the help of // 'compare' function PriorityQueue<Node> queue = new PriorityQueue<>(new NodeComparator()); Node at[] = new Node[K]; Node head = new Node(0); Node last = head; // Push the head nodes of all // the k lists in 'queue' for (int i = 0; i < K; i++) { if (arr[i] != null) { queue.add(arr[i]); } } // Handles the case when k = 0 // or lists have no elements in them if (queue.isEmpty()) return null; // Loop till 'queue' is not empty while (!queue.isEmpty()) { // Get the top element of 'queue' Node curr = queue.poll(); // Add the top element of 'queue' // to the resultant merged list last.next = curr; last = last.next; // Check if there is a node // next to the 'top' node // in the list of which 'top' // node is a member if (curr.next != null) { // Push the next node of top node // in 'queue' queue.add(curr.next); } } // Address of head node of the required // merged list return head.next; } // Print linked list public static void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { int N = 4; // array to store head of linkedlist Node[] a = new Node[N]; // Linkedlist1 Node head1 = new Node(1); a[0] = head1; head1.next = new Node(2); head1.next.next = new Node(3); // Limkedlist2 Node head2 = new Node(4); a[1] = head2; head2.next = new Node(5); // Linkedlist3 Node head3 = new Node(5); a[2] = head3; head3.next = new Node(6); // Linkedlist4 Node head4 = new Node(7); a[3] = head4; head4.next = new Node(8); Node res = mergeKList(a, N); if (res != null) printList(res); System.out.println(); }}", "e": 34021, "s": 31161, "text": null }, { "code": null, "e": 34029, "s": 34021, "text": "Output:" }, { "code": null, "e": 34056, "s": 34029, "text": "0 1 2 3 4 5 6 7 8 9 10 11 " }, { "code": null, "e": 34077, "s": 34056, "text": "Complexity Analysis:" }, { "code": null, "e": 34409, "s": 34077, "text": "Time Complexity: O(N * log k) or O(n * k * log k), where, ‘N’ is the total number of elements among all the linked lists, ‘k’ is the total number of lists, and ‘n’ is the size of each linked list.Insertion and deletion operation will be performed in min-heap for all N nodes.Insertion and deletion in a min-heap require log k time." }, { "code": null, "e": 34575, "s": 34409, "text": "Auxiliary Space: O(k).The priority queue will have atmost ‘k’ number of elements at any point of time, hence the additional space required for our algorithm is O(k)." }, { "code": null, "e": 35000, "s": 34575, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35015, "s": 35000, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 35028, "s": 35015, "text": "AdarshTadwai" }, { "code": null, "e": 35039, "s": 35028, "text": "andrew1234" }, { "code": null, "e": 35054, "s": 35039, "text": "tridib_samanta" }, { "code": null, "e": 35068, "s": 35054, "text": "mittulmandhan" }, { "code": null, "e": 35089, "s": 35068, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35101, "s": 35089, "text": "pratikpatle" }, { "code": null, "e": 35116, "s": 35101, "text": "varshagumber28" }, { "code": null, "e": 35123, "s": 35116, "text": "Amazon" }, { "code": null, "e": 35130, "s": 35123, "text": "VMWare" }, { "code": null, "e": 35135, "s": 35130, "text": "Heap" }, { "code": null, "e": 35147, "s": 35135, "text": "Linked List" }, { "code": null, "e": 35154, "s": 35147, "text": "VMWare" }, { "code": null, "e": 35161, "s": 35154, "text": "Amazon" }, { "code": null, "e": 35173, "s": 35161, "text": "Linked List" }, { "code": null, "e": 35178, "s": 35173, "text": "Heap" }, { "code": null, "e": 35276, "s": 35178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35308, "s": 35276, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 35325, "s": 35308, "text": "Max Heap in Java" }, { "code": null, "e": 35350, "s": 35325, "text": "Priority Queue in Python" }, { "code": null, "e": 35383, "s": 35350, "text": "Priority Queue using Binary Heap" }, { "code": null, "e": 35433, "s": 35383, "text": "Median in a stream of integers (running integers)" }, { "code": null, "e": 35468, "s": 35433, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 35507, "s": 35468, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 35529, "s": 35507, "text": "Reverse a linked list" }, { "code": null, "e": 35577, "s": 35529, "text": "Stack Data Structure (Introduction and Program)" } ]
How to get the second-to-last element of a list in Python?
Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index. >>> L1=[1,2,3,4,5] >>> print (L1[-2]) 4
[ { "code": null, "e": 1302, "s": 1062, "text": "Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index." }, { "code": null, "e": 1342, "s": 1302, "text": ">>> L1=[1,2,3,4,5]\n>>> print (L1[-2])\n4" } ]
Chain of Responsibility Design Pattern - GeeksforGeeks
24 Feb, 2022 Chain of responsibility pattern is used to achieve loose coupling in software design where a request from the client is passed to a chain of objects to process them. Later, the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.Where and When Chain of Responsibility pattern is applicable : When you want to decouple a request’s sender and receiver Multiple objects, determined at runtime, are candidates to handle a request When you don’t want to specify handlers explicitly in your code When you want to issue a request to one of several objects without specifying the receiver explicitly. This pattern is recommended when multiple objects can handle a request and the handler doesn’t have to be a specific object. Also, the handler is determined at runtime. Please note that a request not handled at all by any handler is a valid use case. Handler : This can be an interface which will primarily receive the request and dispatches the request to a chain of handlers. It has reference to the only first handler in the chain and does not know anything about the rest of the handlers. Concrete handlers : These are actual handlers of the request chained in some sequential order. Client : Originator of request and this will access the handler to handle it. How to send a request in the application using the Chain of Responsibility The Client in need of a request to be handled sends it to the chain of handlers which are classes that extend the Handler class. Each of the handlers in the chain takes its turn trying to handle the request it receives from the client. If ConcreteHandler1 can handle it, then the request is handled, if not it is sent to the handler ConcreteHandler2, the next one in the chain.Let’s see an Example of Chain of Responsibility Design Pattern: Java public class Chain{Processor chain; public Chain(){ buildChain();} private void buildChain(){ chain = new NegativeProcessor(new ZeroProcessor(new PositiveProcessor(null)));} public void process(Number request) { chain.process(request);} } abstract class Processor{ private Processor nextProcessor; public Processor(Processor nextProcessor){ this.nextProcessor = nextProcessor; }; public void process(Number request){ if(nextProcessor != null) nextProcessor.process(request); };} class Number{ private int number; public Number(int number) { this.number = number; } public int getNumber() { return number; } } class NegativeProcessor extends Processor{ public NegativeProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() < 0) { System.out.println("NegativeProcessor : " + request.getNumber()); } else { super.process(request); } }} class ZeroProcessor extends Processor{ public ZeroProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() == 0) { System.out.println("ZeroProcessor : " + request.getNumber()); } else { super.process(request); } }} class PositiveProcessor extends Processor{ public PositiveProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() > 0) { System.out.println("PositiveProcessor : " + request.getNumber()); } else { super.process(request); } }} class TestChain{ public static void main(String[] args) { Chain chain = new Chain(); //Calling chain of responsibility chain.process(new Number(90)); chain.process(new Number(-50)); chain.process(new Number(0)); chain.process(new Number(91)); }} PositiveProcessor : 90 NegativeProcessor : -50 ZeroProcessor : 0 PositiveProcessor : 91 Advantages of Chain of Responsibility Design Pattern To reduce the coupling degree. Decoupling it will request the sender and receiver. Simplified object. The object does not need to know the chain structure. Enhance flexibility of object assigned duties. By changing the members within the chain or change their order, allow dynamic adding or deleting responsibility. Increase the request processing new class of very convenient. DisAdvantages of Chain of Responsibility Design Pattern The request must be received not guarantee. The performance of the system will be affected, but also in the code debugging is not easy may cause cycle call. It may not be easy to observe the characteristics of operation, due to debug. Further Read: Chain of Responsibility Design Pattern in Python This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai Rahul 2 gabaa406 sureshsanjeevi Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation Factory method design pattern in Java Builder Design Pattern MVC Design Pattern Unified Modeling Language (UML) | An Introduction Unified Modeling Language (UML) | Activity Diagrams Unified Modeling Language (UML) | State Diagrams Introduction of Programming Paradigms Observer Pattern | Set 1 (Introduction) Abstract Factory Pattern
[ { "code": null, "e": 24960, "s": 24932, "text": "\n24 Feb, 2022" }, { "code": null, "e": 25366, "s": 24960, "text": "Chain of responsibility pattern is used to achieve loose coupling in software design where a request from the client is passed to a chain of objects to process them. Later, the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.Where and When Chain of Responsibility pattern is applicable : " }, { "code": null, "e": 25424, "s": 25366, "text": "When you want to decouple a request’s sender and receiver" }, { "code": null, "e": 25500, "s": 25424, "text": "Multiple objects, determined at runtime, are candidates to handle a request" }, { "code": null, "e": 25564, "s": 25500, "text": "When you don’t want to specify handlers explicitly in your code" }, { "code": null, "e": 25667, "s": 25564, "text": "When you want to issue a request to one of several objects without specifying the receiver explicitly." }, { "code": null, "e": 25919, "s": 25667, "text": "This pattern is recommended when multiple objects can handle a request and the handler doesn’t have to be a specific object. Also, the handler is determined at runtime. Please note that a request not handled at all by any handler is a valid use case. " }, { "code": null, "e": 26163, "s": 25921, "text": "Handler : This can be an interface which will primarily receive the request and dispatches the request to a chain of handlers. It has reference to the only first handler in the chain and does not know anything about the rest of the handlers." }, { "code": null, "e": 26258, "s": 26163, "text": "Concrete handlers : These are actual handlers of the request chained in some sequential order." }, { "code": null, "e": 26336, "s": 26258, "text": "Client : Originator of request and this will access the handler to handle it." }, { "code": null, "e": 26413, "s": 26338, "text": "How to send a request in the application using the Chain of Responsibility" }, { "code": null, "e": 26855, "s": 26413, "text": "The Client in need of a request to be handled sends it to the chain of handlers which are classes that extend the Handler class. Each of the handlers in the chain takes its turn trying to handle the request it receives from the client. If ConcreteHandler1 can handle it, then the request is handled, if not it is sent to the handler ConcreteHandler2, the next one in the chain.Let’s see an Example of Chain of Responsibility Design Pattern: " }, { "code": null, "e": 26860, "s": 26855, "text": "Java" }, { "code": "public class Chain{Processor chain; public Chain(){ buildChain();} private void buildChain(){ chain = new NegativeProcessor(new ZeroProcessor(new PositiveProcessor(null)));} public void process(Number request) { chain.process(request);} } abstract class Processor{ private Processor nextProcessor; public Processor(Processor nextProcessor){ this.nextProcessor = nextProcessor; }; public void process(Number request){ if(nextProcessor != null) nextProcessor.process(request); };} class Number{ private int number; public Number(int number) { this.number = number; } public int getNumber() { return number; } } class NegativeProcessor extends Processor{ public NegativeProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() < 0) { System.out.println(\"NegativeProcessor : \" + request.getNumber()); } else { super.process(request); } }} class ZeroProcessor extends Processor{ public ZeroProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() == 0) { System.out.println(\"ZeroProcessor : \" + request.getNumber()); } else { super.process(request); } }} class PositiveProcessor extends Processor{ public PositiveProcessor(Processor nextProcessor){ super(nextProcessor); } public void process(Number request) { if (request.getNumber() > 0) { System.out.println(\"PositiveProcessor : \" + request.getNumber()); } else { super.process(request); } }} class TestChain{ public static void main(String[] args) { Chain chain = new Chain(); //Calling chain of responsibility chain.process(new Number(90)); chain.process(new Number(-50)); chain.process(new Number(0)); chain.process(new Number(91)); }}", "e": 28997, "s": 26860, "text": null }, { "code": null, "e": 29085, "s": 28997, "text": "PositiveProcessor : 90\nNegativeProcessor : -50\nZeroProcessor : 0\nPositiveProcessor : 91" }, { "code": null, "e": 29142, "s": 29087, "text": "Advantages of Chain of Responsibility Design Pattern " }, { "code": null, "e": 29225, "s": 29142, "text": "To reduce the coupling degree. Decoupling it will request the sender and receiver." }, { "code": null, "e": 29298, "s": 29225, "text": "Simplified object. The object does not need to know the chain structure." }, { "code": null, "e": 29458, "s": 29298, "text": "Enhance flexibility of object assigned duties. By changing the members within the chain or change their order, allow dynamic adding or deleting responsibility." }, { "code": null, "e": 29520, "s": 29458, "text": "Increase the request processing new class of very convenient." }, { "code": null, "e": 29577, "s": 29520, "text": "DisAdvantages of Chain of Responsibility Design Pattern " }, { "code": null, "e": 29621, "s": 29577, "text": "The request must be received not guarantee." }, { "code": null, "e": 29734, "s": 29621, "text": "The performance of the system will be affected, but also in the code debugging is not easy may cause cycle call." }, { "code": null, "e": 29812, "s": 29734, "text": "It may not be easy to observe the characteristics of operation, due to debug." }, { "code": null, "e": 29876, "s": 29812, "text": "Further Read: Chain of Responsibility Design Pattern in Python " }, { "code": null, "e": 30296, "s": 29876, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30311, "s": 30298, "text": "Akanksha_Rai" }, { "code": null, "e": 30319, "s": 30311, "text": "Rahul 2" }, { "code": null, "e": 30328, "s": 30319, "text": "gabaa406" }, { "code": null, "e": 30343, "s": 30328, "text": "sureshsanjeevi" }, { "code": null, "e": 30358, "s": 30343, "text": "Design Pattern" }, { "code": null, "e": 30456, "s": 30358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30505, "s": 30456, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30543, "s": 30505, "text": "Factory method design pattern in Java" }, { "code": null, "e": 30566, "s": 30543, "text": "Builder Design Pattern" }, { "code": null, "e": 30585, "s": 30566, "text": "MVC Design Pattern" }, { "code": null, "e": 30635, "s": 30585, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 30687, "s": 30635, "text": "Unified Modeling Language (UML) | Activity Diagrams" }, { "code": null, "e": 30736, "s": 30687, "text": "Unified Modeling Language (UML) | State Diagrams" }, { "code": null, "e": 30774, "s": 30736, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 30814, "s": 30774, "text": "Observer Pattern | Set 1 (Introduction)" } ]
exp() function C++
The C / C++ library function double exp(double x) returns the value of e raised to the xth power. Following is the declaration for exp() function. double exp(double x) The parameter is a floating point value. And this function returns the exponential value of x. Live Demo #include <iostream> #include <cmath> using namespace std; int main () { double x = 0; cout << "The exponential value of " << x << " is " << exp(x) << endl; cout << "The exponential value of " << x+1 << " is " << exp(x+1) << endl; cout << "The exponential value of " << x+2 << " is " << exp(x+2) << endl; return(0); } The exponential value of 0 is 1 The exponential value of 1 is 2.71828 The exponential value of 2 is 7.38906
[ { "code": null, "e": 1209, "s": 1062, "text": "The C / C++ library function double exp(double x) returns the value of e raised to the\nxth power. Following is the declaration for exp() function." }, { "code": null, "e": 1230, "s": 1209, "text": "double exp(double x)" }, { "code": null, "e": 1325, "s": 1230, "text": "The parameter is a floating point value. And this function returns the exponential\nvalue of x." }, { "code": null, "e": 1336, "s": 1325, "text": " Live Demo" }, { "code": null, "e": 1677, "s": 1336, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main () {\n double x = 0;\n cout << \"The exponential value of \" << x << \" is \" << exp(x) << endl;\n cout << \"The exponential value of \" << x+1 << \" is \" << exp(x+1) <<\n endl;\n cout << \"The exponential value of \" << x+2 << \" is \" << exp(x+2) <<\n endl;\n return(0);\n}" }, { "code": null, "e": 1785, "s": 1677, "text": "The exponential value of 0 is 1\nThe exponential value of 1 is 2.71828\nThe exponential value of 2 is 7.38906" } ]
LISP - Sequences
Sequence is an abstract data type in LISP. Vectors and lists are the two concrete subtypes of this data type. All the functionalities defined on sequence data type are actually applied on all vectors and list types. In this section, we will discuss most commonly used functions on sequences. Before starting on various ways of manipulating sequences (i.e., vectors and lists), let us have a look at the list of all available functions. The function make-sequence allows you to create a sequence of any type. The syntax for this function is − make-sequence sqtype sqsize &key :initial-element It creates a sequence of type sqtype and of length sqsize. You may optionally specify some value using the :initial-element argument, then each of the elements will be initialized to this value. For example, Create a new source code file named main.lisp and type the following code in it. (write (make-sequence '(vector float) 10 :initial-element 1.0)) When you execute the code, it returns the following result − #(1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0) elt It allows access to individual elements through an integer index. length It returns the length of a sequence. subseq It returns a sub-sequence by extracting the subsequence starting at a particular index and continuing to a particular ending index or the end of the sequence. copy-seq It returns a sequence that contains the same elements as its argument. fill It is used to set multiple elements of a sequence to a single value. replace It takes two sequences and the first argument sequence is destructively modified by copying successive elements into it from the second argument sequence. count It takes an item and a sequence and returns the number of times the item appears in the sequence. reverse It returns a sequence contains the same elements of the argument but in reverse order. nreverse It returns the same sequence containing the same elements as sequence but in reverse order. concatenate It creates a new sequence containing the concatenation of any number of sequences. position It takes an item and a sequence and returns the index of the item in the sequence or nil. find It takes an item and a sequence. It finds the item in the sequence and returns it, if not found then it returns nil. sort It takes a sequence and a two-argument predicate and returns a sorted version of the sequence. merge It takes two sequences and a predicate and returns a sequence produced by merging the two sequences, according to the predicate. map It takes an n-argument function and n sequences and returns a new sequence containing the result of applying the function to subsequent elements of the sequences. some It takes a predicate as an argument and iterates over the argument sequence, and returns the first non-NIL value returned by the predicate or returns false if the predicate is never satisfied. every It takes a predicate as an argument and iterate over the argument sequence, it terminates, returning false, as soon as the predicate fails. If the predicate is always satisfied, it returns true. notany It takes a predicate as an argument and iterate over the argument sequence, and returns false as soon as the predicate is satisfied or true if it never is. notevery It takes a predicate as an argument and iterate over the argument sequence, and returns true as soon as the predicate fails or false if the predicate is always satisfied. reduce It maps over a single sequence, applying a two-argument function first to the first two elements of the sequence and then to the value returned by the function and subsequent elements of the sequence. search It searches a sequence to locate one or more elements satisfying some test. remove It takes an item and a sequence and returns the sequence with instances of item removed. delete This also takes an item and a sequence and returns a sequence of the same kind as the argument sequence that has the same elements except the item. substitute It takes a new item, an existing item, and a sequence and returns a sequence with instances of the existing item replaced with the new item. nsubstitute It takes a new item, an existing item, and a sequence and returns the same sequence with instances of the existing item replaced with the new item. mismatch It takes two sequences and returns the index of the first pair of mismatched elements. We have just discussed various functions and keywords that are used as arguments in these functions working on sequences. In the next sections, we will see how to use these functions using examples. The length function returns the length of a sequence, and the elt function allows you to access individual elements using an integer index. Create a new source code file named main.lisp and type the following code in it. (setq x (vector 'a 'b 'c 'd 'e)) (write (length x)) (terpri) (write (elt x 3)) When you execute the code, it returns the following result − 5 D Some sequence functions allows iterating through the sequence and perform some operations like, searching, removing, counting or filtering specific elements without writing explicit loops. The following example demonstrates this − Create a new source code file named main.lisp and type the following code in it. (write (count 7 '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (remove 5 '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (delete 5 '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (substitute 10 7 '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (find 7 '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (position 5 '(1 5 6 7 8 9 2 7 3 4 5))) When you execute the code, it returns the following result − 2 (1 6 7 8 9 2 7 3 4) (1 6 7 8 9 2 7 3 4) (1 5 6 10 8 9 2 10 3 4 5) 7 1 Create a new source code file named main.lisp and type the following code in it. (write (delete-if #'oddp '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (delete-if #'evenp '(1 5 6 7 8 9 2 7 3 4 5))) (terpri) (write (remove-if #'evenp '(1 5 6 7 8 9 2 7 3 4 5) :count 1 :from-end t)) (terpri) (setq x (vector 'a 'b 'c 'd 'e 'f 'g)) (fill x 'p :start 1 :end 4) (write x) When you execute the code, it returns the following result − (6 8 2 4) (1 5 7 9 7 3 5) (1 5 6 7 8 9 2 7 3 5) #(A P P P E F G) The sorting functions take a sequence and a two-argument predicate and return a sorted version of the sequence. Create a new source code file named main.lisp and type the following code in it. (write (sort '(2 4 7 3 9 1 5 4 6 3 8) #'<)) (terpri) (write (sort '(2 4 7 3 9 1 5 4 6 3 8) #'>)) (terpri) When you execute the code, it returns the following result − (1 2 3 3 4 4 5 6 7 8 9) (9 8 7 6 5 4 4 3 3 2 1) Create a new source code file named main.lisp and type the following code in it. (write (merge 'vector #(1 3 5) #(2 4 6) #'<)) (terpri) (write (merge 'list #(1 3 5) #(2 4 6) #'<)) (terpri) When you execute the code, it returns the following result − #(1 2 3 4 5 6) (1 2 3 4 5 6) The functions every, some, notany, and notevery are called the sequence predicates. These functions iterate over sequences and test the Boolean predicate. All these functions takes a predicate as the first argument and the remaining arguments are sequences. Create a new source code file named main.lisp and type the following code in it. (write (every #'evenp #(2 4 6 8 10))) (terpri) (write (some #'evenp #(2 4 6 8 10 13 14))) (terpri) (write (every #'evenp #(2 4 6 8 10 13 14))) (terpri) (write (notany #'evenp #(2 4 6 8 10))) (terpri) (write (notevery #'evenp #(2 4 6 8 10 13 14))) (terpri) When you execute the code, it returns the following result − T T NIL NIL T We have already discussed the mapping functions. Similarly the map function allows you to apply a function on to subsequent elements of one or more sequences. The map function takes a n-argument function and n sequences and returns a new sequence after applying the function to subsequent elements of the sequences. Create a new source code file named main.lisp and type the following code in it. (write (map 'vector #'* #(2 3 4 5) #(3 5 4 8))) When you execute the code, it returns the following result − #(6 15 16 40) 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2060, "text": "Sequence is an abstract data type in LISP. Vectors and lists are the two concrete subtypes of this data type. All the functionalities defined on sequence data type are actually applied on all vectors and list types." }, { "code": null, "e": 2352, "s": 2276, "text": "In this section, we will discuss most commonly used functions on sequences." }, { "code": null, "e": 2496, "s": 2352, "text": "Before starting on various ways of manipulating sequences (i.e., vectors and lists), let us have a look at the list of all available functions." }, { "code": null, "e": 2602, "s": 2496, "text": "The function make-sequence allows you to create a sequence of any type. The syntax for this function is −" }, { "code": null, "e": 2653, "s": 2602, "text": "make-sequence sqtype sqsize &key :initial-element\n" }, { "code": null, "e": 2712, "s": 2653, "text": "It creates a sequence of type sqtype and of length sqsize." }, { "code": null, "e": 2848, "s": 2712, "text": "You may optionally specify some value using the :initial-element argument, then each of the elements will be initialized to this value." }, { "code": null, "e": 2942, "s": 2848, "text": "For example, Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 3014, "s": 2942, "text": "(write (make-sequence '(vector float) \n 10 \n :initial-element 1.0))" }, { "code": null, "e": 3075, "s": 3014, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 3119, "s": 3075, "text": "#(1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0)\n" }, { "code": null, "e": 3123, "s": 3119, "text": "elt" }, { "code": null, "e": 3189, "s": 3123, "text": "It allows access to individual elements through an integer index." }, { "code": null, "e": 3196, "s": 3189, "text": "length" }, { "code": null, "e": 3233, "s": 3196, "text": "It returns the length of a sequence." }, { "code": null, "e": 3240, "s": 3233, "text": "subseq" }, { "code": null, "e": 3399, "s": 3240, "text": "It returns a sub-sequence by extracting the subsequence starting at a particular index and continuing to a particular ending index or the end of the sequence." }, { "code": null, "e": 3408, "s": 3399, "text": "copy-seq" }, { "code": null, "e": 3479, "s": 3408, "text": "It returns a sequence that contains the same elements as its argument." }, { "code": null, "e": 3484, "s": 3479, "text": "fill" }, { "code": null, "e": 3553, "s": 3484, "text": "It is used to set multiple elements of a sequence to a single value." }, { "code": null, "e": 3561, "s": 3553, "text": "replace" }, { "code": null, "e": 3716, "s": 3561, "text": "It takes two sequences and the first argument sequence is destructively modified by copying successive elements into it from the second argument sequence." }, { "code": null, "e": 3722, "s": 3716, "text": "count" }, { "code": null, "e": 3820, "s": 3722, "text": "It takes an item and a sequence and returns the number of times the item appears in the sequence." }, { "code": null, "e": 3828, "s": 3820, "text": "reverse" }, { "code": null, "e": 3915, "s": 3828, "text": "It returns a sequence contains the same elements of the argument but in reverse order." }, { "code": null, "e": 3924, "s": 3915, "text": "nreverse" }, { "code": null, "e": 4016, "s": 3924, "text": "It returns the same sequence containing the same elements as sequence but in reverse order." }, { "code": null, "e": 4028, "s": 4016, "text": "concatenate" }, { "code": null, "e": 4111, "s": 4028, "text": "It creates a new sequence containing the concatenation of any number of sequences." }, { "code": null, "e": 4120, "s": 4111, "text": "position" }, { "code": null, "e": 4210, "s": 4120, "text": "It takes an item and a sequence and returns the index of the item in the sequence or nil." }, { "code": null, "e": 4215, "s": 4210, "text": "find" }, { "code": null, "e": 4332, "s": 4215, "text": "It takes an item and a sequence. It finds the item in the sequence and returns it, if not found then it returns nil." }, { "code": null, "e": 4337, "s": 4332, "text": "sort" }, { "code": null, "e": 4432, "s": 4337, "text": "It takes a sequence and a two-argument predicate and returns a sorted version of the sequence." }, { "code": null, "e": 4438, "s": 4432, "text": "merge" }, { "code": null, "e": 4567, "s": 4438, "text": "It takes two sequences and a predicate and returns a sequence produced by merging the two sequences, according to the predicate." }, { "code": null, "e": 4571, "s": 4567, "text": "map" }, { "code": null, "e": 4734, "s": 4571, "text": "It takes an n-argument function and n sequences and returns a new sequence containing the result of applying the function to subsequent elements of the sequences." }, { "code": null, "e": 4739, "s": 4734, "text": "some" }, { "code": null, "e": 4932, "s": 4739, "text": "It takes a predicate as an argument and iterates over the argument sequence, and returns the first non-NIL value returned by the predicate or returns false if the predicate is never satisfied." }, { "code": null, "e": 4938, "s": 4932, "text": "every" }, { "code": null, "e": 5133, "s": 4938, "text": "It takes a predicate as an argument and iterate over the argument sequence, it terminates, returning false, as soon as the predicate fails. If the predicate is always satisfied, it returns true." }, { "code": null, "e": 5140, "s": 5133, "text": "notany" }, { "code": null, "e": 5296, "s": 5140, "text": "It takes a predicate as an argument and iterate over the argument sequence, and returns false as soon as the predicate is satisfied or true if it never is." }, { "code": null, "e": 5305, "s": 5296, "text": "notevery" }, { "code": null, "e": 5476, "s": 5305, "text": "It takes a predicate as an argument and iterate over the argument sequence, and returns true as soon as the predicate fails or false if the predicate is always satisfied." }, { "code": null, "e": 5483, "s": 5476, "text": "reduce" }, { "code": null, "e": 5684, "s": 5483, "text": "It maps over a single sequence, applying a two-argument function first to the first two elements of the sequence and then to the value returned by the function and subsequent elements of the sequence." }, { "code": null, "e": 5691, "s": 5684, "text": "search" }, { "code": null, "e": 5767, "s": 5691, "text": "It searches a sequence to locate one or more elements satisfying some test." }, { "code": null, "e": 5774, "s": 5767, "text": "remove" }, { "code": null, "e": 5863, "s": 5774, "text": "It takes an item and a sequence and returns the sequence with instances of item removed." }, { "code": null, "e": 5870, "s": 5863, "text": "delete" }, { "code": null, "e": 6018, "s": 5870, "text": "This also takes an item and a sequence and returns a sequence of the same kind as the argument sequence that has the same elements except the item." }, { "code": null, "e": 6029, "s": 6018, "text": "substitute" }, { "code": null, "e": 6170, "s": 6029, "text": "It takes a new item, an existing item, and a sequence and returns a sequence with instances of the existing item replaced with the new item." }, { "code": null, "e": 6182, "s": 6170, "text": "nsubstitute" }, { "code": null, "e": 6330, "s": 6182, "text": "It takes a new item, an existing item, and a sequence and returns the same sequence with instances of the existing item replaced with the new item." }, { "code": null, "e": 6339, "s": 6330, "text": "mismatch" }, { "code": null, "e": 6426, "s": 6339, "text": "It takes two sequences and returns the index of the first pair of mismatched elements." }, { "code": null, "e": 6625, "s": 6426, "text": "We have just discussed various functions and keywords that are used as arguments in these functions working on sequences. In the next sections, we will see how to use these functions using examples." }, { "code": null, "e": 6765, "s": 6625, "text": "The length function returns the length of a sequence, and the elt function allows you to access individual elements using an integer index." }, { "code": null, "e": 6846, "s": 6765, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 6925, "s": 6846, "text": "(setq x (vector 'a 'b 'c 'd 'e))\n(write (length x))\n(terpri)\n(write (elt x 3))" }, { "code": null, "e": 6986, "s": 6925, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 6991, "s": 6986, "text": "5\nD\n" }, { "code": null, "e": 7180, "s": 6991, "text": "Some sequence functions allows iterating through the sequence and perform some operations like, searching, removing, counting or filtering specific elements without writing explicit loops." }, { "code": null, "e": 7222, "s": 7180, "text": "The following example demonstrates this −" }, { "code": null, "e": 7303, "s": 7222, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 7618, "s": 7303, "text": "(write (count 7 '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (remove 5 '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (delete 5 '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (substitute 10 7 '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (find 7 '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (position 5 '(1 5 6 7 8 9 2 7 3 4 5)))" }, { "code": null, "e": 7679, "s": 7618, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 7752, "s": 7679, "text": "2\n(1 6 7 8 9 2 7 3 4)\n(1 6 7 8 9 2 7 3 4)\n(1 5 6 10 8 9 2 10 3 4 5)\n7\n1\n" }, { "code": null, "e": 7833, "s": 7752, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 8116, "s": 7833, "text": "(write (delete-if #'oddp '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (delete-if #'evenp '(1 5 6 7 8 9 2 7 3 4 5)))\n(terpri)\n(write (remove-if #'evenp '(1 5 6 7 8 9 2 7 3 4 5) :count 1 :from-end t))\n(terpri)\n(setq x (vector 'a 'b 'c 'd 'e 'f 'g))\n(fill x 'p :start 1 :end 4)\n(write x)" }, { "code": null, "e": 8177, "s": 8116, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 8243, "s": 8177, "text": "(6 8 2 4)\n(1 5 7 9 7 3 5)\n(1 5 6 7 8 9 2 7 3 5)\n#(A P P P E F G)\n" }, { "code": null, "e": 8355, "s": 8243, "text": "The sorting functions take a sequence and a two-argument predicate and return a sorted version of the sequence." }, { "code": null, "e": 8436, "s": 8355, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 8542, "s": 8436, "text": "(write (sort '(2 4 7 3 9 1 5 4 6 3 8) #'<))\n(terpri)\n(write (sort '(2 4 7 3 9 1 5 4 6 3 8) #'>))\n(terpri)" }, { "code": null, "e": 8603, "s": 8542, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 8652, "s": 8603, "text": "(1 2 3 3 4 4 5 6 7 8 9)\n(9 8 7 6 5 4 4 3 3 2 1)\n" }, { "code": null, "e": 8733, "s": 8652, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 8841, "s": 8733, "text": "(write (merge 'vector #(1 3 5) #(2 4 6) #'<))\n(terpri)\n(write (merge 'list #(1 3 5) #(2 4 6) #'<))\n(terpri)" }, { "code": null, "e": 8902, "s": 8841, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 8932, "s": 8902, "text": "#(1 2 3 4 5 6)\n(1 2 3 4 5 6)\n" }, { "code": null, "e": 9016, "s": 8932, "text": "The functions every, some, notany, and notevery are called the sequence predicates." }, { "code": null, "e": 9087, "s": 9016, "text": "These functions iterate over sequences and test the Boolean predicate." }, { "code": null, "e": 9190, "s": 9087, "text": "All these functions takes a predicate as the first argument and the remaining arguments are sequences." }, { "code": null, "e": 9271, "s": 9190, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 9527, "s": 9271, "text": "(write (every #'evenp #(2 4 6 8 10)))\n(terpri)\n(write (some #'evenp #(2 4 6 8 10 13 14)))\n(terpri)\n(write (every #'evenp #(2 4 6 8 10 13 14)))\n(terpri)\n(write (notany #'evenp #(2 4 6 8 10)))\n(terpri)\n(write (notevery #'evenp #(2 4 6 8 10 13 14)))\n(terpri)" }, { "code": null, "e": 9588, "s": 9527, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 9603, "s": 9588, "text": "T\nT\nNIL\nNIL\nT\n" }, { "code": null, "e": 9762, "s": 9603, "text": "We have already discussed the mapping functions. Similarly the map function allows you to apply a function on to subsequent elements of one or more sequences." }, { "code": null, "e": 9919, "s": 9762, "text": "The map function takes a n-argument function and n sequences and returns a new sequence after applying the function to subsequent elements of the sequences." }, { "code": null, "e": 10000, "s": 9919, "text": "Create a new source code file named main.lisp and type the following code in it." }, { "code": null, "e": 10048, "s": 10000, "text": "(write (map 'vector #'* #(2 3 4 5) #(3 5 4 8)))" }, { "code": null, "e": 10109, "s": 10048, "text": "When you execute the code, it returns the following result −" }, { "code": null, "e": 10124, "s": 10109, "text": "#(6 15 16 40)\n" }, { "code": null, "e": 10157, "s": 10124, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 10172, "s": 10157, "text": " Arnold Higuit" }, { "code": null, "e": 10179, "s": 10172, "text": " Print" }, { "code": null, "e": 10190, "s": 10179, "text": " Add Notes" } ]
MomentJS - Subtract
Just like the add method, subtract allows to subtract days, months, hours, minutes, seconds etc., from a given date. moment().subtract(Number, String); moment().subtract(Duration); moment().subtract(Object); Observe the following example that shows how to use the subtract method − <html> <head> <title>MomentJS - Subtract Method</title> <script type="text/JavaScript" src="https://MomentJS.com/downloads/moment.js"></script> <style> div { border: solid 1px #ccc; padding:10px; font-family: "Segoe UI",Arial,sans-serif; width: 75%; } </style> </head> <body> <h1>MomentJS - Subtract Method</h1> <div style="font-size:25px" id="currentdate"></div> <br/> <br/> <div style="font-size:25px" id="changeddate"></div> <br/> <br/> <div style="font-size:25px" id="changeddate1"></div> <br/> <br/> <div style="font-size:25px" id="changeddate2"v</div> <script type="text/JavaScript"> var day = moment(); document.getElementById("currentdate").innerHTML = "Current Date: " + day._d; var changeddate = moment().subtract(5, 'days').subtract(2, 'months'); document.getElementById("changeddate").innerHTML = "Subtracting 5 days and 2 month using chaining method: " + changeddate._d; var changeddate1 = moment().subtract({ days: 5, months: 2 }); document.getElementById("changeddate1").innerHTML = "Subtracting 5 days and 2 month using object method: " + changeddate1._d; var duration = moment.duration({ 'days': 10 }); var changeddate2 = moment([2017, 10, 15]).subtract(duration); document.getElementById("changeddate2").innerHTML = "Subtracting 10 days from given date using duration method: " + changeddate2._d; </script> </body> </html> To subtract days, months from the date we have done following − //chaining subtract method var changeddate = moment().subtract(5, 'days').subtract(2, 'months'); // subtract object method var changeddate1 = moment().subtract({ days: 5, months: 2 }); //using duration in subract method var duration = moment.duration({ 'days': 10 }); var changeddate2 = moment([2017, 10, 15]).subtract(duration); The output for the same in shown in the above example. Print Add Notes Bookmark this page
[ { "code": null, "e": 2077, "s": 1960, "text": "Just like the add method, subtract allows to subtract days, months, hours, minutes, seconds etc., from a given date." }, { "code": null, "e": 2169, "s": 2077, "text": "moment().subtract(Number, String);\nmoment().subtract(Duration);\nmoment().subtract(Object);\n" }, { "code": null, "e": 2243, "s": 2169, "text": "Observe the following example that shows how to use the subtract method −" }, { "code": null, "e": 3848, "s": 2243, "text": "<html>\n <head>\n <title>MomentJS - Subtract Method</title>\n <script type=\"text/JavaScript\" src=\"https://MomentJS.com/downloads/moment.js\"></script>\n <style>\n div {\n border: solid 1px #ccc;\n padding:10px;\n font-family: \"Segoe UI\",Arial,sans-serif;\n width: 75%;\n }\n </style>\n </head>\n <body>\n <h1>MomentJS - Subtract Method</h1>\n <div style=\"font-size:25px\" id=\"currentdate\"></div>\n <br/>\n <br/>\n <div style=\"font-size:25px\" id=\"changeddate\"></div>\n <br/>\n <br/>\n <div style=\"font-size:25px\" id=\"changeddate1\"></div>\n <br/>\n <br/>\n <div style=\"font-size:25px\" id=\"changeddate2\"v</div>\n <script type=\"text/JavaScript\">\n var day = moment();\n document.getElementById(\"currentdate\").innerHTML = \"Current Date: \" + day._d;\n var changeddate = moment().subtract(5, 'days').subtract(2, 'months');\n document.getElementById(\"changeddate\").innerHTML = \"Subtracting 5 days and 2 month using chaining method: \" + changeddate._d;\n var changeddate1 = moment().subtract({ days: 5, months: 2 });\n document.getElementById(\"changeddate1\").innerHTML = \"Subtracting 5 days and 2 month using object method: \" + changeddate1._d;\n var duration = moment.duration({ 'days': 10 });\n var changeddate2 = moment([2017, 10, 15]).subtract(duration);\n document.getElementById(\"changeddate2\").innerHTML = \"Subtracting 10 days from given date using duration method: \" + changeddate2._d;\n </script>\n </body>\n</html>" }, { "code": null, "e": 3912, "s": 3848, "text": "To subtract days, months from the date we have done following −" }, { "code": null, "e": 4244, "s": 3912, "text": "//chaining subtract method\nvar changeddate = moment().subtract(5, 'days').subtract(2, 'months');\n\n// subtract object method\nvar changeddate1 = moment().subtract({ days: 5, months: 2 });\n\n//using duration in subract method\nvar duration = moment.duration({ 'days': 10 });\nvar changeddate2 = moment([2017, 10, 15]).subtract(duration);" }, { "code": null, "e": 4299, "s": 4244, "text": "The output for the same in shown in the above example." }, { "code": null, "e": 4306, "s": 4299, "text": " Print" }, { "code": null, "e": 4317, "s": 4306, "text": " Add Notes" } ]
View Recycling in Android with ListView - GeeksforGeeks
18 Feb, 2021 Memory management is a crucial aspect of app development. Since mobile devices have very limited memory, it is necessary to use it carefully in our applications. One of the best practices involved in doing so is “view recycling“. This article is about view recycling in Android and then a simple app is created which implements the practice of view recycling using ListView and ArrayAdapter in conjunction. Need for View Recycling in AndroidIt is a practice to use as little memory as possible by recycling unused views to display new content instead of creating new views for the same. Suppose, we are scrolling down through a list of one thousand words. If we create a TextView for each word, we would need one thousand TextViews for this. This would waste a lot of memory since our device’s screen displays only 7-8 TextViews at a time and we need to scroll down if we want to see the rest of them. When we scroll down, the TextViews which are at the top are not visible anymore. So, an inference can be taken that the top TextViews are not used by the user when they scroll down the ListView. Hence, unused TextViews are recycled and are used at the bottom when the user scrolls down. This way, instead of having one thousand TextViews, our task can be achieved with a few of them only. Example for View Recycling in AndroidOne of the most common example is our mobile’s phone-book. We can have many contacts on our phone but instead of creating a new TextViews for each contact, our phone just recycles the unused scrolled up/down views and fills them with the new contact information and displays it again when the user scrolls up/down. Implementation of View Recycling using ArrayAdapter and Listview ArrayAdapter is a Java public class which extends from BaseAdapter class. An ArrayAdapter object makes the data (which is to be displayed) adapt to an array. Basically adapter is a bridge between UI component and data that helps to fill data in the UI component. ListView is a Java public class which extends from AbsListView. ListView is a view which groups several items and displays them in a vertical list. This list is also automatically made scrollable if the amount of data supplied cannot be accommodated on the screen. ArrayAdapter and ListView are required for view recycling. ListView asks for views from ArrayAdpapter by sending it a request and a specified position. ArrayAdpapter then returns the view at the specified position as the ListView keeps on asking for it until the device’s screen is filled. Now, when the user scrolls down, ListView gives ArrayAdpapter the top views which aren’t displayed on the device’s screen anymore. The ArrayAdpapter then erases the previous data of that ScrapView and sets new data and returns it to the ListView instead of creating a new view! Below is a simple app to demonstrate this practice of memory management. Step 1: Add the below code in activity_main.xml file which would just contain a ListView and a TextView.activity_main.xmlactivity_main.xml<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#66bb6a" android:padding="8dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stuff you can learn at GeeksforGeeks:" android:background="#a5d6a7" android:textSize="22sp" android:fontFamily="sans-serif-condensed-light" android:textColor="#fafafa"/> <ListView android:id="@+id/list" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"/></LinearLayout>Output: activity_main.xml <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="#66bb6a" android:padding="8dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stuff you can learn at GeeksforGeeks:" android:background="#a5d6a7" android:textSize="22sp" android:fontFamily="sans-serif-condensed-light" android:textColor="#fafafa"/> <ListView android:id="@+id/list" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"/></LinearLayout> Output: Step 2: In the below code, when we initialize the ArrayAdapter, we pass a layout called android.R.layout.simple_list_item_1 along with our ArrayList and Context. The android.R.layout.simple_list_item_1 is a inbuilt layout that describes the design in which a single list item will be shown. It conventionally consists of just a single TextViewOnce the ListView and ArrayAdapter are initialized, set the ArrayAdapter on the ListView using the setAdapter() method.MainActivity.javaMainActivity.javapackage com.example.gfgrecycleview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class .getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a list of study fields. ArrayList<String> stuff = new ArrayList<>(); stuff.add("Data Structures"); stuff.add("Algorithms"); stuff.add("Competitive Programming"); stuff.add("Interview Questions"); stuff.add("Python"); stuff.add("Java"); stuff.add("Designing"); stuff.add("Coding"); stuff.add("Developing"); stuff.add("Project Ideas"); stuff.add("C++"); stuff.add("Basically Everything!"); // Find a reference to the //{@link ListView} in the layout ListView itemListView = (ListView)findViewById(R.id.list); // Create a new {@link ArrayAdapter} // of study fields ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, stuff); // Set the adapter // on the {@link ListView} // so the list can be populated /// in the user interface itemListView.setAdapter(adapter); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200608114433/Android-Emulator-Nexus_4_API_23_5556-2020-06-08-11-10-27_Trim.mp400:0000:0000:12Use Up/Down Arrow keys to increase or decrease volume.Want a more fast-paced & competitive environment to learn the fundamentals of Android? Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes arrow_drop_upSave MainActivity.java package com.example.gfgrecycleview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class .getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a list of study fields. ArrayList<String> stuff = new ArrayList<>(); stuff.add("Data Structures"); stuff.add("Algorithms"); stuff.add("Competitive Programming"); stuff.add("Interview Questions"); stuff.add("Python"); stuff.add("Java"); stuff.add("Designing"); stuff.add("Coding"); stuff.add("Developing"); stuff.add("Project Ideas"); stuff.add("C++"); stuff.add("Basically Everything!"); // Find a reference to the //{@link ListView} in the layout ListView itemListView = (ListView)findViewById(R.id.list); // Create a new {@link ArrayAdapter} // of study fields ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, stuff); // Set the adapter // on the {@link ListView} // so the list can be populated /// in the user interface itemListView.setAdapter(adapter); }} Output: android Android-View Android Java Write From Home Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Android Listview in Java with Example How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24749, "s": 24721, "text": "\n18 Feb, 2021" }, { "code": null, "e": 24979, "s": 24749, "text": "Memory management is a crucial aspect of app development. Since mobile devices have very limited memory, it is necessary to use it carefully in our applications. One of the best practices involved in doing so is “view recycling“." }, { "code": null, "e": 25156, "s": 24979, "text": "This article is about view recycling in Android and then a simple app is created which implements the practice of view recycling using ListView and ArrayAdapter in conjunction." }, { "code": null, "e": 25651, "s": 25156, "text": "Need for View Recycling in AndroidIt is a practice to use as little memory as possible by recycling unused views to display new content instead of creating new views for the same. Suppose, we are scrolling down through a list of one thousand words. If we create a TextView for each word, we would need one thousand TextViews for this. This would waste a lot of memory since our device’s screen displays only 7-8 TextViews at a time and we need to scroll down if we want to see the rest of them." }, { "code": null, "e": 26040, "s": 25651, "text": "When we scroll down, the TextViews which are at the top are not visible anymore. So, an inference can be taken that the top TextViews are not used by the user when they scroll down the ListView. Hence, unused TextViews are recycled and are used at the bottom when the user scrolls down. This way, instead of having one thousand TextViews, our task can be achieved with a few of them only." }, { "code": null, "e": 26392, "s": 26040, "text": "Example for View Recycling in AndroidOne of the most common example is our mobile’s phone-book. We can have many contacts on our phone but instead of creating a new TextViews for each contact, our phone just recycles the unused scrolled up/down views and fills them with the new contact information and displays it again when the user scrolls up/down." }, { "code": null, "e": 26457, "s": 26392, "text": "Implementation of View Recycling using ArrayAdapter and Listview" }, { "code": null, "e": 26720, "s": 26457, "text": "ArrayAdapter is a Java public class which extends from BaseAdapter class. An ArrayAdapter object makes the data (which is to be displayed) adapt to an array. Basically adapter is a bridge between UI component and data that helps to fill data in the UI component." }, { "code": null, "e": 26985, "s": 26720, "text": "ListView is a Java public class which extends from AbsListView. ListView is a view which groups several items and displays them in a vertical list. This list is also automatically made scrollable if the amount of data supplied cannot be accommodated on the screen." }, { "code": null, "e": 27553, "s": 26985, "text": "ArrayAdapter and ListView are required for view recycling. ListView asks for views from ArrayAdpapter by sending it a request and a specified position. ArrayAdpapter then returns the view at the specified position as the ListView keeps on asking for it until the device’s screen is filled. Now, when the user scrolls down, ListView gives ArrayAdpapter the top views which aren’t displayed on the device’s screen anymore. The ArrayAdpapter then erases the previous data of that ScrapView and sets new data and returns it to the ListView instead of creating a new view!" }, { "code": null, "e": 27626, "s": 27553, "text": "Below is a simple app to demonstrate this practice of memory management." }, { "code": null, "e": 28524, "s": 27626, "text": "Step 1: Add the below code in activity_main.xml file which would just contain a ListView and a TextView.activity_main.xmlactivity_main.xml<LinearLayout android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:background=\"#66bb6a\" android:padding=\"8dp\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Stuff you can learn at GeeksforGeeks:\" android:background=\"#a5d6a7\" android:textSize=\"22sp\" android:fontFamily=\"sans-serif-condensed-light\" android:textColor=\"#fafafa\"/> <ListView android:id=\"@+id/list\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/></LinearLayout>Output:" }, { "code": null, "e": 28542, "s": 28524, "text": "activity_main.xml" }, { "code": "<LinearLayout android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:background=\"#66bb6a\" android:padding=\"8dp\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Stuff you can learn at GeeksforGeeks:\" android:background=\"#a5d6a7\" android:textSize=\"22sp\" android:fontFamily=\"sans-serif-condensed-light\" android:textColor=\"#fafafa\"/> <ListView android:id=\"@+id/list\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/></LinearLayout>", "e": 29295, "s": 28542, "text": null }, { "code": null, "e": 29303, "s": 29295, "text": "Output:" }, { "code": null, "e": 31856, "s": 29303, "text": "Step 2: In the below code, when we initialize the ArrayAdapter, we pass a layout called android.R.layout.simple_list_item_1 along with our ArrayList and Context. The android.R.layout.simple_list_item_1 is a inbuilt layout that describes the design in which a single list item will be shown. It conventionally consists of just a single TextViewOnce the ListView and ArrayAdapter are initialized, set the ArrayAdapter on the ListView using the setAdapter() method.MainActivity.javaMainActivity.javapackage com.example.gfgrecycleview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class .getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a list of study fields. ArrayList<String> stuff = new ArrayList<>(); stuff.add(\"Data Structures\"); stuff.add(\"Algorithms\"); stuff.add(\"Competitive Programming\"); stuff.add(\"Interview Questions\"); stuff.add(\"Python\"); stuff.add(\"Java\"); stuff.add(\"Designing\"); stuff.add(\"Coding\"); stuff.add(\"Developing\"); stuff.add(\"Project Ideas\"); stuff.add(\"C++\"); stuff.add(\"Basically Everything!\"); // Find a reference to the //{@link ListView} in the layout ListView itemListView = (ListView)findViewById(R.id.list); // Create a new {@link ArrayAdapter} // of study fields ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, stuff); // Set the adapter // on the {@link ListView} // so the list can be populated /// in the user interface itemListView.setAdapter(adapter); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200608114433/Android-Emulator-Nexus_4_API_23_5556-2020-06-08-11-10-27_Trim.mp400:0000:0000:12Use Up/Down Arrow keys to increase or decrease volume.Want a more fast-paced & competitive environment to learn the fundamentals of Android?\nClick here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31874, "s": 31856, "text": "MainActivity.java" }, { "code": "package com.example.gfgrecycleview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final String LOG_TAG = MainActivity.class .getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a list of study fields. ArrayList<String> stuff = new ArrayList<>(); stuff.add(\"Data Structures\"); stuff.add(\"Algorithms\"); stuff.add(\"Competitive Programming\"); stuff.add(\"Interview Questions\"); stuff.add(\"Python\"); stuff.add(\"Java\"); stuff.add(\"Designing\"); stuff.add(\"Coding\"); stuff.add(\"Developing\"); stuff.add(\"Project Ideas\"); stuff.add(\"C++\"); stuff.add(\"Basically Everything!\"); // Find a reference to the //{@link ListView} in the layout ListView itemListView = (ListView)findViewById(R.id.list); // Create a new {@link ArrayAdapter} // of study fields ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, stuff); // Set the adapter // on the {@link ListView} // so the list can be populated /// in the user interface itemListView.setAdapter(adapter); }}", "e": 33477, "s": 31874, "text": null }, { "code": null, "e": 33485, "s": 33477, "text": "Output:" }, { "code": null, "e": 33493, "s": 33485, "text": "android" }, { "code": null, "e": 33506, "s": 33493, "text": "Android-View" }, { "code": null, "e": 33514, "s": 33506, "text": "Android" }, { "code": null, "e": 33519, "s": 33514, "text": "Java" }, { "code": null, "e": 33535, "s": 33519, "text": "Write From Home" }, { "code": null, "e": 33540, "s": 33535, "text": "Java" }, { "code": null, "e": 33548, "s": 33540, "text": "Android" }, { "code": null, "e": 33646, "s": 33548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33655, "s": 33646, "text": "Comments" }, { "code": null, "e": 33668, "s": 33655, "text": "Old Comments" }, { "code": null, "e": 33707, "s": 33668, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33757, "s": 33707, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 33795, "s": 33757, "text": "Android Listview in Java with Example" }, { "code": null, "e": 33846, "s": 33795, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 33888, "s": 33846, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 33903, "s": 33888, "text": "Arrays in Java" }, { "code": null, "e": 33947, "s": 33903, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33969, "s": 33947, "text": "For-each loop in Java" }, { "code": null, "e": 33994, "s": 33969, "text": "Reverse a string in Java" } ]
C | Structure & Union | Question 10 - GeeksforGeeks
28 Jun, 2021 Predict the output of following C program #include<stdio.h>struct Point{ int x, y, z;}; int main(){ struct Point p1 = {.y = 0, .z = 1, .x = 2}; printf("%d %d %d", p1.x, p1.y, p1.z); return 0;} (A) Compiler Error(B) 2 0 1(C) 0 1 2(D) 2 1 0Answer: (B)Explanation: Refer designated Initialization discussed here.Quiz of this Question C-Structure & Union Structure & Union C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Function Pointer in C TCP Server-Client implementation in C Enumeration (or enum) in C Data Types in C Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C Output of C programs | Set 64 (Pointers) C | Structure & Union | Question 10 C | File Handling | Question 1
[ { "code": null, "e": 24362, "s": 24334, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24404, "s": 24362, "text": "Predict the output of following C program" }, { "code": "#include<stdio.h>struct Point{ int x, y, z;}; int main(){ struct Point p1 = {.y = 0, .z = 1, .x = 2}; printf(\"%d %d %d\", p1.x, p1.y, p1.z); return 0;}", "e": 24560, "s": 24404, "text": null }, { "code": null, "e": 24698, "s": 24560, "text": "(A) Compiler Error(B) 2 0 1(C) 0 1 2(D) 2 1 0Answer: (B)Explanation: Refer designated Initialization discussed here.Quiz of this Question" }, { "code": null, "e": 24718, "s": 24698, "text": "C-Structure & Union" }, { "code": null, "e": 24736, "s": 24718, "text": "Structure & Union" }, { "code": null, "e": 24747, "s": 24736, "text": "C Language" }, { "code": null, "e": 24754, "s": 24747, "text": "C Quiz" }, { "code": null, "e": 24852, "s": 24754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24864, "s": 24852, "text": "fork() in C" }, { "code": null, "e": 24886, "s": 24864, "text": "Function Pointer in C" }, { "code": null, "e": 24924, "s": 24886, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 24951, "s": 24924, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 24967, "s": 24951, "text": "Data Types in C" }, { "code": null, "e": 25009, "s": 24967, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25052, "s": 25009, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25093, "s": 25052, "text": "Output of C programs | Set 64 (Pointers)" }, { "code": null, "e": 25129, "s": 25093, "text": "C | Structure & Union | Question 10" } ]
ExpressJS - Templating
Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this. To use Pug with Express, we need to install it, npm install --save pug Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file. app.set('view engine', 'pug'); app.set('views','./views'); Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it. doctype html html head title = "Hello Pug" body p.greetings#people Hello World! To run this page, add the following route to your app − app.get('/first_template', function(req, res){ res.render('first_view'); }); You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to − <!DOCTYPE html> <html> <head> <title>Hello Pug</title> </head> <body> <p class = "greetings" id = "people">Hello World!</p> </body> </html> Pug is capable of doing much more than simplifying HTML markup. Let us now explore a few important features of Pug. Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag. We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us. To put text inside of a tag, we have 3 methods − Space seperated Space seperated h1 Welcome to Pug Piped text Piped text div | To insert multiline text, | You can use the pipe operator. Block of text Block of text div. But that gets tedious if you have a lot of text. You can use "." at the end of tag to denote block of text. To put tags inside this block, simply enter tag in a new line and indent it accordingly. Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example, //This is a Pug comment This comment gets converted to the following. <!--This is a Pug comment--> To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag. div.container.column.main#division(width = "100", height = "100") This line of code, gets converted to the following. − <div class = "container column main" id = "division" width = "100" height = "100"></div> When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following. var express = require('express'); var app = express(); app.get('/dynamic_view', function(req, res){ res.render('dynamic', { name: "TutorialsPoint", url:"http://www.tutorialspoint.com" }); }); app.listen(3000); And create a new view file in views directory, called dynamic.pug, with the following code − html head title=name body h1=name a(href = url) URL Open localhost:3000/dynamic_view in your browser; You should get the following output − We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following. html head title = name body h1 Greetings from #{name} a(href = url) URL This method of using values is called interpolation. The above code will display the following output. − We can use conditional statements and looping constructs as well. Consider the following − If a User is logged in, the page should display "Hi, User" and if not, then the "Login/Sign Up" link. To achieve this, we can define a simple template like − html head title Simple template body if(user) h1 Hi, #{user.name} else a(href = "/sign_up") Sign Up When we render this using our routes, we can pass an object as in the following program − res.render('/dynamic',{ user: {name: "Ayush", age: "20"} }); You will receive a message − Hi, Ayush. But if we don’t pass any object or pass one with no user key, then we will get a signup link. Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view we create, we can use the include feature. Following example shows how we can use this feature − Create 3 views with the following code − HEADER.PUG div.header. I'm the header for this website. CONTENT.PUG html head title Simple template body include ./header.pug h3 I'm the main content include ./footer.pug FOOTER.PUG div.footer. I'm the footer for this website. Create a route for this as follows − var express = require('express'); var app = express(); app.get('/components', function(req, res){ res.render('content'); }); app.listen(3000); Go to localhost:3000/components, you will receive the following output − include can also be used to include plaintext, css and JavaScript. There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug. 16 Lectures 1 hours Anadi Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2061, "text": "Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this." }, { "code": null, "e": 2467, "s": 2419, "text": "To use Pug with Express, we need to install it," }, { "code": null, "e": 2491, "s": 2467, "text": "npm install --save pug\n" }, { "code": null, "e": 2642, "s": 2491, "text": "Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file." }, { "code": null, "e": 2701, "s": 2642, "text": "app.set('view engine', 'pug');\napp.set('views','./views');" }, { "code": null, "e": 2827, "s": 2701, "text": "Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it." }, { "code": null, "e": 2925, "s": 2827, "text": "doctype html\nhtml\n head\n title = \"Hello Pug\"\n body\n p.greetings#people Hello World!" }, { "code": null, "e": 2981, "s": 2925, "text": "To run this page, add the following route to your app −" }, { "code": null, "e": 3061, "s": 2981, "text": "app.get('/first_template', function(req, res){\n res.render('first_view');\n});" }, { "code": null, "e": 3324, "s": 3061, "text": "You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to −" }, { "code": null, "e": 3492, "s": 3324, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Hello Pug</title>\n </head>\n \n <body>\n <p class = \"greetings\" id = \"people\">Hello World!</p>\n </body>\n</html>" }, { "code": null, "e": 3556, "s": 3492, "text": "Pug is capable of doing much more than simplifying HTML markup." }, { "code": null, "e": 3608, "s": 3556, "text": "Let us now explore a few important features of Pug." }, { "code": null, "e": 3835, "s": 3608, "text": "Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag." }, { "code": null, "e": 3965, "s": 3835, "text": "We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us." }, { "code": null, "e": 4014, "s": 3965, "text": "To put text inside of a tag, we have 3 methods −" }, { "code": null, "e": 4030, "s": 4014, "text": "Space seperated" }, { "code": null, "e": 4046, "s": 4030, "text": "Space seperated" }, { "code": null, "e": 4065, "s": 4046, "text": "h1 Welcome to Pug\n" }, { "code": null, "e": 4076, "s": 4065, "text": "Piped text" }, { "code": null, "e": 4087, "s": 4076, "text": "Piped text" }, { "code": null, "e": 4160, "s": 4087, "text": "div\n | To insert multiline text, \n | You can use the pipe operator.\n" }, { "code": null, "e": 4174, "s": 4160, "text": "Block of text" }, { "code": null, "e": 4188, "s": 4174, "text": "Block of text" }, { "code": null, "e": 4404, "s": 4188, "text": "div.\n But that gets tedious if you have a lot of text.\n You can use \".\" at the end of tag to denote block of text.\n To put tags inside this block, simply enter tag in a new line and \n indent it accordingly.\n" }, { "code": null, "e": 4550, "s": 4404, "text": "Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example," }, { "code": null, "e": 4575, "s": 4550, "text": "//This is a Pug comment\n" }, { "code": null, "e": 4621, "s": 4575, "text": "This comment gets converted to the following." }, { "code": null, "e": 4651, "s": 4621, "text": "<!--This is a Pug comment-->\n" }, { "code": null, "e": 4880, "s": 4651, "text": "To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag." }, { "code": null, "e": 4947, "s": 4880, "text": "div.container.column.main#division(width = \"100\", height = \"100\")\n" }, { "code": null, "e": 5001, "s": 4947, "text": "This line of code, gets converted to the following. −" }, { "code": null, "e": 5090, "s": 5001, "text": "<div class = \"container column main\" id = \"division\" width = \"100\" height = \"100\"></div>" }, { "code": null, "e": 5263, "s": 5090, "text": "When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following." }, { "code": null, "e": 5494, "s": 5263, "text": "var express = require('express');\nvar app = express();\n\napp.get('/dynamic_view', function(req, res){\n res.render('dynamic', {\n name: \"TutorialsPoint\", \n url:\"http://www.tutorialspoint.com\"\n });\n});\n\napp.listen(3000);" }, { "code": null, "e": 5587, "s": 5494, "text": "And create a new view file in views directory, called dynamic.pug, with the following code −" }, { "code": null, "e": 5664, "s": 5587, "text": "html\n head\n title=name\n body\n h1=name\n a(href = url) URL\n" }, { "code": null, "e": 5752, "s": 5664, "text": "Open localhost:3000/dynamic_view in your browser; You should get the following output −" }, { "code": null, "e": 6013, "s": 5752, "text": "We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following." }, { "code": null, "e": 6110, "s": 6013, "text": "html\n head\n title = name\n body\n h1 Greetings from #{name}\n a(href = url) URL\n" }, { "code": null, "e": 6215, "s": 6110, "text": "This method of using values is called interpolation. The above code will display the following output. −" }, { "code": null, "e": 6281, "s": 6215, "text": "We can use conditional statements and looping constructs as well." }, { "code": null, "e": 6306, "s": 6281, "text": "Consider the following −" }, { "code": null, "e": 6464, "s": 6306, "text": "If a User is logged in, the page should display \"Hi, User\" and if not, then the \"Login/Sign Up\" link. To achieve this, we can define a simple template like −" }, { "code": null, "e": 6607, "s": 6464, "text": "html\n head\n title Simple template\n body\n if(user)\n h1 Hi, #{user.name}\n else\n a(href = \"/sign_up\") Sign Up\n" }, { "code": null, "e": 6697, "s": 6607, "text": "When we render this using our routes, we can pass an object as in the following program −" }, { "code": null, "e": 6762, "s": 6697, "text": "res.render('/dynamic',{\n user: {name: \"Ayush\", age: \"20\"}\n});\n" }, { "code": null, "e": 6896, "s": 6762, "text": "You will receive a message − Hi, Ayush. But if we don’t pass any object or pass one with no user key, then we will get a signup link." }, { "code": null, "e": 7195, "s": 6896, "text": "Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view we create, we can use the include feature. Following example shows how we can use this feature −" }, { "code": null, "e": 7236, "s": 7195, "text": "Create 3 views with the following code −" }, { "code": null, "e": 7247, "s": 7236, "text": "HEADER.PUG" }, { "code": null, "e": 7296, "s": 7247, "text": "div.header.\n I'm the header for this website.\n" }, { "code": null, "e": 7308, "s": 7296, "text": "CONTENT.PUG" }, { "code": null, "e": 7442, "s": 7308, "text": "html\n head\n title Simple template\n body\n include ./header.pug\n h3 I'm the main content\n include ./footer.pug\n" }, { "code": null, "e": 7453, "s": 7442, "text": "FOOTER.PUG" }, { "code": null, "e": 7502, "s": 7453, "text": "div.footer.\n I'm the footer for this website.\n" }, { "code": null, "e": 7539, "s": 7502, "text": "Create a route for this as follows −" }, { "code": null, "e": 7688, "s": 7539, "text": "var express = require('express');\nvar app = express();\n\napp.get('/components', function(req, res){\n res.render('content');\n});\n\napp.listen(3000);" }, { "code": null, "e": 7761, "s": 7688, "text": "Go to localhost:3000/components, you will receive the following output −" }, { "code": null, "e": 7828, "s": 7761, "text": "include can also be used to include plaintext, css and JavaScript." }, { "code": null, "e": 7951, "s": 7828, "text": "There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug." }, { "code": null, "e": 7984, "s": 7951, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7998, "s": 7984, "text": " Anadi Sharma" }, { "code": null, "e": 8005, "s": 7998, "text": " Print" }, { "code": null, "e": 8016, "s": 8005, "text": " Add Notes" } ]
Write a program to Delete a Tree - GeeksforGeeks
18 Feb, 2022 To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use – inorder transversal, preorder transversal, or the postorder transversal? The answer is simple. We should use the postorder transversal because before deleting the parent node, we should delete its child nodes first.We can delete the tree with other traversals also with extra space complexity but why should we go for the other traversals if we have the postorder one available which does the work without storing anything in the same time complexity.For the following tree, nodes are deleted in the order – 4, 5, 2, 3, 1. Note : In Java automatic garbage collection happens, so we can simply make root null to delete the tree “root = null”; C++ C Java Python3 C# Javascript // C++ program to Delete a Tree #include<bits/stdc++.h>#include<iostream>using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; /* This function traverses treein post order to delete eachand every node of the tree */void deleteTree(node* node){ if (node == NULL) return; /* first delete both subtrees */ deleteTree(node->left); deleteTree(node->right); /* then delete the node */ cout << "\n Deleting node: " << node->data; delete node;} /* Driver code*/int main(){ node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); deleteTree(root); root = NULL; cout << "\n Tree deleted "; return 0;} //This code is contributed by rathbhupendra // C program to Delete a Tree#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* This function traverses tree in post order to to delete each and every node of the tree */void deleteTree(struct node* node){ if (node == NULL) return; /* first delete both subtrees */ deleteTree(node->left); deleteTree(node->right); /* then delete the node */ printf("\n Deleting node: %d", node->data); free(node);} /* Driver program to test deleteTree function*/ int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); deleteTree(root); root = NULL; printf("\n Tree deleted "); return 0;} // Java program to delete a tree // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function traverses tree in post order to to delete each and every node of the tree */ void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.deleteTree(tree.root); tree.root = null; System.out.println("Tree deleted"); }} """ program to Delete a Tree """ # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None """ This function traverses tree in post order to to delete each and every node of the tree """def deleteTree( node) : if node != None: deleteTree(node.left) deleteTree(node.right) del node # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) deleteTree(root) root = None print("Tree deleted ") # This code is contributed by# Shubham Prashar(shubhamprashar) using System; // C# program to delete a tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* This function traverses tree in post order to to delete each and every node of the tree */ public virtual void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.deleteTree(tree.root); tree.root = null; Console.WriteLine("Tree deleted"); }} // This code is contributed by Shrikant13 <script>// javascript program to delete a tree // A binary tree nodeclass Node { constructor(item) { this.data = item; this.left = this.right = null; }} var root; /* * This function traverses tree in post order to to delete each and every node * of the tree */ function deleteTree(node) { // In javascript automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ deleteTree(root); root = null; document.write("Tree deleted"); // This code contributed by gauravrajput1</script> The above deleteTree() function deletes the tree but doesn’t change the root to NULL which may cause problems if the user of deleteTree() doesn’t change root to NULL and tries to access the values using the root pointer. We can modify the deleteTree() function to take reference to the root node so that this problem doesn’t occur. See the following code. C++ C Java Python3 C# Javascript // CPP program to Delete a Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* This function is same as deleteTree()in the previous program */void _deleteTree(node* node){ if (node == NULL) return; /* first delete both subtrees */ _deleteTree(node->left); _deleteTree(node->right); /* then delete the node */ cout << "Deleting node: " << node->data << endl; delete node;} /* Deletes a tree and sets the root as NULL */void deleteTree(node** node_ref){ _deleteTree(*node_ref); *node_ref = NULL;} /* Driver code*/int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Note that we pass the address of root here deleteTree(&root); cout << "Tree deleted "; return 0;} // This code is contributed by rathbhupendra // C program to Delete a Tree#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* This function is same as deleteTree() in the previous program */void _deleteTree(struct node* node){ if (node == NULL) return; /* first delete both subtrees */ _deleteTree(node->left); _deleteTree(node->right); /* then delete the node */ printf("\n Deleting node: %d", node->data); free(node);} /* Deletes a tree and sets the root as NULL */void deleteTree(struct node** node_ref){ _deleteTree(*node_ref); *node_ref = NULL;} /* Driver program to test deleteTree function*/int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Note that we pass the address of root here deleteTree(&root); printf("\n Tree deleted "); getchar(); return 0;} // Java program to delete a tree /* A binary tree node has data, pointer to left child and pointer to right child */class Node{ int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree{ static Node root; /* This function is same as deleteTree() in the previous program */ void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Wrapper function that deletes the tree and sets root node as null */ void deleteTreeRef(Node nodeRef) { deleteTree(nodeRef); nodeRef=null; } /* Driver program to test deleteTree function */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Note that we pass root node here */ tree.deleteTreeRef(root); System.out.println("Tree deleted"); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to count all nodes# having k leaves in subtree rooted with them # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node # with the given data and None left and# right pointersclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' This function is same as deleteTree()in the previous program '''def _deleteTree(node): if (node == None): return # first delete both subtrees _deleteTree(node.left) _deleteTree(node.right) # then delete the node print("Deleting node: ", node.data) node = None # Deletes a tree and sets the root as NULLdef deleteTree(node_ref): _deleteTree(node_ref[0]) node_ref[0] = None # Driver coderoot = [0]root[0] = newNode(1)root[0].left = newNode(2)root[0].right = newNode(3)root[0].left.left = newNode(4)root[0].left.right = newNode(5) # Note that we pass the address# of root heredeleteTree(root)print("Tree deleted ") # This code is contributed by SHUBHAMSINGH10 using System; // C# program to delete a tree /* A binary tree node has data, pointer to left child and pointer to right child */public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node root; /* This function is same as deleteTree() in the previous program */ public virtual void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Wrapper function that deletes the tree and sets root node as null */ public virtual void deleteTreeRef(Node nodeRef) { deleteTree(nodeRef); nodeRef = null; } /* Driver program to test deleteTree function */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(1); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(5); /* Note that we pass root node here */ tree.deleteTreeRef(root); Console.WriteLine("Tree deleted"); }} // This code is contributed by Shrikant13 <script> // JavaScript program to delete a tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function is same as deleteTree() in the previous program */ function deleteTree(node) { if (node == null) return; /* first delete both subtrees */ deleteTree(node.left); deleteTree(node.right); /* then delete the node */ document.write("Deleting node: " + node.data + "</br>"); } /* Wrapper function that deletes the tree and sets root node as null */ function deleteTreeRef(nodeRef) { deleteTree(nodeRef); nodeRef=null; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Note that we pass root node here */ deleteTreeRef(root); document.write("Tree deleted"); </script> Output: Deleting node: 4 Deleting node: 5 Deleting node: 2 Deleting node: 3 Deleting node: 1 Tree deleted Time Complexity: O(n) Space Complexity: If we don’t consider size of stack for function calls then O(1) otherwise O(n) YouTubeGeeksforGeeks500K subscribersProgram to Delete a Tree | 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 / 5:07•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qRpM8nrAyTI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> shrikanth13 SHUBHAMSINGH10 rathbhupendra SaiTeja47 divyanshu_gupta1 rameshtravel07 shubhamprashar GauravRajput1 simranarora5sos simmytarika5 Delete Tree tree-traversal Trees Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not Decision Tree Construct Tree from given Inorder and Preorder traversals Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree (Array implementation) BFS vs DFS for Binary Tree
[ { "code": null, "e": 24543, "s": 24515, "text": "\n18 Feb, 2022" }, { "code": null, "e": 25192, "s": 24543, "text": "To delete a tree, we must traverse all the nodes of the tree and delete them one by one. So, which traversal we should use – inorder transversal, preorder transversal, or the postorder transversal? The answer is simple. We should use the postorder transversal because before deleting the parent node, we should delete its child nodes first.We can delete the tree with other traversals also with extra space complexity but why should we go for the other traversals if we have the postorder one available which does the work without storing anything in the same time complexity.For the following tree, nodes are deleted in the order – 4, 5, 2, 3, 1. " }, { "code": null, "e": 25314, "s": 25194, "text": "Note : In Java automatic garbage collection happens, so we can simply make root null to delete the tree “root = null”; " }, { "code": null, "e": 25318, "s": 25314, "text": "C++" }, { "code": null, "e": 25320, "s": 25318, "text": "C" }, { "code": null, "e": 25325, "s": 25320, "text": "Java" }, { "code": null, "e": 25333, "s": 25325, "text": "Python3" }, { "code": null, "e": 25336, "s": 25333, "text": "C#" }, { "code": null, "e": 25347, "s": 25336, "text": "Javascript" }, { "code": "// C++ program to Delete a Tree #include<bits/stdc++.h>#include<iostream>using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node{ public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; /* This function traverses treein post order to delete eachand every node of the tree */void deleteTree(node* node){ if (node == NULL) return; /* first delete both subtrees */ deleteTree(node->left); deleteTree(node->right); /* then delete the node */ cout << \"\\n Deleting node: \" << node->data; delete node;} /* Driver code*/int main(){ node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); deleteTree(root); root = NULL; cout << \"\\n Tree deleted \"; return 0;} //This code is contributed by rathbhupendra", "e": 26484, "s": 25347, "text": null }, { "code": "// C program to Delete a Tree#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* This function traverses tree in post order to to delete each and every node of the tree */void deleteTree(struct node* node){ if (node == NULL) return; /* first delete both subtrees */ deleteTree(node->left); deleteTree(node->right); /* then delete the node */ printf(\"\\n Deleting node: %d\", node->data); free(node);} /* Driver program to test deleteTree function*/ int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); deleteTree(root); root = NULL; printf(\"\\n Tree deleted \"); return 0;}", "e": 27714, "s": 26484, "text": null }, { "code": "// Java program to delete a tree // A binary tree nodeclass Node{ int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; /* This function traverses tree in post order to to delete each and every node of the tree */ void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.deleteTree(tree.root); tree.root = null; System.out.println(\"Tree deleted\"); }}", "e": 28728, "s": 27714, "text": null }, { "code": "\"\"\" program to Delete a Tree \"\"\" # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Construct to create a new node def __init__(self, key): self.data = key self.left = None self.right = None \"\"\" This function traverses tree in post order to to delete each and every node of the tree \"\"\"def deleteTree( node) : if node != None: deleteTree(node.left) deleteTree(node.right) del node # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) deleteTree(root) root = None print(\"Tree deleted \") # This code is contributed by# Shubham Prashar(shubhamprashar)", "e": 29550, "s": 28728, "text": null }, { "code": "using System; // C# program to delete a tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ public Node root; /* This function traverses tree in post order to to delete each and every node of the tree */ public virtual void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ tree.deleteTree(tree.root); tree.root = null; Console.WriteLine(\"Tree deleted\"); }} // This code is contributed by Shrikant13", "e": 30669, "s": 29550, "text": null }, { "code": "<script>// javascript program to delete a tree // A binary tree nodeclass Node { constructor(item) { this.data = item; this.left = this.right = null; }} var root; /* * This function traverses tree in post order to to delete each and every node * of the tree */ function deleteTree(node) { // In javascript automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Driver program to test above functions */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Print all root-to-leaf paths of the input tree */ deleteTree(root); root = null; document.write(\"Tree deleted\"); // This code contributed by gauravrajput1</script>", "e": 31583, "s": 30669, "text": null }, { "code": null, "e": 31941, "s": 31583, "text": "The above deleteTree() function deletes the tree but doesn’t change the root to NULL which may cause problems if the user of deleteTree() doesn’t change root to NULL and tries to access the values using the root pointer. We can modify the deleteTree() function to take reference to the root node so that this problem doesn’t occur. See the following code. " }, { "code": null, "e": 31945, "s": 31941, "text": "C++" }, { "code": null, "e": 31947, "s": 31945, "text": "C" }, { "code": null, "e": 31952, "s": 31947, "text": "Java" }, { "code": null, "e": 31960, "s": 31952, "text": "Python3" }, { "code": null, "e": 31963, "s": 31960, "text": "C#" }, { "code": null, "e": 31974, "s": 31963, "text": "Javascript" }, { "code": "// CPP program to Delete a Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} /* This function is same as deleteTree()in the previous program */void _deleteTree(node* node){ if (node == NULL) return; /* first delete both subtrees */ _deleteTree(node->left); _deleteTree(node->right); /* then delete the node */ cout << \"Deleting node: \" << node->data << endl; delete node;} /* Deletes a tree and sets the root as NULL */void deleteTree(node** node_ref){ _deleteTree(*node_ref); *node_ref = NULL;} /* Driver code*/int main(){ node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Note that we pass the address of root here deleteTree(&root); cout << \"Tree deleted \"; return 0;} // This code is contributed by rathbhupendra", "e": 33239, "s": 31974, "text": null }, { "code": "// C program to Delete a Tree#include<stdio.h>#include<stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} /* This function is same as deleteTree() in the previous program */void _deleteTree(struct node* node){ if (node == NULL) return; /* first delete both subtrees */ _deleteTree(node->left); _deleteTree(node->right); /* then delete the node */ printf(\"\\n Deleting node: %d\", node->data); free(node);} /* Deletes a tree and sets the root as NULL */void deleteTree(struct node** node_ref){ _deleteTree(*node_ref); *node_ref = NULL;} /* Driver program to test deleteTree function*/int main(){ struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Note that we pass the address of root here deleteTree(&root); printf(\"\\n Tree deleted \"); getchar(); return 0;}", "e": 34610, "s": 33239, "text": null }, { "code": "// Java program to delete a tree /* A binary tree node has data, pointer to left child and pointer to right child */class Node{ int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree{ static Node root; /* This function is same as deleteTree() in the previous program */ void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Wrapper function that deletes the tree and sets root node as null */ void deleteTreeRef(Node nodeRef) { deleteTree(nodeRef); nodeRef=null; } /* Driver program to test deleteTree function */ public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); /* Note that we pass root node here */ tree.deleteTreeRef(root); System.out.println(\"Tree deleted\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 35868, "s": 34610, "text": null }, { "code": "# Python3 program to count all nodes# having k leaves in subtree rooted with them # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node # with the given data and None left and# right pointersclass newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' This function is same as deleteTree()in the previous program '''def _deleteTree(node): if (node == None): return # first delete both subtrees _deleteTree(node.left) _deleteTree(node.right) # then delete the node print(\"Deleting node: \", node.data) node = None # Deletes a tree and sets the root as NULLdef deleteTree(node_ref): _deleteTree(node_ref[0]) node_ref[0] = None # Driver coderoot = [0]root[0] = newNode(1)root[0].left = newNode(2)root[0].right = newNode(3)root[0].left.left = newNode(4)root[0].left.right = newNode(5) # Note that we pass the address# of root heredeleteTree(root)print(\"Tree deleted \") # This code is contributed by SHUBHAMSINGH10", "e": 36966, "s": 35868, "text": null }, { "code": "using System; // C# program to delete a tree /* A binary tree node has data, pointer to left child and pointer to right child */public class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree{ public static Node root; /* This function is same as deleteTree() in the previous program */ public virtual void deleteTree(Node node) { // In Java automatic garbage collection // happens, so we can simply make root // null to delete the tree root = null; } /* Wrapper function that deletes the tree and sets root node as null */ public virtual void deleteTreeRef(Node nodeRef) { deleteTree(nodeRef); nodeRef = null; } /* Driver program to test deleteTree function */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(1); BinaryTree.root.left = new Node(2); BinaryTree.root.right = new Node(3); BinaryTree.root.left.left = new Node(4); BinaryTree.root.left.right = new Node(5); /* Note that we pass root node here */ tree.deleteTreeRef(root); Console.WriteLine(\"Tree deleted\"); }} // This code is contributed by Shrikant13", "e": 38307, "s": 36966, "text": null }, { "code": "<script> // JavaScript program to delete a tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function is same as deleteTree() in the previous program */ function deleteTree(node) { if (node == null) return; /* first delete both subtrees */ deleteTree(node.left); deleteTree(node.right); /* then delete the node */ document.write(\"Deleting node: \" + node.data + \"</br>\"); } /* Wrapper function that deletes the tree and sets root node as null */ function deleteTreeRef(nodeRef) { deleteTree(nodeRef); nodeRef=null; } root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); /* Note that we pass root node here */ deleteTreeRef(root); document.write(\"Tree deleted\"); </script>", "e": 39328, "s": 38307, "text": null }, { "code": null, "e": 39338, "s": 39328, "text": "Output: " }, { "code": null, "e": 39443, "s": 39338, "text": " Deleting node: 4\n Deleting node: 5\n Deleting node: 2\n Deleting node: 3\n Deleting node: 1\n Tree deleted " }, { "code": null, "e": 39563, "s": 39443, "text": "Time Complexity: O(n) Space Complexity: If we don’t consider size of stack for function calls then O(1) otherwise O(n) " }, { "code": null, "e": 40386, "s": 39563, "text": "YouTubeGeeksforGeeks500K subscribersProgram to Delete a Tree | 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 / 5:07•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=qRpM8nrAyTI\" 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": 40400, "s": 40388, "text": "shrikanth13" }, { "code": null, "e": 40415, "s": 40400, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 40429, "s": 40415, "text": "rathbhupendra" }, { "code": null, "e": 40439, "s": 40429, "text": "SaiTeja47" }, { "code": null, "e": 40456, "s": 40439, "text": "divyanshu_gupta1" }, { "code": null, "e": 40471, "s": 40456, "text": "rameshtravel07" }, { "code": null, "e": 40486, "s": 40471, "text": "shubhamprashar" }, { "code": null, "e": 40500, "s": 40486, "text": "GauravRajput1" }, { "code": null, "e": 40516, "s": 40500, "text": "simranarora5sos" }, { "code": null, "e": 40529, "s": 40516, "text": "simmytarika5" }, { "code": null, "e": 40541, "s": 40529, "text": "Delete Tree" }, { "code": null, "e": 40556, "s": 40541, "text": "tree-traversal" }, { "code": null, "e": 40562, "s": 40556, "text": "Trees" }, { "code": null, "e": 40567, "s": 40562, "text": "Tree" }, { "code": null, "e": 40572, "s": 40567, "text": "Tree" }, { "code": null, "e": 40670, "s": 40572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40679, "s": 40670, "text": "Comments" }, { "code": null, "e": 40692, "s": 40679, "text": "Old Comments" }, { "code": null, "e": 40735, "s": 40692, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 40768, "s": 40735, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 40818, "s": 40768, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 40832, "s": 40818, "text": "Decision Tree" }, { "code": null, "e": 40890, "s": 40832, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 40973, "s": 40890, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 41009, "s": 40973, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41057, "s": 41009, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 41092, "s": 41057, "text": "Binary Tree (Array implementation)" } ]
Comparing and Filtering NumPy array - GeeksforGeeks
07 Apr, 2021 In this article, we are going to see how to perform a comparison and filtering of the NumPy array. Let’s see the comparison operators that will be used in comparing NumPy Arrays – Greater than (>) Or numpy.greater(). Less Than (<) numpy.less(). Equal(==) or numpy.equal() Not Equal(!=) or numpy.not_equal(). Greater than and equal to(>=). Less than Equal to(<=). Steps for NumPy Array Comparison: Step 1: First install NumPy in your system or Environment. By using the following command. pip install numpy(command prompt) !pip install numpy(jupyter) Step 2: Import NumPy module. import numpy as np Step 3: Create an array of elements using NumPy Array method. np.array([elements]) Step 4: Now use comparison operators for comparing NumPy Array. Example 1: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using greater() method. Python3 # importing NumPy Moduleimport numpy as np # Creating Arraya = np.array([1,2,3,4]) b = np.array([3,8,5,6]) # Comparing two arraysnp.greater(a, b) Output: array([False, False, False, False]) Example 2: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using less() method. Python3 # Importing NumPy Moduleimport numpy as np # Creating Array using NumPya = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6])np.less(a, b) Output: array([ True, True, True, True]) Example 3: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using equal() method. Python3 # Importing NumPy Module.import numpy as np # Create Arrays using np.array() Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # Compare a and b array elements# if the elements in a and b are equal# it returns True else returns False.np.equal(a, b) Output: array([ False, False, False, False]) Example 4: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using not_equal() method. Python3 # Importing NumPy Module.import numpy as np # Create Arrays using np.array() Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # Compare a and b array elements if the# elements in a and b are not equal# it returns True else returns False.np.not_equal(a, b) Output: array([ True, True, True, True]) Example 5: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using >= operator. Python3 # Importing NumPy Module.import numpy as np # Create Arrays using np.array()# Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # it returns if elements in a are# greater than a equal to bprint(a >= b) Output: [False False False False] Example 6: Import NumPy module. Create array using numpy.array() method. Now compare two arrays using <= operator. Python3 # Importing NumPy Module.import numpy as np # Create Arrays using np.array()# Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # it returns if elements in a are less# than a equal to bprint(a <= b) Output: [ True True True True] Filtering means taking the elements which satisfy the condition given by us. For example, Even elements in an array, elements greater than 10 in an array, etc. Steps for Filtering NumPy Array’s: Import NumPy module. Create arrays using np.array() function. Write any condition for filtering the array. Create a new array with that filtering function. Note: In Filtering and Comparison both give boolean values as an output. Example 1: Import NumPy module. Create array using numpy.array() method. Now take a condition for filtering array. Now create a new array that satisfies the condition. Python3 import numpy as np a = np.array([1, 2, 3, 40, 50, 100, 45, 87, 98]) # Taking a condition to filter the arrayfilter_ex = a < 16 # Creating new array using Condition.new_arr = np.array([filter_ex]) # Printing new Arrayprint(*new_arr) Output: [False False False True True True True True True] Example 2: Import NumPy module. Create array using numpy.array() method. Now take a condition for filtering array. Now create a new array that satisfies the condition. Python3 # Importing NumPy Moduleimport numpy as np # Creating Arraya = np.array([1, 2, 3, 40, 50, 100, 45, 87, 98]) # Filtering Conditionfilter2 = a % 2 == 0even = np.array([filter2])print(*even) Output: [False True False True True True False False True] Picked 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": 24292, "s": 24264, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24391, "s": 24292, "text": "In this article, we are going to see how to perform a comparison and filtering of the NumPy array." }, { "code": null, "e": 24472, "s": 24391, "text": "Let’s see the comparison operators that will be used in comparing NumPy Arrays –" }, { "code": null, "e": 24509, "s": 24472, "text": "Greater than (>) Or numpy.greater()." }, { "code": null, "e": 24537, "s": 24509, "text": "Less Than (<) numpy.less()." }, { "code": null, "e": 24564, "s": 24537, "text": "Equal(==) or numpy.equal()" }, { "code": null, "e": 24600, "s": 24564, "text": "Not Equal(!=) or numpy.not_equal()." }, { "code": null, "e": 24631, "s": 24600, "text": "Greater than and equal to(>=)." }, { "code": null, "e": 24655, "s": 24631, "text": "Less than Equal to(<=)." }, { "code": null, "e": 24689, "s": 24655, "text": "Steps for NumPy Array Comparison:" }, { "code": null, "e": 24780, "s": 24689, "text": "Step 1: First install NumPy in your system or Environment. By using the following command." }, { "code": null, "e": 24842, "s": 24780, "text": "pip install numpy(command prompt)\n!pip install numpy(jupyter)" }, { "code": null, "e": 24871, "s": 24842, "text": "Step 2: Import NumPy module." }, { "code": null, "e": 24890, "s": 24871, "text": "import numpy as np" }, { "code": null, "e": 24952, "s": 24890, "text": "Step 3: Create an array of elements using NumPy Array method." }, { "code": null, "e": 24973, "s": 24952, "text": "np.array([elements])" }, { "code": null, "e": 25037, "s": 24973, "text": "Step 4: Now use comparison operators for comparing NumPy Array." }, { "code": null, "e": 25048, "s": 25037, "text": "Example 1:" }, { "code": null, "e": 25069, "s": 25048, "text": "Import NumPy module." }, { "code": null, "e": 25110, "s": 25069, "text": "Create array using numpy.array() method." }, { "code": null, "e": 25157, "s": 25110, "text": "Now compare two arrays using greater() method." }, { "code": null, "e": 25165, "s": 25157, "text": "Python3" }, { "code": "# importing NumPy Moduleimport numpy as np # Creating Arraya = np.array([1,2,3,4]) b = np.array([3,8,5,6]) # Comparing two arraysnp.greater(a, b)", "e": 25314, "s": 25165, "text": null }, { "code": null, "e": 25322, "s": 25314, "text": "Output:" }, { "code": null, "e": 25358, "s": 25322, "text": "array([False, False, False, False])" }, { "code": null, "e": 25369, "s": 25358, "text": "Example 2:" }, { "code": null, "e": 25390, "s": 25369, "text": "Import NumPy module." }, { "code": null, "e": 25431, "s": 25390, "text": "Create array using numpy.array() method." }, { "code": null, "e": 25475, "s": 25431, "text": "Now compare two arrays using less() method." }, { "code": null, "e": 25483, "s": 25475, "text": "Python3" }, { "code": "# Importing NumPy Moduleimport numpy as np # Creating Array using NumPya = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6])np.less(a, b)", "e": 25621, "s": 25483, "text": null }, { "code": null, "e": 25629, "s": 25621, "text": "Output:" }, { "code": null, "e": 25665, "s": 25629, "text": "array([ True, True, True, True])" }, { "code": null, "e": 25676, "s": 25665, "text": "Example 3:" }, { "code": null, "e": 25697, "s": 25676, "text": "Import NumPy module." }, { "code": null, "e": 25738, "s": 25697, "text": "Create array using numpy.array() method." }, { "code": null, "e": 25783, "s": 25738, "text": "Now compare two arrays using equal() method." }, { "code": null, "e": 25791, "s": 25783, "text": "Python3" }, { "code": "# Importing NumPy Module.import numpy as np # Create Arrays using np.array() Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # Compare a and b array elements# if the elements in a and b are equal# it returns True else returns False.np.equal(a, b)", "e": 26054, "s": 25791, "text": null }, { "code": null, "e": 26062, "s": 26054, "text": "Output:" }, { "code": null, "e": 26101, "s": 26062, "text": "array([ False, False, False, False])" }, { "code": null, "e": 26112, "s": 26101, "text": "Example 4:" }, { "code": null, "e": 26133, "s": 26112, "text": "Import NumPy module." }, { "code": null, "e": 26174, "s": 26133, "text": "Create array using numpy.array() method." }, { "code": null, "e": 26223, "s": 26174, "text": "Now compare two arrays using not_equal() method." }, { "code": null, "e": 26231, "s": 26223, "text": "Python3" }, { "code": "# Importing NumPy Module.import numpy as np # Create Arrays using np.array() Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # Compare a and b array elements if the# elements in a and b are not equal# it returns True else returns False.np.not_equal(a, b)", "e": 26503, "s": 26231, "text": null }, { "code": null, "e": 26511, "s": 26503, "text": "Output:" }, { "code": null, "e": 26547, "s": 26511, "text": "array([ True, True, True, True])" }, { "code": null, "e": 26558, "s": 26547, "text": "Example 5:" }, { "code": null, "e": 26579, "s": 26558, "text": "Import NumPy module." }, { "code": null, "e": 26620, "s": 26579, "text": "Create array using numpy.array() method." }, { "code": null, "e": 26662, "s": 26620, "text": "Now compare two arrays using >= operator." }, { "code": null, "e": 26670, "s": 26662, "text": "Python3" }, { "code": "# Importing NumPy Module.import numpy as np # Create Arrays using np.array()# Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # it returns if elements in a are# greater than a equal to bprint(a >= b)", "e": 26887, "s": 26670, "text": null }, { "code": null, "e": 26895, "s": 26887, "text": "Output:" }, { "code": null, "e": 26921, "s": 26895, "text": "[False False False False]" }, { "code": null, "e": 26932, "s": 26921, "text": "Example 6:" }, { "code": null, "e": 26953, "s": 26932, "text": "Import NumPy module." }, { "code": null, "e": 26994, "s": 26953, "text": "Create array using numpy.array() method." }, { "code": null, "e": 27036, "s": 26994, "text": "Now compare two arrays using <= operator." }, { "code": null, "e": 27044, "s": 27036, "text": "Python3" }, { "code": "# Importing NumPy Module.import numpy as np # Create Arrays using np.array()# Function.a = np.array([1, 2, 3, 4])b = np.array([3, 8, 5, 6]) # it returns if elements in a are less# than a equal to bprint(a <= b)", "e": 27260, "s": 27044, "text": null }, { "code": null, "e": 27268, "s": 27260, "text": "Output:" }, { "code": null, "e": 27294, "s": 27268, "text": "[ True True True True]" }, { "code": null, "e": 27455, "s": 27294, "text": "Filtering means taking the elements which satisfy the condition given by us. For example, Even elements in an array, elements greater than 10 in an array, etc. " }, { "code": null, "e": 27490, "s": 27455, "text": "Steps for Filtering NumPy Array’s:" }, { "code": null, "e": 27511, "s": 27490, "text": "Import NumPy module." }, { "code": null, "e": 27552, "s": 27511, "text": "Create arrays using np.array() function." }, { "code": null, "e": 27597, "s": 27552, "text": "Write any condition for filtering the array." }, { "code": null, "e": 27646, "s": 27597, "text": "Create a new array with that filtering function." }, { "code": null, "e": 27719, "s": 27646, "text": "Note: In Filtering and Comparison both give boolean values as an output." }, { "code": null, "e": 27730, "s": 27719, "text": "Example 1:" }, { "code": null, "e": 27751, "s": 27730, "text": "Import NumPy module." }, { "code": null, "e": 27792, "s": 27751, "text": "Create array using numpy.array() method." }, { "code": null, "e": 27834, "s": 27792, "text": "Now take a condition for filtering array." }, { "code": null, "e": 27887, "s": 27834, "text": "Now create a new array that satisfies the condition." }, { "code": null, "e": 27895, "s": 27887, "text": "Python3" }, { "code": "import numpy as np a = np.array([1, 2, 3, 40, 50, 100, 45, 87, 98]) # Taking a condition to filter the arrayfilter_ex = a < 16 # Creating new array using Condition.new_arr = np.array([filter_ex]) # Printing new Arrayprint(*new_arr)", "e": 28146, "s": 27895, "text": null }, { "code": null, "e": 28154, "s": 28146, "text": "Output:" }, { "code": null, "e": 28210, "s": 28154, "text": "[False False False True True True True True True]" }, { "code": null, "e": 28221, "s": 28210, "text": "Example 2:" }, { "code": null, "e": 28242, "s": 28221, "text": "Import NumPy module." }, { "code": null, "e": 28283, "s": 28242, "text": "Create array using numpy.array() method." }, { "code": null, "e": 28325, "s": 28283, "text": "Now take a condition for filtering array." }, { "code": null, "e": 28378, "s": 28325, "text": "Now create a new array that satisfies the condition." }, { "code": null, "e": 28386, "s": 28378, "text": "Python3" }, { "code": "# Importing NumPy Moduleimport numpy as np # Creating Arraya = np.array([1, 2, 3, 40, 50, 100, 45, 87, 98]) # Filtering Conditionfilter2 = a % 2 == 0even = np.array([filter2])print(*even)", "e": 28591, "s": 28386, "text": null }, { "code": null, "e": 28599, "s": 28591, "text": "Output:" }, { "code": null, "e": 28655, "s": 28599, "text": "[False True False True True True False False True]" }, { "code": null, "e": 28662, "s": 28655, "text": "Picked" }, { "code": null, "e": 28693, "s": 28662, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 28706, "s": 28693, "text": "Python-numpy" }, { "code": null, "e": 28713, "s": 28706, "text": "Python" }, { "code": null, "e": 28811, "s": 28713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28843, "s": 28811, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28885, "s": 28843, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28941, "s": 28885, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28983, "s": 28941, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29038, "s": 28983, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29069, "s": 29038, "text": "Python | os.path.join() method" }, { "code": null, "e": 29091, "s": 29069, "text": "Defaultdict in Python" }, { "code": null, "e": 29120, "s": 29091, "text": "Create a directory in Python" }, { "code": null, "e": 29159, "s": 29120, "text": "Python | Get unique values from a list" } ]
4 Different Ways to Efficiently Sort a Pandas DataFrame | by Byron Dolon | Towards Data Science
Sorting data properly can make it easy for you to understand it. Many people turn to advanced indexing and aggregate functions in Pandas to answer questions at every stage of analysis. These features can be incredibly useful when you need to manipulate data. However, Pandas also offers different ways of sorting a DataFrame, which could be more suited to analyzing data than .loc[] and other vectorized solutions. If you have multiple columns you want to sort by, or if you just need to sort a series, Pandas has built-in functionality that can help with that. By the end of this piece, using different methods of sorting in Pandas, we’ll have answered the following questions: Which five video games have the most sales in the European market?solved with: .sort_values() What game was published the earliest and has the lowest global sales in its year?solved with: multiple arguments .sort_values() What are the top four highest and lowest video game sales values for the North American market?solved with: nsmallest() and nlargest() Which publishers had the highest Xbox One sales in a year, and what did its sales for PC and PS4 look like in the same year?solved with: MultiIndex .sort_values() We’ll be using this video game sales data, so download the csv file if you want to follow along. As always, don’t forget to import pandas before you get going. import pandas as pd# load datadf = pd.read_csv('vgsales.csv').dropna()df['Year'] = df['Year'].astype(int)df.head() All of the sorting methods available in Pandas fall under the following three categories: Sorting by index labels; Sorting by column values; Sorting by a combination of index labels and column values. Pandas automatically generates an index for every DataFrame you create. The index label starts at 0 and increments by 1 for every row. You can see on the screenshot above that the index labels are present in the leftmost column (the one with no column name). You can see that there wouldn’t really be a point in sorting the DataFrame based on its auto-generated index. However, if we set the “Name” column as the DataFrame’s index, then we could sort the table by alphabetical order. We can change and sort by the index with a simple line of code: df.set_index('Name').sort_index() Here, we can see that the .sort_index() function re-organized that data so the games with a punctuation mark as the first character of its name are at the top of the list. If you look further down, it will show the games with a number as the first character of its name next, and then after that those that start with letters. Last in the sorting hierarchy are special symbols, like the final entry on the table above. That was a really quick example of sorting by a DataFrame’s index. Now let’s get into some more advanced sorting! To answer this question, we’re going to use the .sort_values() function. The code is as follows: df.sort_values(by='EU_Sales', ascending=False).head(5) Here, we input the column to sort by (EU_Sales) and organize our data so that the highest values come first (set ascending to “False”). You can see the output below. The sorted DataFrame has been reorganized, so we can now see that the games with the most sales in the EU are not exactly the same as the games with the most sales globally. To answer this question, we are interested in both the “Year” column and the “Global_Sales” column. We’re going to use the .sort_values() function again, but with a slight change: df.sort_values(by=['Year','Global_Sales']).head(1) This is a case where we wanted to sort our data by more than one column. You can sort by as many columns as you want with this function, simply by passing a list of column names. In this case, we have written “Year” first and “Global_Sales” second, which means the function will sort the DataFrame by its publishing year first and then its sales. By default, the function will sort the DataFrame with the lowest numerical value first, so we don’t need to pass ascending=True (although you could if you wanted to). You can see the result below. Here, we have identified the game “Checkers” published by “Atari” as the earliest game published (1980) in the dataset with the lowest global sales. With this question, we only care about the sales values, which means we don’t need the video game metadata like “Name” and “Platform”. We only care about one column, which is “NA_Sales” that gives us the values for the North American market. This means we are working with a “series”, which is a one-dimensional array in Pandas. Because we’re working with a series, we can use the nsmallest() and nlargest() methods that give us the smallest or largest “n” values in the series. To use this function, you simply pass a value “n” which refers to the number of results you want to see. To answer this question, we write the following: df['NA_Sales'].nlargest(4) And: df['NA_Sales'].nsmallest(4) According to the Pandas documentation, you could use these methods because they might be faster than using the .sort_values() and head() method that we’ve been doing so far. However, it seems that this applies more to very large data sets, as even for one with 16,291 rows there was no difference. For example: df['NA_Sales'].sort_values(ascending=False).head(4) You can see that we get the same values with a different line of code, and it also took the same time (11 milliseconds). However, I think using nlargest() and nsmallest() make for cleaner code. The function names are self-explanatory and easy to understand, so you don’t have to sacrifice readability for a nifty function. To answer this question, we’re going to create a pivot table. These are great when you want to aggregate and present data in an easy-to-read table. The code to create a pivot table looks like this: df_pivot = df.loc[df['Platform'].isin(['PC','XOne','PS4'])]df_pivot = df_pivot[['Platform','Year','Publisher','Global_Sales']]df_pivot = df_pivot.pivot_table(index = ['Publisher','Year'], columns = 'Platform', aggfunc = 'sum', fill_value = 0) If you’re unfamiliar with pivot tables and using a MultiIndex, I’d suggest checking out my previous piece on the topic. towardsdatascience.com To answer our question, we want to be able to compare the PC, PS4 and Xbox One sales, so this pivot table makes it easy for us to look at the data. The initial pivot table looks like this: Now, when sorting this data, we’re interested in the highest “Global_Sales” for “XOne”. If we look at the columns in this DataFrame, we’ll see that there is a MultiIndex in place. df_pivot.columns When sorting by a MultiIndex column, you need to make sure to specify all levels of the MultiIndex in question. To sort our newly created pivot table, we use the following code: df_pivot.sort_values(by=('Global_Sales','XOne'), ascending=False) Here, you can see we pass a tuple into the .sort_values() function. This is because the column name we want to sort by is (‘Global_Sales’, ‘XOne’). You cannot only pass “XOne”, as that is not a valid column name in this case. So make sure to specify every level of the MultiIndex when sorting this kind of DataFrame. The resulting table looks like this: Based on this, we can see that Electronic Arts (EA) has the highest Xbox One sales across all years in 2015. We can also see that its sales in the PC and PS4 segments in the same year. The sorted pivot table makes it easy to do a side-by-side comparison of different columns, so keep this method in mind, as you can use it for many different situations. And we’re done! This was just an introduction to sorting with Pandas. There are many different ways to find answers to the questions we went through, but I find that sorting is a quick and easy way to conduct preliminary analysis. Remember that there’s more than one way to sort a DataFrame. Some methods may be more effective than others, and that Pandas offers in-built methods to help you write cleaner looking code. Good luck with your sorting adventures!
[ { "code": null, "e": 236, "s": 171, "text": "Sorting data properly can make it easy for you to understand it." }, { "code": null, "e": 586, "s": 236, "text": "Many people turn to advanced indexing and aggregate functions in Pandas to answer questions at every stage of analysis. These features can be incredibly useful when you need to manipulate data. However, Pandas also offers different ways of sorting a DataFrame, which could be more suited to analyzing data than .loc[] and other vectorized solutions." }, { "code": null, "e": 733, "s": 586, "text": "If you have multiple columns you want to sort by, or if you just need to sort a series, Pandas has built-in functionality that can help with that." }, { "code": null, "e": 850, "s": 733, "text": "By the end of this piece, using different methods of sorting in Pandas, we’ll have answered the following questions:" }, { "code": null, "e": 944, "s": 850, "text": "Which five video games have the most sales in the European market?solved with: .sort_values()" }, { "code": null, "e": 1072, "s": 944, "text": "What game was published the earliest and has the lowest global sales in its year?solved with: multiple arguments .sort_values()" }, { "code": null, "e": 1207, "s": 1072, "text": "What are the top four highest and lowest video game sales values for the North American market?solved with: nsmallest() and nlargest()" }, { "code": null, "e": 1370, "s": 1207, "text": "Which publishers had the highest Xbox One sales in a year, and what did its sales for PC and PS4 look like in the same year?solved with: MultiIndex .sort_values()" }, { "code": null, "e": 1530, "s": 1370, "text": "We’ll be using this video game sales data, so download the csv file if you want to follow along. As always, don’t forget to import pandas before you get going." }, { "code": null, "e": 1645, "s": 1530, "text": "import pandas as pd# load datadf = pd.read_csv('vgsales.csv').dropna()df['Year'] = df['Year'].astype(int)df.head()" }, { "code": null, "e": 1735, "s": 1645, "text": "All of the sorting methods available in Pandas fall under the following three categories:" }, { "code": null, "e": 1760, "s": 1735, "text": "Sorting by index labels;" }, { "code": null, "e": 1786, "s": 1760, "text": "Sorting by column values;" }, { "code": null, "e": 1846, "s": 1786, "text": "Sorting by a combination of index labels and column values." }, { "code": null, "e": 2105, "s": 1846, "text": "Pandas automatically generates an index for every DataFrame you create. The index label starts at 0 and increments by 1 for every row. You can see on the screenshot above that the index labels are present in the leftmost column (the one with no column name)." }, { "code": null, "e": 2394, "s": 2105, "text": "You can see that there wouldn’t really be a point in sorting the DataFrame based on its auto-generated index. However, if we set the “Name” column as the DataFrame’s index, then we could sort the table by alphabetical order. We can change and sort by the index with a simple line of code:" }, { "code": null, "e": 2428, "s": 2394, "text": "df.set_index('Name').sort_index()" }, { "code": null, "e": 2600, "s": 2428, "text": "Here, we can see that the .sort_index() function re-organized that data so the games with a punctuation mark as the first character of its name are at the top of the list." }, { "code": null, "e": 2847, "s": 2600, "text": "If you look further down, it will show the games with a number as the first character of its name next, and then after that those that start with letters. Last in the sorting hierarchy are special symbols, like the final entry on the table above." }, { "code": null, "e": 2961, "s": 2847, "text": "That was a really quick example of sorting by a DataFrame’s index. Now let’s get into some more advanced sorting!" }, { "code": null, "e": 3058, "s": 2961, "text": "To answer this question, we’re going to use the .sort_values() function. The code is as follows:" }, { "code": null, "e": 3113, "s": 3058, "text": "df.sort_values(by='EU_Sales', ascending=False).head(5)" }, { "code": null, "e": 3279, "s": 3113, "text": "Here, we input the column to sort by (EU_Sales) and organize our data so that the highest values come first (set ascending to “False”). You can see the output below." }, { "code": null, "e": 3453, "s": 3279, "text": "The sorted DataFrame has been reorganized, so we can now see that the games with the most sales in the EU are not exactly the same as the games with the most sales globally." }, { "code": null, "e": 3633, "s": 3453, "text": "To answer this question, we are interested in both the “Year” column and the “Global_Sales” column. We’re going to use the .sort_values() function again, but with a slight change:" }, { "code": null, "e": 3684, "s": 3633, "text": "df.sort_values(by=['Year','Global_Sales']).head(1)" }, { "code": null, "e": 4031, "s": 3684, "text": "This is a case where we wanted to sort our data by more than one column. You can sort by as many columns as you want with this function, simply by passing a list of column names. In this case, we have written “Year” first and “Global_Sales” second, which means the function will sort the DataFrame by its publishing year first and then its sales." }, { "code": null, "e": 4228, "s": 4031, "text": "By default, the function will sort the DataFrame with the lowest numerical value first, so we don’t need to pass ascending=True (although you could if you wanted to). You can see the result below." }, { "code": null, "e": 4377, "s": 4228, "text": "Here, we have identified the game “Checkers” published by “Atari” as the earliest game published (1980) in the dataset with the lowest global sales." }, { "code": null, "e": 4706, "s": 4377, "text": "With this question, we only care about the sales values, which means we don’t need the video game metadata like “Name” and “Platform”. We only care about one column, which is “NA_Sales” that gives us the values for the North American market. This means we are working with a “series”, which is a one-dimensional array in Pandas." }, { "code": null, "e": 5010, "s": 4706, "text": "Because we’re working with a series, we can use the nsmallest() and nlargest() methods that give us the smallest or largest “n” values in the series. To use this function, you simply pass a value “n” which refers to the number of results you want to see. To answer this question, we write the following:" }, { "code": null, "e": 5037, "s": 5010, "text": "df['NA_Sales'].nlargest(4)" }, { "code": null, "e": 5042, "s": 5037, "text": "And:" }, { "code": null, "e": 5070, "s": 5042, "text": "df['NA_Sales'].nsmallest(4)" }, { "code": null, "e": 5381, "s": 5070, "text": "According to the Pandas documentation, you could use these methods because they might be faster than using the .sort_values() and head() method that we’ve been doing so far. However, it seems that this applies more to very large data sets, as even for one with 16,291 rows there was no difference. For example:" }, { "code": null, "e": 5433, "s": 5381, "text": "df['NA_Sales'].sort_values(ascending=False).head(4)" }, { "code": null, "e": 5756, "s": 5433, "text": "You can see that we get the same values with a different line of code, and it also took the same time (11 milliseconds). However, I think using nlargest() and nsmallest() make for cleaner code. The function names are self-explanatory and easy to understand, so you don’t have to sacrifice readability for a nifty function." }, { "code": null, "e": 5904, "s": 5756, "text": "To answer this question, we’re going to create a pivot table. These are great when you want to aggregate and present data in an easy-to-read table." }, { "code": null, "e": 5954, "s": 5904, "text": "The code to create a pivot table looks like this:" }, { "code": null, "e": 6290, "s": 5954, "text": "df_pivot = df.loc[df['Platform'].isin(['PC','XOne','PS4'])]df_pivot = df_pivot[['Platform','Year','Publisher','Global_Sales']]df_pivot = df_pivot.pivot_table(index = ['Publisher','Year'], columns = 'Platform', aggfunc = 'sum', fill_value = 0)" }, { "code": null, "e": 6410, "s": 6290, "text": "If you’re unfamiliar with pivot tables and using a MultiIndex, I’d suggest checking out my previous piece on the topic." }, { "code": null, "e": 6433, "s": 6410, "text": "towardsdatascience.com" }, { "code": null, "e": 6622, "s": 6433, "text": "To answer our question, we want to be able to compare the PC, PS4 and Xbox One sales, so this pivot table makes it easy for us to look at the data. The initial pivot table looks like this:" }, { "code": null, "e": 6802, "s": 6622, "text": "Now, when sorting this data, we’re interested in the highest “Global_Sales” for “XOne”. If we look at the columns in this DataFrame, we’ll see that there is a MultiIndex in place." }, { "code": null, "e": 6819, "s": 6802, "text": "df_pivot.columns" }, { "code": null, "e": 6997, "s": 6819, "text": "When sorting by a MultiIndex column, you need to make sure to specify all levels of the MultiIndex in question. To sort our newly created pivot table, we use the following code:" }, { "code": null, "e": 7063, "s": 6997, "text": "df_pivot.sort_values(by=('Global_Sales','XOne'), ascending=False)" }, { "code": null, "e": 7417, "s": 7063, "text": "Here, you can see we pass a tuple into the .sort_values() function. This is because the column name we want to sort by is (‘Global_Sales’, ‘XOne’). You cannot only pass “XOne”, as that is not a valid column name in this case. So make sure to specify every level of the MultiIndex when sorting this kind of DataFrame. The resulting table looks like this:" }, { "code": null, "e": 7771, "s": 7417, "text": "Based on this, we can see that Electronic Arts (EA) has the highest Xbox One sales across all years in 2015. We can also see that its sales in the PC and PS4 segments in the same year. The sorted pivot table makes it easy to do a side-by-side comparison of different columns, so keep this method in mind, as you can use it for many different situations." }, { "code": null, "e": 7787, "s": 7771, "text": "And we’re done!" }, { "code": null, "e": 8002, "s": 7787, "text": "This was just an introduction to sorting with Pandas. There are many different ways to find answers to the questions we went through, but I find that sorting is a quick and easy way to conduct preliminary analysis." }, { "code": null, "e": 8191, "s": 8002, "text": "Remember that there’s more than one way to sort a DataFrame. Some methods may be more effective than others, and that Pandas offers in-built methods to help you write cleaner looking code." } ]
Powershell - Brackets
Powershell supports three types of brackets. Parenthesis brackets. − () Parenthesis brackets. − () Braces brackets. − {} Braces brackets. − {} Square brackets. − [] Square brackets. − [] This type of brackets is used to pass arguments pass arguments enclose multiple set of instructions enclose multiple set of instructions resolve ambiguity resolve ambiguity create array create array > $array = @("item1", "item2", "item3") > foreach ($element in $array) { $element } item1 item2 item3 This type of brackets is used to enclose statements enclose statements block commands block commands $x = 10 if($x -le 20){ write-host("This is if statement") } This will produce the following result − This is if statement. This type of brackets is used to access to array access to array access to hashtables access to hashtables filter using regular expression filter using regular expression > $array = @("item1", "item2", "item3") > for($i = 0; $i -lt $array.length; $i++){ $array[$i] } item1 item2 item3 >Get-Process [r-s]* Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 320 72 27300 33764 227 3.95 4028 SCNotification 2298 77 57792 48712 308 2884 SearchIndexer
[ { "code": null, "e": 2213, "s": 2168, "text": "Powershell supports three types of brackets." }, { "code": null, "e": 2242, "s": 2213, "text": "Parenthesis brackets. − () \n" }, { "code": null, "e": 2270, "s": 2242, "text": "Parenthesis brackets. − () " }, { "code": null, "e": 2294, "s": 2270, "text": "Braces brackets. − {} \n" }, { "code": null, "e": 2317, "s": 2294, "text": "Braces brackets. − {} " }, { "code": null, "e": 2341, "s": 2317, "text": "Square brackets. − [] \n" }, { "code": null, "e": 2364, "s": 2341, "text": "Square brackets. − [] " }, { "code": null, "e": 2397, "s": 2364, "text": "This type of brackets is used to" }, { "code": null, "e": 2412, "s": 2397, "text": "pass arguments" }, { "code": null, "e": 2427, "s": 2412, "text": "pass arguments" }, { "code": null, "e": 2464, "s": 2427, "text": "enclose multiple set of instructions" }, { "code": null, "e": 2501, "s": 2464, "text": "enclose multiple set of instructions" }, { "code": null, "e": 2519, "s": 2501, "text": "resolve ambiguity" }, { "code": null, "e": 2537, "s": 2519, "text": "resolve ambiguity" }, { "code": null, "e": 2550, "s": 2537, "text": "create array" }, { "code": null, "e": 2563, "s": 2550, "text": "create array" }, { "code": null, "e": 2667, "s": 2563, "text": "> $array = @(\"item1\", \"item2\", \"item3\")\n \n> foreach ($element in $array) { $element }\nitem1\nitem2\nitem3" }, { "code": null, "e": 2700, "s": 2667, "text": "This type of brackets is used to" }, { "code": null, "e": 2719, "s": 2700, "text": "enclose statements" }, { "code": null, "e": 2738, "s": 2719, "text": "enclose statements" }, { "code": null, "e": 2753, "s": 2738, "text": "block commands" }, { "code": null, "e": 2768, "s": 2753, "text": "block commands" }, { "code": null, "e": 2832, "s": 2768, "text": "$x = 10\n\nif($x -le 20){\n write-host(\"This is if statement\")\n}" }, { "code": null, "e": 2873, "s": 2832, "text": "This will produce the following result −" }, { "code": null, "e": 2896, "s": 2873, "text": "This is if statement.\n" }, { "code": null, "e": 2929, "s": 2896, "text": "This type of brackets is used to" }, { "code": null, "e": 2945, "s": 2929, "text": "access to array" }, { "code": null, "e": 2961, "s": 2945, "text": "access to array" }, { "code": null, "e": 2982, "s": 2961, "text": "access to hashtables" }, { "code": null, "e": 3003, "s": 2982, "text": "access to hashtables" }, { "code": null, "e": 3035, "s": 3003, "text": "filter using regular expression" }, { "code": null, "e": 3067, "s": 3035, "text": "filter using regular expression" } ]
Program for n-th even number
25 Oct, 2018 Given a number n, print the nth even number. The 1st even number is 2, 2nd is 4 and so on. Examples: Input : 3 Output : 6 First three even numbers are 2, 4, 6, .. Input : 5 Output : 10 First five even numbers are 2, 4, 6, 8, 19.. The nth even number is given by the formula 2*n. C++ Java Python3 C# PHP // CPP program to find the nth even number#include <bits/stdc++.h>using namespace std; // Function to find the nth even numberint nthEven(int n){ return (2 * n);} // Driver codeint main(){ int n = 10; cout << nthEven(n); return 0;} // JAVA program to find the nth EVEN number class GFG{ // Function to find the nth odd number static int nthEven(int n) { return (2 * n); } // Driver code public static void main(String [] args) { int n = 10; System.out.println(nthEven(n)); }} // This code is contributed// by ihritik # Python 3 program to find the # nth odd number # Function to find the nth Even numberdef nthEven(n): return (2 * n) # Driver codeif __name__=='__main__': n = 10 print(nthEven(n)) # This code is contributed# by ihritik // C# program to find the // nth EVEN numberusing System; class GFG{// Function to find the// nth odd numberstatic int nthEven(int n){ return (2 * n);} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(nthEven(n));}} // This code is contributed// by anuj_67 <?php// PHP program to find the// nth even number // Function to find the// nth even numberfunction nthEven($n){ return (2 * $n);} // Driver code$n = 10;echo nthEven($n); // This code is contributed// by anuj_67?> Output: 20 ihritik vt_m series C++ C++ Programs Mathematical School Programming Mathematical series CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Oct, 2018" }, { "code": null, "e": 144, "s": 53, "text": "Given a number n, print the nth even number. The 1st even number is 2, 2nd is 4 and so on." }, { "code": null, "e": 154, "s": 144, "text": "Examples:" }, { "code": null, "e": 285, "s": 154, "text": "Input : 3\nOutput : 6\nFirst three even numbers are 2, 4, 6, ..\n\nInput : 5\nOutput : 10\nFirst five even numbers are 2, 4, 6, 8, 19..\n" }, { "code": null, "e": 334, "s": 285, "text": "The nth even number is given by the formula 2*n." }, { "code": null, "e": 338, "s": 334, "text": "C++" }, { "code": null, "e": 343, "s": 338, "text": "Java" }, { "code": null, "e": 351, "s": 343, "text": "Python3" }, { "code": null, "e": 354, "s": 351, "text": "C#" }, { "code": null, "e": 358, "s": 354, "text": "PHP" }, { "code": "// CPP program to find the nth even number#include <bits/stdc++.h>using namespace std; // Function to find the nth even numberint nthEven(int n){ return (2 * n);} // Driver codeint main(){ int n = 10; cout << nthEven(n); return 0;}", "e": 604, "s": 358, "text": null }, { "code": "// JAVA program to find the nth EVEN number class GFG{ // Function to find the nth odd number static int nthEven(int n) { return (2 * n); } // Driver code public static void main(String [] args) { int n = 10; System.out.println(nthEven(n)); }} // This code is contributed// by ihritik", "e": 952, "s": 604, "text": null }, { "code": "# Python 3 program to find the # nth odd number # Function to find the nth Even numberdef nthEven(n): return (2 * n) # Driver codeif __name__=='__main__': n = 10 print(nthEven(n)) # This code is contributed# by ihritik", "e": 1190, "s": 952, "text": null }, { "code": "// C# program to find the // nth EVEN numberusing System; class GFG{// Function to find the// nth odd numberstatic int nthEven(int n){ return (2 * n);} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(nthEven(n));}} // This code is contributed// by anuj_67", "e": 1481, "s": 1190, "text": null }, { "code": "<?php// PHP program to find the// nth even number // Function to find the// nth even numberfunction nthEven($n){ return (2 * $n);} // Driver code$n = 10;echo nthEven($n); // This code is contributed// by anuj_67?>", "e": 1701, "s": 1481, "text": null }, { "code": null, "e": 1709, "s": 1701, "text": "Output:" }, { "code": null, "e": 1712, "s": 1709, "text": "20" }, { "code": null, "e": 1720, "s": 1712, "text": "ihritik" }, { "code": null, "e": 1725, "s": 1720, "text": "vt_m" }, { "code": null, "e": 1732, "s": 1725, "text": "series" }, { "code": null, "e": 1736, "s": 1732, "text": "C++" }, { "code": null, "e": 1749, "s": 1736, "text": "C++ Programs" }, { "code": null, "e": 1762, "s": 1749, "text": "Mathematical" }, { "code": null, "e": 1781, "s": 1762, "text": "School Programming" }, { "code": null, "e": 1794, "s": 1781, "text": "Mathematical" }, { "code": null, "e": 1801, "s": 1794, "text": "series" }, { "code": null, "e": 1805, "s": 1801, "text": "CPP" }, { "code": null, "e": 1903, "s": 1805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1957, "s": 1903, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2000, "s": 1957, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 2034, "s": 2000, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2059, "s": 2034, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2076, "s": 2059, "text": "Substring in C++" }, { "code": null, "e": 2111, "s": 2076, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 2145, "s": 2111, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 2189, "s": 2145, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 2248, "s": 2189, "text": "How to return multiple values from a function in C or C++?" } ]
Number of ways to split N as sum of K numbers from the given range
09 Aug, 2021 Given four positive integer N, K, L, and R, the task is to split N as sum of K numbers lying in the range [L, R].Note: Since the number of ways can be very large. Output answer modulo 1000000007.Examples: Input : N = 12, K = 3, L = 1, R = 5 Output : 10 {2, 5, 5} {3, 4, 5} {3, 5, 4} {4, 3, 5} {4, 4, 4} {4, 5, 3} {5, 2, 5} {5, 3, 4} {5, 4, 3} {5, 5, 2} Input : N = 23, K = 4, L = 2, R = 10 Output : 480 Naive Approach We can solve the problem using recursion. At each step of recursion try to make a group of size L to R all There will be two arguments in the recursion which changes: pos – the group number left – how much of N is left to be distributed Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] #include <bits/stdc++.h> using namespace std; const int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // put all possible values // greater equal to prev for (int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codeint main(){ int N = 12; int K = 3; int L = 1; int R = 5; cout << countWaystoDivide(N, K, L, R); return 0;} // Java implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]class GFG{ static int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = ((answer + calculate(pos + 1,left - i, k, L, R)) % mod); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codepublic static void main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; System.out.print(countWaystoDivide(N, K, L, R));}} // This code is contributed by Amit Katiyar # Python3 implementation to count the# number of ways to divide N in K# groups such that each group# has elements in range [L, R] mod = 1000000007 # Function to count the number# of ways to divide the number N# in K groups such that each group# has number of elements in range [L, R]def calculate(pos, left, k, L, R): # Base Case if (pos == k): if (left == 0): return 1 else: return 0 # If N is divides completely # into less than k groups if (left == 0): return 0 answer = 0 # Put all possible values # greater equal to prev for i in range(L, R + 1): if (i > left): break answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod return answer # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k, L, R): return calculate(0, n, k, L, R) # Driver CodeN = 12K = 3L = 1R = 5 print(countWaystoDivide(N, K, L, R)) # This code is contributed by divyamohan123 // C# implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]using System; class GFG{ static int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = ((answer + calculate(pos + 1,left - i, k, L, R)) % mod); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codepublic static void Main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; Console.Write(countWaystoDivide(N, K, L, R));}} // This code is contributed by Amit Katiyar <script> // Javascript implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] var mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]function calculate(pos, left, k, L, R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; var answer = 0; // put all possible values // greater equal to prev for (var i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k, L, R){ return calculate(0, n, k, L, R);} // Driver Codevar N = 12;var K = 3;var L = 1;var R = 5;document.write( countWaystoDivide(N, K, L, R)); // This code is contributed by noob2000.</script> 10 Time Complexity: O(NK). Efficient Approach: In the previous approach we can see that we are solving the subproblems repeatedly, i.e. it follows the property of Overlapping Subproblems. So we can memoize the same using DP table. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] #include <bits/stdc++.h> using namespace std; const int mod = 1000000007; // DP Tableint dp[1000][1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return calculate(0, n, k, L, R);} // Driver Codeint main(){ int N = 12; int K = 3; int L = 1; int R = 5; cout << countWaystoDivide(N, K, L, R); return 0;} // Java implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]class GFG{ static int mod = 1000000007; // DP Tablestatic int [][]dp = new int[1000][1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { dp[i][j] = -1; } } return calculate(0, n, k, L, R);} // Driver Codepublic static void main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; System.out.print(countWaystoDivide(N, K, L, R));}} // This code is contributed by 29AjayKumar # Python3 implementation to count the# number of ways to divide N in K# groups such that each group# has elements in range [L, R]mod = 1000000007 # DP Tabledp = [[-1 for j in range(1000)] for i in range(1000)] # Function to count the number# of ways to divide the number N# in K groups such that each group# has number of elements in range [L, R]def calculate(pos, left, k, L, R): # Base Case if (pos == k): if (left == 0): return 1 else: return 0 # if N is divides completely # into less than k groups if (left == 0): return 0 # If the subproblem has been # solved, use the value if (dp[pos][left] != -1): return dp[pos][left] answer = 0 # put all possible values # greater equal to prev for i in range(L, R + 1): if (i > left): break answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod dp[pos][left] = answer return answer # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k, L, R): return calculate(0, n, k, L, R) # Driver codeif __name__=="__main__": N = 12 K = 3 L = 1 R = 5 print(countWaystoDivide(N, K, L, R)) # This code is contributed by rutvik_56 // C# implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]using System;class GFG{ static int mod = 1000000007; // DP Tablestatic int [,]dp = new int[1000, 1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos, left] != -1) return dp[pos, left]; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos, left] = answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { dp[i, j] = -1; } } return calculate(0, n, k, L, R);} // Driver Codepublic static void Main(){ int N = 12; int K = 3; int L = 1; int R = 5; Console.Write(countWaystoDivide(N, K, L, R));}} // This code is contributed by Code_Mech <script> // JavaScript implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] var mod = 1000000007; // DP Tablevar dp = Array.from(Array(1000), ()=>Array(1000)); // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]function calculate(pos, left, k, L, R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; var answer = 0; // put all possible values // greater equal to prev for (var i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k, L, R){ // Initialize DP Table as -1 dp = Array.from(Array(1000), ()=>Array(1000).fill(-1)); return calculate(0, n, k, L, R);} // Driver Codevar N = 12;var K = 3;var L = 1;var R = 5;document.write( countWaystoDivide(N, K, L, R)); </script> 10 Time Complexity: O(N*K).Auxiliary Space: O(N*K). divyamohan123 amit143katiyar 29AjayKumar Code_Mech rutvik_56 Akanksha_Rai noob2000 famously pankajsharmagfg Algorithms Competitive Programming Dynamic Programming Recursion Dynamic Programming Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph Understanding Time Complexity with Simple Examples Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 234, "s": 28, "text": "Given four positive integer N, K, L, and R, the task is to split N as sum of K numbers lying in the range [L, R].Note: Since the number of ways can be very large. Output answer modulo 1000000007.Examples: " }, { "code": null, "e": 382, "s": 234, "text": "Input : N = 12, K = 3, L = 1, R = 5 Output : 10 {2, 5, 5} {3, 4, 5} {3, 5, 4} {4, 3, 5} {4, 4, 4} {4, 5, 3} {5, 2, 5} {5, 3, 4} {5, 4, 3} {5, 5, 2}" }, { "code": null, "e": 433, "s": 382, "text": "Input : N = 23, K = 4, L = 2, R = 10 Output : 480 " }, { "code": null, "e": 616, "s": 433, "text": "Naive Approach We can solve the problem using recursion. At each step of recursion try to make a group of size L to R all There will be two arguments in the recursion which changes: " }, { "code": null, "e": 639, "s": 616, "text": "pos – the group number" }, { "code": null, "e": 686, "s": 639, "text": "left – how much of N is left to be distributed" }, { "code": null, "e": 737, "s": 686, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 741, "s": 737, "text": "C++" }, { "code": null, "e": 746, "s": 741, "text": "Java" }, { "code": null, "e": 754, "s": 746, "text": "Python3" }, { "code": null, "e": 757, "s": 754, "text": "C#" }, { "code": null, "e": 768, "s": 757, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] #include <bits/stdc++.h> using namespace std; const int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // put all possible values // greater equal to prev for (int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codeint main(){ int N = 12; int K = 3; int L = 1; int R = 5; cout << countWaystoDivide(N, K, L, R); return 0;}", "e": 2008, "s": 768, "text": null }, { "code": "// Java implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]class GFG{ static int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = ((answer + calculate(pos + 1,left - i, k, L, R)) % mod); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codepublic static void main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; System.out.print(countWaystoDivide(N, K, L, R));}} // This code is contributed by Amit Katiyar", "e": 3307, "s": 2008, "text": null }, { "code": "# Python3 implementation to count the# number of ways to divide N in K# groups such that each group# has elements in range [L, R] mod = 1000000007 # Function to count the number# of ways to divide the number N# in K groups such that each group# has number of elements in range [L, R]def calculate(pos, left, k, L, R): # Base Case if (pos == k): if (left == 0): return 1 else: return 0 # If N is divides completely # into less than k groups if (left == 0): return 0 answer = 0 # Put all possible values # greater equal to prev for i in range(L, R + 1): if (i > left): break answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod return answer # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k, L, R): return calculate(0, n, k, L, R) # Driver CodeN = 12K = 3L = 1R = 5 print(countWaystoDivide(N, K, L, R)) # This code is contributed by divyamohan123", "e": 4368, "s": 3307, "text": null }, { "code": "// C# implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]using System; class GFG{ static int mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = ((answer + calculate(pos + 1,left - i, k, L, R)) % mod); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ return calculate(0, n, k, L, R);} // Driver Codepublic static void Main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; Console.Write(countWaystoDivide(N, K, L, R));}} // This code is contributed by Amit Katiyar", "e": 5681, "s": 4368, "text": null }, { "code": "<script> // Javascript implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] var mod = 1000000007; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]function calculate(pos, left, k, L, R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; var answer = 0; // put all possible values // greater equal to prev for (var i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k, L, R){ return calculate(0, n, k, L, R);} // Driver Codevar N = 12;var K = 3;var L = 1;var R = 5;document.write( countWaystoDivide(N, K, L, R)); // This code is contributed by noob2000.</script>", "e": 6838, "s": 5681, "text": null }, { "code": null, "e": 6841, "s": 6838, "text": "10" }, { "code": null, "e": 6867, "s": 6843, "text": "Time Complexity: O(NK)." }, { "code": null, "e": 7072, "s": 6867, "text": "Efficient Approach: In the previous approach we can see that we are solving the subproblems repeatedly, i.e. it follows the property of Overlapping Subproblems. So we can memoize the same using DP table. " }, { "code": null, "e": 7123, "s": 7072, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7127, "s": 7123, "text": "C++" }, { "code": null, "e": 7132, "s": 7127, "text": "Java" }, { "code": null, "e": 7140, "s": 7132, "text": "Python3" }, { "code": null, "e": 7143, "s": 7140, "text": "C#" }, { "code": null, "e": 7154, "s": 7143, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] #include <bits/stdc++.h> using namespace std; const int mod = 1000000007; // DP Tableint dp[1000][1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return calculate(0, n, k, L, R);} // Driver Codeint main(){ int N = 12; int K = 3; int L = 1; int R = 5; cout << countWaystoDivide(N, K, L, R); return 0;}", "e": 8623, "s": 7154, "text": null }, { "code": "// Java implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]class GFG{ static int mod = 1000000007; // DP Tablestatic int [][]dp = new int[1000][1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { dp[i][j] = -1; } } return calculate(0, n, k, L, R);} // Driver Codepublic static void main(String[] args){ int N = 12; int K = 3; int L = 1; int R = 5; System.out.print(countWaystoDivide(N, K, L, R));}} // This code is contributed by 29AjayKumar", "e": 10261, "s": 8623, "text": null }, { "code": "# Python3 implementation to count the# number of ways to divide N in K# groups such that each group# has elements in range [L, R]mod = 1000000007 # DP Tabledp = [[-1 for j in range(1000)] for i in range(1000)] # Function to count the number# of ways to divide the number N# in K groups such that each group# has number of elements in range [L, R]def calculate(pos, left, k, L, R): # Base Case if (pos == k): if (left == 0): return 1 else: return 0 # if N is divides completely # into less than k groups if (left == 0): return 0 # If the subproblem has been # solved, use the value if (dp[pos][left] != -1): return dp[pos][left] answer = 0 # put all possible values # greater equal to prev for i in range(L, R + 1): if (i > left): break answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod dp[pos][left] = answer return answer # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k, L, R): return calculate(0, n, k, L, R) # Driver codeif __name__==\"__main__\": N = 12 K = 3 L = 1 R = 5 print(countWaystoDivide(N, K, L, R)) # This code is contributed by rutvik_56", "e": 11625, "s": 10261, "text": null }, { "code": "// C# implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R]using System;class GFG{ static int mod = 1000000007; // DP Tablestatic int [,]dp = new int[1000, 1000]; // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]static int calculate(int pos, int left, int k, int L, int R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos, left] != -1) return dp[pos, left]; int answer = 0; // Put all possible values // greater equal to prev for(int i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos, left] = answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k, int L, int R){ // Initialize DP Table as -1 for(int i = 0; i < 1000; i++) { for(int j = 0; j < 1000; j++) { dp[i, j] = -1; } } return calculate(0, n, k, L, R);} // Driver Codepublic static void Main(){ int N = 12; int K = 3; int L = 1; int R = 5; Console.Write(countWaystoDivide(N, K, L, R));}} // This code is contributed by Code_Mech", "e": 13264, "s": 11625, "text": null }, { "code": "<script> // JavaScript implementation to count the// number of ways to divide N in K// groups such that each group// has elements in range [L, R] var mod = 1000000007; // DP Tablevar dp = Array.from(Array(1000), ()=>Array(1000)); // Function to count the number// of ways to divide the number N// in K groups such that each group// has number of elements in range [L, R]function calculate(pos, left, k, L, R){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][left] != -1) return dp[pos][left]; var answer = 0; // put all possible values // greater equal to prev for (var i = L; i <= R; i++) { if (i > left) break; answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod; } return dp[pos][left] = answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k, L, R){ // Initialize DP Table as -1 dp = Array.from(Array(1000), ()=>Array(1000).fill(-1)); return calculate(0, n, k, L, R);} // Driver Codevar N = 12;var K = 3;var L = 1;var R = 5;document.write( countWaystoDivide(N, K, L, R)); </script>", "e": 14670, "s": 13264, "text": null }, { "code": null, "e": 14673, "s": 14670, "text": "10" }, { "code": null, "e": 14725, "s": 14675, "text": "Time Complexity: O(N*K).Auxiliary Space: O(N*K). " }, { "code": null, "e": 14739, "s": 14725, "text": "divyamohan123" }, { "code": null, "e": 14754, "s": 14739, "text": "amit143katiyar" }, { "code": null, "e": 14766, "s": 14754, "text": "29AjayKumar" }, { "code": null, "e": 14776, "s": 14766, "text": "Code_Mech" }, { "code": null, "e": 14786, "s": 14776, "text": "rutvik_56" }, { "code": null, "e": 14799, "s": 14786, "text": "Akanksha_Rai" }, { "code": null, "e": 14808, "s": 14799, "text": "noob2000" }, { "code": null, "e": 14817, "s": 14808, "text": "famously" }, { "code": null, "e": 14833, "s": 14817, "text": "pankajsharmagfg" }, { "code": null, "e": 14844, "s": 14833, "text": "Algorithms" }, { "code": null, "e": 14868, "s": 14844, "text": "Competitive Programming" }, { "code": null, "e": 14888, "s": 14868, "text": "Dynamic Programming" }, { "code": null, "e": 14898, "s": 14888, "text": "Recursion" }, { "code": null, "e": 14918, "s": 14898, "text": "Dynamic Programming" }, { "code": null, "e": 14928, "s": 14918, "text": "Recursion" }, { "code": null, "e": 14939, "s": 14928, "text": "Algorithms" }, { "code": null, "e": 15037, "s": 14939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15062, "s": 15037, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 15111, "s": 15062, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 15149, "s": 15111, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 15217, "s": 15149, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 15268, "s": 15217, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 15311, "s": 15268, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 15354, "s": 15311, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 15395, "s": 15354, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 15422, "s": 15395, "text": "Modulo 10^9+7 (1000000007)" } ]
Concurrency Control Techniques
07 Jul, 2022 Concurrency control is provided in a database to: (i) enforce isolation among transactions. (ii) preserve database consistency through consistency preserving execution of transactions. (iii) resolve read-write and write-read conflicts. Various concurrency control techniques are: 1. Two-phase locking Protocol 2. Time stamp ordering Protocol 3. Multi version concurrency control 4. Validation concurrency control These are briefly explained below. 1. Two-Phase Locking Protocol: Locking is an operation which secures: permission to read, OR permission to write a data item. Two phase locking is a process used to gain ownership of shared resources without creating the possibility of deadlock. The 3 activities taking place in the two phase update algorithm are: (i). Lock Acquisition (ii). Modification of Data (iii). Release Lock Two phase locking prevents deadlock from occurring in distributed systems by releasing all the resources it has acquired, if it is not possible to acquire all the resources required without waiting for another process to finish using a lock. This means that no process is ever in a state where it is holding some shared resources, and waiting for another process to release a shared resource which it requires. This means that deadlock cannot occur due to resource contention. A transaction in the Two Phase Locking Protocol can assume one of the 2 phases: (i) Growing Phase: In this phase a transaction can only acquire locks but cannot release any lock. The point when a transaction acquires all the locks it needs is called the Lock Point. (ii) Shrinking Phase: In this phase a transaction can only release locks but cannot acquire any. 2. Time Stamp Ordering Protocol: A timestamp is a tag that can be attached to any transaction or any data item, which denotes a specific time on which the transaction or the data item had been used in any way. A timestamp can be implemented in 2 ways. One is to directly assign the current value of the clock to the transaction or data item. The other is to attach the value of a logical counter that keeps increment as new timestamps are required. The timestamp of a data item can be of 2 types: (i) W-timestamp(X): This means the latest time when the data item X has been written into. (ii) R-timestamp(X): This means the latest time when the data item X has been read from. These 2 timestamps are updated each time a successful read/write operation is performed on the data item X. 3. Multiversion Concurrency Control: Multiversion schemes keep old versions of data item to increase concurrency. Multiversion 2 phase locking: Each successful write results in the creation of a new version of the data item written. Timestamps are used to label the versions. When a read(X) operation is issued, select an appropriate version of X based on the timestamp of the transaction. 4. Validation Concurrency Control: The optimistic approach is based on the assumption that the majority of the database operations do not conflict. The optimistic approach requires neither locking nor time stamping techniques. Instead, a transaction is executed without restrictions until it is committed. Using an optimistic approach, each transaction moves through 2 or 3 phases, referred to as read, validation and write. (i) During read phase, the transaction reads the database, executes the needed computations and makes the updates to a private copy of the database values. All update operations of the transactions are recorded in a temporary update file, which is not accessed by the remaining transactions. (ii) During the validation phase, the transaction is validated to ensure that the changes made will not affect the integrity and consistency of the database. If the validation test is positive, the transaction goes to a write phase. If the validation test is negative, he transaction is restarted and the changes are discarded. (iii) During the write phase, the changes are permanently applied to the database. DBMS-Transactions and Concurrency Control DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index SQL | Views SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Layers of OSI Model Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 104, "s": 54, "text": "Concurrency control is provided in a database to:" }, { "code": null, "e": 146, "s": 104, "text": "(i) enforce isolation among transactions." }, { "code": null, "e": 239, "s": 146, "text": "(ii) preserve database consistency through consistency preserving execution of transactions." }, { "code": null, "e": 290, "s": 239, "text": "(iii) resolve read-write and write-read conflicts." }, { "code": null, "e": 334, "s": 290, "text": "Various concurrency control techniques are:" }, { "code": null, "e": 468, "s": 334, "text": "1. Two-phase locking Protocol\n2. Time stamp ordering Protocol\n3. Multi version concurrency control\n4. Validation concurrency control " }, { "code": null, "e": 818, "s": 468, "text": "These are briefly explained below. 1. Two-Phase Locking Protocol: Locking is an operation which secures: permission to read, OR permission to write a data item. Two phase locking is a process used to gain ownership of shared resources without creating the possibility of deadlock. The 3 activities taking place in the two phase update algorithm are:" }, { "code": null, "e": 888, "s": 818, "text": "(i). Lock Acquisition\n(ii). Modification of Data\n(iii). Release Lock " }, { "code": null, "e": 1445, "s": 888, "text": "Two phase locking prevents deadlock from occurring in distributed systems by releasing all the resources it has acquired, if it is not possible to acquire all the resources required without waiting for another process to finish using a lock. This means that no process is ever in a state where it is holding some shared resources, and waiting for another process to release a shared resource which it requires. This means that deadlock cannot occur due to resource contention. A transaction in the Two Phase Locking Protocol can assume one of the 2 phases:" }, { "code": null, "e": 1631, "s": 1445, "text": "(i) Growing Phase: In this phase a transaction can only acquire locks but cannot release any lock. The point when a transaction acquires all the locks it needs is called the Lock Point." }, { "code": null, "e": 1728, "s": 1631, "text": "(ii) Shrinking Phase: In this phase a transaction can only release locks but cannot acquire any." }, { "code": null, "e": 2225, "s": 1728, "text": "2. Time Stamp Ordering Protocol: A timestamp is a tag that can be attached to any transaction or any data item, which denotes a specific time on which the transaction or the data item had been used in any way. A timestamp can be implemented in 2 ways. One is to directly assign the current value of the clock to the transaction or data item. The other is to attach the value of a logical counter that keeps increment as new timestamps are required. The timestamp of a data item can be of 2 types:" }, { "code": null, "e": 2316, "s": 2225, "text": "(i) W-timestamp(X): This means the latest time when the data item X has been written into." }, { "code": null, "e": 2513, "s": 2316, "text": "(ii) R-timestamp(X): This means the latest time when the data item X has been read from. These 2 timestamps are updated each time a successful read/write operation is performed on the data item X." }, { "code": null, "e": 3328, "s": 2513, "text": "3. Multiversion Concurrency Control: Multiversion schemes keep old versions of data item to increase concurrency. Multiversion 2 phase locking: Each successful write results in the creation of a new version of the data item written. Timestamps are used to label the versions. When a read(X) operation is issued, select an appropriate version of X based on the timestamp of the transaction. 4. Validation Concurrency Control: The optimistic approach is based on the assumption that the majority of the database operations do not conflict. The optimistic approach requires neither locking nor time stamping techniques. Instead, a transaction is executed without restrictions until it is committed. Using an optimistic approach, each transaction moves through 2 or 3 phases, referred to as read, validation and write." }, { "code": null, "e": 3621, "s": 3328, "text": "(i) During read phase, the transaction reads the database, executes the needed computations and makes the updates to a private copy of the database values. All update operations of the transactions are recorded in a temporary update file, which is not accessed by the remaining transactions." }, { "code": null, "e": 3949, "s": 3621, "text": "(ii) During the validation phase, the transaction is validated to ensure that the changes made will not affect the integrity and consistency of the database. If the validation test is positive, the transaction goes to a write phase. If the validation test is negative, he transaction is restarted and the changes are discarded." }, { "code": null, "e": 4032, "s": 3949, "text": "(iii) During the write phase, the changes are permanently applied to the database." }, { "code": null, "e": 4074, "s": 4032, "text": "DBMS-Transactions and Concurrency Control" }, { "code": null, "e": 4079, "s": 4074, "text": "DBMS" }, { "code": null, "e": 4087, "s": 4079, "text": "GATE CS" }, { "code": null, "e": 4092, "s": 4087, "text": "DBMS" }, { "code": null, "e": 4190, "s": 4092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4201, "s": 4190, "text": "CTE in SQL" }, { "code": null, "e": 4254, "s": 4201, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 4266, "s": 4254, "text": "SQL | Views" }, { "code": null, "e": 4290, "s": 4266, "text": "SQL Interview Questions" }, { "code": null, "e": 4335, "s": 4290, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 4355, "s": 4335, "text": "Layers of OSI Model" }, { "code": null, "e": 4382, "s": 4355, "text": "Types of Operating Systems" }, { "code": null, "e": 4395, "s": 4382, "text": "TCP/IP Model" }, { "code": null, "e": 4444, "s": 4395, "text": "Page Replacement Algorithms in Operating Systems" } ]
Ruby | Time now() function
07 Jan, 2020 The now() is an inbuilt method in Ruby returns the current time. Syntax: time.now() Parameters: The function accepts no parameter Return Value: It returns the current time Example 1: # Ruby code for now() method # Include Timerequire 'time' # Declaring time a = Time.now() # Prints current time puts a Output: 2019-08-27 08:26:42 +0000 Example 2: # Ruby code for now() method # Include Timerequire 'time' # Declaring time a = Time.now() # Prints current time puts a Output: 2019-08-27 08:26:42 +0000 Ruby Time-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Ruby | Array slice() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | unless Statement and unless Modifier Ruby | Data Types
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2020" }, { "code": null, "e": 93, "s": 28, "text": "The now() is an inbuilt method in Ruby returns the current time." }, { "code": null, "e": 112, "s": 93, "text": "Syntax: time.now()" }, { "code": null, "e": 158, "s": 112, "text": "Parameters: The function accepts no parameter" }, { "code": null, "e": 200, "s": 158, "text": "Return Value: It returns the current time" }, { "code": null, "e": 211, "s": 200, "text": "Example 1:" }, { "code": "# Ruby code for now() method # Include Timerequire 'time' # Declaring time a = Time.now() # Prints current time puts a", "e": 333, "s": 211, "text": null }, { "code": null, "e": 341, "s": 333, "text": "Output:" }, { "code": null, "e": 368, "s": 341, "text": "2019-08-27 08:26:42 +0000\n" }, { "code": null, "e": 379, "s": 368, "text": "Example 2:" }, { "code": "# Ruby code for now() method # Include Timerequire 'time' # Declaring time a = Time.now() # Prints current time puts a", "e": 501, "s": 379, "text": null }, { "code": null, "e": 509, "s": 501, "text": "Output:" }, { "code": null, "e": 536, "s": 509, "text": "2019-08-27 08:26:42 +0000\n" }, { "code": null, "e": 552, "s": 536, "text": "Ruby Time-class" }, { "code": null, "e": 565, "s": 552, "text": "Ruby-Methods" }, { "code": null, "e": 570, "s": 565, "text": "Ruby" }, { "code": null, "e": 668, "s": 570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 714, "s": 668, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 745, "s": 714, "text": "Ruby | Array count() operation" }, { "code": null, "e": 775, "s": 745, "text": "Ruby | Array slice() function" }, { "code": null, "e": 802, "s": 775, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 826, "s": 802, "text": "Global Variable in Ruby" }, { "code": null, "e": 869, "s": 826, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 891, "s": 869, "text": "Ruby | Case Statement" }, { "code": null, "e": 922, "s": 891, "text": "Ruby | Array select() function" }, { "code": null, "e": 966, "s": 922, "text": "Ruby | unless Statement and unless Modifier" } ]
Python | Converting all strings in list to integers
29 Nov, 2018 Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting. # Python3 code to demonstrate # converting list of strings to int# using naive method # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint ("Original list is : " + str(test_list)) # using naive method to# perform conversionfor i in range(0, len(test_list)): test_list[i] = int(test_list[i]) # Printing modified list print ("Modified list is : " + str(test_list)) Original list is : ['1', '4', '3', '6', '7'] Modified list is : [1, 4, 3, 6, 7] Method #2 : Using list comprehension This is just a kind of replica of the above method, just implemented using list comprehension, kind of shorthand that a developer looks for always. It saves time and complexity of coding a solution. # Python3 code to demonstrate # converting list of strings to int# using list comprehension # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint ("Original list is : " + str(test_list)) # using list comprehension to# perform conversiontest_list = [int(i) for i in test_list] # Printing modified list print ("Modified list is : " + str(test_list)) Original list is : ['1', '4', '3', '6', '7'] Modified list is : [1, 4, 3, 6, 7] Method #3 : Using map() This is the most elegant, pythonic and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them. # Python3 code to demonstrate # converting list of strings to int# using map() # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint ("Original list is : " + str(test_list)) # using map() to# perform conversiontest_list = list(map(int, test_list)) # Printing modified list print ("Modified list is : " + str(test_list)) Original list is : ['1', '4', '3', '6', '7'] Modified list is : [1, 4, 3, 6, 7] Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Nov, 2018" }, { "code": null, "e": 302, "s": 54, "text": "Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem." }, { "code": null, "e": 327, "s": 302, "text": "Method #1 : Naive Method" }, { "code": null, "e": 516, "s": 327, "text": "This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting." }, { "code": "# Python3 code to demonstrate # converting list of strings to int# using naive method # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint (\"Original list is : \" + str(test_list)) # using naive method to# perform conversionfor i in range(0, len(test_list)): test_list[i] = int(test_list[i]) # Printing modified list print (\"Modified list is : \" + str(test_list))", "e": 928, "s": 516, "text": null }, { "code": null, "e": 1009, "s": 928, "text": "Original list is : ['1', '4', '3', '6', '7']\nModified list is : [1, 4, 3, 6, 7]\n" }, { "code": null, "e": 1047, "s": 1009, "text": " Method #2 : Using list comprehension" }, { "code": null, "e": 1246, "s": 1047, "text": "This is just a kind of replica of the above method, just implemented using list comprehension, kind of shorthand that a developer looks for always. It saves time and complexity of coding a solution." }, { "code": "# Python3 code to demonstrate # converting list of strings to int# using list comprehension # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint (\"Original list is : \" + str(test_list)) # using list comprehension to# perform conversiontest_list = [int(i) for i in test_list] # Printing modified list print (\"Modified list is : \" + str(test_list))", "e": 1638, "s": 1246, "text": null }, { "code": null, "e": 1719, "s": 1638, "text": "Original list is : ['1', '4', '3', '6', '7']\nModified list is : [1, 4, 3, 6, 7]\n" }, { "code": null, "e": 1744, "s": 1719, "text": " Method #3 : Using map()" }, { "code": null, "e": 1927, "s": 1744, "text": "This is the most elegant, pythonic and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them." }, { "code": "# Python3 code to demonstrate # converting list of strings to int# using map() # initializing list test_list = ['1', '4', '3', '6', '7'] # Printing original listprint (\"Original list is : \" + str(test_list)) # using map() to# perform conversiontest_list = list(map(int, test_list)) # Printing modified list print (\"Modified list is : \" + str(test_list))", "e": 2291, "s": 1927, "text": null }, { "code": null, "e": 2372, "s": 2291, "text": "Original list is : ['1', '4', '3', '6', '7']\nModified list is : [1, 4, 3, 6, 7]\n" }, { "code": null, "e": 2393, "s": 2372, "text": "Python list-programs" }, { "code": null, "e": 2405, "s": 2393, "text": "python-list" }, { "code": null, "e": 2412, "s": 2405, "text": "Python" }, { "code": null, "e": 2424, "s": 2412, "text": "python-list" }, { "code": null, "e": 2522, "s": 2424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2540, "s": 2522, "text": "Python Dictionary" }, { "code": null, "e": 2582, "s": 2540, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2604, "s": 2582, "text": "Enumerate() in Python" }, { "code": null, "e": 2630, "s": 2604, "text": "Python String | replace()" }, { "code": null, "e": 2662, "s": 2630, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2691, "s": 2662, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2718, "s": 2691, "text": "Python Classes and Objects" }, { "code": null, "e": 2739, "s": 2718, "text": "Python OOPs Concepts" }, { "code": null, "e": 2775, "s": 2739, "text": "Convert integer to string in Python" } ]
Sort ArrayList in Descending Order Using Comparator in Java
11 Dec, 2020 Comparator is an interface that is used to rearrange the ArrayList in a sorted manner. Comparator is used to sort an ArrayList of User-defined objects. In java, a Comparator is provided in java.util package. Using Comparator sort ArrayList on the basis of multiple variables, or simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator override the compare() method provided by the comparator interface. Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order. Change only in the comparison part for descending order. See the difference between both compare() function. Ascending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (s1.Property > s2.Property) return 1; else return -1; } Descending Order public int compare(Item i1, Item i2) { if (i1.Property== i2.Property) return 0; else if (s1.Property < s2.Property) return 1; else return -1; } If there is any need to reorder an ArrayList on the basis of the variable of string type like name, etc. rewrite the compare() function Like below. Ascending Order public int compare(Shop s1, Shop s2) { return s1.name.compareTo(s2.name); } Descending Order public int compare(Shop s1, Shop s2) { return s2.name.compareTo(s1.name); } Example: Java // Java Program to sort the ArrayList // in descending order using comparatorimport java.util.*; // create the Laptop classclass Laptop { int ModalNo; String name; int ram; Laptop(int ModalNo, String name, int ram) { this.ModalNo = ModalNo; this.name = name; this.ram = ram; }} // creates the comparator for comparing RAMclass RamComparator implements Comparator<Laptop> { // override the compare() method public int compare(Laptop l1, Laptop l2) { if (l1.ram == l2.ram) { return 0; } else if (l1.ram < l2.ram) { return 1; } else { return -1; } }} class GFG { public static void main(String[] args) { // create the ArrayList object ArrayList<Laptop> l = new ArrayList<Laptop>(); l.add(new Laptop(322, "Dell", 2)); l.add(new Laptop(342, "Asus", 8)); l.add(new Laptop(821, "HP", 16)); l.add(new Laptop(251, "Lenovo", 6)); l.add(new Laptop(572, "Acer", 4)); System.out.println("before sorting"); System.out.println("Ram" + " " + "Name" + " " + "ModalNo"); for (Laptop laptop : l) { System.out.println(laptop.ram + " " + laptop.name + " " + laptop.ModalNo); } System.out.println(); System.out.println("After sorting(sorted by Ram)"); System.out.println("Ram" + " " + "Name" + " " + "ModalNo"); // call the sort function Collections.sort(l, new RamComparator()); for (Laptop laptop : l) { System.out.println(laptop.ram + " " + laptop.name + " " + laptop.ModalNo); } }} before sorting Ram Name ModalNo 2 Dell 322 8 Asus 342 16 HP 821 6 Lenovo 251 4 Acer 572 After sorting(sorted by Ram) Ram Name ModalNo 16 HP 821 8 Asus 342 6 Lenovo 251 4 Acer 572 2 Dell 322 Java-ArrayList Java-Comparator 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. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 493, "s": 28, "text": "Comparator is an interface that is used to rearrange the ArrayList in a sorted manner. Comparator is used to sort an ArrayList of User-defined objects. In java, a Comparator is provided in java.util package. Using Comparator sort ArrayList on the basis of multiple variables, or simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator override the compare() method provided by the comparator interface. " }, { "code": null, "e": 728, "s": 493, "text": "Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order. Change only in the comparison part for descending order. See the difference between both compare() function." }, { "code": null, "e": 1190, "s": 728, "text": "Ascending Order\npublic int compare(Item i1, Item i2)\n {\n if (i1.Property== i2.Property)\n return 0;\n else if (s1.Property > s2.Property)\n return 1;\n else\n return -1;\n }\n \nDescending Order\npublic int compare(Item i1, Item i2)\n {\n if (i1.Property== i2.Property)\n return 0;\n else if (s1.Property < s2.Property)\n return 1;\n else\n return -1;\n }" }, { "code": null, "e": 1338, "s": 1190, "text": "If there is any need to reorder an ArrayList on the basis of the variable of string type like name, etc. rewrite the compare() function Like below." }, { "code": null, "e": 1560, "s": 1338, "text": "Ascending Order\npublic int compare(Shop s1, Shop s2)\n {\n return s1.name.compareTo(s2.name);\n }\n \nDescending Order\npublic int compare(Shop s1, Shop s2)\n {\n return s2.name.compareTo(s1.name);\n }" }, { "code": null, "e": 1569, "s": 1560, "text": "Example:" }, { "code": null, "e": 1574, "s": 1569, "text": "Java" }, { "code": "// Java Program to sort the ArrayList // in descending order using comparatorimport java.util.*; // create the Laptop classclass Laptop { int ModalNo; String name; int ram; Laptop(int ModalNo, String name, int ram) { this.ModalNo = ModalNo; this.name = name; this.ram = ram; }} // creates the comparator for comparing RAMclass RamComparator implements Comparator<Laptop> { // override the compare() method public int compare(Laptop l1, Laptop l2) { if (l1.ram == l2.ram) { return 0; } else if (l1.ram < l2.ram) { return 1; } else { return -1; } }} class GFG { public static void main(String[] args) { // create the ArrayList object ArrayList<Laptop> l = new ArrayList<Laptop>(); l.add(new Laptop(322, \"Dell\", 2)); l.add(new Laptop(342, \"Asus\", 8)); l.add(new Laptop(821, \"HP\", 16)); l.add(new Laptop(251, \"Lenovo\", 6)); l.add(new Laptop(572, \"Acer\", 4)); System.out.println(\"before sorting\"); System.out.println(\"Ram\" + \" \" + \"Name\" + \" \" + \"ModalNo\"); for (Laptop laptop : l) { System.out.println(laptop.ram + \" \" + laptop.name + \" \" + laptop.ModalNo); } System.out.println(); System.out.println(\"After sorting(sorted by Ram)\"); System.out.println(\"Ram\" + \" \" + \"Name\" + \" \" + \"ModalNo\"); // call the sort function Collections.sort(l, new RamComparator()); for (Laptop laptop : l) { System.out.println(laptop.ram + \" \" + laptop.name + \" \" + laptop.ModalNo); } }}", "e": 3558, "s": 1574, "text": null }, { "code": null, "e": 3749, "s": 3558, "text": "before sorting\nRam Name ModalNo\n2 Dell 322\n8 Asus 342\n16 HP 821\n6 Lenovo 251\n4 Acer 572\n\nAfter sorting(sorted by Ram)\nRam Name ModalNo\n16 HP 821\n8 Asus 342\n6 Lenovo 251\n4 Acer 572\n2 Dell 322" }, { "code": null, "e": 3764, "s": 3749, "text": "Java-ArrayList" }, { "code": null, "e": 3780, "s": 3764, "text": "Java-Comparator" }, { "code": null, "e": 3787, "s": 3780, "text": "Picked" }, { "code": null, "e": 3811, "s": 3787, "text": "Technical Scripter 2020" }, { "code": null, "e": 3816, "s": 3811, "text": "Java" }, { "code": null, "e": 3830, "s": 3816, "text": "Java Programs" }, { "code": null, "e": 3849, "s": 3830, "text": "Technical Scripter" }, { "code": null, "e": 3854, "s": 3849, "text": "Java" }, { "code": null, "e": 3952, "s": 3854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3967, "s": 3952, "text": "Stream In Java" }, { "code": null, "e": 3988, "s": 3967, "text": "Introduction to Java" }, { "code": null, "e": 4009, "s": 3988, "text": "Constructors in Java" }, { "code": null, "e": 4028, "s": 4009, "text": "Exceptions in Java" }, { "code": null, "e": 4045, "s": 4028, "text": "Generics in Java" }, { "code": null, "e": 4071, "s": 4045, "text": "Java Programming Examples" }, { "code": null, "e": 4105, "s": 4071, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 4152, "s": 4105, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4190, "s": 4152, "text": "Factory method design pattern in Java" } ]
Longest Path with Same Values in a Binary Tree
08 Feb, 2022 Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. The length of path between two nodes is represented by the number of edges between them.Examples: Input : 2 / \ 7 2 / \ \ 1 1 2 Output : 2 Input : 4 / \ 4 4 / \ \ 4 9 5 Output : 3 The idea is to recursively traverse given binary tree. We can think of any path (of nodes with the same values) in up to two directions(left and right) from it’s root. Then, for each node, we want to know what is the longest possible length extending in the left and the longest possible length extending in the right directions. The longest length that extends from the node will be 1 + length(node->left) if node->left exists, and has the same value as node. Similarly for the node->right case.While we are computing lengths, each candidate answer will be the sum of the lengths in both directions from that node. We keep updating these answers and return the maximum one. C++ Java Python3 C# Javascript // C++ program to find the length of longest// path with same values in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Function to print the longest path of same values */int length(Node *node, int *ans) { if (!node) return 0; // Recursive calls to check for subtrees int left = length(node->left, ans); int right = length(node->right, ans); // Variables to store maximum lengths in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child has same value if (node->left && node->left->val == node->val) Leftmax += left + 1; // If curr node and it's right child has same value if (node->right && node->right->val == node->val) Rightmax += right + 1; *ans = max(*ans, Leftmax + Rightmax); return max(Leftmax, Rightmax);} /* Driver function to find length of longest same value path*/int longestSameValuePath(Node *root) { int ans = 0; length(root, &ans); return ans;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node *newNode(int data) { Node *temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main() { /* Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 */ Node *root = NULL; root = newNode(4); root->left = newNode(4); root->right = newNode(4); root->left->left = newNode(4); root->left->right = newNode(9); root->right->right = newNode(5); cout << longestSameValuePath(root); return 0;} // Java program to find the length of longest// path with same values in a binary tree.class GFG{static int ans; /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node{ int val; Node left, right;}; /* Function to print the longest pathof same values */static int length(Node node){ if (node == null) return 0; // Recursive calls to check for subtrees int left = length(node.left); int right = length(node.right); // Variables to store maximum lengths // in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.max(ans, Leftmax + Rightmax); return Math.max(Leftmax, Rightmax);} // Function to find length of// longest same value pathstatic int longestSameValuePath(Node root){ ans = 0; length(root); return ans;} /* Helper function that allocates anew node with the given data andnull left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 */ Node root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); System.out.print(longestSameValuePath(root));}} // This code is contributed by PrinciRaj1992 # Python3 program to find the length of longest# path with same values in a binary tree. # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Function to print the longest path# of same valuesdef length(node, ans): if (not node): return 0 # Recursive calls to check for subtrees left = length(node.left, ans) right = length(node.right, ans) # Variables to store maximum lengths # in two directions Leftmax = 0 Rightmax = 0 # If curr node and it's left child has same value if (node.left and node.left.val == node.val): Leftmax += left + 1 # If curr node and it's right child has same value if (node.right and node.right.val == node.val): Rightmax += right + 1 ans[0] = max(ans[0], Leftmax + Rightmax) return max(Leftmax, Rightmax) # Driver function to find length of# longest same value pathdef longestSameValuePath(root): ans = [0] length(root, ans) return ans[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \ # 4 4 # / \ \ # 4 9 5 root = None root = newNode(4) root.left = newNode(4) root.right = newNode(4) root.left.left = newNode(4) root.left.right = newNode(9) root.right.right = newNode(5) print(longestSameValuePath(root)) # This code is contributed by PranchalK // C# program to find the length of longest// path with same values in a binary tree.using System; class GFG{static int ans; /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;}; /* Function to print the longest pathof same values */static int length(Node node){ if (node == null) return 0; // Recursive calls to check for subtrees int left = length(node.left); int right = length(node.right); // Variables to store maximum lengths // in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.Max(ans, Leftmax + Rightmax); return Math.Max(Leftmax, Rightmax);} // Function to find length of// longest same value pathstatic int longestSameValuePath(Node root){ ans = 0; length(root); return ans;} /* Helper function that allocates anew node with the given data andnull left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 */ Node root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); Console.Write(longestSameValuePath(root));}} // This code is contributed by 29AjayKumar <script> // JavaScript program to find the length of longest // path with same values in a binary tree. let ans; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.left = null; this.right = null; this.val = data; } } /* Function to print the longest path of same values */ function length(node) { if (node == null) return 0; // Recursive calls to check for subtrees let left = length(node.left); let right = length(node.right); // Variables to store maximum lengths // in two directions let Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.max(ans, Leftmax + Rightmax); return Math.max(Leftmax, Rightmax); } // Function to find length of // longest same value path function longestSameValuePath(root) { ans = 0; length(root); return ans; } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function newNode(data) { let temp = new Node(data); temp.val = data; temp.left = temp.right = null; return temp; } /* Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 */ let root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); document.write(longestSameValuePath(root)); </script> Output: 3 Complexity Analysis: Time complexity: O(n), where n is the number of nodes in tree as every node is processed once. Auxiliary Space: O(h), where h is the height of tree as recursion can go upto depth h. PranchalKatiyar princiraj1992 29AjayKumar nidhi_biet divyesh072019 simmytarika5 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 Decision Tree Construct Tree from given Inorder and Preorder traversals Diagonal Traversal of Binary Tree Insertion in a Binary Tree in level order Print Left View of a Binary Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Feb, 2022" }, { "code": null, "e": 305, "s": 52, "text": "Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. The length of path between two nodes is represented by the number of edges between them.Examples: " }, { "code": null, "e": 524, "s": 305, "text": "Input :\n 2\n / \\\n 7 2\n / \\ \\\n 1 1 2\nOutput : 2\n\nInput :\n 4\n / \\\n 4 4\n / \\ \\\n 4 9 5\nOutput : 3" }, { "code": null, "e": 1203, "s": 526, "text": "The idea is to recursively traverse given binary tree. We can think of any path (of nodes with the same values) in up to two directions(left and right) from it’s root. Then, for each node, we want to know what is the longest possible length extending in the left and the longest possible length extending in the right directions. The longest length that extends from the node will be 1 + length(node->left) if node->left exists, and has the same value as node. Similarly for the node->right case.While we are computing lengths, each candidate answer will be the sum of the lengths in both directions from that node. We keep updating these answers and return the maximum one. " }, { "code": null, "e": 1207, "s": 1203, "text": "C++" }, { "code": null, "e": 1212, "s": 1207, "text": "Java" }, { "code": null, "e": 1220, "s": 1212, "text": "Python3" }, { "code": null, "e": 1223, "s": 1220, "text": "C#" }, { "code": null, "e": 1234, "s": 1223, "text": "Javascript" }, { "code": "// C++ program to find the length of longest// path with same values in a binary tree.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer toleft child and a pointer to right child */struct Node { int val; struct Node *left, *right;}; /* Function to print the longest path of same values */int length(Node *node, int *ans) { if (!node) return 0; // Recursive calls to check for subtrees int left = length(node->left, ans); int right = length(node->right, ans); // Variables to store maximum lengths in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child has same value if (node->left && node->left->val == node->val) Leftmax += left + 1; // If curr node and it's right child has same value if (node->right && node->right->val == node->val) Rightmax += right + 1; *ans = max(*ans, Leftmax + Rightmax); return max(Leftmax, Rightmax);} /* Driver function to find length of longest same value path*/int longestSameValuePath(Node *root) { int ans = 0; length(root, &ans); return ans;} /* Helper function that allocates anew node with the given data andNULL left and right pointers. */Node *newNode(int data) { Node *temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp;} // Driver codeint main() { /* Let us construct a Binary Tree 4 / \\ 4 4 / \\ \\ 4 9 5 */ Node *root = NULL; root = newNode(4); root->left = newNode(4); root->right = newNode(4); root->left->left = newNode(4); root->left->right = newNode(9); root->right->right = newNode(5); cout << longestSameValuePath(root); return 0;}", "e": 2893, "s": 1234, "text": null }, { "code": "// Java program to find the length of longest// path with same values in a binary tree.class GFG{static int ans; /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node{ int val; Node left, right;}; /* Function to print the longest pathof same values */static int length(Node node){ if (node == null) return 0; // Recursive calls to check for subtrees int left = length(node.left); int right = length(node.right); // Variables to store maximum lengths // in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.max(ans, Leftmax + Rightmax); return Math.max(Leftmax, Rightmax);} // Function to find length of// longest same value pathstatic int longestSameValuePath(Node root){ ans = 0; length(root); return ans;} /* Helper function that allocates anew node with the given data andnull left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = temp.right = null; return temp;} // Driver codepublic static void main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 4 4 / \\ \\ 4 9 5 */ Node root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); System.out.print(longestSameValuePath(root));}} // This code is contributed by PrinciRaj1992", "e": 4720, "s": 2893, "text": null }, { "code": "# Python3 program to find the length of longest# path with same values in a binary tree. # Helper function that allocates a# new node with the given data and# None left and right pointers.class newNode: def __init__(self, data): self.val = data self.left = self.right = None # Function to print the longest path# of same valuesdef length(node, ans): if (not node): return 0 # Recursive calls to check for subtrees left = length(node.left, ans) right = length(node.right, ans) # Variables to store maximum lengths # in two directions Leftmax = 0 Rightmax = 0 # If curr node and it's left child has same value if (node.left and node.left.val == node.val): Leftmax += left + 1 # If curr node and it's right child has same value if (node.right and node.right.val == node.val): Rightmax += right + 1 ans[0] = max(ans[0], Leftmax + Rightmax) return max(Leftmax, Rightmax) # Driver function to find length of# longest same value pathdef longestSameValuePath(root): ans = [0] length(root, ans) return ans[0] # Driver codeif __name__ == '__main__': # Let us construct a Binary Tree # 4 # / \\ # 4 4 # / \\ \\ # 4 9 5 root = None root = newNode(4) root.left = newNode(4) root.right = newNode(4) root.left.left = newNode(4) root.left.right = newNode(9) root.right.right = newNode(5) print(longestSameValuePath(root)) # This code is contributed by PranchalK", "e": 6177, "s": 4720, "text": null }, { "code": "// C# program to find the length of longest// path with same values in a binary tree.using System; class GFG{static int ans; /* A binary tree node has data, pointer toleft child and a pointer to right child */public class Node{ public int val; public Node left, right;}; /* Function to print the longest pathof same values */static int length(Node node){ if (node == null) return 0; // Recursive calls to check for subtrees int left = length(node.left); int right = length(node.right); // Variables to store maximum lengths // in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.Max(ans, Leftmax + Rightmax); return Math.Max(Leftmax, Rightmax);} // Function to find length of// longest same value pathstatic int longestSameValuePath(Node root){ ans = 0; length(root); return ans;} /* Helper function that allocates anew node with the given data andnull left and right pointers. */static Node newNode(int data){ Node temp = new Node(); temp.val = data; temp.left = temp.right = null; return temp;} // Driver codepublic static void Main(String[] args){ /* Let us construct a Binary Tree 4 / \\ 4 4 / \\ \\ 4 9 5 */ Node root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); Console.Write(longestSameValuePath(root));}} // This code is contributed by 29AjayKumar", "e": 8025, "s": 6177, "text": null }, { "code": "<script> // JavaScript program to find the length of longest // path with same values in a binary tree. let ans; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { constructor(data) { this.left = null; this.right = null; this.val = data; } } /* Function to print the longest path of same values */ function length(node) { if (node == null) return 0; // Recursive calls to check for subtrees let left = length(node.left); let right = length(node.right); // Variables to store maximum lengths // in two directions let Leftmax = 0, Rightmax = 0; // If curr node and it's left child // has same value if (node.left != null && node.left.val == node.val) Leftmax += left + 1; // If curr node and it's right child // has same value if (node.right != null && node.right.val == node.val) Rightmax += right + 1; ans = Math.max(ans, Leftmax + Rightmax); return Math.max(Leftmax, Rightmax); } // Function to find length of // longest same value path function longestSameValuePath(root) { ans = 0; length(root); return ans; } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function newNode(data) { let temp = new Node(data); temp.val = data; temp.left = temp.right = null; return temp; } /* Let us construct a Binary Tree 4 / \\ 4 4 / \\ \\ 4 9 5 */ let root = null; root = newNode(4); root.left = newNode(4); root.right = newNode(4); root.left.left = newNode(4); root.left.right = newNode(9); root.right.right = newNode(5); document.write(longestSameValuePath(root)); </script>", "e": 9999, "s": 8025, "text": null }, { "code": null, "e": 10009, "s": 9999, "text": "Output: " }, { "code": null, "e": 10011, "s": 10009, "text": "3" }, { "code": null, "e": 10034, "s": 10011, "text": "Complexity Analysis: " }, { "code": null, "e": 10129, "s": 10034, "text": "Time complexity: O(n), where n is the number of nodes in tree as every node is processed once." }, { "code": null, "e": 10216, "s": 10129, "text": "Auxiliary Space: O(h), where h is the height of tree as recursion can go upto depth h." }, { "code": null, "e": 10234, "s": 10218, "text": "PranchalKatiyar" }, { "code": null, "e": 10248, "s": 10234, "text": "princiraj1992" }, { "code": null, "e": 10260, "s": 10248, "text": "29AjayKumar" }, { "code": null, "e": 10271, "s": 10260, "text": "nidhi_biet" }, { "code": null, "e": 10285, "s": 10271, "text": "divyesh072019" }, { "code": null, "e": 10298, "s": 10285, "text": "simmytarika5" }, { "code": null, "e": 10303, "s": 10298, "text": "Tree" }, { "code": null, "e": 10308, "s": 10303, "text": "Tree" }, { "code": null, "e": 10406, "s": 10308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10438, "s": 10406, "text": "Introduction to Data Structures" }, { "code": null, "e": 10474, "s": 10438, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 10538, "s": 10474, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 10571, "s": 10538, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 10597, "s": 10571, "text": "Diameter of a Binary Tree" }, { "code": null, "e": 10611, "s": 10597, "text": "Decision Tree" }, { "code": null, "e": 10669, "s": 10611, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 10703, "s": 10669, "text": "Diagonal Traversal of Binary Tree" }, { "code": null, "e": 10745, "s": 10703, "text": "Insertion in a Binary Tree in level order" } ]
numpy.invert() in Python
29 Nov, 2018 numpy.invert() function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. Syntax : numpy.invert(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘invert’) Parameters :x : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.**kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional] True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. Return : [ndarray or scalar] Result. This is a scalar if x is scalar. Code #1 : Working # Python program explaining# invert() function import numpy as geekin_num = 10print ("Input number : ", in_num) out_num = geek.invert(in_num) print ("inversion of 10 : ", out_num) Output : Input number : 10 inversion of 10 : -11 Code #2 : # Python program explaining# invert() function import numpy as geek in_arr = [2, 0, 25]print ("Input array : ", in_arr) out_arr = geek.invert(in_arr) print ("Output array after inversion: ", out_arr) Output : Input array : [2, 0, 25] Output array after inversion: [ -3 -1 -26] Code #3 : # Python program explaining# invert() function import numpy as geek in_arr = [True, False]print("Input array : ", in_arr) out_arr = geek.invert(in_arr) print ("Output array after inversion: ", out_arr) Output : Input array : [True, False] Output array after inversion: [False True] Python numpy-Binary Operation 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 ? 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 Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 226, "s": 28, "text": "numpy.invert() function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays." }, { "code": null, "e": 396, "s": 226, "text": "For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value." }, { "code": null, "e": 509, "s": 396, "text": "Syntax : numpy.invert(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘invert’)" }, { "code": null, "e": 1059, "s": 509, "text": "Parameters :x : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.**kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional] True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone." }, { "code": null, "e": 1129, "s": 1059, "text": "Return : [ndarray or scalar] Result. This is a scalar if x is scalar." }, { "code": null, "e": 1147, "s": 1129, "text": "Code #1 : Working" }, { "code": "# Python program explaining# invert() function import numpy as geekin_num = 10print (\"Input number : \", in_num) out_num = geek.invert(in_num) print (\"inversion of 10 : \", out_num) ", "e": 1333, "s": 1147, "text": null }, { "code": null, "e": 1342, "s": 1333, "text": "Output :" }, { "code": null, "e": 1386, "s": 1342, "text": "Input number : 10\ninversion of 10 : -11\n" }, { "code": null, "e": 1397, "s": 1386, "text": " Code #2 :" }, { "code": "# Python program explaining# invert() function import numpy as geek in_arr = [2, 0, 25]print (\"Input array : \", in_arr) out_arr = geek.invert(in_arr) print (\"Output array after inversion: \", out_arr) ", "e": 1603, "s": 1397, "text": null }, { "code": null, "e": 1612, "s": 1603, "text": "Output :" }, { "code": null, "e": 1684, "s": 1612, "text": "Input array : [2, 0, 25]\nOutput array after inversion: [ -3 -1 -26]\n" }, { "code": null, "e": 1695, "s": 1684, "text": " Code #3 :" }, { "code": "# Python program explaining# invert() function import numpy as geek in_arr = [True, False]print(\"Input array : \", in_arr) out_arr = geek.invert(in_arr) print (\"Output array after inversion: \", out_arr) ", "e": 1906, "s": 1695, "text": null }, { "code": null, "e": 1915, "s": 1906, "text": "Output :" }, { "code": null, "e": 1990, "s": 1915, "text": "Input array : [True, False]\nOutput array after inversion: [False True]\n" }, { "code": null, "e": 2020, "s": 1990, "text": "Python numpy-Binary Operation" }, { "code": null, "e": 2033, "s": 2020, "text": "Python-numpy" }, { "code": null, "e": 2040, "s": 2033, "text": "Python" }, { "code": null, "e": 2138, "s": 2040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2170, "s": 2138, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2197, "s": 2170, "text": "Python Classes and Objects" }, { "code": null, "e": 2218, "s": 2197, "text": "Python OOPs Concepts" }, { "code": null, "e": 2241, "s": 2218, "text": "Introduction To PYTHON" }, { "code": null, "e": 2272, "s": 2241, "text": "Python | os.path.join() method" }, { "code": null, "e": 2328, "s": 2272, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2370, "s": 2328, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2412, "s": 2370, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2451, "s": 2412, "text": "Python | Get unique values from a list" } ]
Length of the largest subarray with contiguous elements | Set 1
23 Jun, 2022 Given an array of distinct integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. Examples: Input: arr[] = {10, 12, 11}; Output: Length of the longest contiguous subarray is 3 Input: arr[] = {14, 12, 11, 20}; Output: Length of the longest contiguous subarray is 2 Input: arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; Output: Length of the longest contiguous subarray is 5 We strongly recommend to minimize the browser and try this yourself first. The important thing to note in question is, it is given that all elements are distinct. If all elements are distinct, then a subarray has contiguous elements if and only if the difference between maximum and minimum elements in subarray is equal to the difference between last and first indexes of subarray. So the idea is to keep track of minimum and maximum element in every subarray. The following is the implementation of above idea. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ Java Python3 C# PHP Javascript #include<iostream>using namespace std; // Utility functions to find minimum and maximum of// two elementsint min(int x, int y) { return (x < y)? x : y; }int max(int x, int y) { return (x > y)? x : y; } // Returns length of the longest contiguous subarrayint findLength(int arr[], int n){ int max_len = 1; // Initialize result for (int i=0; i<n-1; i++) { // Initialize min and max for all subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting with i and ending with j for (int j=i+1; j<n; j++) { // Update min and max in this subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all contiguous elements if ((mx - mn) == j-i) max_len = max(max_len, mx-mn+1); } } return max_len; // Return result} // Driver program to test above functionint main(){ int arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Length of the longest contiguous subarray is " << findLength(arr, n); return 0;} class LargestSubArray2 { // Utility functions to find minimum and maximum of // two elements int min(int x, int y) { return (x < y) ? x : y; } int max(int x, int y) { return (x > y) ? x : y; } // Returns length of the longest contiguous subarray int findLength(int arr[], int n) { int max_len = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Initialize min and max for all subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting with i and ending with j for (int j = i + 1; j < n; j++) { // Update min and max in this subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all contiguous elements if ((mx - mn) == j - i) max_len = max(max_len, mx - mn + 1); } } return max_len; // Return result } public static void main(String[] args) { LargestSubArray2 large = new LargestSubArray2(); int arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = arr.length; System.out.println("Length of the longest contiguous subarray is " + large.findLength(arr, n)); }} // This code has been contributed by Mayank Jaiswal # Python3 program to find length# of the longest subarray # Utility functions to find minimum # and maximum of two elementsdef min(x, y): return x if(x < y) else y def max(x, y): return x if(x > y) else y # Returns length of the longest# contiguous subarraydef findLength(arr, n): # Initialize result max_len = 1 for i in range(n - 1): # Initialize min and max for # all subarrays starting with i mn = arr[i] mx = arr[i] # Consider all subarrays starting # with i and ending with j for j in range(i + 1, n): # Update min and max in # this subarray if needed mn = min(mn, arr[j]) mx = max(mx, arr[j]) # If current subarray has # all contiguous elements if ((mx - mn) == j - i): max_len = max(max_len, mx - mn + 1) return max_len # Driver Codearr = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45]n = len(arr)print("Length of the longest contiguous subarray is ", findLength(arr, n)) # This code is contributed by Anant Agarwal. using System; class GFG { // Returns length of the longest // contiguous subarray static int findLength(int []arr, int n) { int max_len = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Initialize min and max for all // subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting // with i and ending with j for (int j = i + 1; j < n; j++) { // Update min and max in this // subarray if needed mn = Math.Min(mn, arr[j]); mx = Math.Max(mx, arr[j]); // If current subarray has all // contiguous elements if ((mx - mn) == j - i) max_len = Math.Max(max_len, mx - mn + 1); } } return max_len; // Return result } public static void Main() { int []arr = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = arr.Length; Console.WriteLine("Length of the longest" + " contiguous subarray is " + findLength(arr, n)); }} // This code is contributed by Sam007. <?php// Utility functions to find minimum // and maximum of two elementsfunction mins($x, $y){ if($x < $y) return $x; else return $y;} function maxi($a, $b){ if($a > $b) return $a; else return $b;} // Returns length of the longest// contiguous subarrayfunction findLength(&$arr, $n){ $max_len = 1; // Initialize result for ($i = 0; $i < $n - 1; $i++) { // Initialize min and max for all // subarrays starting with i $mn = $arr[$i]; $mx = $arr[$i]; // Consider all subarrays starting // with i and ending with j for ($j = $i + 1; $j < $n; $j++) { // Update min and max in this // subarray if needed $mn = mins($mn, $arr[$j]); $mx = maxi($mx, $arr[$j]); // If current subarray has all // contiguous elements if (($mx - $mn) == $j - $i) $max_len = maxi($max_len, $mx - $mn + 1); } } return $max_len; // Return result} // Driver Code$arr = array(1, 56, 58, 57, 90, 92, 94, 93, 91, 45);$n = sizeof($arr);echo ("Length of the longest contiguous" . " subarray is ");echo (findLength($arr, $n)); // This code is contributed // by Shivi_Aggarwal.?> <script> // Utility functions to find minimum // and maximum of two elementsfunction min( x, y) { return (x < y)? x : y; }function max( x, y) { return (x > y)? x : y; } // Returns length of the longest // contiguous subarrayfunction findLength( arr, n){ let max_len = 1; // Initialize result for (let i=0; i<n-1; i++) { // Initialize min and max for all // subarrays starting with i let mn = arr[i], mx = arr[i]; // Consider all subarrays starting // with i and ending with j for (let j=i+1; j<n; j++) { // Update min and max in this // subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all // contiguous elements if ((mx - mn) == j-i) max_len = Math.max(max_len, mx-mn+1); } } return max_len; // Return result} // driver code let arr = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45]; let n = arr.length; document.write("Length of the longest contiguous subarray is " + findLength(arr, n)); </script> Length of the longest contiguous subarray is 5 Time Complexity of the above solution is O(n2). We will soon be covering solution for the problem where duplicate elements are allowed in subarray. Length of the largest subarray with contiguous elements | Set 2 Sam007 Shivi_Aggarwal jana_sayantan hardikkoriintern 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) Introduction to Arrays Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Find Second largest element in an array Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 198, "s": 54, "text": "Given an array of distinct integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. " }, { "code": null, "e": 209, "s": 198, "text": "Examples: " }, { "code": null, "e": 497, "s": 209, "text": "Input: arr[] = {10, 12, 11};\nOutput: Length of the longest contiguous subarray is 3\n\nInput: arr[] = {14, 12, 11, 20};\nOutput: Length of the longest contiguous subarray is 2\n\nInput: arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45};\nOutput: Length of the longest contiguous subarray is 5" }, { "code": null, "e": 572, "s": 497, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 960, "s": 572, "text": "The important thing to note in question is, it is given that all elements are distinct. If all elements are distinct, then a subarray has contiguous elements if and only if the difference between maximum and minimum elements in subarray is equal to the difference between last and first indexes of subarray. So the idea is to keep track of minimum and maximum element in every subarray. " }, { "code": null, "e": 1012, "s": 960, "text": "The following is the implementation of above idea. " }, { "code": null, "e": 1021, "s": 1012, "text": "Chapters" }, { "code": null, "e": 1048, "s": 1021, "text": "descriptions off, selected" }, { "code": null, "e": 1098, "s": 1048, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1121, "s": 1098, "text": "captions off, selected" }, { "code": null, "e": 1129, "s": 1121, "text": "English" }, { "code": null, "e": 1153, "s": 1129, "text": "This is a modal window." }, { "code": null, "e": 1222, "s": 1153, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1244, "s": 1222, "text": "End of dialog window." }, { "code": null, "e": 1248, "s": 1244, "text": "C++" }, { "code": null, "e": 1253, "s": 1248, "text": "Java" }, { "code": null, "e": 1261, "s": 1253, "text": "Python3" }, { "code": null, "e": 1264, "s": 1261, "text": "C#" }, { "code": null, "e": 1268, "s": 1264, "text": "PHP" }, { "code": null, "e": 1279, "s": 1268, "text": "Javascript" }, { "code": "#include<iostream>using namespace std; // Utility functions to find minimum and maximum of// two elementsint min(int x, int y) { return (x < y)? x : y; }int max(int x, int y) { return (x > y)? x : y; } // Returns length of the longest contiguous subarrayint findLength(int arr[], int n){ int max_len = 1; // Initialize result for (int i=0; i<n-1; i++) { // Initialize min and max for all subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting with i and ending with j for (int j=i+1; j<n; j++) { // Update min and max in this subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all contiguous elements if ((mx - mn) == j-i) max_len = max(max_len, mx-mn+1); } } return max_len; // Return result} // Driver program to test above functionint main(){ int arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Length of the longest contiguous subarray is \" << findLength(arr, n); return 0;}", "e": 2435, "s": 1279, "text": null }, { "code": "class LargestSubArray2 { // Utility functions to find minimum and maximum of // two elements int min(int x, int y) { return (x < y) ? x : y; } int max(int x, int y) { return (x > y) ? x : y; } // Returns length of the longest contiguous subarray int findLength(int arr[], int n) { int max_len = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Initialize min and max for all subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting with i and ending with j for (int j = i + 1; j < n; j++) { // Update min and max in this subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all contiguous elements if ((mx - mn) == j - i) max_len = max(max_len, mx - mn + 1); } } return max_len; // Return result } public static void main(String[] args) { LargestSubArray2 large = new LargestSubArray2(); int arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = arr.length; System.out.println(\"Length of the longest contiguous subarray is \" + large.findLength(arr, n)); }} // This code has been contributed by Mayank Jaiswal", "e": 3848, "s": 2435, "text": null }, { "code": "# Python3 program to find length# of the longest subarray # Utility functions to find minimum # and maximum of two elementsdef min(x, y): return x if(x < y) else y def max(x, y): return x if(x > y) else y # Returns length of the longest# contiguous subarraydef findLength(arr, n): # Initialize result max_len = 1 for i in range(n - 1): # Initialize min and max for # all subarrays starting with i mn = arr[i] mx = arr[i] # Consider all subarrays starting # with i and ending with j for j in range(i + 1, n): # Update min and max in # this subarray if needed mn = min(mn, arr[j]) mx = max(mx, arr[j]) # If current subarray has # all contiguous elements if ((mx - mn) == j - i): max_len = max(max_len, mx - mn + 1) return max_len # Driver Codearr = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45]n = len(arr)print(\"Length of the longest contiguous subarray is \", findLength(arr, n)) # This code is contributed by Anant Agarwal.", "e": 5042, "s": 3848, "text": null }, { "code": "using System; class GFG { // Returns length of the longest // contiguous subarray static int findLength(int []arr, int n) { int max_len = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Initialize min and max for all // subarrays starting with i int mn = arr[i], mx = arr[i]; // Consider all subarrays starting // with i and ending with j for (int j = i + 1; j < n; j++) { // Update min and max in this // subarray if needed mn = Math.Min(mn, arr[j]); mx = Math.Max(mx, arr[j]); // If current subarray has all // contiguous elements if ((mx - mn) == j - i) max_len = Math.Max(max_len, mx - mn + 1); } } return max_len; // Return result } public static void Main() { int []arr = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45}; int n = arr.Length; Console.WriteLine(\"Length of the longest\" + \" contiguous subarray is \" + findLength(arr, n)); }} // This code is contributed by Sam007.", "e": 6372, "s": 5042, "text": null }, { "code": "<?php// Utility functions to find minimum // and maximum of two elementsfunction mins($x, $y){ if($x < $y) return $x; else return $y;} function maxi($a, $b){ if($a > $b) return $a; else return $b;} // Returns length of the longest// contiguous subarrayfunction findLength(&$arr, $n){ $max_len = 1; // Initialize result for ($i = 0; $i < $n - 1; $i++) { // Initialize min and max for all // subarrays starting with i $mn = $arr[$i]; $mx = $arr[$i]; // Consider all subarrays starting // with i and ending with j for ($j = $i + 1; $j < $n; $j++) { // Update min and max in this // subarray if needed $mn = mins($mn, $arr[$j]); $mx = maxi($mx, $arr[$j]); // If current subarray has all // contiguous elements if (($mx - $mn) == $j - $i) $max_len = maxi($max_len, $mx - $mn + 1); } } return $max_len; // Return result} // Driver Code$arr = array(1, 56, 58, 57, 90, 92, 94, 93, 91, 45);$n = sizeof($arr);echo (\"Length of the longest contiguous\" . \" subarray is \");echo (findLength($arr, $n)); // This code is contributed // by Shivi_Aggarwal.?>", "e": 7716, "s": 6372, "text": null }, { "code": "<script> // Utility functions to find minimum // and maximum of two elementsfunction min( x, y) { return (x < y)? x : y; }function max( x, y) { return (x > y)? x : y; } // Returns length of the longest // contiguous subarrayfunction findLength( arr, n){ let max_len = 1; // Initialize result for (let i=0; i<n-1; i++) { // Initialize min and max for all // subarrays starting with i let mn = arr[i], mx = arr[i]; // Consider all subarrays starting // with i and ending with j for (let j=i+1; j<n; j++) { // Update min and max in this // subarray if needed mn = min(mn, arr[j]); mx = max(mx, arr[j]); // If current subarray has all // contiguous elements if ((mx - mn) == j-i) max_len = Math.max(max_len, mx-mn+1); } } return max_len; // Return result} // driver code let arr = [1, 56, 58, 57, 90, 92, 94, 93, 91, 45]; let n = arr.length; document.write(\"Length of the longest contiguous subarray is \" + findLength(arr, n)); </script>", "e": 8860, "s": 7716, "text": null }, { "code": null, "e": 8907, "s": 8860, "text": "Length of the longest contiguous subarray is 5" }, { "code": null, "e": 8955, "s": 8907, "text": "Time Complexity of the above solution is O(n2)." }, { "code": null, "e": 9055, "s": 8955, "text": "We will soon be covering solution for the problem where duplicate elements are allowed in subarray." }, { "code": null, "e": 9120, "s": 9055, "text": "Length of the largest subarray with contiguous elements | Set 2 " }, { "code": null, "e": 9127, "s": 9120, "text": "Sam007" }, { "code": null, "e": 9142, "s": 9127, "text": "Shivi_Aggarwal" }, { "code": null, "e": 9156, "s": 9142, "text": "jana_sayantan" }, { "code": null, "e": 9173, "s": 9156, "text": "hardikkoriintern" }, { "code": null, "e": 9180, "s": 9173, "text": "Arrays" }, { "code": null, "e": 9187, "s": 9180, "text": "Arrays" }, { "code": null, "e": 9285, "s": 9187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9353, "s": 9285, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9397, "s": 9353, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9429, "s": 9397, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9477, "s": 9429, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 9500, "s": 9477, "text": "Introduction to Arrays" }, { "code": null, "e": 9514, "s": 9500, "text": "Linear Search" }, { "code": null, "e": 9570, "s": 9514, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9610, "s": 9570, "text": "Find Second largest element in an array" }, { "code": null, "e": 9642, "s": 9610, "text": "Introduction to Data Structures" } ]
Number of subsets with sum divisible by M | Set 2
13 May, 2021 Given an array arr[] of N integers and an integer M, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by M. Examples: Input: arr[] = {1, 2, 3}, M = 1 Output: 7 Number of non-empty subsets of this array are 7. Since m = 1, m will divide all the possible subsets.Input: arr[] = {1, 2, 3}, M = 2 Output: 3 Approach: A dynamic programming-based approach with O(N * SUM) time complexity where N is the length of the array and SUM is the sum of all the array elements has been discussed in this article.In this article, an improvement over the previous approach will be discussed. Instead of the sum as one of the states of DP, (sum % m) will be used as one of the states of the DP as it is sufficient. Thus, the time complexity boils down to O(m * N).Recurrence relation: dp[i][curr] = dp[i + 1][(curr + arr[i]) % m] + dp[i + 1][curr] Let’s define the states now, dp[i][curr] simply means number of subsets of the sub-array arr[i...N-1] such that (sum of its element + curr) % m = 0. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define maxN 20#define maxM 10 // To store the states of DPint dp[maxN][maxM];bool v[maxN][maxM]; // Function to find the required countint findCnt(int* arr, int i, int curr, int n, int m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = 1; // Recurrence relation return dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m);} // Driver codeint main(){ int arr[] = { 3, 3, 3, 3 }; int n = sizeof(arr) / sizeof(int); int m = 6; cout << findCnt(arr, 0, 0, n, m) - 1; return 0;} // Java implementation of the approachclass GFG{static int maxN = 20;static int maxM = 10; // To store the states of DPstatic int [][]dp = new int[maxN][maxM];static boolean [][]v = new boolean[maxN][maxM]; // Function to find the required countstatic int findCnt(int[] arr, int i, int curr, int n, int m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = true; // Recurrence relation return dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m);} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 3, 3 }; int n = arr.length; int m = 6; System.out.println(findCnt(arr, 0, 0, n, m) - 1);}} // This code is contributed by 29AjayKumar # Python3 implementation of the approachmaxN = 20maxM = 10 # To store the states of DPdp = [[0 for i in range(maxN)] for i in range(maxM)]v = [[0 for i in range(maxN)] for i in range(maxM)] # Function to find the required countdef findCnt(arr, i, curr, n, m): # Base case if (i == n): if (curr == 0): return 1 else: return 0 # If the state has been solved before # return the value of the state if (v[i][curr]): return dp[i][curr] # Setting the state as solved v[i][curr] = 1 # Recurrence relation dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + \ findCnt(arr, i + 1, (curr + arr[i]) % m, n, m) return dp[i][curr] # Driver codearr = [3, 3, 3, 3]n = len(arr)m = 6 print(findCnt(arr, 0, 0, n, m) - 1) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ static int maxN = 20; static int maxM = 10; // To store the states of DP static int [,]dp = new int[maxN, maxM]; static bool [,]v = new bool[maxN, maxM]; // Function to find the required count static int findCnt(int[] arr, int i, int curr, int n, int m) { // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i, curr]) return dp[i, curr]; // Setting the state as solved v[i, curr] = true; // Recurrence relation return dp[i, curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m); } // Driver code public static void Main() { int []arr = { 3, 3, 3, 3 }; int n = arr.Length; int m = 6; Console.WriteLine(findCnt(arr, 0, 0, n, m) - 1); }} // This code is contributed by kanugargng <script> // Javascript implementation of the approachvar maxN = 20var maxM = 10 // To store the states of DPvar dp = Array.from(Array(maxN), () => Array(maxM));var v = Array.from(Array(maxN), () => Array(maxM)); // Function to find the required countfunction findCnt(arr, i, curr, n, m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = 1; // Recurrence relation dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m); return dp[i][curr];} // Driver codevar arr = [3, 3, 3, 3];var n = arr.length;var m = 6;document.write( findCnt(arr, 0, 0, n, m) - 1); </script> 7 mohit kumar 29 29AjayKumar kanugargng itsok divisibility subset Arrays Combinatorial Dynamic Programming Arrays Dynamic Programming subset Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 52, "s": 24, "text": "\n13 May, 2021" }, { "code": null, "e": 218, "s": 52, "text": "Given an array arr[] of N integers and an integer M, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by M." }, { "code": null, "e": 230, "s": 218, "text": "Examples: " }, { "code": null, "e": 417, "s": 230, "text": "Input: arr[] = {1, 2, 3}, M = 1 Output: 7 Number of non-empty subsets of this array are 7. Since m = 1, m will divide all the possible subsets.Input: arr[] = {1, 2, 3}, M = 2 Output: 3 " }, { "code": null, "e": 882, "s": 417, "text": "Approach: A dynamic programming-based approach with O(N * SUM) time complexity where N is the length of the array and SUM is the sum of all the array elements has been discussed in this article.In this article, an improvement over the previous approach will be discussed. Instead of the sum as one of the states of DP, (sum % m) will be used as one of the states of the DP as it is sufficient. Thus, the time complexity boils down to O(m * N).Recurrence relation: " }, { "code": null, "e": 947, "s": 882, "text": "dp[i][curr] = dp[i + 1][(curr + arr[i]) % m] + dp[i + 1][curr] " }, { "code": null, "e": 1096, "s": 947, "text": "Let’s define the states now, dp[i][curr] simply means number of subsets of the sub-array arr[i...N-1] such that (sum of its element + curr) % m = 0." }, { "code": null, "e": 1149, "s": 1096, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1153, "s": 1149, "text": "C++" }, { "code": null, "e": 1158, "s": 1153, "text": "Java" }, { "code": null, "e": 1166, "s": 1158, "text": "Python3" }, { "code": null, "e": 1169, "s": 1166, "text": "C#" }, { "code": null, "e": 1180, "s": 1169, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define maxN 20#define maxM 10 // To store the states of DPint dp[maxN][maxM];bool v[maxN][maxM]; // Function to find the required countint findCnt(int* arr, int i, int curr, int n, int m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = 1; // Recurrence relation return dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m);} // Driver codeint main(){ int arr[] = { 3, 3, 3, 3 }; int n = sizeof(arr) / sizeof(int); int m = 6; cout << findCnt(arr, 0, 0, n, m) - 1; return 0;}", "e": 2168, "s": 1180, "text": null }, { "code": "// Java implementation of the approachclass GFG{static int maxN = 20;static int maxM = 10; // To store the states of DPstatic int [][]dp = new int[maxN][maxM];static boolean [][]v = new boolean[maxN][maxM]; // Function to find the required countstatic int findCnt(int[] arr, int i, int curr, int n, int m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = true; // Recurrence relation return dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m);} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 3, 3, 3 }; int n = arr.length; int m = 6; System.out.println(findCnt(arr, 0, 0, n, m) - 1);}} // This code is contributed by 29AjayKumar", "e": 3266, "s": 2168, "text": null }, { "code": "# Python3 implementation of the approachmaxN = 20maxM = 10 # To store the states of DPdp = [[0 for i in range(maxN)] for i in range(maxM)]v = [[0 for i in range(maxN)] for i in range(maxM)] # Function to find the required countdef findCnt(arr, i, curr, n, m): # Base case if (i == n): if (curr == 0): return 1 else: return 0 # If the state has been solved before # return the value of the state if (v[i][curr]): return dp[i][curr] # Setting the state as solved v[i][curr] = 1 # Recurrence relation dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + \\ findCnt(arr, i + 1, (curr + arr[i]) % m, n, m) return dp[i][curr] # Driver codearr = [3, 3, 3, 3]n = len(arr)m = 6 print(findCnt(arr, 0, 0, n, m) - 1) # This code is contributed by Mohit Kumar", "e": 4169, "s": 3266, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int maxN = 20; static int maxM = 10; // To store the states of DP static int [,]dp = new int[maxN, maxM]; static bool [,]v = new bool[maxN, maxM]; // Function to find the required count static int findCnt(int[] arr, int i, int curr, int n, int m) { // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i, curr]) return dp[i, curr]; // Setting the state as solved v[i, curr] = true; // Recurrence relation return dp[i, curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m); } // Driver code public static void Main() { int []arr = { 3, 3, 3, 3 }; int n = arr.Length; int m = 6; Console.WriteLine(findCnt(arr, 0, 0, n, m) - 1); }} // This code is contributed by kanugargng", "e": 5400, "s": 4169, "text": null }, { "code": "<script> // Javascript implementation of the approachvar maxN = 20var maxM = 10 // To store the states of DPvar dp = Array.from(Array(maxN), () => Array(maxM));var v = Array.from(Array(maxN), () => Array(maxM)); // Function to find the required countfunction findCnt(arr, i, curr, n, m){ // Base case if (i == n) { if (curr == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][curr]) return dp[i][curr]; // Setting the state as solved v[i][curr] = 1; // Recurrence relation dp[i][curr] = findCnt(arr, i + 1, curr, n, m) + findCnt(arr, i + 1, (curr + arr[i]) % m, n, m); return dp[i][curr];} // Driver codevar arr = [3, 3, 3, 3];var n = arr.length;var m = 6;document.write( findCnt(arr, 0, 0, n, m) - 1); </script>", "e": 6379, "s": 5400, "text": null }, { "code": null, "e": 6381, "s": 6379, "text": "7" }, { "code": null, "e": 6398, "s": 6383, "text": "mohit kumar 29" }, { "code": null, "e": 6410, "s": 6398, "text": "29AjayKumar" }, { "code": null, "e": 6421, "s": 6410, "text": "kanugargng" }, { "code": null, "e": 6427, "s": 6421, "text": "itsok" }, { "code": null, "e": 6440, "s": 6427, "text": "divisibility" }, { "code": null, "e": 6447, "s": 6440, "text": "subset" }, { "code": null, "e": 6454, "s": 6447, "text": "Arrays" }, { "code": null, "e": 6468, "s": 6454, "text": "Combinatorial" }, { "code": null, "e": 6488, "s": 6468, "text": "Dynamic Programming" }, { "code": null, "e": 6495, "s": 6488, "text": "Arrays" }, { "code": null, "e": 6515, "s": 6495, "text": "Dynamic Programming" }, { "code": null, "e": 6522, "s": 6515, "text": "subset" }, { "code": null, "e": 6536, "s": 6522, "text": "Combinatorial" }, { "code": null, "e": 6634, "s": 6536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6666, "s": 6634, "text": "Introduction to Data Structures" }, { "code": null, "e": 6713, "s": 6666, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 6738, "s": 6713, "text": "Window Sliding Technique" }, { "code": null, "e": 6769, "s": 6738, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 6827, "s": 6769, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 6887, "s": 6827, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6925, "s": 6887, "text": "Permutation and Combination in Python" }, { "code": null, "e": 6953, "s": 6925, "text": "Factorial of a large number" }, { "code": null, "e": 6990, "s": 6953, "text": "Count of subsets with sum equal to X" } ]
Valid variants of main() in Java
11 May, 2022 We know that a Java code begins to execute from the main method. During runtime, if JVM can’t find any main method then we will get a runtime exception: No such Method Error: Main method not found in class, please define the main method as: public static void main(String[] args) to avoid this problem there should be the main method. We also know that the java main method has a particular prototype, which looks like: public static void main(String[] args) Even though the above syntax(prototype) is very strict but some little changes are acceptable. This makes it not so strict that if we perform any change then we will get a runtime exception. We can do several allowed modification to our main method. The following Changes are acceptable. Let’s understand the different variants of main() that are valid. Default prototype: Below is the most common way to write main() in Java. Java class Test{ public static void main(String[] args) { System.out.println("Main Method"); }} Output: Main Method Meaning of the main Syntax: public: JVM can execute the method from anywhere. static: Main method can be called without object. void: The main method doesn't return anything. main(): Name configured in the JVM. String[]: Accepts the command line arguments. args:- the name of the String array is args. Order of Modifiers: We can swap positions of static and public in main(). Java //Java code to understand that The Order of Modifiers don't mattersclass Test{ static public void main(String[] args) { System.out.println("Main Method"); }} Output: Main Method Variants of String array arguments: We can place square brackets at different positions for string parameter. Java class Test{ public static void main(String[] args) { System.out.println("Main Method"); }} Output: Main Method Java class Test{ public static void main(String []args) { System.out.println("Main Method"); }} Output: Main Method Java class Test{ public static void main(String args[]) { System.out.println("Main Method"); }} Output: Main Method Args or anything: Instead of args we can write anything which is a valid java identifier. You can write anything here, you can write your name or company’s name or anything you want to write but it must follow the rule of being a java identifier. Example: Java class Gfg{ public static void main(String[] geeksforgeeks){ System.out.println("Instead of args we have written geeksforgeeks"); }} Output: Instead of args we have written geeksforgeeks Var-args instead of String array: According to the rule whenever there is one dimensional array we can replace the array with var-arg parameter.So here we can change our string array using var-args. (the triple dots instead of []) Example: Java //Java code-> using Var-Args instead of the array//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Gfg{ final public static void main(String... args){ System.out.println("Var-args main method"); }} Output: Var-args main method Final Modifier String argument: We can make String args[] as final. Java class Test{ public static void main(final String[] args) { System.out.println("Main Method"); }} Output: Main Method Final main method: We can declare the main method with the final keyword.This cannot change the execution or give any error. Example: Java //Java code having the final main method////please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Gfg{ final public static void main(String[] args){ System.out.println("final main method"); }} Output: final main method synchronized keyword to static main method: We can make main() synchronized. Java //Java code having Synchronized main method//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Test{ public synchronized static void main(String[] args) { System.out.println("Main Method"); }} Output: Main Method strictfp keyword to static main method: strictfp can be used to restrict floating point calculations. Java //Java code-> using strictfp modifier in main method//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Test{ public strictfp static void main(String[] args) { System.out.println("Main Method"); }} Output: Main Method Combinations of all above keyword to static main method: So we can declare the java main method with the following modifiers: Overloading Main method: We can overload main() with different types of parameters. Java class Test{ public static void main(String[] args) { System.out.println("Main Method String Array"); } public static void main(int[] args) { System.out.println("Main Method int Array"); }} Output: Main Method String Array Inheritance of Main method: JVM Executes the main() without any errors. Java class A{ public static void main(String[] args) { System.out.println("Main Method Parent"); }} class B extends A{ } Two class files, A.class and B.class are generated by a compiler. When we execute any of the two .class, JVM executes with no error. O/P: Java A Main Method Parent O/P: Java B Main Method Parent Method Hiding of main(), but not Overriding: Since main() is static, derived class main() hides the base class main. (See Shadowing of static functions for details.) Java class A{ public static void main(String[] args) { System.out.println("Main Method Parent"); }}class B extends A{ public static void main(String[] args) { System.out.println("Main Method Child"); }} Two classes, A.class and B.class are generated by Java Compiler javac. When we execute both the .class, JVM executes with no error. O/P: Java A Main Method Parent O/P: Java B Main Method Child This article is contributed by Mahesh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PinakiBanerjee0 simmytarika5 mitalibhola94 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Interfaces in Java Collections in Java Queue Interface In Java For-each loop in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 229, "s": 52, "text": "We know that a Java code begins to execute from the main method. During runtime, if JVM can’t find any main method then we will get a runtime exception: No such Method Error: " }, { "code": null, "e": 335, "s": 229, "text": "Main method not found in class, please define the main method as:\npublic static void main(String[] args) " }, { "code": null, "e": 477, "s": 335, "text": "to avoid this problem there should be the main method. We also know that the java main method has a particular prototype, which looks like: " }, { "code": null, "e": 516, "s": 477, "text": "public static void main(String[] args)" }, { "code": null, "e": 872, "s": 516, "text": " Even though the above syntax(prototype) is very strict but some little changes are acceptable. This makes it not so strict that if we perform any change then we will get a runtime exception. We can do several allowed modification to our main method. The following Changes are acceptable. Let’s understand the different variants of main() that are valid. " }, { "code": null, "e": 946, "s": 872, "text": "Default prototype: Below is the most common way to write main() in Java. " }, { "code": null, "e": 951, "s": 946, "text": "Java" }, { "code": "class Test{ public static void main(String[] args) { System.out.println(\"Main Method\"); }}", "e": 1058, "s": 951, "text": null }, { "code": null, "e": 1066, "s": 1058, "text": "Output:" }, { "code": null, "e": 1078, "s": 1066, "text": "Main Method" }, { "code": null, "e": 1107, "s": 1078, "text": "Meaning of the main Syntax: " }, { "code": null, "e": 1389, "s": 1107, "text": "public: JVM can execute the method from anywhere.\nstatic: Main method can be called without object.\nvoid: The main method doesn't return anything.\nmain(): Name configured in the JVM.\nString[]: Accepts the command line arguments.\nargs:- the name of the String array is args.\n " }, { "code": null, "e": 1464, "s": 1389, "text": "Order of Modifiers: We can swap positions of static and public in main(). " }, { "code": null, "e": 1469, "s": 1464, "text": "Java" }, { "code": "//Java code to understand that The Order of Modifiers don't mattersclass Test{ static public void main(String[] args) { System.out.println(\"Main Method\"); }}", "e": 1643, "s": 1469, "text": null }, { "code": null, "e": 1651, "s": 1643, "text": "Output:" }, { "code": null, "e": 1663, "s": 1651, "text": "Main Method" }, { "code": null, "e": 1774, "s": 1663, "text": "Variants of String array arguments: We can place square brackets at different positions for string parameter. " }, { "code": null, "e": 1779, "s": 1774, "text": "Java" }, { "code": "class Test{ public static void main(String[] args) { System.out.println(\"Main Method\"); }}", "e": 1886, "s": 1779, "text": null }, { "code": null, "e": 1894, "s": 1886, "text": "Output:" }, { "code": null, "e": 1906, "s": 1894, "text": "Main Method" }, { "code": null, "e": 1911, "s": 1906, "text": "Java" }, { "code": "class Test{ public static void main(String []args) { System.out.println(\"Main Method\"); }}", "e": 2018, "s": 1911, "text": null }, { "code": null, "e": 2026, "s": 2018, "text": "Output:" }, { "code": null, "e": 2038, "s": 2026, "text": "Main Method" }, { "code": null, "e": 2043, "s": 2038, "text": "Java" }, { "code": "class Test{ public static void main(String args[]) { System.out.println(\"Main Method\"); }}", "e": 2150, "s": 2043, "text": null }, { "code": null, "e": 2158, "s": 2150, "text": "Output:" }, { "code": null, "e": 2170, "s": 2158, "text": "Main Method" }, { "code": null, "e": 2427, "s": 2170, "text": "Args or anything: Instead of args we can write anything which is a valid java identifier. You can write anything here, you can write your name or company’s name or anything you want to write but it must follow the rule of being a java identifier. Example: " }, { "code": null, "e": 2432, "s": 2427, "text": "Java" }, { "code": "class Gfg{ public static void main(String[] geeksforgeeks){ System.out.println(\"Instead of args we have written geeksforgeeks\"); }}", "e": 2591, "s": 2432, "text": null }, { "code": null, "e": 2600, "s": 2591, "text": "Output: " }, { "code": null, "e": 2646, "s": 2600, "text": "Instead of args we have written geeksforgeeks" }, { "code": null, "e": 2887, "s": 2646, "text": "Var-args instead of String array: According to the rule whenever there is one dimensional array we can replace the array with var-arg parameter.So here we can change our string array using var-args. (the triple dots instead of []) Example: " }, { "code": null, "e": 2892, "s": 2887, "text": "Java" }, { "code": "//Java code-> using Var-Args instead of the array//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Gfg{ final public static void main(String... args){ System.out.println(\"Var-args main method\"); }}", "e": 3157, "s": 2892, "text": null }, { "code": null, "e": 3166, "s": 3157, "text": "Output: " }, { "code": null, "e": 3187, "s": 3166, "text": "Var-args main method" }, { "code": null, "e": 3256, "s": 3187, "text": "Final Modifier String argument: We can make String args[] as final. " }, { "code": null, "e": 3261, "s": 3256, "text": "Java" }, { "code": "class Test{ public static void main(final String[] args) { System.out.println(\"Main Method\"); }}", "e": 3374, "s": 3261, "text": null }, { "code": null, "e": 3382, "s": 3374, "text": "Output:" }, { "code": null, "e": 3394, "s": 3382, "text": "Main Method" }, { "code": null, "e": 3530, "s": 3394, "text": "Final main method: We can declare the main method with the final keyword.This cannot change the execution or give any error. Example: " }, { "code": null, "e": 3535, "s": 3530, "text": "Java" }, { "code": "//Java code having the final main method////please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Gfg{ final public static void main(String[] args){ System.out.println(\"final main method\"); }}", "e": 3798, "s": 3535, "text": null }, { "code": null, "e": 3807, "s": 3798, "text": "Output: " }, { "code": null, "e": 3825, "s": 3807, "text": "final main method" }, { "code": null, "e": 3903, "s": 3825, "text": "synchronized keyword to static main method: We can make main() synchronized. " }, { "code": null, "e": 3908, "s": 3903, "text": "Java" }, { "code": "//Java code having Synchronized main method//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Test{ public synchronized static void main(String[] args) { System.out.println(\"Main Method\"); }}", "e": 4160, "s": 3908, "text": null }, { "code": null, "e": 4168, "s": 4160, "text": "Output:" }, { "code": null, "e": 4180, "s": 4168, "text": "Main Method" }, { "code": null, "e": 4284, "s": 4180, "text": "strictfp keyword to static main method: strictfp can be used to restrict floating point calculations. " }, { "code": null, "e": 4289, "s": 4284, "text": "Java" }, { "code": "//Java code-> using strictfp modifier in main method//please note these code may not run in gfg IDE, better run it on other IDEs e.g, eclipseclass Test{ public strictfp static void main(String[] args) { System.out.println(\"Main Method\"); }}", "e": 4546, "s": 4289, "text": null }, { "code": null, "e": 4554, "s": 4546, "text": "Output:" }, { "code": null, "e": 4566, "s": 4554, "text": "Main Method" }, { "code": null, "e": 4692, "s": 4566, "text": "Combinations of all above keyword to static main method: So we can declare the java main method with the following modifiers:" }, { "code": null, "e": 4777, "s": 4692, "text": "Overloading Main method: We can overload main() with different types of parameters. " }, { "code": null, "e": 4782, "s": 4777, "text": "Java" }, { "code": "class Test{ public static void main(String[] args) { System.out.println(\"Main Method String Array\"); } public static void main(int[] args) { System.out.println(\"Main Method int Array\"); }}", "e": 5003, "s": 4782, "text": null }, { "code": null, "e": 5011, "s": 5003, "text": "Output:" }, { "code": null, "e": 5036, "s": 5011, "text": "Main Method String Array" }, { "code": null, "e": 5109, "s": 5036, "text": "Inheritance of Main method: JVM Executes the main() without any errors. " }, { "code": null, "e": 5114, "s": 5109, "text": "Java" }, { "code": "class A{ public static void main(String[] args) { System.out.println(\"Main Method Parent\"); }} class B extends A{ }", "e": 5246, "s": 5114, "text": null }, { "code": null, "e": 5380, "s": 5246, "text": "Two class files, A.class and B.class are generated by a compiler. When we execute any of the two .class, JVM executes with no error. " }, { "code": null, "e": 5442, "s": 5380, "text": "O/P: Java A\nMain Method Parent\nO/P: Java B\nMain Method Parent" }, { "code": null, "e": 5609, "s": 5442, "text": "Method Hiding of main(), but not Overriding: Since main() is static, derived class main() hides the base class main. (See Shadowing of static functions for details.) " }, { "code": null, "e": 5614, "s": 5609, "text": "Java" }, { "code": "class A{ public static void main(String[] args) { System.out.println(\"Main Method Parent\"); }}class B extends A{ public static void main(String[] args) { System.out.println(\"Main Method Child\"); }}", "e": 5844, "s": 5614, "text": null }, { "code": null, "e": 5976, "s": 5844, "text": "Two classes, A.class and B.class are generated by Java Compiler javac. When we execute both the .class, JVM executes with no error." }, { "code": null, "e": 6037, "s": 5976, "text": "O/P: Java A\nMain Method Parent\nO/P: Java B\nMain Method Child" }, { "code": null, "e": 6200, "s": 6037, "text": "This article is contributed by Mahesh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 6216, "s": 6200, "text": "PinakiBanerjee0" }, { "code": null, "e": 6229, "s": 6216, "text": "simmytarika5" }, { "code": null, "e": 6243, "s": 6229, "text": "mitalibhola94" }, { "code": null, "e": 6248, "s": 6243, "text": "Java" }, { "code": null, "e": 6253, "s": 6248, "text": "Java" }, { "code": null, "e": 6351, "s": 6253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6366, "s": 6351, "text": "Arrays in Java" }, { "code": null, "e": 6417, "s": 6366, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6453, "s": 6417, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6497, "s": 6453, "text": "Split() String method in Java with examples" }, { "code": null, "e": 6522, "s": 6497, "text": "Reverse a string in Java" }, { "code": null, "e": 6541, "s": 6522, "text": "Interfaces in Java" }, { "code": null, "e": 6561, "s": 6541, "text": "Collections in Java" }, { "code": null, "e": 6585, "s": 6561, "text": "Queue Interface In Java" }, { "code": null, "e": 6607, "s": 6585, "text": "For-each loop in Java" } ]
Quick way to check if all the characters of a string are same
20 Jun, 2022 Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks" Output : No Input : s = "gggg" Output : Yes Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop. C++ Java Python3 C# PHP Javascript // C++ program to find whether the string// has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){ int n = s.length(); for (int i = 1; i < n; i++) if (s[i] != s[0]) return false; return true;} // Driver codeint main(){ string s = "aaa"; if (allCharactersSame(s)) cout << "Yes"; else cout << "No"; return 0;} // Java program to find whether the String// has all same characters or not.import java.io.*; public class GFG{ static boolean allCharactersSame(String s){ int n = s.length(); for (int i = 1; i < n; i++) if (s.charAt(i) != s.charAt(0)) return false; return true;} // Driver code static public void main (String[] args){ String s = "aaa"; if (allCharactersSame(s)) System.out.println("Yes"); else System.out.println("No"); }} // This Code is contributed by vt_m. # Python3 program to find whether the string# has all same characters or not. # Function to check the string has# all same characters or not .def allCharactersSame(s) : n = len(s) for i in range(1, n) : if s[i] != s[0] : return False return True # Driver codeif __name__ == "__main__" : s = "aaa" if allCharactersSame(s) : print("Yes") else : print("No") # This code is contributed by ANKITRAI1 // C# program to find whether the string// has all same characters or not.using System; public class GFG{ static bool allCharactersSame(string s){ int n = s.Length; for (int i = 1; i < n; i++) if (s[i] != s[0]) return false; return true;} // Driver code static public void Main (String []args){ string s = "aaa"; if (allCharactersSame(s)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP program to find whether// the string has all same// characters or not.function allCharactersSame($s){ $n = strlen($s); for ($i = 1; $i < $n; $i++) if ($s[$i] != $s[0]) return false; return true;} // Driver code$s = "aaa";if (allCharactersSame($s))echo "Yes";elseecho "No"; // This code is contributed// by ChitraNayal?> <script> // Javascript program to find whether the string // has all same characters or not. function allCharactersSame(s) { let n = s.length; for (let i = 1; i < n; i++) if (s[i] != s[0]) return false; return true; } let s = "aaa"; if (allCharactersSame(s)) document.write("Yes"); else document.write("No"); // This code is contributed by suresh07.</script> Yes Time Complexity: O(n) Here n is the length of the string. Auxiliary Space: O(1) As constant extra space is used. Quick Way (Not time complexity wise, but in terms of number of lines of code) The idea is to use find_first_not_of() in C++ STL. find_first_not_of() finds and returns the position of the first character that does not match a specified character (or any of the specified characters in case of a string). C++ // A quick C++ program to find whether the// string has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){ return (s.find_first_not_of(s[0]) == string::npos);} // Driver codeint main(){ string s = "aaa"; if (allCharactersSame(s)) cout << "Yes"; else cout << "No"; return 0;} Yes One other way is using a SET The idea is to add all the characters of a string to a set. After adding, if the size of the set is greater than 1, it means different characters are present, if the size is exactly 1, it means there is only one unique character. Below is the implementation of the above logic. C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to check is all the// characters in string are or notvoid allCharactersSame(string s){ set <char> s1; // Insert characters in the set for ( int i=0 ; i < s.length() ; i++) s1.insert(s[i]); // If all characters are same // Size of set will always be 1 if ( s1.size() == 1 ) cout << "YES"; else cout << "NO";} // Driver codeint main(){ string str = "nnnn"; allCharactersSame(str); return 0;} // Java program for above approachimport java.io.*;import java.util.*; class GFG{ // Function to check is all the// characters in string are or notpublic static void allCharactersSame(String s){ Set<Character> s1 = new HashSet<Character>(); // Insert characters in the set for(int i = 0; i < s.length(); i++) s1.add(s.charAt(i)); // If all characters are same // Size of set will always be 1 if (s1.size() == 1) System.out.println("YES"); else System.out.println("NO");} // Driver Codepublic static void main(String[] args){ String str = "nnnn"; allCharactersSame(str);}} // This code is contributed by divyeshrabadiya07 # Python3 program for# the above approach # Function to check is# all the characters in# string are or notdef allCharactersSame(s): s1 = [] # Insert characters in # the set for i in range(len(s)): s1.append(s[i]) # If all characters are same # Size of set will always be 1 s1 = list(set(s1)) if(len(s1) == 1): print("YES") else: print("NO") # Driver codeStr = "nnnn"allCharactersSame(Str) # This code is contributed by avanitrachhadiya2155 // C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Function to check is all the// characters in string are or notstatic void allCharactersSame(string s){ HashSet<char> s1 = new HashSet<char>(); // Insert characters in the set for(int i = 0; i < s.Length; i++) s1.Add(s[i]); // If all characters are same // Size of set will always be 1 if (s1.Count == 1) Console.WriteLine("YES"); else Console.WriteLine("NO");} // Driver code static void Main(){ string str = "nnnn"; allCharactersSame(str);}} // This code is contributed by divyesh072019 <script>// Javascript program for above approach // Function to check is all the // characters in string are or not function allCharactersSame(s) { let s1 = new Set(); // Insert characters in the set for(let i = 0; i < s.length; i++) { s1.add(s[i]); } // If all characters are same // Size of set will always be 1 if (s1.size == 1) document.write("YES"); else document.write("NO"); } // Driver Code let str = "nnnn"; allCharactersSame(str); //This code is contributed by rag2127 </script> YES Time Complexity: O(nLogn) As insertion in a set takes Logn time and we are inserting n elements. Auxiliary Space: O(n) Extra space is used to store the elements in the set. This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m ankthon ukasp OrdinaryMoron nikhilmohite3 avanitrachhadiya2155 divyeshrabadiya07 divyesh072019 suresh07 rag2127 abhijeet19403 STL C++ Strings Strings STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Map in C++ Standard Template Library (STL) std::sort() in C++ STL Initialize a vector in C++ (7 different ways) Bitwise Operators in C/C++ Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 132, "s": 53, "text": "Given a string, check if all the characters of the string are the same or not." }, { "code": null, "e": 143, "s": 132, "text": "Examples: " }, { "code": null, "e": 209, "s": 143, "text": "Input : s = \"geeks\"\nOutput : No\n\nInput : s = \"gggg\" \nOutput : Yes" }, { "code": null, "e": 220, "s": 209, "text": "Simple Way" }, { "code": null, "e": 463, "s": 220, "text": "To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop. " }, { "code": null, "e": 467, "s": 463, "text": "C++" }, { "code": null, "e": 472, "s": 467, "text": "Java" }, { "code": null, "e": 480, "s": 472, "text": "Python3" }, { "code": null, "e": 483, "s": 480, "text": "C#" }, { "code": null, "e": 487, "s": 483, "text": "PHP" }, { "code": null, "e": 498, "s": 487, "text": "Javascript" }, { "code": "// C++ program to find whether the string// has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){ int n = s.length(); for (int i = 1; i < n; i++) if (s[i] != s[0]) return false; return true;} // Driver codeint main(){ string s = \"aaa\"; if (allCharactersSame(s)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 911, "s": 498, "text": null }, { "code": "// Java program to find whether the String// has all same characters or not.import java.io.*; public class GFG{ static boolean allCharactersSame(String s){ int n = s.length(); for (int i = 1; i < n; i++) if (s.charAt(i) != s.charAt(0)) return false; return true;} // Driver code static public void main (String[] args){ String s = \"aaa\"; if (allCharactersSame(s)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This Code is contributed by vt_m.", "e": 1451, "s": 911, "text": null }, { "code": "# Python3 program to find whether the string# has all same characters or not. # Function to check the string has# all same characters or not .def allCharactersSame(s) : n = len(s) for i in range(1, n) : if s[i] != s[0] : return False return True # Driver codeif __name__ == \"__main__\" : s = \"aaa\" if allCharactersSame(s) : print(\"Yes\") else : print(\"No\") # This code is contributed by ANKITRAI1", "e": 1902, "s": 1451, "text": null }, { "code": "// C# program to find whether the string// has all same characters or not.using System; public class GFG{ static bool allCharactersSame(string s){ int n = s.Length; for (int i = 1; i < n; i++) if (s[i] != s[0]) return false; return true;} // Driver code static public void Main (String []args){ string s = \"aaa\"; if (allCharactersSame(s)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 2407, "s": 1902, "text": null }, { "code": "<?php// PHP program to find whether// the string has all same// characters or not.function allCharactersSame($s){ $n = strlen($s); for ($i = 1; $i < $n; $i++) if ($s[$i] != $s[0]) return false; return true;} // Driver code$s = \"aaa\";if (allCharactersSame($s))echo \"Yes\";elseecho \"No\"; // This code is contributed// by ChitraNayal?>", "e": 2767, "s": 2407, "text": null }, { "code": "<script> // Javascript program to find whether the string // has all same characters or not. function allCharactersSame(s) { let n = s.length; for (let i = 1; i < n; i++) if (s[i] != s[0]) return false; return true; } let s = \"aaa\"; if (allCharactersSame(s)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by suresh07.</script>", "e": 3238, "s": 2767, "text": null }, { "code": null, "e": 3242, "s": 3238, "text": "Yes" }, { "code": null, "e": 3264, "s": 3242, "text": "Time Complexity: O(n)" }, { "code": null, "e": 3300, "s": 3264, "text": "Here n is the length of the string." }, { "code": null, "e": 3322, "s": 3300, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3355, "s": 3322, "text": "As constant extra space is used." }, { "code": null, "e": 3433, "s": 3355, "text": "Quick Way (Not time complexity wise, but in terms of number of lines of code)" }, { "code": null, "e": 3659, "s": 3433, "text": "The idea is to use find_first_not_of() in C++ STL. find_first_not_of() finds and returns the position of the first character that does not match a specified character (or any of the specified characters in case of a string). " }, { "code": null, "e": 3663, "s": 3659, "text": "C++" }, { "code": "// A quick C++ program to find whether the// string has all same characters or not.#include <iostream>using namespace std; bool allCharactersSame(string s){ return (s.find_first_not_of(s[0]) == string::npos);} // Driver codeint main(){ string s = \"aaa\"; if (allCharactersSame(s)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 4018, "s": 3663, "text": null }, { "code": null, "e": 4022, "s": 4018, "text": "Yes" }, { "code": null, "e": 4051, "s": 4022, "text": "One other way is using a SET" }, { "code": null, "e": 4281, "s": 4051, "text": "The idea is to add all the characters of a string to a set. After adding, if the size of the set is greater than 1, it means different characters are present, if the size is exactly 1, it means there is only one unique character." }, { "code": null, "e": 4329, "s": 4281, "text": "Below is the implementation of the above logic." }, { "code": null, "e": 4333, "s": 4329, "text": "C++" }, { "code": null, "e": 4338, "s": 4333, "text": "Java" }, { "code": null, "e": 4346, "s": 4338, "text": "Python3" }, { "code": null, "e": 4349, "s": 4346, "text": "C#" }, { "code": null, "e": 4360, "s": 4349, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to check is all the// characters in string are or notvoid allCharactersSame(string s){ set <char> s1; // Insert characters in the set for ( int i=0 ; i < s.length() ; i++) s1.insert(s[i]); // If all characters are same // Size of set will always be 1 if ( s1.size() == 1 ) cout << \"YES\"; else cout << \"NO\";} // Driver codeint main(){ string str = \"nnnn\"; allCharactersSame(str); return 0;}", "e": 4901, "s": 4360, "text": null }, { "code": "// Java program for above approachimport java.io.*;import java.util.*; class GFG{ // Function to check is all the// characters in string are or notpublic static void allCharactersSame(String s){ Set<Character> s1 = new HashSet<Character>(); // Insert characters in the set for(int i = 0; i < s.length(); i++) s1.add(s.charAt(i)); // If all characters are same // Size of set will always be 1 if (s1.size() == 1) System.out.println(\"YES\"); else System.out.println(\"NO\");} // Driver Codepublic static void main(String[] args){ String str = \"nnnn\"; allCharactersSame(str);}} // This code is contributed by divyeshrabadiya07", "e": 5590, "s": 4901, "text": null }, { "code": "# Python3 program for# the above approach # Function to check is# all the characters in# string are or notdef allCharactersSame(s): s1 = [] # Insert characters in # the set for i in range(len(s)): s1.append(s[i]) # If all characters are same # Size of set will always be 1 s1 = list(set(s1)) if(len(s1) == 1): print(\"YES\") else: print(\"NO\") # Driver codeStr = \"nnnn\"allCharactersSame(Str) # This code is contributed by avanitrachhadiya2155", "e": 6083, "s": 5590, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections.Generic; class GFG{ // Function to check is all the// characters in string are or notstatic void allCharactersSame(string s){ HashSet<char> s1 = new HashSet<char>(); // Insert characters in the set for(int i = 0; i < s.Length; i++) s1.Add(s[i]); // If all characters are same // Size of set will always be 1 if (s1.Count == 1) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\");} // Driver code static void Main(){ string str = \"nnnn\"; allCharactersSame(str);}} // This code is contributed by divyesh072019", "e": 6734, "s": 6083, "text": null }, { "code": "<script>// Javascript program for above approach // Function to check is all the // characters in string are or not function allCharactersSame(s) { let s1 = new Set(); // Insert characters in the set for(let i = 0; i < s.length; i++) { s1.add(s[i]); } // If all characters are same // Size of set will always be 1 if (s1.size == 1) document.write(\"YES\"); else document.write(\"NO\"); } // Driver Code let str = \"nnnn\"; allCharactersSame(str); //This code is contributed by rag2127 </script>", "e": 7331, "s": 6734, "text": null }, { "code": null, "e": 7335, "s": 7331, "text": "YES" }, { "code": null, "e": 7361, "s": 7335, "text": "Time Complexity: O(nLogn)" }, { "code": null, "e": 7432, "s": 7361, "text": "As insertion in a set takes Logn time and we are inserting n elements." }, { "code": null, "e": 7454, "s": 7432, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 7508, "s": 7454, "text": "Extra space is used to store the elements in the set." }, { "code": null, "e": 7929, "s": 7508, "text": " This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7936, "s": 7931, "text": "vt_m" }, { "code": null, "e": 7944, "s": 7936, "text": "ankthon" }, { "code": null, "e": 7950, "s": 7944, "text": "ukasp" }, { "code": null, "e": 7964, "s": 7950, "text": "OrdinaryMoron" }, { "code": null, "e": 7978, "s": 7964, "text": "nikhilmohite3" }, { "code": null, "e": 7999, "s": 7978, "text": "avanitrachhadiya2155" }, { "code": null, "e": 8017, "s": 7999, "text": "divyeshrabadiya07" }, { "code": null, "e": 8031, "s": 8017, "text": "divyesh072019" }, { "code": null, "e": 8040, "s": 8031, "text": "suresh07" }, { "code": null, "e": 8048, "s": 8040, "text": "rag2127" }, { "code": null, "e": 8062, "s": 8048, "text": "abhijeet19403" }, { "code": null, "e": 8066, "s": 8062, "text": "STL" }, { "code": null, "e": 8070, "s": 8066, "text": "C++" }, { "code": null, "e": 8078, "s": 8070, "text": "Strings" }, { "code": null, "e": 8086, "s": 8078, "text": "Strings" }, { "code": null, "e": 8090, "s": 8086, "text": "STL" }, { "code": null, "e": 8094, "s": 8090, "text": "CPP" }, { "code": null, "e": 8192, "s": 8094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8210, "s": 8192, "text": "Vector in C++ STL" }, { "code": null, "e": 8253, "s": 8210, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 8276, "s": 8253, "text": "std::sort() in C++ STL" }, { "code": null, "e": 8322, "s": 8276, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 8349, "s": 8322, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 8395, "s": 8349, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 8420, "s": 8395, "text": "Reverse a string in Java" }, { "code": null, "e": 8480, "s": 8420, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8495, "s": 8480, "text": "C++ Data Types" } ]
How to Perform Arithmetic Operation using Switch Case in PHP through HTML form ?
05 Jun, 2021 We are going to perform the basic arithmetic operations like- addition, subtraction, multiplication, and division using PHP. We are using HTML form to take the input values and choose an option to perform particular operation using Switch Case. Arithmetic Operations are used to perform operations like addition, subtraction etc. on the values. To perform arithmetic operations on the data we need at least two values. Addition: It performs the sum of given numbers. Subtraction: It performs the difference of given numbers. Multiplication: It performs the multiplication of given numbers. Division: It performs the division of given numbers. Example: Addition = val + val2 + ... + valn Example: add = 4 + 4 = 8 Subtraction = val - val2 - ... - valn Example: sub = 4 - 4 = 0 Multiplication = val1 * val2 * ... * valn Example: mul = 4 * 4 = 16 Division = val1 / val2 Example: mul = 4 / 4 = 1 Program 1: PHP <?php $x = 15;$y = 30; $add = $x + $y; $sub = $x - $y;$mul = $x * $y;$div = $y / $x; echo "Sum: " . $add . "\n";echo "Diff: " . $sub . "\n";echo "Mul: " . $mul . "\n";echo "Div: " . $div; ?> Output: Sum: 45 Diff: -15 Mul: 450 Div: 2 Using Switch Case: The switch statement is used to perform different actions based on different conditions. Syntax: switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; . . . case labeln: code to be executed if n=labellast; break; default: code to be executed if n is different from all labels; } Execution Steps: Start XAMPP Server Open Notepad and type the below code and save the folder in path given in image Program 2: PHP <!DOCTYPE html><html><head> <title>GFG</title></head> <body><center> <h1> ARITHMETIC OPERATIONS DEMO USING SWITCH CASE IN PHP </h1> <h3>Option-1 = Addition</h3> <h3>Option-2 = Subtraction</h3> <h3>Option-3 = Multiplication</h3> <h3>Option-4 = Division</h3> <form method="post"> <table border="0"> <tr> <!-- Taking value 1 in an text box --> <td> <input type="text" name="num1" value="" placeholder="Enter value 1"/> </td> </tr> <tr> <!-- Taking value 1 in an text box --> <td> <input type="text" name="num2" value="" placeholder="Enter value 2"/> </td> </tr> <tr> <!-- Taking option in an text box --> <td> <input type="text" name="option" value="" placeholder="Enter option 1-4 only"/> </td> </tr> <tr> <td> <input type="submit" name="submit" value="Submit"/> </td> </tr> </table> </form></center> <?php // Checking submit conditionif(isset($_POST['submit'])) { // Taking first number from the // form data to variable 'a' $a = $_POST['num1']; // Taking second number from the // form data to a variable 'b' $b = $_POST['num2']; // Taking option from the form // data to a variable 'ch' $ch = $_POST['option']; switch($ch) { case 1: // Execute addition operation // when option 1 is given $r = $a + $b; echo " Addition of two numbers = " . $r ; break; case 2: // Executing subtraction operation // when option 2 is given $r = $a - $b; echo " Subtraction of two numbers= " . $r ; break; case 3: // Executing multiplication operation // when option 3 is given $r = $a * $b; echo " Multiplication of two numbers = " . $r ; break; case 4: // Executing division operation // when option 4 is given $r = $a / $b; echo " Division of two numbers = " . $r ; break; default: // When 1 to 4 option is not given // then this condition is executed echo ("invalid option\n"); } return 0;}?></body></html> Output: Open Web Browser and type localhost/gfg/code.php Addition Subtraction Multiplication Division adnanirshad158 HTML-Misc PHP-Misc HTML PHP PHP Programs Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2021" }, { "code": null, "e": 273, "s": 28, "text": "We are going to perform the basic arithmetic operations like- addition, subtraction, multiplication, and division using PHP. We are using HTML form to take the input values and choose an option to perform particular operation using Switch Case." }, { "code": null, "e": 447, "s": 273, "text": "Arithmetic Operations are used to perform operations like addition, subtraction etc. on the values. To perform arithmetic operations on the data we need at least two values." }, { "code": null, "e": 495, "s": 447, "text": "Addition: It performs the sum of given numbers." }, { "code": null, "e": 553, "s": 495, "text": "Subtraction: It performs the difference of given numbers." }, { "code": null, "e": 618, "s": 553, "text": "Multiplication: It performs the multiplication of given numbers." }, { "code": null, "e": 671, "s": 618, "text": "Division: It performs the division of given numbers." }, { "code": null, "e": 680, "s": 671, "text": "Example:" }, { "code": null, "e": 922, "s": 680, "text": "Addition = val + val2 + ... + valn\nExample: add = 4 + 4 = 8\n\nSubtraction = val - val2 - ... - valn\nExample: sub = 4 - 4 = 0\n\nMultiplication = val1 * val2 * ... * valn\nExample: mul = 4 * 4 = 16\n\nDivision = val1 / val2\nExample: mul = 4 / 4 = 1" }, { "code": null, "e": 933, "s": 922, "text": "Program 1:" }, { "code": null, "e": 937, "s": 933, "text": "PHP" }, { "code": "<?php $x = 15;$y = 30; $add = $x + $y; $sub = $x - $y;$mul = $x * $y;$div = $y / $x; echo \"Sum: \" . $add . \"\\n\";echo \"Diff: \" . $sub . \"\\n\";echo \"Mul: \" . $mul . \"\\n\";echo \"Div: \" . $div; ?>", "e": 1130, "s": 937, "text": null }, { "code": null, "e": 1138, "s": 1130, "text": "Output:" }, { "code": null, "e": 1172, "s": 1138, "text": "Sum: 45\nDiff: -15\nMul: 450\nDiv: 2" }, { "code": null, "e": 1280, "s": 1172, "text": "Using Switch Case: The switch statement is used to perform different actions based on different conditions." }, { "code": null, "e": 1288, "s": 1280, "text": "Syntax:" }, { "code": null, "e": 1690, "s": 1288, "text": "switch (n) {\n case label1:\n code to be executed if n=label1;\n break;\n case label2:\n code to be executed if n=label2;\n break;\n case label3:\n code to be executed if n=label3;\n break;\n\n . . .\n \n case labeln:\n code to be executed if n=labellast;\n break;\n default:\n code to be executed if n is different from all labels;\n}" }, { "code": null, "e": 1707, "s": 1690, "text": "Execution Steps:" }, { "code": null, "e": 1728, "s": 1707, "text": "Start XAMPP Server " }, { "code": null, "e": 1810, "s": 1728, "text": "Open Notepad and type the below code and save the folder in path given in image " }, { "code": null, "e": 1821, "s": 1810, "text": "Program 2:" }, { "code": null, "e": 1825, "s": 1821, "text": "PHP" }, { "code": "<!DOCTYPE html><html><head> <title>GFG</title></head> <body><center> <h1> ARITHMETIC OPERATIONS DEMO USING SWITCH CASE IN PHP </h1> <h3>Option-1 = Addition</h3> <h3>Option-2 = Subtraction</h3> <h3>Option-3 = Multiplication</h3> <h3>Option-4 = Division</h3> <form method=\"post\"> <table border=\"0\"> <tr> <!-- Taking value 1 in an text box --> <td> <input type=\"text\" name=\"num1\" value=\"\" placeholder=\"Enter value 1\"/> </td> </tr> <tr> <!-- Taking value 1 in an text box --> <td> <input type=\"text\" name=\"num2\" value=\"\" placeholder=\"Enter value 2\"/> </td> </tr> <tr> <!-- Taking option in an text box --> <td> <input type=\"text\" name=\"option\" value=\"\" placeholder=\"Enter option 1-4 only\"/> </td> </tr> <tr> <td> <input type=\"submit\" name=\"submit\" value=\"Submit\"/> </td> </tr> </table> </form></center> <?php // Checking submit conditionif(isset($_POST['submit'])) { // Taking first number from the // form data to variable 'a' $a = $_POST['num1']; // Taking second number from the // form data to a variable 'b' $b = $_POST['num2']; // Taking option from the form // data to a variable 'ch' $ch = $_POST['option']; switch($ch) { case 1: // Execute addition operation // when option 1 is given $r = $a + $b; echo \" Addition of two numbers = \" . $r ; break; case 2: // Executing subtraction operation // when option 2 is given $r = $a - $b; echo \" Subtraction of two numbers= \" . $r ; break; case 3: // Executing multiplication operation // when option 3 is given $r = $a * $b; echo \" Multiplication of two numbers = \" . $r ; break; case 4: // Executing division operation // when option 4 is given $r = $a / $b; echo \" Division of two numbers = \" . $r ; break; default: // When 1 to 4 option is not given // then this condition is executed echo (\"invalid option\\n\"); } return 0;}?></body></html>", "e": 4345, "s": 1825, "text": null }, { "code": null, "e": 4402, "s": 4345, "text": "Output: Open Web Browser and type localhost/gfg/code.php" }, { "code": null, "e": 4411, "s": 4402, "text": "Addition" }, { "code": null, "e": 4423, "s": 4411, "text": "Subtraction" }, { "code": null, "e": 4438, "s": 4423, "text": "Multiplication" }, { "code": null, "e": 4447, "s": 4438, "text": "Division" }, { "code": null, "e": 4462, "s": 4447, "text": "adnanirshad158" }, { "code": null, "e": 4472, "s": 4462, "text": "HTML-Misc" }, { "code": null, "e": 4481, "s": 4472, "text": "PHP-Misc" }, { "code": null, "e": 4486, "s": 4481, "text": "HTML" }, { "code": null, "e": 4490, "s": 4486, "text": "PHP" }, { "code": null, "e": 4503, "s": 4490, "text": "PHP Programs" }, { "code": null, "e": 4520, "s": 4503, "text": "Web Technologies" }, { "code": null, "e": 4547, "s": 4520, "text": "Web technologies Questions" }, { "code": null, "e": 4552, "s": 4547, "text": "HTML" }, { "code": null, "e": 4556, "s": 4552, "text": "PHP" } ]
Draw Spiraling Star using Turtle in Python
01 Aug, 2020 Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen).To move turtle(pen) there are some functions i.e forward(), backward(), etcApproach to draw a Spiraling Star of size n: import turtle and create a turtle instance. Using for loop(i=0 to i<n) and repeat below stepturtle.forward(i*10)turtle.right(144) turtle.forward(i*10) turtle.right(144) close the turtle instance. Python3 # importing turtle moduleimport turtle # number of sidesn = 10 # creating instance of turtlepen = turtle.Turtle() # loop to draw a sidefor i in range(n): # drawing side of # length i*10 pen.forward(i * 10) # changing direction of pen # by 144 degree in clockwise pen.right(144) # closing the instanceturtle.done() Output: Python-projects Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Aug, 2020" }, { "code": null, "e": 402, "s": 53, "text": "Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen).To move turtle(pen) there are some functions i.e forward(), backward(), etcApproach to draw a Spiraling Star of size n: " }, { "code": null, "e": 446, "s": 402, "text": "import turtle and create a turtle instance." }, { "code": null, "e": 532, "s": 446, "text": "Using for loop(i=0 to i<n) and repeat below stepturtle.forward(i*10)turtle.right(144)" }, { "code": null, "e": 553, "s": 532, "text": "turtle.forward(i*10)" }, { "code": null, "e": 571, "s": 553, "text": "turtle.right(144)" }, { "code": null, "e": 599, "s": 571, "text": "close the turtle instance. " }, { "code": null, "e": 607, "s": 599, "text": "Python3" }, { "code": "# importing turtle moduleimport turtle # number of sidesn = 10 # creating instance of turtlepen = turtle.Turtle() # loop to draw a sidefor i in range(n): # drawing side of # length i*10 pen.forward(i * 10) # changing direction of pen # by 144 degree in clockwise pen.right(144) # closing the instanceturtle.done()", "e": 947, "s": 607, "text": null }, { "code": null, "e": 957, "s": 947, "text": "Output: " }, { "code": null, "e": 975, "s": 959, "text": "Python-projects" }, { "code": null, "e": 989, "s": 975, "text": "Python-turtle" }, { "code": null, "e": 996, "s": 989, "text": "Python" }, { "code": null, "e": 1094, "s": 996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1126, "s": 1094, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1155, "s": 1126, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1182, "s": 1155, "text": "Python Classes and Objects" }, { "code": null, "e": 1203, "s": 1182, "text": "Python OOPs Concepts" }, { "code": null, "e": 1226, "s": 1203, "text": "Introduction To PYTHON" }, { "code": null, "e": 1262, "s": 1226, "text": "Convert integer to string in Python" }, { "code": null, "e": 1318, "s": 1262, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1349, "s": 1318, "text": "Python | os.path.join() method" }, { "code": null, "e": 1386, "s": 1349, "text": "Create a Pandas DataFrame from Lists" } ]
Find the number of distinct islands in a 2D matrix
11 Aug, 2021 Given a boolean 2D matrix. The task is to find the number of distinct islands where a group of connected 1s (horizontally or vertically) forms an island. Two islands are considered to be distinct if and only if one island is equal to another (not rotated or reflected).Examples: Input: grid[][] = {{1, 1, 0, 0, 0}, 1, 1, 0, 0, 0}, 0, 0, 0, 1, 1}, 0, 0, 0, 1, 1}}Output: 1 Island 1, 1 at the top left corner is same as island 1, 1 at the bottom right cornerInput: grid[][] = {{1, 1, 0, 1, 1}, 1, 0, 0, 0, 0}, 0, 0, 0, 0, 1}, 1, 1, 0, 1, 1}}Output: 3 Distinct islands in the example above are: 1, 1 at the top left corner; 1, 1 at the top right corner and 1 at the bottom right corner. We ignore the island 1, 1 at the bottom left corner since 1, 1 it is identical to the top right corner. Approach: This problem is an extension of the problem Number of Islands.The core of the question is to know if 2 islands are equal. The primary criteria is that the number of 1’s should be same in both. But this cannot be the only criteria as we have seen in example 2 above. So how do we know? We could use the position/coordinates of the 1’s. If we take the first coordinates of any island as a base point and then compute the coordinates of other points from the base point, we can eliminate duplicates to get the distinct count of islands. So, using this approach, the coordinates for the 2 islands in example 1 above can be represented as: [(0, 0), (0, 1), (1, 0), (1, 1)].Below is the implementation of above approach: C++ Python3 // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // 2D array for the storing the horizontal and vertical// directions. (Up, left, down, right}vector<vector<int> > dirs = { { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 0 } }; // Function to perform dfs of the input gridvoid dfs(vector<vector<int> >& grid, int x0, int y0, int i, int j, vector<pair<int, int> >& v){ int rows = grid.size(), cols = grid[0].size(); if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] <= 0) return; // marking the visited element as -1 grid[i][j] *= -1; // computing coordinates with x0, y0 as base v.push_back({ i - x0, j - y0 }); // repeat dfs for neighbors for (auto dir : dirs) { dfs(grid, x0, y0, i + dir[0], j + dir[1], v); }} // Main function that returns distinct count of islands in// a given boolean 2D matrixint countDistinctIslands(vector<vector<int> >& grid){ int rows = grid.size(); if (rows == 0) return 0; int cols = grid[0].size(); if (cols == 0) return 0; set<vector<pair<int, int> > > coordinates; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { // If a cell is not 1 // no need to dfs if (grid[i][j] != 1) continue; // vector to hold coordinates // of this island vector<pair<int, int> > v; dfs(grid, i, j, i, j, v); // insert the coordinates for // this island to set coordinates.insert(v); } } return coordinates.size();} // Driver codeint main(){ vector<vector<int> > grid = { { 1, 1, 0, 1, 1 }, { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1 }, { 1, 1, 0, 1, 1 } }; cout << "Number of distinct islands is " << countDistinctIslands(grid); return 0;} # Python implementation of above approach # 2D array for the storing the horizontal and vertical# directions. (Up, left, down, rightdirs = [ [ 0, -1 ], [ -1, 0 ], [ 0, 1 ], [ 1, 0 ] ] # Function to perform dfs of the input griddef dfs(grid, x0, y0, i, j, v): rows = len(grid) cols = len(grid[0]) if i < 0 or i >= rows or j < 0 or j >= cols or grid[i][j] <= 0: return # marking the visited element as -1 grid[i][j] *= -1 # computing coordinates with x0, y0 as base v.append( (i - x0, j - y0) ) # repeat dfs for neighbors for dir in dirs: dfs(grid, x0, y0, i + dir[0], j + dir[1], v) # Main function that returns distinct count of islands in# a given boolean 2D matrixdef countDistinctIslands(grid): rows = len(grid) if rows == 0: return 0 cols = len(grid[0]) if cols == 0: return 0 coordinates = set() for i in range(rows): for j in range(cols): # If a cell is not 1 # no need to dfs if grid[i][j] != 1: continue # to hold coordinates # of this island v = [] dfs(grid, i, j, i, j, v) # insert the coordinates for # this island to set coordinates.add(tuple(v)) return len(coordinates) # Driver codegrid = [[ 1, 1, 0, 1, 1 ],[ 1, 0, 0, 0, 0 ],[ 0, 0, 0, 0, 1 ],[ 1, 1, 0, 1, 1 ] ] print("Number of distinct islands is", countDistinctIslands(grid)) # This code is contributed by ankush_953 Number of distinct islands is 3 Time complexity: O(rows * cols), where rows is the number of rows and cols is the number of columns in the matrix.Space complexity: O(rows * cols) ankush_953 vaibhavdodiya pankajsharmagfg DFS Technical Scripter 2018 Algorithms Graph Matrix DFS Matrix Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 332, "s": 52, "text": "Given a boolean 2D matrix. The task is to find the number of distinct islands where a group of connected 1s (horizontally or vertically) forms an island. Two islands are considered to be distinct if and only if one island is equal to another (not rotated or reflected).Examples: " }, { "code": null, "e": 841, "s": 332, "text": "Input: grid[][] = {{1, 1, 0, 0, 0}, 1, 1, 0, 0, 0}, 0, 0, 0, 1, 1}, 0, 0, 0, 1, 1}}Output: 1 Island 1, 1 at the top left corner is same as island 1, 1 at the bottom right cornerInput: grid[][] = {{1, 1, 0, 1, 1}, 1, 0, 0, 0, 0}, 0, 0, 0, 0, 1}, 1, 1, 0, 1, 1}}Output: 3 Distinct islands in the example above are: 1, 1 at the top left corner; 1, 1 at the top right corner and 1 at the bottom right corner. We ignore the island 1, 1 at the bottom left corner since 1, 1 it is identical to the top right corner." }, { "code": null, "e": 1570, "s": 843, "text": "Approach: This problem is an extension of the problem Number of Islands.The core of the question is to know if 2 islands are equal. The primary criteria is that the number of 1’s should be same in both. But this cannot be the only criteria as we have seen in example 2 above. So how do we know? We could use the position/coordinates of the 1’s. If we take the first coordinates of any island as a base point and then compute the coordinates of other points from the base point, we can eliminate duplicates to get the distinct count of islands. So, using this approach, the coordinates for the 2 islands in example 1 above can be represented as: [(0, 0), (0, 1), (1, 0), (1, 1)].Below is the implementation of above approach: " }, { "code": null, "e": 1574, "s": 1570, "text": "C++" }, { "code": null, "e": 1582, "s": 1574, "text": "Python3" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // 2D array for the storing the horizontal and vertical// directions. (Up, left, down, right}vector<vector<int> > dirs = { { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 0 } }; // Function to perform dfs of the input gridvoid dfs(vector<vector<int> >& grid, int x0, int y0, int i, int j, vector<pair<int, int> >& v){ int rows = grid.size(), cols = grid[0].size(); if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] <= 0) return; // marking the visited element as -1 grid[i][j] *= -1; // computing coordinates with x0, y0 as base v.push_back({ i - x0, j - y0 }); // repeat dfs for neighbors for (auto dir : dirs) { dfs(grid, x0, y0, i + dir[0], j + dir[1], v); }} // Main function that returns distinct count of islands in// a given boolean 2D matrixint countDistinctIslands(vector<vector<int> >& grid){ int rows = grid.size(); if (rows == 0) return 0; int cols = grid[0].size(); if (cols == 0) return 0; set<vector<pair<int, int> > > coordinates; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { // If a cell is not 1 // no need to dfs if (grid[i][j] != 1) continue; // vector to hold coordinates // of this island vector<pair<int, int> > v; dfs(grid, i, j, i, j, v); // insert the coordinates for // this island to set coordinates.insert(v); } } return coordinates.size();} // Driver codeint main(){ vector<vector<int> > grid = { { 1, 1, 0, 1, 1 }, { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1 }, { 1, 1, 0, 1, 1 } }; cout << \"Number of distinct islands is \" << countDistinctIslands(grid); return 0;}", "e": 3622, "s": 1582, "text": null }, { "code": "# Python implementation of above approach # 2D array for the storing the horizontal and vertical# directions. (Up, left, down, rightdirs = [ [ 0, -1 ], [ -1, 0 ], [ 0, 1 ], [ 1, 0 ] ] # Function to perform dfs of the input griddef dfs(grid, x0, y0, i, j, v): rows = len(grid) cols = len(grid[0]) if i < 0 or i >= rows or j < 0 or j >= cols or grid[i][j] <= 0: return # marking the visited element as -1 grid[i][j] *= -1 # computing coordinates with x0, y0 as base v.append( (i - x0, j - y0) ) # repeat dfs for neighbors for dir in dirs: dfs(grid, x0, y0, i + dir[0], j + dir[1], v) # Main function that returns distinct count of islands in# a given boolean 2D matrixdef countDistinctIslands(grid): rows = len(grid) if rows == 0: return 0 cols = len(grid[0]) if cols == 0: return 0 coordinates = set() for i in range(rows): for j in range(cols): # If a cell is not 1 # no need to dfs if grid[i][j] != 1: continue # to hold coordinates # of this island v = [] dfs(grid, i, j, i, j, v) # insert the coordinates for # this island to set coordinates.add(tuple(v)) return len(coordinates) # Driver codegrid = [[ 1, 1, 0, 1, 1 ],[ 1, 0, 0, 0, 0 ],[ 0, 0, 0, 0, 1 ],[ 1, 1, 0, 1, 1 ] ] print(\"Number of distinct islands is\", countDistinctIslands(grid)) # This code is contributed by ankush_953", "e": 5161, "s": 3622, "text": null }, { "code": null, "e": 5193, "s": 5161, "text": "Number of distinct islands is 3" }, { "code": null, "e": 5343, "s": 5195, "text": "Time complexity: O(rows * cols), where rows is the number of rows and cols is the number of columns in the matrix.Space complexity: O(rows * cols) " }, { "code": null, "e": 5354, "s": 5343, "text": "ankush_953" }, { "code": null, "e": 5368, "s": 5354, "text": "vaibhavdodiya" }, { "code": null, "e": 5384, "s": 5368, "text": "pankajsharmagfg" }, { "code": null, "e": 5388, "s": 5384, "text": "DFS" }, { "code": null, "e": 5412, "s": 5388, "text": "Technical Scripter 2018" }, { "code": null, "e": 5423, "s": 5412, "text": "Algorithms" }, { "code": null, "e": 5429, "s": 5423, "text": "Graph" }, { "code": null, "e": 5436, "s": 5429, "text": "Matrix" }, { "code": null, "e": 5440, "s": 5436, "text": "DFS" }, { "code": null, "e": 5447, "s": 5440, "text": "Matrix" }, { "code": null, "e": 5453, "s": 5447, "text": "Graph" }, { "code": null, "e": 5464, "s": 5453, "text": "Algorithms" } ]
How to sort a list in C# | List.Sort() Method Set -2
22 Sep, 2021 List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows: Sort(IComparer<T>)Sort(Int32, Int32, IComparer)Sort()Sort(Comparison<T>) Sort(IComparer<T>) Sort(Int32, Int32, IComparer) Sort() Sort(Comparison<T>) Here, the first two methods are discussed in Set – 1. So, We will discuss the last two methods. This method is used to sort the elements in the entire List<T> using the default comparer. Syntax: public void Sort (); Exception: This method will give InvalidOperationException if the default Comparer cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T. Example 1: // C# program to demonstrate the // use of List<T>.Sort() methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List initialize List<int> list1 = new List<int> { // list elements 1, 5, 6, 2, 4, 3 }; Console.WriteLine("Original List"); foreach(int g in list1) { // Display Original List Console.WriteLine(g); } Console.WriteLine("\nSorted List"); // use of List<T>.Sort() method list1.Sort(); foreach(int g in list1) { // Display sorted list Console.WriteLine(g); } }} Original List 1 5 6 2 4 3 Sorted List 1 2 3 4 5 6 Example 2: // C# program to demonstrate the // use of List<T>.Sort() methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add("A"); list1.Add("I"); list1.Add("G"); list1.Add("B"); list1.Add("E"); list1.Add("H"); list1.Add("F"); list1.Add("C"); list1.Add("D"); Console.WriteLine("Original List"); // Display Original List Display(list1); Console.WriteLine("\nSorted List"); // use of List.Sort() method list1.Sort(); // Display sorted List Display(list1); } // Display function public static void Display(List<string> list) { foreach(string g in list) { Console.Write(g + " "); } }} Original List A I G B E H F C D Sorted List A B C D E F G H I Example 3: // C# program to demonstrate the// use of List<T>.Sort() methodusing System;using System.Collections.Generic; public class GFG { // Main Method public static void Main() { // array elements String[] list = {"C++", "Java", "C", "Python", "HTML", "CSS", "Scala", "Ruby", "Perl"}; var list1 = new List<String>(); // "AddRange" method to add the // string array elements into the List list1.AddRange(list); Console.WriteLine("List in unsorted order: "); Display(list1); Console.WriteLine(Environment.NewLine); // using List.Sort() method list1.Sort(); Console.WriteLine("List in sorted order: "); Display(list1); } // Display method static void Display(List<string> list) { foreach(string g in list) { Console.Write(g + "\t"); } }} List in unsorted order: C++ Java C Python HTML CSS Scala Ruby Perl List in sorted order: C C++ CSS HTML Java Perl Python Ruby Scala This method is used to sort the elements in the entire List<T> using the specified comparer. Syntax: public void Sort (Comparison<T> comparison); Parameter:comparison: It is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default. Exceptions: ArgumentNullException: If the comparer is null, and the default comparer Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T. ArgumentException: If the implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the use of // List<T>.Sort(comparison <T>) methodusing System;using System.Collections.Generic; class GFG { private static int Geek(string x, string y) { if (x == null) { if (y == null) { // If x and y is null // then they are equal return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } else { if (y == null) { return 1; } else { // If the strings are of equal length, // sort them with string comparison. return x.CompareTo(y); } } } // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add("AB"); list1.Add("CD"); list1.Add("GH"); list1.Add("EF"); list1.Add("IJ"); list1.Add("KL"); Console.WriteLine("Original List :"); // displaying original list Display(list1); Console.WriteLine("\nSort with generic Comparison object :"); // Sort(Comparison<t>) method //"Geek" is Comparison object list1.Sort(Geek); // displaying sorted list Display(list1); } // display function private static void Display(List<string> list) { foreach(string g in list) { Console.WriteLine(g); } }} Original List : AB CD GH EF IJ KL Sort with generic Comparison object : AB CD EF GH IJ KL Example 2: // C# program to demonstrate the use of// List<T>.Sort(comparison <T>) methodusing System;using System.Collections.Generic; class GFG { private static int Geek(int x, int y) { if (x == 0) { if (y == 0) { // If x and y is null // then they are equal return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } else { if (y == 0) { return 1; } else { // If the strings are of equal length, // sort them with string comparison. return x.CompareTo(y); } } } public static void Main() { List<int> list1 = new List<int>(); // list elements list1.Add(2); list1.Add(5); list1.Add(6); list1.Add(4); list1.Add(1); list1.Add(3); Console.WriteLine("Original List :"); // displaying original list Display(list1); Console.WriteLine("\nSort with generic "+ "Comparison object :"); // Sort(Comparison<t>) method //"Geek" is Comparison object list1.Sort(Geek); // displaying sorted list Display(list1); } // display function private static void Display(List<int> list) { foreach(int g in list) { Console.WriteLine(g); } }} Original List : 2 5 6 4 1 3 Sort with generic Comparison object : 1 2 3 4 5 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=netframework-4.7.2 anikaseth98 CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 326, "s": 28, "text": "List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows:" }, { "code": null, "e": 399, "s": 326, "text": "Sort(IComparer<T>)Sort(Int32, Int32, IComparer)Sort()Sort(Comparison<T>)" }, { "code": null, "e": 418, "s": 399, "text": "Sort(IComparer<T>)" }, { "code": null, "e": 448, "s": 418, "text": "Sort(Int32, Int32, IComparer)" }, { "code": null, "e": 455, "s": 448, "text": "Sort()" }, { "code": null, "e": 475, "s": 455, "text": "Sort(Comparison<T>)" }, { "code": null, "e": 571, "s": 475, "text": "Here, the first two methods are discussed in Set – 1. So, We will discuss the last two methods." }, { "code": null, "e": 662, "s": 571, "text": "This method is used to sort the elements in the entire List<T> using the default comparer." }, { "code": null, "e": 691, "s": 662, "text": "Syntax: public void Sort ();" }, { "code": null, "e": 885, "s": 691, "text": "Exception: This method will give InvalidOperationException if the default Comparer cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T." }, { "code": null, "e": 896, "s": 885, "text": "Example 1:" }, { "code": "// C# program to demonstrate the // use of List<T>.Sort() methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List initialize List<int> list1 = new List<int> { // list elements 1, 5, 6, 2, 4, 3 }; Console.WriteLine(\"Original List\"); foreach(int g in list1) { // Display Original List Console.WriteLine(g); } Console.WriteLine(\"\\nSorted List\"); // use of List<T>.Sort() method list1.Sort(); foreach(int g in list1) { // Display sorted list Console.WriteLine(g); } }}", "e": 1613, "s": 896, "text": null }, { "code": null, "e": 1665, "s": 1613, "text": "Original List\n1\n5\n6\n2\n4\n3\n\nSorted List\n1\n2\n3\n4\n5\n6\n" }, { "code": null, "e": 1676, "s": 1665, "text": "Example 2:" }, { "code": "// C# program to demonstrate the // use of List<T>.Sort() methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add(\"A\"); list1.Add(\"I\"); list1.Add(\"G\"); list1.Add(\"B\"); list1.Add(\"E\"); list1.Add(\"H\"); list1.Add(\"F\"); list1.Add(\"C\"); list1.Add(\"D\"); Console.WriteLine(\"Original List\"); // Display Original List Display(list1); Console.WriteLine(\"\\nSorted List\"); // use of List.Sort() method list1.Sort(); // Display sorted List Display(list1); } // Display function public static void Display(List<string> list) { foreach(string g in list) { Console.Write(g + \" \"); } }}", "e": 2572, "s": 1676, "text": null }, { "code": null, "e": 2636, "s": 2572, "text": "Original List\nA I G B E H F C D \nSorted List\nA B C D E F G H I\n" }, { "code": null, "e": 2647, "s": 2636, "text": "Example 3:" }, { "code": "// C# program to demonstrate the// use of List<T>.Sort() methodusing System;using System.Collections.Generic; public class GFG { // Main Method public static void Main() { // array elements String[] list = {\"C++\", \"Java\", \"C\", \"Python\", \"HTML\", \"CSS\", \"Scala\", \"Ruby\", \"Perl\"}; var list1 = new List<String>(); // \"AddRange\" method to add the // string array elements into the List list1.AddRange(list); Console.WriteLine(\"List in unsorted order: \"); Display(list1); Console.WriteLine(Environment.NewLine); // using List.Sort() method list1.Sort(); Console.WriteLine(\"List in sorted order: \"); Display(list1); } // Display method static void Display(List<string> list) { foreach(string g in list) { Console.Write(g + \"\\t\"); } }}", "e": 3597, "s": 2647, "text": null }, { "code": null, "e": 3785, "s": 3597, "text": "List in unsorted order: \nC++ Java C Python HTML CSS Scala Ruby Perl \n\nList in sorted order: \nC C++ CSS HTML Java Perl Python Ruby Scala\n" }, { "code": null, "e": 3878, "s": 3785, "text": "This method is used to sort the elements in the entire List<T> using the specified comparer." }, { "code": null, "e": 3931, "s": 3878, "text": "Syntax: public void Sort (Comparison<T> comparison);" }, { "code": null, "e": 4068, "s": 3931, "text": "Parameter:comparison: It is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default." }, { "code": null, "e": 4080, "s": 4068, "text": "Exceptions:" }, { "code": null, "e": 4269, "s": 4080, "text": "ArgumentNullException: If the comparer is null, and the default comparer Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T." }, { "code": null, "e": 4432, "s": 4269, "text": "ArgumentException: If the implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself." }, { "code": null, "e": 4497, "s": 4432, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 4508, "s": 4497, "text": "Example 1:" }, { "code": "// C# program to demonstrate the use of // List<T>.Sort(comparison <T>) methodusing System;using System.Collections.Generic; class GFG { private static int Geek(string x, string y) { if (x == null) { if (y == null) { // If x and y is null // then they are equal return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } else { if (y == null) { return 1; } else { // If the strings are of equal length, // sort them with string comparison. return x.CompareTo(y); } } } // Main Method public static void Main() { List<string> list1 = new List<string>(); // list elements list1.Add(\"AB\"); list1.Add(\"CD\"); list1.Add(\"GH\"); list1.Add(\"EF\"); list1.Add(\"IJ\"); list1.Add(\"KL\"); Console.WriteLine(\"Original List :\"); // displaying original list Display(list1); Console.WriteLine(\"\\nSort with generic Comparison object :\"); // Sort(Comparison<t>) method //\"Geek\" is Comparison object list1.Sort(Geek); // displaying sorted list Display(list1); } // display function private static void Display(List<string> list) { foreach(string g in list) { Console.WriteLine(g); } }}", "e": 6140, "s": 4508, "text": null }, { "code": null, "e": 6232, "s": 6140, "text": "Original List :\nAB\nCD\nGH\nEF\nIJ\nKL\n\nSort with generic Comparison object :\nAB\nCD\nEF\nGH\nIJ\nKL\n" }, { "code": null, "e": 6243, "s": 6232, "text": "Example 2:" }, { "code": "// C# program to demonstrate the use of// List<T>.Sort(comparison <T>) methodusing System;using System.Collections.Generic; class GFG { private static int Geek(int x, int y) { if (x == 0) { if (y == 0) { // If x and y is null // then they are equal return 0; } else { // If x is null but y is not // null then y is greater. return -1; } } else { if (y == 0) { return 1; } else { // If the strings are of equal length, // sort them with string comparison. return x.CompareTo(y); } } } public static void Main() { List<int> list1 = new List<int>(); // list elements list1.Add(2); list1.Add(5); list1.Add(6); list1.Add(4); list1.Add(1); list1.Add(3); Console.WriteLine(\"Original List :\"); // displaying original list Display(list1); Console.WriteLine(\"\\nSort with generic \"+ \"Comparison object :\"); // Sort(Comparison<t>) method //\"Geek\" is Comparison object list1.Sort(Geek); // displaying sorted list Display(list1); } // display function private static void Display(List<int> list) { foreach(int g in list) { Console.WriteLine(g); } }}", "e": 7810, "s": 6243, "text": null }, { "code": null, "e": 7890, "s": 7810, "text": "Original List :\n2\n5\n6\n4\n1\n3\n\nSort with generic Comparison object :\n1\n2\n3\n4\n5\n6\n" }, { "code": null, "e": 7901, "s": 7890, "text": "Reference:" }, { "code": null, "e": 8008, "s": 7901, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=netframework-4.7.2" }, { "code": null, "e": 8020, "s": 8008, "text": "anikaseth98" }, { "code": null, "e": 8040, "s": 8020, "text": "CSharp-Generic-List" }, { "code": null, "e": 8065, "s": 8040, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 8079, "s": 8065, "text": "CSharp-method" }, { "code": null, "e": 8082, "s": 8079, "text": "C#" }, { "code": null, "e": 8101, "s": 8082, "text": "Technical Scripter" }, { "code": null, "e": 8199, "s": 8101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8227, "s": 8199, "text": "C# Dictionary with examples" }, { "code": null, "e": 8258, "s": 8227, "text": "Introduction to .NET Framework" }, { "code": null, "e": 8273, "s": 8258, "text": "C# | Delegates" }, { "code": null, "e": 8316, "s": 8273, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 8365, "s": 8316, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 8388, "s": 8365, "text": "C# | Method Overriding" }, { "code": null, "e": 8404, "s": 8388, "text": "C# | Data Types" }, { "code": null, "e": 8422, "s": 8404, "text": "C# | Constructors" }, { "code": null, "e": 8462, "s": 8422, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Python | Pandas Series.round()
12 Jun, 2021 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.When doing mathematical operations on series, many times the returned series is having decimal values and decimal values could go to upto many places. Pandas Series.round() method is used in such cases only to round of decimal values in series. Syntax: Series.round(decimals=0, *args, **kwargs) Parameters: decimals: Int value, specifies upto what number of decimal places the value should be rounded of, default is 0.Return type: Series with updated values To download the data set used in following example, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example: Since in the dataframe, there isn’t any series with decimal values more than 1 place. Hence the Salary column is divided by the Weight column first to get a series with decimal values. Since the returned series is having values with decimal upto 6 places. First a new series created by using round() method and another series new2 is created by passing a parameter of 2 to round() method to see working of this method. Before doing any operations, null rows were removed using dropna() method. Python3 # importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(inplace = True) # creating new column with divided valuesdata["New_Salary"]= data["Salary"].div(data['Weight']) # rounding of values and storing in new columndata['New']= data['New_Salary'].round() # variable for max decimal placesdec_places = 2 # rounding of values and storing in new columndata['New2']= data['New_Salary'].round(dec_places) # displaydata.head(10) Output: As shown in the Output image, the new series is completely rounded of with no decimal values and new2 series contains decimals upto 2 places after that only. arorakashish0911 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 Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2021" }, { "code": null, "e": 487, "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.When doing mathematical operations on series, many times the returned series is having decimal values and decimal values could go to upto many places. Pandas Series.round() method is used in such cases only to round of decimal values in series. " }, { "code": null, "e": 700, "s": 487, "text": "Syntax: Series.round(decimals=0, *args, **kwargs) Parameters: decimals: Int value, specifies upto what number of decimal places the value should be rounded of, default is 0.Return type: Series with updated values" }, { "code": null, "e": 913, "s": 700, "text": "To download the data set used in following example, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. " }, { "code": null, "e": 1417, "s": 913, "text": "Example: Since in the dataframe, there isn’t any series with decimal values more than 1 place. Hence the Salary column is divided by the Weight column first to get a series with decimal values. Since the returned series is having values with decimal upto 6 places. First a new series created by using round() method and another series new2 is created by passing a parameter of 2 to round() method to see working of this method. Before doing any operations, null rows were removed using dropna() method. " }, { "code": null, "e": 1425, "s": 1417, "text": "Python3" }, { "code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(inplace = True) # creating new column with divided valuesdata[\"New_Salary\"]= data[\"Salary\"].div(data['Weight']) # rounding of values and storing in new columndata['New']= data['New_Salary'].round() # variable for max decimal placesdec_places = 2 # rounding of values and storing in new columndata['New2']= data['New_Salary'].round(dec_places) # displaydata.head(10)", "e": 1988, "s": 1425, "text": null }, { "code": null, "e": 2156, "s": 1988, "text": "Output: As shown in the Output image, the new series is completely rounded of with no decimal values and new2 series contains decimals upto 2 places after that only. " }, { "code": null, "e": 2175, "s": 2158, "text": "arorakashish0911" }, { "code": null, "e": 2196, "s": 2175, "text": "Python pandas-series" }, { "code": null, "e": 2225, "s": 2196, "text": "Python pandas-series-methods" }, { "code": null, "e": 2239, "s": 2225, "text": "Python-pandas" }, { "code": null, "e": 2246, "s": 2239, "text": "Python" }, { "code": null, "e": 2344, "s": 2246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2362, "s": 2344, "text": "Python Dictionary" }, { "code": null, "e": 2404, "s": 2362, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2426, "s": 2404, "text": "Enumerate() in Python" }, { "code": null, "e": 2458, "s": 2426, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2487, "s": 2458, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2514, "s": 2487, "text": "Python Classes and Objects" }, { "code": null, "e": 2550, "s": 2514, "text": "Convert integer to string in Python" }, { "code": null, "e": 2581, "s": 2550, "text": "Python | os.path.join() method" }, { "code": null, "e": 2602, "s": 2581, "text": "Python OOPs Concepts" } ]
Angular 8 - Animations
Animation gives the web application a refreshing look and rich user interaction. In HTML, animation is basically the transformation of HTML element from one CSS style to another over a specific period of time. For example, an image element can be enlarged by changing its width and height. If the width and height of the image is changed from initial value to final value in steps over a period of time, say 10 seconds, then we get an animation effect. So, the scope of the animation depends on the feature / property provided by the CSS to style a HTML element. Angular provides a separate module BrowserAnimationModule to do the animation. BrowserAnimationModule provides an easy and clear approach to do animation. Let us learn how to configure animation module in this chapter. Follow below mentioned steps to configure animation module, BrowserAnimationModule in an application. Import BrowserAnimationModule in AppModule. import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule ], declarations: [ ], bootstrap: [ ] }) export class AppModule { } Import animation function in the relevant components. import { state, style, transition, animate, trigger } from '@angular/animations' Add animations metadata property in the relevant component. @Component({ animations: [ // animation functionality goes here ] }) export class MyAnimationComponent In angular, we need to understand the five core concept and its relationship to do animation. State State refers the specific state of the component. A component can have multiple defined state. The state is created using state() method. state() method has two arguments. name − Unique name of the state. name − Unique name of the state. style − Style of the state defined using style() method. style − Style of the state defined using style() method. animations: [ ... state('start', style( { width: 200px; } )) ... ] Here, start is the name of the state. Style Style refers the CSS style applied in a particular state. style() method is used to style the particular state of a component. It uses the CSS property and can have multiple items. animations: [ ... state('start', style( { width: 200px; opacity: 1 } )) ... ] Here, start state defines two CSS property, width with value 200px and opacity with value 1. Transition refers the transition from one state to another. Animation can have multiple transition. Each transition is defined using transition() function. transition() takes two argument. Specifies the direction between two transition state. For example, start => end refers that the initial state is start and the final state is end. Actually, it is an expression with rich functionality. Specifies the direction between two transition state. For example, start => end refers that the initial state is start and the final state is end. Actually, it is an expression with rich functionality. Specifies the animation details using animate() function. Specifies the animation details using animate() function. animations: [ ... transition('start => end', [ animate('1s') ]) ... ] Here, transition() function defines the transition from start state to end state with animation defined in animate() method. Animation defines the way the transition from one state to another take place. animation() function is used to set the animation details. animate() takes a single argument in the form of below expression − duration delay easing duration − refers the duration of the transition. It is expressed as 1s, 100ms, etc., duration − refers the duration of the transition. It is expressed as 1s, 100ms, etc., delay − refers the delay time to start the transition. It is expressed similar to duration delay − refers the delay time to start the transition. It is expressed similar to duration easing − refers how do to accelerates / decelerates the transition in the given time duration. easing − refers how do to accelerates / decelerates the transition in the given time duration. Every animation needs a trigger to start the animation. trigger() method is used to set all the animation information such as state, style, transition and animation in one place and give it a unique name. The unique name is used further to trigger the animation. animations: [ trigger('enlarge', [ state('start', style({ height: '200px', })), state('end', style({ height: '500px', })), transition('start => end', [ animate('1s') ]), transition('end => start', [ animate('0.5s') ]) ]), ] Here, enlarge is the unique name given to the particular animation. It has two state and related styles. It has two transition one from start to end and another from end to start. End to start state do the reverse of the animation. Trigger can be attached to an element as specified below − <div [@triggerName]="expression">...</div>; For example, <img [@enlarge]="isEnlarge ? 'end' : 'start'">...</img>; Here, @enlarge − trigger is set to image tag and attrached to an expression. @enlarge − trigger is set to image tag and attrached to an expression. If isEnlarge value is changed to true, then end state will be set and it triggers start => end transition. If isEnlarge value is changed to true, then end state will be set and it triggers start => end transition. If isEnlarge value is changed to false, then start state will be set and it triggers end => start transition. If isEnlarge value is changed to false, then start state will be set and it triggers end => start transition. Let us write a new angular application to better understand the animation concept by enlarging an image with animation effect. Open command prompt and create new angular application. cd /go/to/workspace ng new animation-app cd animation-app Configure BrowserAnimationModule in the AppModule (src/app/app.module.ts) import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core' import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Open AppComponent (src/app/app.component.ts) and import necessary animation functions. import { state, style, transition, animate, trigger } from '@angular/animations'; Add animation functionality, which will animate the image during the enlarging / shrinking of the image. @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], animations: [ trigger('enlarge', [ state('start', style({ height: '150px' })), state('end', style({ height: '250px' })), transition('start => end', [ animate('1s 2s') ]), transition('end => start', [ animate('1s 2s') ]) ]) ] }) Open AppComponent template, src/app/app.component.html and remove sample code. Then, include a header with application title, image and a button to enlarge / shrink the image. <h1>{{ title }}</h1> <img src="assets/puppy.jpeg" style="height: 200px" /> <br /> <button>{{ this.buttonText }}</button> Write a function to change the animation expression. export class AppComponent { title = 'Animation Application'; isEnlarge: boolean = false; buttonText: string = "Enlarge"; triggerAnimation() { this.isEnlarge = !this.isEnlarge; if(this.isEnlarge) this.buttonText = "Shrink"; else this.buttonText = "Enlarge"; } } Attach the animation in the image tag. Also, attach the click event for the button. <h1>{{ title }}</h1> <img [@enlarge]="isEnlarge ? 'end' : 'start'" src="assets/puppy.jpeg" style="height: 200px" /> <br /> <button (click)='triggerAnimation()'>{{ this.buttonText }}</button> The complete AppComponent code is as follows − import { Component } from '@angular/core'; import { state, style, transition, animate, trigger } from '@angular/animations'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], animations: [ trigger('enlarge', [ state('start', style({ height: '150px' })), state('end', style({ height: '250px' })), transition('start => end', [ animate('1s 2s') ]), transition('end => start', [ animate('1s 2s') ]) ]) ] }) export class AppComponent { title = 'Animation Application'; isEnlarge: boolean = false; buttonText: string = "Enlarge"; triggerAnimation() { this.isEnlarge = !this.isEnlarge; if(this.isEnlarge) this.buttonText = "Shrink"; else this.buttonText = "Enlarge"; } } The complete AppComponent template code is as follows − <h1>{{ title }}</h1> <img [@enlarge]="isEnlarge ? 'end' : 'start'" src="assets/puppy.jpeg" style="height: 200px" /> <br /> <button (click)='triggerAnimation()'>{{ this.buttonText }}</button> Run the application using below command − ng serve Click the enlarge button, it will enlarge the image with animation. The result will be as shown below − Click the button again to shrink it. The result will be as shown below − 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2678, "s": 2388, "text": "Animation gives the web application a refreshing look and rich user interaction. In HTML, animation is basically the transformation of HTML element from one CSS style to another over a specific period of time. For example, an image element can be enlarged by changing its width and height." }, { "code": null, "e": 2951, "s": 2678, "text": "If the width and height of the image is changed from initial value to final value in steps over a period of time, say 10 seconds, then we get an animation effect. So, the scope of the animation depends on the feature / property provided by the CSS to style a HTML element." }, { "code": null, "e": 3106, "s": 2951, "text": "Angular provides a separate module BrowserAnimationModule to do the animation. BrowserAnimationModule provides an easy and clear approach to do animation." }, { "code": null, "e": 3170, "s": 3106, "text": "Let us learn how to configure animation module in this chapter." }, { "code": null, "e": 3272, "s": 3170, "text": "Follow below mentioned steps to configure animation module, BrowserAnimationModule in an application." }, { "code": null, "e": 3316, "s": 3272, "text": "Import BrowserAnimationModule in AppModule." }, { "code": null, "e": 3558, "s": 3316, "text": "import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; \n@NgModule({ \n imports: [ \n BrowserModule, \n BrowserAnimationsModule \n ], \n declarations: [ ], \n bootstrap: [ ] \n}) \nexport class AppModule { }" }, { "code": null, "e": 3612, "s": 3558, "text": "Import animation function in the relevant components." }, { "code": null, "e": 3693, "s": 3612, "text": "import { state, style, transition, animate, trigger } from '@angular/animations'" }, { "code": null, "e": 3753, "s": 3693, "text": "Add animations metadata property in the relevant component." }, { "code": null, "e": 3873, "s": 3753, "text": "@Component({ \n animations: [ \n // animation functionality goes here \n ] \n}) \nexport class MyAnimationComponent" }, { "code": null, "e": 3967, "s": 3873, "text": "In angular, we need to understand the five core concept and its relationship to do animation." }, { "code": null, "e": 3973, "s": 3967, "text": "State" }, { "code": null, "e": 4145, "s": 3973, "text": "State refers the specific state of the component. A component can have multiple defined state. The state is created using state() method. state() method has two arguments." }, { "code": null, "e": 4178, "s": 4145, "text": "name − Unique name of the state." }, { "code": null, "e": 4211, "s": 4178, "text": "name − Unique name of the state." }, { "code": null, "e": 4268, "s": 4211, "text": "style − Style of the state defined using style() method." }, { "code": null, "e": 4325, "s": 4268, "text": "style − Style of the state defined using style() method." }, { "code": null, "e": 4405, "s": 4325, "text": "animations: [ \n ... \n state('start', style( { width: 200px; } )) \n ... \n]" }, { "code": null, "e": 4443, "s": 4405, "text": "Here, start is the name of the state." }, { "code": null, "e": 4449, "s": 4443, "text": "Style" }, { "code": null, "e": 4630, "s": 4449, "text": "Style refers the CSS style applied in a particular state. style() method is used to style the particular state of a component. It uses the CSS property and can have multiple items." }, { "code": null, "e": 4721, "s": 4630, "text": "animations: [ \n ... \n state('start', style( { width: 200px; opacity: 1 } )) \n ... \n]" }, { "code": null, "e": 4814, "s": 4721, "text": "Here, start state defines two CSS property, width with value 200px and opacity with value 1." }, { "code": null, "e": 5003, "s": 4814, "text": "Transition refers the transition from one state to another. Animation can have multiple transition. Each transition is defined using transition() function. transition() takes two argument." }, { "code": null, "e": 5205, "s": 5003, "text": "Specifies the direction between two transition state. For example, start => end refers that the initial state is start and the final state is end. Actually, it is an expression with rich functionality." }, { "code": null, "e": 5407, "s": 5205, "text": "Specifies the direction between two transition state. For example, start => end refers that the initial state is start and the final state is end. Actually, it is an expression with rich functionality." }, { "code": null, "e": 5465, "s": 5407, "text": "Specifies the animation details using animate() function." }, { "code": null, "e": 5523, "s": 5465, "text": "Specifies the animation details using animate() function." }, { "code": null, "e": 5616, "s": 5523, "text": "animations: [ \n ... \n transition('start => end', [ \n animate('1s') \n ])\n ... \n]" }, { "code": null, "e": 5741, "s": 5616, "text": "Here, transition() function defines the transition from start state to end state with animation defined in animate() method." }, { "code": null, "e": 5947, "s": 5741, "text": "Animation defines the way the transition from one state to another take place. animation() function is used to set the animation details. animate() takes a single argument in the form of below expression −" }, { "code": null, "e": 5970, "s": 5947, "text": "duration delay easing\n" }, { "code": null, "e": 6056, "s": 5970, "text": "duration − refers the duration of the transition. It is expressed as 1s, 100ms, etc.," }, { "code": null, "e": 6142, "s": 6056, "text": "duration − refers the duration of the transition. It is expressed as 1s, 100ms, etc.," }, { "code": null, "e": 6233, "s": 6142, "text": "delay − refers the delay time to start the transition. It is expressed similar to duration" }, { "code": null, "e": 6324, "s": 6233, "text": "delay − refers the delay time to start the transition. It is expressed similar to duration" }, { "code": null, "e": 6419, "s": 6324, "text": "easing − refers how do to accelerates / decelerates the transition in the given time duration." }, { "code": null, "e": 6514, "s": 6419, "text": "easing − refers how do to accelerates / decelerates the transition in the given time duration." }, { "code": null, "e": 6777, "s": 6514, "text": "Every animation needs a trigger to start the animation. trigger() method is used to set all the animation information such as state, style, transition and animation in one place and give it a unique name. The unique name is used further to trigger the animation." }, { "code": null, "e": 7100, "s": 6777, "text": "animations: [ \n trigger('enlarge', [ \n state('start', style({ \n height: '200px', \n })), \n state('end', style({ \n height: '500px', \n })), \n transition('start => end', [ \n animate('1s') \n ]), \n transition('end => start', [ \n animate('0.5s') \n ]) ]), \n]\n" }, { "code": null, "e": 7332, "s": 7100, "text": "Here, enlarge is the unique name given to the particular animation. It has two state and related styles. It has two transition one from start to end and another from end to start. End to start state do the reverse of the animation." }, { "code": null, "e": 7391, "s": 7332, "text": "Trigger can be attached to an element as specified below −" }, { "code": null, "e": 7436, "s": 7391, "text": "<div [@triggerName]=\"expression\">...</div>;\n" }, { "code": null, "e": 7449, "s": 7436, "text": "For example," }, { "code": null, "e": 7507, "s": 7449, "text": "<img [@enlarge]=\"isEnlarge ? 'end' : 'start'\">...</img>;\n" }, { "code": null, "e": 7513, "s": 7507, "text": "Here," }, { "code": null, "e": 7584, "s": 7513, "text": "@enlarge − trigger is set to image tag and attrached to an expression." }, { "code": null, "e": 7655, "s": 7584, "text": "@enlarge − trigger is set to image tag and attrached to an expression." }, { "code": null, "e": 7762, "s": 7655, "text": "If isEnlarge value is changed to true, then end state will be set and it triggers start => end transition." }, { "code": null, "e": 7869, "s": 7762, "text": "If isEnlarge value is changed to true, then end state will be set and it triggers start => end transition." }, { "code": null, "e": 7979, "s": 7869, "text": "If isEnlarge value is changed to false, then start state will be set and it triggers end => start transition." }, { "code": null, "e": 8089, "s": 7979, "text": "If isEnlarge value is changed to false, then start state will be set and it triggers end => start transition." }, { "code": null, "e": 8216, "s": 8089, "text": "Let us write a new angular application to better understand the animation concept by enlarging an image with animation effect." }, { "code": null, "e": 8272, "s": 8216, "text": "Open command prompt and create new angular application." }, { "code": null, "e": 8332, "s": 8272, "text": "cd /go/to/workspace \nng new animation-app \ncd animation-app" }, { "code": null, "e": 8406, "s": 8332, "text": "Configure BrowserAnimationModule in the AppModule (src/app/app.module.ts)" }, { "code": null, "e": 8852, "s": 8406, "text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core' \nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations'; \nimport { AppComponent } from './app.component'; @NgModule({ \n declarations: [ \n AppComponent \n ], \n imports: [ \n BrowserModule, \n BrowserAnimationsModule \n ], \n providers: [], \n bootstrap: [AppComponent] \n}) \nexport class AppModule { }" }, { "code": null, "e": 8939, "s": 8852, "text": "Open AppComponent (src/app/app.component.ts) and import necessary animation functions." }, { "code": null, "e": 9021, "s": 8939, "text": "import { state, style, transition, animate, trigger } from '@angular/animations';" }, { "code": null, "e": 9126, "s": 9021, "text": "Add animation functionality, which will animate the image during the enlarging / shrinking of the image." }, { "code": null, "e": 9609, "s": 9126, "text": "@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css'],\n animations: [\n trigger('enlarge', [\n state('start', style({\n height: '150px'\n })),\n state('end', style({\n height: '250px'\n })),\n transition('start => end', [\n animate('1s 2s')\n ]),\n transition('end => start', [\n animate('1s 2s')\n ])\n ])\n ]\n})" }, { "code": null, "e": 9785, "s": 9609, "text": "Open AppComponent template, src/app/app.component.html and remove sample code. Then, include a header with application title, image and a button to enlarge / shrink the image." }, { "code": null, "e": 9908, "s": 9785, "text": "<h1>{{ title }}</h1> \n<img src=\"assets/puppy.jpeg\" style=\"height: 200px\" /> <br /> \n<button>{{ this.buttonText }}</button>" }, { "code": null, "e": 9961, "s": 9908, "text": "Write a function to change the animation expression." }, { "code": null, "e": 10284, "s": 9961, "text": "export class AppComponent { \n title = 'Animation Application'; \n isEnlarge: boolean = false; \n buttonText: string = \"Enlarge\"; \n triggerAnimation() { \n this.isEnlarge = !this.isEnlarge; \n if(this.isEnlarge) \n this.buttonText = \"Shrink\"; \n else \n this.buttonText = \"Enlarge\"; \n } \n}" }, { "code": null, "e": 10368, "s": 10284, "text": "Attach the animation in the image tag. Also, attach the click event for the button." }, { "code": null, "e": 10559, "s": 10368, "text": "<h1>{{ title }}</h1>\n<img [@enlarge]=\"isEnlarge ? 'end' : 'start'\" src=\"assets/puppy.jpeg\" style=\"height: 200px\" />\n<br />\n<button (click)='triggerAnimation()'>{{ this.buttonText }}</button>" }, { "code": null, "e": 10606, "s": 10559, "text": "The complete AppComponent code is as follows −" }, { "code": null, "e": 11531, "s": 10606, "text": "import { Component } from '@angular/core';\nimport { state, style, transition, animate, trigger } from '@angular/animations';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css'],\n animations: [\n trigger('enlarge', [\n state('start', style({\n height: '150px'\n })),\n state('end', style({\n height: '250px'\n })),\n transition('start => end', [\n animate('1s 2s')\n ]),\n transition('end => start', [\n animate('1s 2s')\n ])\n ])\n ]\n})\nexport class AppComponent {\n title = 'Animation Application';\n isEnlarge: boolean = false;\n buttonText: string = \"Enlarge\";\n\n\n triggerAnimation() {\n this.isEnlarge = !this.isEnlarge;\n\n if(this.isEnlarge) \n this.buttonText = \"Shrink\";\n else\n this.buttonText = \"Enlarge\";\n }\n}" }, { "code": null, "e": 11587, "s": 11531, "text": "The complete AppComponent template code is as follows −" }, { "code": null, "e": 11778, "s": 11587, "text": "<h1>{{ title }}</h1>\n<img [@enlarge]=\"isEnlarge ? 'end' : 'start'\" src=\"assets/puppy.jpeg\" style=\"height: 200px\" />\n<br />\n<button (click)='triggerAnimation()'>{{ this.buttonText }}</button>" }, { "code": null, "e": 11820, "s": 11778, "text": "Run the application using below command −" }, { "code": null, "e": 11829, "s": 11820, "text": "ng serve" }, { "code": null, "e": 11933, "s": 11829, "text": "Click the enlarge button, it will enlarge the image with animation. The result will be as shown below −" }, { "code": null, "e": 12006, "s": 11933, "text": "Click the button again to shrink it. The result will be as shown below −" }, { "code": null, "e": 12041, "s": 12006, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12055, "s": 12041, "text": " Anadi Sharma" }, { "code": null, "e": 12090, "s": 12055, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12104, "s": 12090, "text": " Anadi Sharma" }, { "code": null, "e": 12139, "s": 12104, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12159, "s": 12139, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12194, "s": 12159, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12211, "s": 12194, "text": " Frahaan Hussain" }, { "code": null, "e": 12244, "s": 12211, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 12256, "s": 12244, "text": " Senol Atac" }, { "code": null, "e": 12291, "s": 12256, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12303, "s": 12291, "text": " Senol Atac" }, { "code": null, "e": 12310, "s": 12303, "text": " Print" }, { "code": null, "e": 12321, "s": 12310, "text": " Add Notes" } ]
Creating custom modules in Node.js
The node.js modules are a kind of package that contains certain functions or methods to be used by those who imports them. Some modules are present on the web to be used by developers such as fs, fs-extra, crypto, stream, etc. You can also make a package of your own and use it in your code. exports.function_name = function(arg1, arg2, ....argN) { // Put your function body here... }; Create two file with name – calc.js and index.js and copy the below code snippet. The calc.js is the custom node module which will hold the node functions. The index.js will import calc.js and use it in the node process. calc.js //Creating a custom node module // And making different functions exports.add = function (a, b) { return a + b; // Adding the numbers }; exports.sub = function (a, b) { return a - b; // Subtracting the numbers }; exports.mul = function (a, b) { return a * b; // Multiplying the numbers }; exports.div = function (a, b) { return a / b; // Dividing the numbers }; index.js // Importing the custom node module with the below statement var calculator = require('./calc'); var a = 21 , b = 67 console.log("Addition of " + a + " and " + b + " is " + calculator.add(a, b)); console.log("Subtraction of " + a + " and " + b + " is " + calculator.sub(a, b)); console.log("Multiplication of " + a + " and " + b + " is " + calculator.mul(a, b)); console.log("Division of " + a + " and " + b + " is " + calculator.div(a, b)); C:\home\node>> node index.js Addition of 21 and 67 is 88 Subtraction of 21 and 67 is -46 Multiplication of 21 and 67 is 1407 Division of 21 and 67 is 0.31343283582089554
[ { "code": null, "e": 1354, "s": 1062, "text": "The node.js modules are a kind of package that contains certain functions or methods to be used by those who imports them. Some modules are present on the web to be used by developers such as fs, fs-extra, crypto, stream, etc. You can also make a package of your own and use it in your code." }, { "code": null, "e": 1451, "s": 1354, "text": "exports.function_name = function(arg1, arg2, ....argN) {\n // Put your function body here...\n};" }, { "code": null, "e": 1533, "s": 1451, "text": "Create two file with name – calc.js and index.js and copy the below code snippet." }, { "code": null, "e": 1607, "s": 1533, "text": "The calc.js is the custom node module which will hold the node functions." }, { "code": null, "e": 1672, "s": 1607, "text": "The index.js will import calc.js and use it in the node process." }, { "code": null, "e": 1680, "s": 1672, "text": "calc.js" }, { "code": null, "e": 2057, "s": 1680, "text": "//Creating a custom node module\n// And making different functions\nexports.add = function (a, b) {\n return a + b; // Adding the numbers\n};\n\nexports.sub = function (a, b) {\n return a - b; // Subtracting the numbers\n};\n\nexports.mul = function (a, b) {\n return a * b; // Multiplying the numbers\n};\n\nexports.div = function (a, b) {\n return a / b; // Dividing the numbers\n};" }, { "code": null, "e": 2066, "s": 2057, "text": "index.js" }, { "code": null, "e": 2513, "s": 2066, "text": "// Importing the custom node module with the below statement\nvar calculator = require('./calc');\n\nvar a = 21 , b = 67\n\nconsole.log(\"Addition of \" + a + \" and \" + b + \" is \" + calculator.add(a, b));\n\nconsole.log(\"Subtraction of \" + a + \" and \" + b + \" is \" + calculator.sub(a, b));\n\nconsole.log(\"Multiplication of \" + a + \" and \" + b + \" is \" + calculator.mul(a, b));\n\nconsole.log(\"Division of \" + a + \" and \" + b + \" is \" + calculator.div(a, b));" }, { "code": null, "e": 2683, "s": 2513, "text": "C:\\home\\node>> node index.js\nAddition of 21 and 67 is 88\nSubtraction of 21 and 67 is -46\nMultiplication of 21 and 67 is 1407\nDivision of 21 and 67 is 0.31343283582089554" } ]
How to read integers from a file using BufferedReader in Java?
The BufferedReader class of Java is used to read the stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter. This class provides a method known as readLine() which reads and returns the next line from the source and returns it in String format. The BufferedReader class doesn’t provide any direct method to read an integer from the user you need to rely on the readLine() method to read integers too. i.e. Initially you need to read the integers in string format. The parseInt() method of the Integer class accepts a String value, parses it as a signed decimal integer and returns it. Using this convert the read Sting value into integer and use. In short, to read integer value-form user using BufferedReader class − Instantiate an InputStreamReader class bypassing your InputStream object as a parameter. Instantiate an InputStreamReader class bypassing your InputStream object as a parameter. Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter. Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter. Now, read integer value from the current reader as String using the readLine() method. Now, read integer value from the current reader as String using the readLine() method. Then parse the read String into an integer using the parseInt() method of the Integer class. Then parse the read String into an integer using the parseInt() method of the Integer class. The following Java program demonstrates how to read integer data from the user using the BufferedReader class. Live Demo import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class Employee{ String name; int id; int age; Employee(String name, int age, int id){ this.name = name; this.age = age; this.id = id; } public void displayDetails(){ System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Id: "+this.id); } } public class ReadData { public static void main(String args[]) throws IOException { BufferedReader reader =new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter your name: "); String name = reader.readLine(); System.out.println("Enter your age: "); int age = Integer.parseInt(reader.readLine()); System.out.println("Enter your Id: "); int id = Integer.parseInt(reader.readLine()); Employee std = new Employee(name, age, id); std.displayDetails(); } } Enter your name: Krishna Enter your age: 25 Enter your Id: 1233 Name: Krishna Age: 25 Id: 1233
[ { "code": null, "e": 1264, "s": 1062, "text": "The BufferedReader class of Java is used to read the stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter." }, { "code": null, "e": 1400, "s": 1264, "text": "This class provides a method known as readLine() which reads and returns the next line from the source and returns it in String format." }, { "code": null, "e": 1619, "s": 1400, "text": "The BufferedReader class doesn’t provide any direct method to read an integer from the user you need to rely on the readLine() method to read integers too. i.e. Initially you need to read the integers in string format." }, { "code": null, "e": 1740, "s": 1619, "text": "The parseInt() method of the Integer class accepts a String value, parses it as a signed decimal integer and returns it." }, { "code": null, "e": 1873, "s": 1740, "text": "Using this convert the read Sting value into integer and use. In short, to read integer value-form user using BufferedReader class −" }, { "code": null, "e": 1962, "s": 1873, "text": "Instantiate an InputStreamReader class bypassing your InputStream object as a parameter." }, { "code": null, "e": 2051, "s": 1962, "text": "Instantiate an InputStreamReader class bypassing your InputStream object as a parameter." }, { "code": null, "e": 2152, "s": 2051, "text": "Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter." }, { "code": null, "e": 2253, "s": 2152, "text": "Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter." }, { "code": null, "e": 2340, "s": 2253, "text": "Now, read integer value from the current reader as String using the readLine() method." }, { "code": null, "e": 2427, "s": 2340, "text": "Now, read integer value from the current reader as String using the readLine() method." }, { "code": null, "e": 2520, "s": 2427, "text": "Then parse the read String into an integer using the parseInt() method of the Integer class." }, { "code": null, "e": 2613, "s": 2520, "text": "Then parse the read String into an integer using the parseInt() method of the Integer class." }, { "code": null, "e": 2724, "s": 2613, "text": "The following Java program demonstrates how to read integer data from the user using the BufferedReader class." }, { "code": null, "e": 2735, "s": 2724, "text": " Live Demo" }, { "code": null, "e": 3706, "s": 2735, "text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nclass Employee{\n String name;\n int id;\n int age;\n Employee(String name, int age, int id){\n this.name = name;\n this.age = age;\n this.id = id;\n }\n public void displayDetails(){\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Id: \"+this.id);\n }\n}\npublic class ReadData {\n public static void main(String args[]) throws IOException {\n BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"Enter your name: \");\n String name = reader.readLine();\n System.out.println(\"Enter your age: \");\n int age = Integer.parseInt(reader.readLine());\n System.out.println(\"Enter your Id: \");\n int id = Integer.parseInt(reader.readLine());\n Employee std = new Employee(name, age, id);\n std.displayDetails();\n }\n}" }, { "code": null, "e": 3801, "s": 3706, "text": "Enter your name:\nKrishna\nEnter your age:\n25\nEnter your Id:\n1233\nName: Krishna\nAge: 25\nId: 1233" } ]
C - Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. The types in C can be classified as follows − Basic Types They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types. Enumerated types They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program. The type void The type specifier void indicates that no value is available. Derived types They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types. The array types and structure types are referred collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see the basic types in the following section, where as other types will be covered in the upcoming chapters. The following table provides the details of standard integer types with their storage sizes and value ranges − To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size of various type on a machine using different constant defined in limits.h header file − #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int main(int argc, char** argv) { printf("CHAR_BIT : %d\n", CHAR_BIT); printf("CHAR_MAX : %d\n", CHAR_MAX); printf("CHAR_MIN : %d\n", CHAR_MIN); printf("INT_MAX : %d\n", INT_MAX); printf("INT_MIN : %d\n", INT_MIN); printf("LONG_MAX : %ld\n", (long) LONG_MAX); printf("LONG_MIN : %ld\n", (long) LONG_MIN); printf("SCHAR_MAX : %d\n", SCHAR_MAX); printf("SCHAR_MIN : %d\n", SCHAR_MIN); printf("SHRT_MAX : %d\n", SHRT_MAX); printf("SHRT_MIN : %d\n", SHRT_MIN); printf("UCHAR_MAX : %d\n", UCHAR_MAX); printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX); printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX); printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX); return 0; } When you compile and execute the above program, it produces the following result on Linux − CHAR_BIT : 8 CHAR_MAX : 127 CHAR_MIN : -128 INT_MAX : 2147483647 INT_MIN : -2147483648 LONG_MAX : 9223372036854775807 LONG_MIN : -9223372036854775808 SCHAR_MAX : 127 SCHAR_MIN : -128 SHRT_MAX : 32767 SHRT_MIN : -32768 UCHAR_MAX : 255 UINT_MAX : 4294967295 ULONG_MAX : 18446744073709551615 USHRT_MAX : 65535 The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision − The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. The following example prints the storage space taken by a float type and its range values − #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int main(int argc, char** argv) { printf("Storage size for float : %d \n", sizeof(float)); printf("FLT_MAX : %g\n", (float) FLT_MAX); printf("FLT_MIN : %g\n", (float) FLT_MIN); printf("-FLT_MAX : %g\n", (float) -FLT_MAX); printf("-FLT_MIN : %g\n", (float) -FLT_MIN); printf("DBL_MAX : %g\n", (double) DBL_MAX); printf("DBL_MIN : %g\n", (double) DBL_MIN); printf("-DBL_MAX : %g\n", (double) -DBL_MAX); printf("Precision value: %d\n", FLT_DIG ); return 0; } When you compile and execute the above program, it produces the following result on Linux − Storage size for float : 4 FLT_MAX : 3.40282e+38 FLT_MIN : 1.17549e-38 -FLT_MAX : -3.40282e+38 -FLT_MIN : -1.17549e-38 DBL_MAX : 1.79769e+308 DBL_MIN : 2.22507e-308 -DBL_MAX : -1.79769e+308 Precision value: 6 The void type specifies that no value is available. It is used in three kinds of situations − Function returns as void There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); Function arguments as void There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, int rand(void); Pointers to void A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type. Print Add Notes Bookmark this page
[ { "code": null, "e": 2310, "s": 2084, "text": "Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted." }, { "code": null, "e": 2356, "s": 2310, "text": "The types in C can be classified as follows −" }, { "code": null, "e": 2368, "s": 2356, "text": "Basic Types" }, { "code": null, "e": 2475, "s": 2368, "text": "They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types." }, { "code": null, "e": 2492, "s": 2475, "text": "Enumerated types" }, { "code": null, "e": 2639, "s": 2492, "text": "They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program." }, { "code": null, "e": 2653, "s": 2639, "text": "The type void" }, { "code": null, "e": 2715, "s": 2653, "text": "The type specifier void indicates that no value is available." }, { "code": null, "e": 2729, "s": 2715, "text": "Derived types" }, { "code": null, "e": 2839, "s": 2729, "text": "They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types." }, { "code": null, "e": 3116, "s": 2839, "text": "The array types and structure types are referred collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see the basic types in the following section, where as other types will be covered in the upcoming chapters." }, { "code": null, "e": 3227, "s": 3116, "text": "The following table provides the details of standard integer types with their storage sizes and value ranges −" }, { "code": null, "e": 3547, "s": 3227, "text": "To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size of various type on a machine using different constant defined in limits.h header file −" }, { "code": null, "e": 4436, "s": 3547, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n#include <float.h>\n\nint main(int argc, char** argv) {\n\n printf(\"CHAR_BIT : %d\\n\", CHAR_BIT);\n printf(\"CHAR_MAX : %d\\n\", CHAR_MAX);\n printf(\"CHAR_MIN : %d\\n\", CHAR_MIN);\n printf(\"INT_MAX : %d\\n\", INT_MAX);\n printf(\"INT_MIN : %d\\n\", INT_MIN);\n printf(\"LONG_MAX : %ld\\n\", (long) LONG_MAX);\n printf(\"LONG_MIN : %ld\\n\", (long) LONG_MIN);\n printf(\"SCHAR_MAX : %d\\n\", SCHAR_MAX);\n printf(\"SCHAR_MIN : %d\\n\", SCHAR_MIN);\n printf(\"SHRT_MAX : %d\\n\", SHRT_MAX);\n printf(\"SHRT_MIN : %d\\n\", SHRT_MIN);\n printf(\"UCHAR_MAX : %d\\n\", UCHAR_MAX);\n printf(\"UINT_MAX : %u\\n\", (unsigned int) UINT_MAX);\n printf(\"ULONG_MAX : %lu\\n\", (unsigned long) ULONG_MAX);\n printf(\"USHRT_MAX : %d\\n\", (unsigned short) USHRT_MAX);\n\n return 0;\n}" }, { "code": null, "e": 4528, "s": 4436, "text": "When you compile and execute the above program, it produces the following result on Linux −" }, { "code": null, "e": 4908, "s": 4528, "text": "CHAR_BIT : 8\nCHAR_MAX : 127\nCHAR_MIN : -128\nINT_MAX : 2147483647\nINT_MIN : -2147483648\nLONG_MAX : 9223372036854775807\nLONG_MIN : -9223372036854775808\nSCHAR_MAX : 127\nSCHAR_MIN : -128\nSHRT_MAX : 32767\nSHRT_MIN : -32768\nUCHAR_MAX : 255\nUINT_MAX : 4294967295\nULONG_MAX : 18446744073709551615\nUSHRT_MAX : 65535\n" }, { "code": null, "e": 5039, "s": 4908, "text": "The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision −" }, { "code": null, "e": 5289, "s": 5039, "text": "The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. The following example prints the storage space taken by a float type and its range values −" }, { "code": null, "e": 5905, "s": 5289, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n#include <float.h>\n\nint main(int argc, char** argv) {\n\n printf(\"Storage size for float : %d \\n\", sizeof(float));\n printf(\"FLT_MAX : %g\\n\", (float) FLT_MAX);\n printf(\"FLT_MIN : %g\\n\", (float) FLT_MIN);\n printf(\"-FLT_MAX : %g\\n\", (float) -FLT_MAX);\n printf(\"-FLT_MIN : %g\\n\", (float) -FLT_MIN);\n printf(\"DBL_MAX : %g\\n\", (double) DBL_MAX);\n printf(\"DBL_MIN : %g\\n\", (double) DBL_MIN);\n printf(\"-DBL_MAX : %g\\n\", (double) -DBL_MAX);\n printf(\"Precision value: %d\\n\", FLT_DIG );\n\n return 0;\n}" }, { "code": null, "e": 5997, "s": 5905, "text": "When you compile and execute the above program, it produces the following result on Linux −" }, { "code": null, "e": 6253, "s": 5997, "text": "Storage size for float : 4 \nFLT_MAX : 3.40282e+38\nFLT_MIN : 1.17549e-38\n-FLT_MAX : -3.40282e+38\n-FLT_MIN : -1.17549e-38\nDBL_MAX : 1.79769e+308\nDBL_MIN : 2.22507e-308\n-DBL_MAX : -1.79769e+308\nPrecision value: 6\n" }, { "code": null, "e": 6347, "s": 6253, "text": "The void type specifies that no value is available. It is used in three kinds of situations −" }, { "code": null, "e": 6372, "s": 6347, "text": "Function returns as void" }, { "code": null, "e": 6566, "s": 6372, "text": "There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);" }, { "code": null, "e": 6593, "s": 6566, "text": "Function arguments as void" }, { "code": null, "e": 6738, "s": 6593, "text": "There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, int rand(void);" }, { "code": null, "e": 6755, "s": 6738, "text": "Pointers to void" }, { "code": null, "e": 6970, "s": 6755, "text": "A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type." }, { "code": null, "e": 6977, "s": 6970, "text": " Print" }, { "code": null, "e": 6988, "s": 6977, "text": " Add Notes" } ]
How can I display an image using Pillow in Tkinter?
Python provides Pillow Package (PIL) to process and load the images in the application. An image can be loaded using the inbuilt Image.open("image location") method. Further, we can use a Label widget to display the Image in the window. #Import tkinter library from tkinter import * from PIL import Image,ImageTk #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("750x550") #Load the image img= Image.open("tutorialspoint.jpg") #Convert To photoimage tkimage= ImageTk.PhotoImage(img) #Display the Image label=Label(win,image=tkimage) label.pack() win.mainloop() Running the above code will display an image in the window. Before executing the code, make sure you have the image in the same project directory, or provide the absolute path of the image location.
[ { "code": null, "e": 1299, "s": 1062, "text": "Python provides Pillow Package (PIL) to process and load the images in the application. An image can be loaded using the inbuilt Image.open(\"image location\") method. Further, we can use a Label widget to display the Image in the window." }, { "code": null, "e": 1653, "s": 1299, "text": "#Import tkinter library\nfrom tkinter import *\nfrom PIL import Image,ImageTk\n#Create an instance of tkinter frame\nwin = Tk()\n#Set the geometry\nwin.geometry(\"750x550\")\n#Load the image\nimg= Image.open(\"tutorialspoint.jpg\")\n#Convert To photoimage\ntkimage= ImageTk.PhotoImage(img)\n#Display the Image\nlabel=Label(win,image=tkimage)\nlabel.pack()\nwin.mainloop()" }, { "code": null, "e": 1713, "s": 1653, "text": "Running the above code will display an image in the window." }, { "code": null, "e": 1852, "s": 1713, "text": "Before executing the code, make sure you have the image in the same project directory, or provide the absolute path of the image location." } ]
DW - Types
There are four types of Data Warehousing system. Data Mart Online Analytical Processing (OLAP) Online Transactional Processing (OLTP) Predictive Analysis (PA) A Data Mart is known as the simplest form of a Data Warehouse system and normally consists of a single functional area in an organization like sales, finance or marketing, etc. Data Mart in an organization and is created and managed by a single department. As it belongs to a single department, the department usually gets data from only a few or one type of sources/applications. This source could be an internal operational system, a data warehouse or an external system. In an OLAP system, there are less number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations. We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all rows. SELECT SUM(salary) FROM employee WHERE title = 'Programmer'; Response time is known as one of the most effective and key measure in an OLAP system. Aggregated stored data is maintained in multi-dimensional schemas like star schemas (When data is arranged into hierarchical groups, often called dimensions and into facts and aggregate facts, it is called Schemas). The latency of an OLAP system is of a few hours as compared to the data marts where latency is expected closer to a day. In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE. In an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP data warehouse system contains current and detailed data and is maintained in the schemas in the entity model (3NF). Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides very fast query processing. OLTP databases contain detailed and current data. Schema used to store OLTP database is the Entity model. The following illustrations shows the key differences between an OLTP and OLAP system. Indexes − OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization. Indexes − OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization. Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized. Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized. Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used. Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used. Predictive analysis is known as finding the hidden patterns in data stored in DW system by using different mathematical functions to predict future outcomes. Predictive Analysis system is different from an OLAP system in terms of its use. It is used to focus on future outcomes. An OALP system focuses on current and historical data processing for analytical reporting. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2910, "s": 2861, "text": "There are four types of Data Warehousing system." }, { "code": null, "e": 2920, "s": 2910, "text": "Data Mart" }, { "code": null, "e": 2956, "s": 2920, "text": "Online Analytical Processing (OLAP)" }, { "code": null, "e": 2995, "s": 2956, "text": "Online Transactional Processing (OLTP)" }, { "code": null, "e": 3020, "s": 2995, "text": "Predictive Analysis (PA)" }, { "code": null, "e": 3197, "s": 3020, "text": "A Data Mart is known as the simplest form of a Data Warehouse system and normally consists of a single functional area in an organization like sales, finance or marketing, etc." }, { "code": null, "e": 3494, "s": 3197, "text": "Data Mart in an organization and is created and managed by a single department. As it belongs to a single department, the department usually gets data from only a few or one type of sources/applications. This source could be an internal operational system, a data warehouse or an external system." }, { "code": null, "e": 3665, "s": 3494, "text": "In an OLAP system, there are less number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations." }, { "code": null, "e": 3908, "s": 3665, "text": "We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all rows." }, { "code": null, "e": 3970, "s": 3908, "text": "SELECT SUM(salary)\nFROM employee\nWHERE title = 'Programmer';\n" }, { "code": null, "e": 4273, "s": 3970, "text": "Response time is known as one of the most effective and key measure in an OLAP system. Aggregated stored data is maintained in multi-dimensional schemas like star schemas (When data is arranged into hierarchical groups, often called dimensions and into facts and aggregate facts, it is called Schemas)." }, { "code": null, "e": 4394, "s": 4273, "text": "The latency of an OLAP system is of a few hours as compared to the data marts where latency is expected closer to a day." }, { "code": null, "e": 4503, "s": 4394, "text": "In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE." }, { "code": null, "e": 4874, "s": 4503, "text": "In an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP data warehouse system contains current and detailed data and is maintained in the schemas in the entity model (3NF)." }, { "code": null, "e": 5148, "s": 4874, "text": "Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides very fast query processing. OLTP databases contain detailed and current data. Schema used to store OLTP database is the Entity model." }, { "code": null, "e": 5235, "s": 5148, "text": "The following illustrations shows the key differences between an OLTP and OLAP system." }, { "code": null, "e": 5355, "s": 5235, "text": "Indexes − OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization." }, { "code": null, "e": 5475, "s": 5355, "text": "Indexes − OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization." }, { "code": null, "e": 5620, "s": 5475, "text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized." }, { "code": null, "e": 5765, "s": 5620, "text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized." }, { "code": null, "e": 5875, "s": 5765, "text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used." }, { "code": null, "e": 5985, "s": 5875, "text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used." }, { "code": null, "e": 6143, "s": 5985, "text": "Predictive analysis is known as finding the hidden patterns in data stored in DW system by using different mathematical functions to predict future outcomes." }, { "code": null, "e": 6355, "s": 6143, "text": "Predictive Analysis system is different from an OLAP system in terms of its use. It is used to focus on future outcomes. An OALP system focuses on current and historical data processing for analytical reporting." }, { "code": null, "e": 6388, "s": 6355, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6402, "s": 6388, "text": " Sanjo Thomas" }, { "code": null, "e": 6435, "s": 6402, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6447, "s": 6435, "text": " Neha Gupta" }, { "code": null, "e": 6482, "s": 6447, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6497, "s": 6482, "text": " Sumit Agarwal" }, { "code": null, "e": 6530, "s": 6497, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6545, "s": 6530, "text": " Sumit Agarwal" }, { "code": null, "e": 6580, "s": 6545, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6592, "s": 6580, "text": " Neha Malik" }, { "code": null, "e": 6627, "s": 6592, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6639, "s": 6627, "text": " Neha Malik" }, { "code": null, "e": 6646, "s": 6639, "text": " Print" }, { "code": null, "e": 6657, "s": 6646, "text": " Add Notes" } ]
How to get first day of week in PHP?
To get the first day of the week in PHP, the code is as follows − Live Demo <?php $res = date('l - d/m/Y', strtotime("this week")); echo "First day = ", $res; ?> This will produce the following output − First day = Monday - 09/12/2019 Let us now see another example − Live Demo <?php echo "Displaying Sunday as first day of a week...\n"; $res = date('l - d/m/Y', strtotime("sunday 0 week")); echo "First day (next week) = ", $res; ?> This will produce the following output − Displaying Sunday as first day of a week... First day (next week) = Sunday - 15/12/2019
[ { "code": null, "e": 1128, "s": 1062, "text": "To get the first day of the week in PHP, the code is as follows −" }, { "code": null, "e": 1139, "s": 1128, "text": " Live Demo" }, { "code": null, "e": 1231, "s": 1139, "text": "<?php\n $res = date('l - d/m/Y', strtotime(\"this week\"));\n echo \"First day = \", $res;\n?>" }, { "code": null, "e": 1272, "s": 1231, "text": "This will produce the following output −" }, { "code": null, "e": 1304, "s": 1272, "text": "First day = Monday - 09/12/2019" }, { "code": null, "e": 1337, "s": 1304, "text": "Let us now see another example −" }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1513, "s": 1348, "text": "<?php\n echo \"Displaying Sunday as first day of a week...\\n\";\n $res = date('l - d/m/Y', strtotime(\"sunday 0 week\"));\n echo \"First day (next week) = \", $res;\n?>" }, { "code": null, "e": 1554, "s": 1513, "text": "This will produce the following output −" }, { "code": null, "e": 1642, "s": 1554, "text": "Displaying Sunday as first day of a week...\nFirst day (next week) = Sunday - 15/12/2019" } ]
Understanding the n_jobs Parameter to Speedup scikit-learn Classification | by Angelica Lo Duca | Towards Data Science
In this tutorial I illustrate the importance of the n_jobs parameter provided by some classes of the scikit-learn library. According to the official scikit-learn library, the n_jobs parameter is described as follows: The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. This means that the n_jobs parameter can be used to distribute and exploit all the CPUs available in the local computer. In this tutorial, I evaluate the time elapsed to fit all the default classification datasets provided by the scikit-learn library, by varying the n_jobs parameter from 1 to the maximum number of CPUs. As example, I will try a K-Neighbors Classifier with Grid Search with Cross Validation. Firstly I define a list of all the classification datasets names, contained in the sklearn.datasets package. datasets_list = ['iris', 'digits', 'wine', 'breast_cancer','diabetes'] Then, I calculate the number of CPUs available in my system. I exploit the cpu_count() function provided by the os package. import os n_cpu = os.cpu_count()print("Number of CPUs in the system:", n_cpu) In my case. the number of CPUs is 4 (a quite old computer, sigh...I should decide to build a newer one...) I also define all the parameters for the Grid Search. import numpy as npparameters = { 'n_neighbors' : np.arange(2, 25), 'weights' : ['uniform', 'distance'], 'metric' : ['euclidean', 'manhattan', 'chebyshev', 'minkowski'], 'algorithm' : ['ball_tree', 'kd_tree'] } Now, I’m ready to define the main function, which will be used to test the time elapsed for training. I import all the needed functions and classes: from sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import GridSearchCVfrom sklearn.datasets import *import time and I define the load_and_train() function, which receives the dataset name as input. In order to load the corresponding dataaset, I exploit the globals() function, which contains a table with all the imported functions. Since I have already imported all the datasets provided by scikit-learn, I can pass the function name to the globals() function. The syntax is: globals()[<function_name>](). def load_and_train(name): dataset = globals()['load_' + name]() X = dataset.data y = dataset.target Once loaded the dataset, I can build a loop which iterates across the number of CPUS and calculates the time elapsed for training, by varying the number of CPUs. I build a list with all the elapsed times, which are eventually returned by the function. tdelta_list = [] for i in range(1, n_cpu+1): s = time.time() model = KNeighborsClassifier(n_jobs=i) clf = GridSearchCV(model, parameters, cv = 10) model.fit(X_train, y_train) e = time.time() tdelta = e - s tdelta_list.append({'time' : tdelta, 'bin' : i}) return tdelta_list Finally I invoke the load_and_train() function for all the datasets names and I plot results. import matplotlib.pyplot as pltimport pandas as pdfor d in datasets_list: tdelta_list = load_and_train(d) df = pd.DataFrame(tdelta_list) plt.plot(df['bin'], df['time'], label=d)plt.grid()plt.legend()plt.xlabel('N Jobs')plt.ylabel('Time for fit (sec.)')plt.title('Time for fit VS number of CPUs')plt.show() For all the datasets, the time elapsed to perform Grid search with Cross Validation for K-Neighbours Classifiers decreases by increasing the number of jobs. For this reason, I strongly suggest you to use the n_jobs parameter. Specifically, I suggest to set n_jobs=n_cpus-1 , in order to avoid that the machine gets stuck. In this tutorial, I have demonstrated how the use of the n_jobs parameter can speedup the training process. The full code for this tutorial can be downloaded from my Github repository. Now Medium provides a new feature, namely it permits to build lists. If you liked this article, you can add it to your favourite list, simply clicking on the button, put on the top right button of the article: If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github.
[ { "code": null, "e": 389, "s": 172, "text": "In this tutorial I illustrate the importance of the n_jobs parameter provided by some classes of the scikit-learn library. According to the official scikit-learn library, the n_jobs parameter is described as follows:" }, { "code": null, "e": 535, "s": 389, "text": "The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors." }, { "code": null, "e": 656, "s": 535, "text": "This means that the n_jobs parameter can be used to distribute and exploit all the CPUs available in the local computer." }, { "code": null, "e": 945, "s": 656, "text": "In this tutorial, I evaluate the time elapsed to fit all the default classification datasets provided by the scikit-learn library, by varying the n_jobs parameter from 1 to the maximum number of CPUs. As example, I will try a K-Neighbors Classifier with Grid Search with Cross Validation." }, { "code": null, "e": 1054, "s": 945, "text": "Firstly I define a list of all the classification datasets names, contained in the sklearn.datasets package." }, { "code": null, "e": 1125, "s": 1054, "text": "datasets_list = ['iris', 'digits', 'wine', 'breast_cancer','diabetes']" }, { "code": null, "e": 1249, "s": 1125, "text": "Then, I calculate the number of CPUs available in my system. I exploit the cpu_count() function provided by the os package." }, { "code": null, "e": 1328, "s": 1249, "text": "import os n_cpu = os.cpu_count()print(\"Number of CPUs in the system:\", n_cpu)" }, { "code": null, "e": 1435, "s": 1328, "text": "In my case. the number of CPUs is 4 (a quite old computer, sigh...I should decide to build a newer one...)" }, { "code": null, "e": 1489, "s": 1435, "text": "I also define all the parameters for the Grid Search." }, { "code": null, "e": 1810, "s": 1489, "text": "import numpy as npparameters = { 'n_neighbors' : np.arange(2, 25), 'weights' : ['uniform', 'distance'], 'metric' : ['euclidean', 'manhattan', 'chebyshev', 'minkowski'], 'algorithm' : ['ball_tree', 'kd_tree'] }" }, { "code": null, "e": 1959, "s": 1810, "text": "Now, I’m ready to define the main function, which will be used to test the time elapsed for training. I import all the needed functions and classes:" }, { "code": null, "e": 2099, "s": 1959, "text": "from sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import GridSearchCVfrom sklearn.datasets import *import time" }, { "code": null, "e": 2494, "s": 2099, "text": "and I define the load_and_train() function, which receives the dataset name as input. In order to load the corresponding dataaset, I exploit the globals() function, which contains a table with all the imported functions. Since I have already imported all the datasets provided by scikit-learn, I can pass the function name to the globals() function. The syntax is: globals()[<function_name>]()." }, { "code": null, "e": 2603, "s": 2494, "text": "def load_and_train(name): dataset = globals()['load_' + name]() X = dataset.data y = dataset.target" }, { "code": null, "e": 2855, "s": 2603, "text": "Once loaded the dataset, I can build a loop which iterates across the number of CPUS and calculates the time elapsed for training, by varying the number of CPUs. I build a list with all the elapsed times, which are eventually returned by the function." }, { "code": null, "e": 3189, "s": 2855, "text": " tdelta_list = [] for i in range(1, n_cpu+1): s = time.time() model = KNeighborsClassifier(n_jobs=i) clf = GridSearchCV(model, parameters, cv = 10) model.fit(X_train, y_train) e = time.time() tdelta = e - s tdelta_list.append({'time' : tdelta, 'bin' : i}) return tdelta_list" }, { "code": null, "e": 3283, "s": 3189, "text": "Finally I invoke the load_and_train() function for all the datasets names and I plot results." }, { "code": null, "e": 3598, "s": 3283, "text": "import matplotlib.pyplot as pltimport pandas as pdfor d in datasets_list: tdelta_list = load_and_train(d) df = pd.DataFrame(tdelta_list) plt.plot(df['bin'], df['time'], label=d)plt.grid()plt.legend()plt.xlabel('N Jobs')plt.ylabel('Time for fit (sec.)')plt.title('Time for fit VS number of CPUs')plt.show()" }, { "code": null, "e": 3824, "s": 3598, "text": "For all the datasets, the time elapsed to perform Grid search with Cross Validation for K-Neighbours Classifiers decreases by increasing the number of jobs. For this reason, I strongly suggest you to use the n_jobs parameter." }, { "code": null, "e": 3920, "s": 3824, "text": "Specifically, I suggest to set n_jobs=n_cpus-1 , in order to avoid that the machine gets stuck." }, { "code": null, "e": 4028, "s": 3920, "text": "In this tutorial, I have demonstrated how the use of the n_jobs parameter can speedup the training process." }, { "code": null, "e": 4105, "s": 4028, "text": "The full code for this tutorial can be downloaded from my Github repository." }, { "code": null, "e": 4315, "s": 4105, "text": "Now Medium provides a new feature, namely it permits to build lists. If you liked this article, you can add it to your favourite list, simply clicking on the button, put on the top right button of the article:" } ]
Erlang - Exceptions
Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application. Normally when an exception or error occurs in Erlang, the following message will be displayed. {"init terminating in do_boot", {undef,[{helloworld,start,[],[]}, {init,start_it,1,[]},{init,start_em,1,[]}]}} Crash dump will be written to − erl_crash.dump init terminating in do_boot () In Erlang, there are 3 types of exceptions − Error − Calling erlang:error(Reason) will end the execution in the current process and include a stack trace of the last functions called with their arguments when you catch it. These are the kind of exceptions that provoke the runtime errors above. Error − Calling erlang:error(Reason) will end the execution in the current process and include a stack trace of the last functions called with their arguments when you catch it. These are the kind of exceptions that provoke the runtime errors above. Exists − There are two kinds of exits: 'internal' exits and 'external' exits. The internal exits are triggered by calling the function exit/1 and make the current process stop its execution. The external exits are called with exit/2 and have to do with multiple processes in the concurrent aspect of Erlang. Exists − There are two kinds of exits: 'internal' exits and 'external' exits. The internal exits are triggered by calling the function exit/1 and make the current process stop its execution. The external exits are called with exit/2 and have to do with multiple processes in the concurrent aspect of Erlang. Throw − A throw is a class of exception used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don't really carry any 'crash that process!' intent behind them, but rather they control the flow. As you use throws while expecting the programmer to handle them, it's usually a good idea to document their use within a module using them. Throw − A throw is a class of exception used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don't really carry any 'crash that process!' intent behind them, but rather they control the flow. As you use throws while expecting the programmer to handle them, it's usually a good idea to document their use within a module using them. A try ... catch is a way to evaluate an expression while letting you handle the successful case as well as the errors encountered. The general syntax of a try catch expression is as follows. try Expression of SuccessfulPattern1 [Guards] -> Expression1; SuccessfulPattern2 [Guards] -> Expression2 catch TypeOfError:ExceptionPattern1 -> Expression3; TypeOfError:ExceptionPattern2 -> Expression4 end The Expression in between try and of is said to be protected. This means that any kind of exception happening within that call will be caught. The patterns and expressions in between the try ... of and catch behave in exactly the same manner as a case ... of. Finally, the catch part – here, you can replace TypeOfError by either error, throw or exit, for each respective type we've seen in this chapter. If no type is provided, a throw is assumed. Following are some of the errors and the error reasons in Erlang − Following is an example of how these exceptions can be used and how things are done. The first function generates all possible types of an exception. The first function generates all possible types of an exception. Then we write a wrapper function to call generate_exception in a try...catch expression. Then we write a wrapper function to call generate_exception in a try...catch expression. -module(helloworld). -compile(export_all). generate_exception(1) -> a; generate_exception(2) -> throw(a); generate_exception(3) -> exit(a); generate_exception(4) -> {'EXIT', a}; generate_exception(5) -> erlang:error(a). demo1() -> [catcher(I) || I <- [1,2,3,4,5]]. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} catch throw:X -> {N, caught, thrown, X}; exit:X -> {N, caught, exited, X}; error:X -> {N, caught, error, X} end. demo2() -> [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]]. demo3() -> try generate_exception(5) catch error:X -> {X, erlang:get_stacktrace()} end. lookup(N) -> case(N) of 1 -> {'EXIT', a}; 2 -> exit(a) end. If we run the program as helloworld:demo(). , we will get the following output − [{1,normal,a}, {2,caught,thrown,a}, {3,caught,exited,a}, {4,normal,{'EXIT',a}}, {5,caught,error,a}] Print Add Notes Bookmark this page
[ { "code": null, "e": 2589, "s": 2301, "text": "Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application." }, { "code": null, "e": 2684, "s": 2589, "text": "Normally when an exception or error occurs in Erlang, the following message will be displayed." }, { "code": null, "e": 2797, "s": 2684, "text": "{\"init terminating in do_boot\", {undef,[{helloworld,start,[],[]}, \n{init,start_it,1,[]},{init,start_em,1,[]}]}}\n" }, { "code": null, "e": 2829, "s": 2797, "text": "Crash dump will be written to −" }, { "code": null, "e": 2876, "s": 2829, "text": "erl_crash.dump\ninit terminating in do_boot ()\n" }, { "code": null, "e": 2921, "s": 2876, "text": "In Erlang, there are 3 types of exceptions −" }, { "code": null, "e": 3171, "s": 2921, "text": "Error − Calling erlang:error(Reason) will end the execution in the current process and include a stack trace of the last functions called with their arguments when you catch it. These are the kind of exceptions that provoke the runtime errors above." }, { "code": null, "e": 3421, "s": 3171, "text": "Error − Calling erlang:error(Reason) will end the execution in the current process and include a stack trace of the last functions called with their arguments when you catch it. These are the kind of exceptions that provoke the runtime errors above." }, { "code": null, "e": 3729, "s": 3421, "text": "Exists − There are two kinds of exits: 'internal' exits and 'external' exits. The internal exits are triggered by calling the function exit/1 and make the current process stop its execution. The external exits are called with exit/2 and have to do with multiple processes in the concurrent aspect of Erlang." }, { "code": null, "e": 4037, "s": 3729, "text": "Exists − There are two kinds of exits: 'internal' exits and 'external' exits. The internal exits are triggered by calling the function exit/1 and make the current process stop its execution. The external exits are called with exit/2 and have to do with multiple processes in the concurrent aspect of Erlang." }, { "code": null, "e": 4420, "s": 4037, "text": "Throw − A throw is a class of exception used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don't really carry any 'crash that process!' intent behind them, but rather they control the flow. As you use throws while expecting the programmer to handle them, it's usually a good idea to document their use within a module using them." }, { "code": null, "e": 4803, "s": 4420, "text": "Throw − A throw is a class of exception used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don't really carry any 'crash that process!' intent behind them, but rather they control the flow. As you use throws while expecting the programmer to handle them, it's usually a good idea to document their use within a module using them." }, { "code": null, "e": 4934, "s": 4803, "text": "A try ... catch is a way to evaluate an expression while letting you handle the successful case as well as the errors encountered." }, { "code": null, "e": 4994, "s": 4934, "text": "The general syntax of a try catch expression is as follows." }, { "code": null, "e": 5212, "s": 4994, "text": "try Expression of \nSuccessfulPattern1 [Guards] -> \nExpression1; \nSuccessfulPattern2 [Guards] -> \nExpression2 \n\ncatch \nTypeOfError:ExceptionPattern1 -> \nExpression3; \nTypeOfError:ExceptionPattern2 -> \nExpression4 \nend\n" }, { "code": null, "e": 5472, "s": 5212, "text": "The Expression in between try and of is said to be protected. This means that any kind of exception happening within that call will be caught. The patterns and expressions in between the try ... of and catch behave in exactly the same manner as a case ... of." }, { "code": null, "e": 5661, "s": 5472, "text": "Finally, the catch part – here, you can replace TypeOfError by either error, throw or exit, for each respective type we've seen in this chapter. If no type is provided, a throw is assumed." }, { "code": null, "e": 5728, "s": 5661, "text": "Following are some of the errors and the error reasons in Erlang −" }, { "code": null, "e": 5813, "s": 5728, "text": "Following is an example of how these exceptions can be used and how things are done." }, { "code": null, "e": 5878, "s": 5813, "text": "The first function generates all possible types of an exception." }, { "code": null, "e": 5943, "s": 5878, "text": "The first function generates all possible types of an exception." }, { "code": null, "e": 6032, "s": 5943, "text": "Then we write a wrapper function to call generate_exception in a try...catch expression." }, { "code": null, "e": 6121, "s": 6032, "text": "Then we write a wrapper function to call generate_exception in a try...catch expression." }, { "code": null, "e": 6906, "s": 6121, "text": "-module(helloworld). \n-compile(export_all). \n\ngenerate_exception(1) -> a; \ngenerate_exception(2) -> throw(a); \ngenerate_exception(3) -> exit(a); \ngenerate_exception(4) -> {'EXIT', a}; \ngenerate_exception(5) -> erlang:error(a). \n\ndemo1() -> \n [catcher(I) || I <- [1,2,3,4,5]]. \ncatcher(N) -> \n try generate_exception(N) of \n Val -> {N, normal, Val} \n catch \n throw:X -> {N, caught, thrown, X}; \n exit:X -> {N, caught, exited, X}; \n error:X -> {N, caught, error, X} \n end. \n \ndemo2() -> \n [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]]. \ndemo3() -> \n try generate_exception(5) \n catch \n error:X -> \n {X, erlang:get_stacktrace()} \n end. \n \nlookup(N) -> \n case(N) of \n 1 -> {'EXIT', a}; \n 2 -> exit(a) \n end." }, { "code": null, "e": 6987, "s": 6906, "text": "If we run the program as helloworld:demo(). , we will get the following output −" }, { "code": null, "e": 7088, "s": 6987, "text": "[{1,normal,a},\n{2,caught,thrown,a},\n{3,caught,exited,a},\n{4,normal,{'EXIT',a}},\n{5,caught,error,a}]\n" }, { "code": null, "e": 7095, "s": 7088, "text": " Print" }, { "code": null, "e": 7106, "s": 7095, "text": " Add Notes" } ]
C library function - getc()
The C library function int getc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. Following is the declaration for getc() function. int getc(FILE *stream) stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed. stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed. This function returns the character read as an unsigned char cast to an int or EOF on end of file or error. The following example shows the usage of getc() function. #include<stdio.h> int main () { char c; printf("Enter character: "); c = getc(stdin); printf("Character entered: "); putc(c, stdout); return(0); } Let us compile and run the above program that will produce the following result − Enter character: a Character entered: a 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2174, "s": 2007, "text": "The C library function int getc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream." }, { "code": null, "e": 2224, "s": 2174, "text": "Following is the declaration for getc() function." }, { "code": null, "e": 2247, "s": 2224, "text": "int getc(FILE *stream)" }, { "code": null, "e": 2363, "s": 2247, "text": "stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed." }, { "code": null, "e": 2479, "s": 2363, "text": "stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed." }, { "code": null, "e": 2587, "s": 2479, "text": "This function returns the character read as an unsigned char cast to an int or EOF on end of file or error." }, { "code": null, "e": 2645, "s": 2587, "text": "The following example shows the usage of getc() function." }, { "code": null, "e": 2816, "s": 2645, "text": "#include<stdio.h>\n\nint main () {\n char c;\n\n printf(\"Enter character: \");\n c = getc(stdin);\n printf(\"Character entered: \");\n putc(c, stdout);\n \n return(0);\n}" }, { "code": null, "e": 2898, "s": 2816, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2939, "s": 2898, "text": "Enter character: a\nCharacter entered: a\n" }, { "code": null, "e": 2972, "s": 2939, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2987, "s": 2972, "text": " Nishant Malik" }, { "code": null, "e": 3022, "s": 2987, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3037, "s": 3022, "text": " Nishant Malik" }, { "code": null, "e": 3072, "s": 3037, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3086, "s": 3072, "text": " Asif Hussain" }, { "code": null, "e": 3119, "s": 3086, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3137, "s": 3119, "text": " Richa Maheshwari" }, { "code": null, "e": 3172, "s": 3137, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3191, "s": 3172, "text": " Vandana Annavaram" }, { "code": null, "e": 3224, "s": 3191, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3236, "s": 3224, "text": " Amit Diwan" }, { "code": null, "e": 3243, "s": 3236, "text": " Print" }, { "code": null, "e": 3254, "s": 3243, "text": " Add Notes" } ]
Special array reversal | Practice | GeeksforGeeks
Given a string S, containing special characters and all the alphabets, reverse the string without affecting the positions of the special characters. Example 1: Input: S = "A&B" Output: "B&A" Explanation: As we ignore '&' and then reverse, so answer is "B&A". ​Example 2: Input: S = "A&x# Output: "x&A#" Explanation: we swap only A and x. Your Task: You don't need to read input or print anything. Your task is to complete the function reverse() which takes the string as inputs and returns required reverse string. Expected Time Complexity: O(|S|) Expected Auxiliary Space: O(1) Constraints: 1 ≤ |S| ≤ 105 0 sachinupreti1901 day ago Easiest question ever seen class Solution{ public: string reverse(string str) { //code here. // halwa; string ptr=""; int i; for(i=0;i<str.size();i++) { if((str[i]>='A' && str[i]<='Z' )|| (str[i]>='a' && str[i]<='z')) ptr+=str[i]; } int j=ptr.size()-1; string fin=""; for(i=0;i<str.size();i++) { if((str[i]>='A' && str[i]<='Z' )|| (str[i]>='a' && str[i]<='z')) { fin+=ptr[j]; j--; } else fin+=str[i]; } return fin; } }; 0 devashishsharma2602 weeks ago JAVA SOLUTION class Solution{ public String reverse(String str) { //complete the function here char arr[]=str.toCharArray(); Stack<Character>st=new Stack<>(); for(int i=0;i<arr.length;i++){ if(arr[i]>='a'&&arr[i]<='z'||arr[i]>='A'&&arr[i]<='Z') st.push(arr[i]); } for(int i=0;i<arr.length;i++){ if(arr[i]>='a'&&arr[i]<='z'||arr[i]>='A'&&arr[i]<='Z') arr[i]=st.pop(); } String res = String.copyValueOf(arr); return res; }} +1 mayank20212 months ago C++string reverse(string str) { string rev=""; for(int i=str.length()-1; i>=0; i--) { if( (str[i]>='a' &&str[i]<='z') || (str[i]>='A' &&str[i]<='Z') ) rev=rev+str[i]; } // cout<<"--1--"<<rev<<endl; int j=0; for(int i=0; i<=str.length()-1; i++) { if( (str[i]>='a' &&str[i]<='z') || (str[i]>='A' &&str[i]<='Z') ) { str[i]=rev[j]; j++; } } return str; } 0 sharma_nitin_262 months ago class Solution { public: string reverse(string str) { int i=0; int j=str.size()-1; while(i<j){ while(i<j){ if(str[i]>='a' && str[i]<='z' || str[i]>='A' && str[i]<='Z') break; i++; } while(i<j){ if(str[j]>='a' && str[j]<='z' || str[j]>='A' && str[j]<='Z') break; j--; } swap(str[i],str[j]); i++; j--; } return str; } }; +1 ayushjha520013 months ago //Java Solution class Solution{ public String reverse(String s) { //complete the function here char[] str=s.toCharArray(); char a; for(int i=0,j=s.length()-1;i<s.length() && i<=j;) { if(!Character.isAlphabetic(str[i])) { i++; } else if(!Character.isAlphabetic(str[j])) { j--; } else { a=str[i]; str[i]=str[j]; str[j]=a; i++; j--; } } String ans=String.valueOf(str); return ans; }} 0 ilihaspatel443 months ago // simple c++ solution string reverse(string str) { int i=0; int j=str.size()-1; while(i<j){ while(isalpha(str[i]) and isalpha(str[j]) and i<j){ swap(str[i],str[j]); i++; j--; } while(!isalpha(str[i]) and i<j ){ i++; } while(!isalpha(str[j]) and j>i ){ j--; } } return str; } +1 illiyazzr3 months ago C++ Solution :- bool alphabet(char ch){ if(ch>=65 && ch<=90 || ch>=97 && ch<=122){ return true; } return false;}void swap(int *x,int *y){ int temp = *x; *x=*y; *y=temp;}int main(){ string str = "A&x#"; int i=0,j=str.size()-1; while(i<j){ if(alphabet(str[i])&&alphabet(str[j])){ swap(str[i++],str[j--]); } else if(alphabet(str[i])){j--;} else if(alphabet(str[j])){i++;} else{i++;j--;} } cout<<str;} 0 amiransarimy3 months ago Python Solutions def reverse(self, s): i = 0 # left most index j = len(s)-1 # right most index mlist = list(s) #convert string into list while i <= j and j >=0: if not mlist[i]. isalpha(): i += 1 elif not mlist[j].isalpha(): j -= 1 else: mlist[i], mlist[j] = mlist[j],mlist[i] i += 1 # increment one index from left j -= 1 # decrement one index from right return ''.join(mlist) 0 yashpatil710973 months ago int i=0; int j=s1.length()-1; char []arr1=s1.toCharArray(); while(i<j) { char ch1=arr1[i]; char ch2=arr1[j]; if(((ch1>=97&&ch1<=122)||(ch1>=65&&ch1<=90))==false) { i++; continue; } else if(((ch2>=97&&ch2<=122)||(ch2>=65&&ch2<=90))==false) { j--; continue; } else { char temp=arr1[i]; arr1[i]=arr1[j]; arr1[j]=temp; i++; j--; } } String res=String.valueOf(arr1); return res; +3 badgujarsachin836 months ago string reverse(string str) { //code here. int low=0; int high=str.size()-1; while(low<=high){ if(!((str[low]>='a'&& str[low]<='z') || (str[low]>='A'&& str[low]<='Z'))){ low++; continue; }else if(!((str[high]>='a'&& str[high]<='z') || (str[high]>='A'&& str[high]<='Z'))){ high--; continue; } swap(str[low],str[high]); low++;high--; } return str; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 387, "s": 238, "text": "Given a string S, containing special characters and all the alphabets, reverse the string without\naffecting the positions of the special characters." }, { "code": null, "e": 398, "s": 387, "text": "Example 1:" }, { "code": null, "e": 498, "s": 398, "text": "Input: S = \"A&B\"\nOutput: \"B&A\"\nExplanation: As we ignore '&' and\nthen reverse, so answer is \"B&A\".\n" }, { "code": null, "e": 513, "s": 498, "text": "​Example 2:" }, { "code": null, "e": 580, "s": 513, "text": "Input: S = \"A&x#\nOutput: \"x&A#\"\nExplanation: we swap only A and x." }, { "code": null, "e": 853, "s": 580, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function reverse() which takes the string as inputs and returns required reverse string.\n\nExpected Time Complexity: O(|S|)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ |S| ≤ 105" }, { "code": null, "e": 855, "s": 853, "text": "0" }, { "code": null, "e": 880, "s": 855, "text": "sachinupreti1901 day ago" }, { "code": null, "e": 907, "s": 880, "text": "Easiest question ever seen" }, { "code": null, "e": 1494, "s": 909, "text": "class Solution{ public: string reverse(string str) { //code here. // halwa; string ptr=\"\"; int i; for(i=0;i<str.size();i++) { if((str[i]>='A' && str[i]<='Z' )|| (str[i]>='a' && str[i]<='z')) ptr+=str[i]; } int j=ptr.size()-1; string fin=\"\"; for(i=0;i<str.size();i++) { if((str[i]>='A' && str[i]<='Z' )|| (str[i]>='a' && str[i]<='z')) { fin+=ptr[j]; j--; } else fin+=str[i]; } return fin; } };" }, { "code": null, "e": 1496, "s": 1494, "text": "0" }, { "code": null, "e": 1526, "s": 1496, "text": "devashishsharma2602 weeks ago" }, { "code": null, "e": 1540, "s": 1526, "text": "JAVA SOLUTION" }, { "code": null, "e": 2059, "s": 1542, "text": "class Solution{ public String reverse(String str) { //complete the function here char arr[]=str.toCharArray(); Stack<Character>st=new Stack<>(); for(int i=0;i<arr.length;i++){ if(arr[i]>='a'&&arr[i]<='z'||arr[i]>='A'&&arr[i]<='Z') st.push(arr[i]); } for(int i=0;i<arr.length;i++){ if(arr[i]>='a'&&arr[i]<='z'||arr[i]>='A'&&arr[i]<='Z') arr[i]=st.pop(); } String res = String.copyValueOf(arr); return res; }}" }, { "code": null, "e": 2064, "s": 2061, "text": "+1" }, { "code": null, "e": 2087, "s": 2064, "text": "mayank20212 months ago" }, { "code": null, "e": 2655, "s": 2087, "text": "C++string reverse(string str) { string rev=\"\"; for(int i=str.length()-1; i>=0; i--) { if( (str[i]>='a' &&str[i]<='z') || (str[i]>='A' &&str[i]<='Z') ) rev=rev+str[i]; } // cout<<\"--1--\"<<rev<<endl; int j=0; for(int i=0; i<=str.length()-1; i++) { if( (str[i]>='a' &&str[i]<='z') || (str[i]>='A' &&str[i]<='Z') ) { str[i]=rev[j]; j++; } } return str; }" }, { "code": null, "e": 2657, "s": 2655, "text": "0" }, { "code": null, "e": 2685, "s": 2657, "text": "sharma_nitin_262 months ago" }, { "code": null, "e": 3260, "s": 2685, "text": "class Solution\n{\n public:\n string reverse(string str)\n { \n int i=0;\n int j=str.size()-1;\n \n while(i<j){\n while(i<j){\n if(str[i]>='a' && str[i]<='z' || str[i]>='A' && str[i]<='Z')\n break;\n i++;\n }\n while(i<j){\n if(str[j]>='a' && str[j]<='z' || str[j]>='A' && str[j]<='Z')\n break;\n j--;\n }\n swap(str[i],str[j]);\n i++;\n j--;\n }\n return str;\n } \n};\n" }, { "code": null, "e": 3263, "s": 3260, "text": "+1" }, { "code": null, "e": 3289, "s": 3263, "text": "ayushjha520013 months ago" }, { "code": null, "e": 3306, "s": 3289, "text": "//Java Solution " }, { "code": null, "e": 3825, "s": 3306, "text": "class Solution{ public String reverse(String s) { //complete the function here char[] str=s.toCharArray(); char a; for(int i=0,j=s.length()-1;i<s.length() && i<=j;) { if(!Character.isAlphabetic(str[i])) { i++; } else if(!Character.isAlphabetic(str[j])) { j--; } else { a=str[i]; str[i]=str[j]; str[j]=a; i++; j--; } } String ans=String.valueOf(str); return ans; }}" }, { "code": null, "e": 3827, "s": 3825, "text": "0" }, { "code": null, "e": 3853, "s": 3827, "text": "ilihaspatel443 months ago" }, { "code": null, "e": 3881, "s": 3853, "text": "// simple c++ solution " }, { "code": null, "e": 4319, "s": 3881, "text": "string reverse(string str) { int i=0; int j=str.size()-1; while(i<j){ while(isalpha(str[i]) and isalpha(str[j]) and i<j){ swap(str[i],str[j]); i++; j--; } while(!isalpha(str[i]) and i<j ){ i++; } while(!isalpha(str[j]) and j>i ){ j--; } } return str; } " }, { "code": null, "e": 4322, "s": 4319, "text": "+1" }, { "code": null, "e": 4344, "s": 4322, "text": "illiyazzr3 months ago" }, { "code": null, "e": 4360, "s": 4344, "text": "C++ Solution :-" }, { "code": null, "e": 4801, "s": 4362, "text": "bool alphabet(char ch){ if(ch>=65 && ch<=90 || ch>=97 && ch<=122){ return true; } return false;}void swap(int *x,int *y){ int temp = *x; *x=*y; *y=temp;}int main(){ string str = \"A&x#\"; int i=0,j=str.size()-1; while(i<j){ if(alphabet(str[i])&&alphabet(str[j])){ swap(str[i++],str[j--]); } else if(alphabet(str[i])){j--;} else if(alphabet(str[j])){i++;} else{i++;j--;} } cout<<str;}" }, { "code": null, "e": 4803, "s": 4801, "text": "0" }, { "code": null, "e": 4828, "s": 4803, "text": "amiransarimy3 months ago" }, { "code": null, "e": 4845, "s": 4828, "text": "Python Solutions" }, { "code": null, "e": 5397, "s": 4847, "text": "def reverse(self, s):\n \n i = 0 # left most index\n j = len(s)-1 # right most index\n mlist = list(s) #convert string into list\n \n while i <= j and j >=0:\n if not mlist[i]. isalpha():\n i += 1\n \n elif not mlist[j].isalpha():\n j -= 1\n \n else:\n mlist[i], mlist[j] = mlist[j],mlist[i]\n i += 1 # increment one index from left\n j -= 1 # decrement one index from right\n \n return ''.join(mlist)" }, { "code": null, "e": 5399, "s": 5397, "text": "0" }, { "code": null, "e": 5426, "s": 5399, "text": "yashpatil710973 months ago" }, { "code": null, "e": 6078, "s": 5426, "text": "int i=0; int j=s1.length()-1; char []arr1=s1.toCharArray(); while(i<j) { char ch1=arr1[i]; char ch2=arr1[j]; if(((ch1>=97&&ch1<=122)||(ch1>=65&&ch1<=90))==false) { i++; continue; } else if(((ch2>=97&&ch2<=122)||(ch2>=65&&ch2<=90))==false) { j--; continue; } else { char temp=arr1[i]; arr1[i]=arr1[j]; arr1[j]=temp; i++; j--; } } String res=String.valueOf(arr1); return res;" }, { "code": null, "e": 6081, "s": 6078, "text": "+3" }, { "code": null, "e": 6110, "s": 6081, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 6665, "s": 6110, "text": "string reverse(string str)\n { \n //code here.\n int low=0;\n int high=str.size()-1;\n while(low<=high){\n if(!((str[low]>='a'&& str[low]<='z') || (str[low]>='A'&& str[low]<='Z'))){\n low++;\n continue;\n }else if(!((str[high]>='a'&& str[high]<='z') || (str[high]>='A'&& str[high]<='Z'))){\n \n high--;\n continue;\n }\n swap(str[low],str[high]);\n low++;high--;\n }\n return str;\n \n } " }, { "code": null, "e": 6811, "s": 6665, "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": 6847, "s": 6811, "text": " Login to access your submissions. " }, { "code": null, "e": 6857, "s": 6847, "text": "\nProblem\n" }, { "code": null, "e": 6867, "s": 6857, "text": "\nContest\n" }, { "code": null, "e": 6930, "s": 6867, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7078, "s": 6930, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7286, "s": 7078, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7392, "s": 7286, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Second most repeated string in a sequence | Practice | GeeksforGeeks
Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. Note: No two strings are the second most repeated, there will be always a single string. Example 1: Input: N = 6 arr[] = {aaa, bbb, ccc, bbb, aaa, aaa} Output: bbb Explanation: "bbb" is the second most occurring string with frequency 2. ​Example 2: Input: N = 6 arr[] = {geek, for, geek, for, geek, aaa} Output: for Explanation: "for" is the second most occurring string with frequency 2. Your Task: You don't need to read input or print anything. Your task is to complete the function secFrequent() which takes the string array arr[] and its size N as inputs and returns the second most frequent string in the array. Expected Time Complexity: O(N*max(|Si|). Expected Auxiliary Space: O(N*max(|Si|). Constraints: 1<=N<=103 0 bhavinraichura281 week ago string secFrequent (string arr[], int n) { //code here. int r1=0,r2=0,count =1; sort(arr,arr+n); string s1=arr[0],s2; for (int i=1;i<n;i++){ if ((arr[i]!=arr[i-1])||(i==n-1)){ if (i==n-1){ count++; } if(r1<count && s1!=arr[i]){ r2=r1; s2=s1; r1=count; s1=arr[i-1]; } else if(r2<count && s1!=arr[i]){ r2=count; s2=arr[i-1]; } count=0; } count++; } return s2; } 0 officialshivaji0071 month ago public: string secFrequent (string arr[], int n) { //code here. map<string,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } int mx = INT_MIN,mx2=INT_MIN; for(auto x:mp){ mx = max(mx,x.second); } string ans ; for(auto x:mp){ if(x.second>mx2 && x.second < mx){ mx2 = x.second; ans = x.first; } } return ans; } +1 sachinnnnnn1 month ago public: bool static mycmp(pair<string,int> &a,pair<string,int> &b){ return a.second>b.second; } string secFrequent (string arr[], int n) { unordered_map<string,int> m; for(int i=0;i<n;i++){ m[arr[i]]++; } vector<pair<string,int>>v; for(auto &a : m){ v.push_back(a); } sort(v.begin(),v.end(),mycmp); return v[1].first; } 0 sudeepgarg6711 month ago #User function Template for python3class Solution: def secFrequent(self, arr, n): arr1 = [] arr2 = set(arr) for i in arr2 : arr1.append(arr.count(i)) arr1.remove(max(arr1)) for j in arr2 : if arr.count(j) == max(arr1): return j 0 bikrantsarmah2 months ago string secFrequent (string arr[], int n) { //code here. map<string,int> u; int i; for(i=0;i<n;i++) u[arr[i]]++; string s="";int m=INT_MIN; for(auto x:u) { if(x.second>m) { s=x.first; m=x.second; } } u[s]=INT_MIN; s=""; m=INT_MIN; for(auto x:u) { if(x.second>m) { s=x.first; m=x.second; } } return s; } +1 kashyapjhon2 months ago C++ Solution (Mirror Map Concept) Time=0.0/1.1 : string secFrequent (string arr[], int n) { //code here. string ans; if(n==1 || n==2){ return ans; } unordered_map<string,int> u1; unordered_map<int,string> u2; vector<int> v; for(int i=0;i<n;i++){ u1[arr[i]]++; } // int m=INT_MIN; for(auto it= u1.begin();it!=u1.end();it++){ v.push_back(it->second); } sort(v.begin(),v.end()); for(auto it= u1.begin();it!=u1.end();it++){ u2.insert({it->second,it->first}); } int N=v.size(); int t=v[N-2]; for(auto it= u2.begin();it!=u2.end();it++){ auto dc= u2.find(t); return dc->second; } } +1 aloksinghbais022 months ago C++ solution having time complexity as O(k*log(k)) and space complexity as O(4*k) where k is total number of distinct strings in arr[] is as follows :- Execution Time :- 0.0 / 1.1 sec string secFrequent (string arr[], int n){ unordered_map<string,bool> vis; unordered_map<int,string> mp; unordered_map<string,int> freq; int code = 1; for(int i = 0; i < n; i++){ if(!vis[arr[i]]){ vis[arr[i]] = true; mp[code++] = arr[i]; // code to string } freq[arr[i]]++; // frequency of string } map<int,string> mp1; for(auto p: mp){ mp1[freq[p.second]] = p.second; } int firstMost = 0,secondMost = 0; string fm{},sm{}; for(auto p: mp1){ string str = p.second; int f = p.first; if(secondMost < firstMost){ sm = fm; secondMost = firstMost; } if(firstMost < f){ fm = str; firstMost = f; } } return (sm); } 0 khunalshaik2 months ago def secFrequent(self, arr, n): res = collections.Counter(arr) out = sorted(res.values()) for k, v in res.items(): if v == out[-2]: return k 0 manish14092 months ago O(n) c++ easy solution string secutil(unordered_map<string,int>&mp){ string ans; int freq=0; for(auto it= mp.begin();it!=mp.end();it++){ if(freq< it->second){ freq=it->second; ans=it->first; } } return ans; } string secFrequent (string arr[], int n) { //code here. unordered_map<string,int>mp;//to store frequency of word for(int i=0;i<n;i++){ mp[arr[i]]++; } string temp= secutil(mp);//secutil function give then freq of largest string mp.erase(temp);//erase largest freq string string ans=secutil(mp);//then first largest return ans; } +1 anshulgupta966262 months ago map<string, int> mp; for(int i=0 ; i<n ; i++){ mp[arr[i]]++; } vector<pair<int, string>> ans; map<string, int> :: iterator it; for(it = mp.begin() ; it != mp.end() ; it++){ ans.push_back({it->second, it->first}); } sort(ans.begin(), ans.end()); int size = ans.size(); return ans[size-2].second; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 360, "s": 238, "text": "Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence." }, { "code": null, "e": 449, "s": 360, "text": "Note: No two strings are the second most repeated, there will be always a single string." }, { "code": null, "e": 460, "s": 449, "text": "Example 1:" }, { "code": null, "e": 600, "s": 460, "text": "Input:\nN = 6\narr[] = {aaa, bbb, ccc, bbb, aaa, aaa}\nOutput: bbb\nExplanation: \"bbb\" is the second most \noccurring string with frequency 2.\n\n" }, { "code": null, "e": 615, "s": 600, "text": "​Example 2:" }, { "code": null, "e": 757, "s": 615, "text": "Input: \nN = 6\narr[] = {geek, for, geek, for, geek, aaa}\nOutput: for\nExplanation: \"for\" is the second most\noccurring string with frequency 2.\n" }, { "code": null, "e": 987, "s": 757, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function secFrequent() which takes the string array arr[] and its size N as inputs and returns the second most frequent string in the array." }, { "code": null, "e": 1070, "s": 987, "text": "\nExpected Time Complexity: O(N*max(|Si|).\nExpected Auxiliary Space: O(N*max(|Si|)." }, { "code": null, "e": 1094, "s": 1070, "text": "\nConstraints:\n1<=N<=103" }, { "code": null, "e": 1098, "s": 1096, "text": "0" }, { "code": null, "e": 1125, "s": 1098, "text": "bhavinraichura281 week ago" }, { "code": null, "e": 1895, "s": 1125, "text": "string secFrequent (string arr[], int n) { //code here. int r1=0,r2=0,count =1; sort(arr,arr+n); string s1=arr[0],s2; for (int i=1;i<n;i++){ if ((arr[i]!=arr[i-1])||(i==n-1)){ if (i==n-1){ count++; } if(r1<count && s1!=arr[i]){ r2=r1; s2=s1; r1=count; s1=arr[i-1]; } else if(r2<count && s1!=arr[i]){ r2=count; s2=arr[i-1]; } count=0; } count++; } return s2; }" }, { "code": null, "e": 1897, "s": 1895, "text": "0" }, { "code": null, "e": 1927, "s": 1897, "text": "officialshivaji0071 month ago" }, { "code": null, "e": 2395, "s": 1927, "text": " public: string secFrequent (string arr[], int n) { //code here. map<string,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } int mx = INT_MIN,mx2=INT_MIN; for(auto x:mp){ mx = max(mx,x.second); } string ans ; for(auto x:mp){ if(x.second>mx2 && x.second < mx){ mx2 = x.second; ans = x.first; } } return ans; }" }, { "code": null, "e": 2398, "s": 2395, "text": "+1" }, { "code": null, "e": 2421, "s": 2398, "text": "sachinnnnnn1 month ago" }, { "code": null, "e": 2821, "s": 2421, "text": "public: bool static mycmp(pair<string,int> &a,pair<string,int> &b){ return a.second>b.second; } string secFrequent (string arr[], int n) { unordered_map<string,int> m; for(int i=0;i<n;i++){ m[arr[i]]++; } vector<pair<string,int>>v; for(auto &a : m){ v.push_back(a); } sort(v.begin(),v.end(),mycmp); return v[1].first; }" }, { "code": null, "e": 2823, "s": 2821, "text": "0" }, { "code": null, "e": 2848, "s": 2823, "text": "sudeepgarg6711 month ago" }, { "code": null, "e": 3142, "s": 2848, "text": "#User function Template for python3class Solution: def secFrequent(self, arr, n): arr1 = [] arr2 = set(arr) for i in arr2 : arr1.append(arr.count(i)) arr1.remove(max(arr1)) for j in arr2 : if arr.count(j) == max(arr1): return j" }, { "code": null, "e": 3144, "s": 3142, "text": "0" }, { "code": null, "e": 3170, "s": 3144, "text": "bikrantsarmah2 months ago" }, { "code": null, "e": 3774, "s": 3170, "text": "string secFrequent (string arr[], int n) { //code here. map<string,int> u; int i; for(i=0;i<n;i++) u[arr[i]]++; string s=\"\";int m=INT_MIN; for(auto x:u) { if(x.second>m) { s=x.first; m=x.second; } } u[s]=INT_MIN; s=\"\"; m=INT_MIN; for(auto x:u) { if(x.second>m) { s=x.first; m=x.second; } } return s; }" }, { "code": null, "e": 3777, "s": 3774, "text": "+1" }, { "code": null, "e": 3801, "s": 3777, "text": "kashyapjhon2 months ago" }, { "code": null, "e": 3850, "s": 3801, "text": "C++ Solution (Mirror Map Concept) Time=0.0/1.1 :" }, { "code": null, "e": 4554, "s": 3850, "text": "string secFrequent (string arr[], int n) { //code here. string ans; if(n==1 || n==2){ return ans; } unordered_map<string,int> u1; unordered_map<int,string> u2; vector<int> v; for(int i=0;i<n;i++){ u1[arr[i]]++; } // int m=INT_MIN; for(auto it= u1.begin();it!=u1.end();it++){ v.push_back(it->second); } sort(v.begin(),v.end()); for(auto it= u1.begin();it!=u1.end();it++){ u2.insert({it->second,it->first}); } int N=v.size(); int t=v[N-2]; for(auto it= u2.begin();it!=u2.end();it++){ auto dc= u2.find(t); return dc->second; } }" }, { "code": null, "e": 4557, "s": 4554, "text": "+1" }, { "code": null, "e": 4585, "s": 4557, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 4738, "s": 4585, "text": "C++ solution having time complexity as O(k*log(k)) and space complexity as O(4*k) where k is total number of distinct strings in arr[] is as follows :- " }, { "code": null, "e": 4772, "s": 4740, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 5678, "s": 4774, "text": "string secFrequent (string arr[], int n){ unordered_map<string,bool> vis; unordered_map<int,string> mp; unordered_map<string,int> freq; int code = 1; for(int i = 0; i < n; i++){ if(!vis[arr[i]]){ vis[arr[i]] = true; mp[code++] = arr[i]; // code to string } freq[arr[i]]++; // frequency of string } map<int,string> mp1; for(auto p: mp){ mp1[freq[p.second]] = p.second; } int firstMost = 0,secondMost = 0; string fm{},sm{}; for(auto p: mp1){ string str = p.second; int f = p.first; if(secondMost < firstMost){ sm = fm; secondMost = firstMost; } if(firstMost < f){ fm = str; firstMost = f; } } return (sm); }" }, { "code": null, "e": 5680, "s": 5678, "text": "0" }, { "code": null, "e": 5704, "s": 5680, "text": "khunalshaik2 months ago" }, { "code": null, "e": 5932, "s": 5704, "text": " def secFrequent(self, arr, n):\n \n res = collections.Counter(arr)\n \n out = sorted(res.values())\n \n for k, v in res.items():\n \n if v == out[-2]:\n return k\n" }, { "code": null, "e": 5934, "s": 5932, "text": "0" }, { "code": null, "e": 5957, "s": 5934, "text": "manish14092 months ago" }, { "code": null, "e": 5980, "s": 5957, "text": "O(n) c++ easy solution" }, { "code": null, "e": 6647, "s": 5982, "text": "string secutil(unordered_map<string,int>&mp){ string ans; int freq=0; for(auto it= mp.begin();it!=mp.end();it++){ if(freq< it->second){ freq=it->second; ans=it->first; } } return ans; } string secFrequent (string arr[], int n) { //code here. unordered_map<string,int>mp;//to store frequency of word for(int i=0;i<n;i++){ mp[arr[i]]++; } string temp= secutil(mp);//secutil function give then freq of largest string mp.erase(temp);//erase largest freq string string ans=secutil(mp);//then first largest return ans; }" }, { "code": null, "e": 6650, "s": 6647, "text": "+1" }, { "code": null, "e": 6679, "s": 6650, "text": "anshulgupta966262 months ago" }, { "code": null, "e": 7072, "s": 6679, "text": "\t\tmap<string, int> mp;\n for(int i=0 ; i<n ; i++){\n mp[arr[i]]++;\n }\n vector<pair<int, string>> ans;\n map<string, int> :: iterator it;\n for(it = mp.begin() ; it != mp.end() ; it++){\n ans.push_back({it->second, it->first});\n }\n sort(ans.begin(), ans.end());\n int size = ans.size();\n return ans[size-2].second;" }, { "code": null, "e": 7218, "s": 7072, "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": 7254, "s": 7218, "text": " Login to access your submissions. " }, { "code": null, "e": 7264, "s": 7254, "text": "\nProblem\n" }, { "code": null, "e": 7274, "s": 7264, "text": "\nContest\n" }, { "code": null, "e": 7337, "s": 7274, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7485, "s": 7337, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7693, "s": 7485, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 7799, "s": 7693, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Apache Solr - Deleting Documents
To delete documents from the index of Apache Solr, we need to specify the ID’s of the documents to be deleted between the <delete></delete> tags. <delete> <id>003</id> <id>005</id> <id>004</id> <id>002</id> </delete> Here, this XML code is used to delete the documents with ID’s 003 and 005. Save this code in a file with the name delete.xml. If you want to delete the documents from the index which belongs to the core named my_core, then you can post the delete.xml file using the post tool, as shown below. [Hadoop@localhost bin]$ ./post -c my_core delete.xml On executing the above command, you will get the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool delete.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots, rtf,htm,html,txt,log POSTing file delete.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.179 Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the specified documents are deleted. Sometimes we need to delete documents based on fields other than ID. For example, we may have to delete the documents where the city is Chennai. In such cases, you need to specify the name and value of the field within the <query></query> tag pair. <delete> <query>city:Chennai</query> </delete> Save it as delete_field.xml and perform the delete operation on the core named my_core using the post tool of Solr. [Hadoop@localhost bin]$ ./post -c my_core delete_field.xml On executing the above command, it produces the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool delete_field.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots, rtf,htm,html,txt,log POSTing file delete_field.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.084 Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted. Just like deleting a specific field, if you want to delete all the documents from an index, you just need to pass the symbol “:” between the tags <query></ query>, as shown below. <delete> <query>*:*</query> </delete> Save it as delete_all.xml and perform the delete operation on the core named my_core using the post tool of Solr. [Hadoop@localhost bin]$ ./post -c my_core delete_all.xml On executing the above command, it produces the following output. /home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core 6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files org.apache.Solr.util.SimplePostTool deleteAll.xml SimplePostTool version 5.0.0 Posting files to [base] url http://localhost:8983/Solr/my_core/update... Entering auto mode. File endings considered are xml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf, htm,html,txt,log POSTing file deleteAll.xml (application/xml) to [base] 1 files indexed. COMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... Time spent: 0:00:00.138 Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted. Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java. import java.io.IOException; import org.apache.Solr.client.Solrj.SolrClient; import org.apache.Solr.client.Solrj.SolrServerException; import org.apache.Solr.client.Solrj.impl.HttpSolrClient; import org.apache.Solr.common.SolrInputDocument; public class DeletingAllDocuments { public static void main(String args[]) throws SolrServerException, IOException { //Preparing the Solr client String urlString = "http://localhost:8983/Solr/my_core"; SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); //Preparing the Solr document SolrInputDocument doc = new SolrInputDocument(); //Deleting the documents from Solr Solr.deleteByQuery("*"); //Saving the document Solr.commit(); System.out.println("Documents deleted"); } } Compile the above code by executing the following commands in the terminal − [Hadoop@localhost bin]$ javac DeletingAllDocuments [Hadoop@localhost bin]$ java DeletingAllDocuments On executing the above command, you will get the following output. Documents deleted 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2170, "s": 2024, "text": "To delete documents from the index of Apache Solr, we need to specify the ID’s of the documents to be deleted between the <delete></delete> tags." }, { "code": null, "e": 2263, "s": 2170, "text": "<delete> \n <id>003</id> \n <id>005</id> \n <id>004</id> \n <id>002</id> \n</delete> " }, { "code": null, "e": 2389, "s": 2263, "text": "Here, this XML code is used to delete the documents with ID’s 003 and 005. Save this code in a file with the name delete.xml." }, { "code": null, "e": 2556, "s": 2389, "text": "If you want to delete the documents from the index which belongs to the core named my_core, then you can post the delete.xml file using the post tool, as shown below." }, { "code": null, "e": 2611, "s": 2556, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete.xml \n" }, { "code": null, "e": 2678, "s": 2611, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 3276, "s": 2678, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool delete.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,\nrtf,htm,html,txt,log \nPOSTing file delete.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.179 \n" }, { "code": null, "e": 3536, "s": 3276, "text": "Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the specified documents are deleted." }, { "code": null, "e": 3681, "s": 3536, "text": "Sometimes we need to delete documents based on fields other than ID. For example, we may have to delete the documents where the city is Chennai." }, { "code": null, "e": 3785, "s": 3681, "text": "In such cases, you need to specify the name and value of the field within the <query></query> tag pair." }, { "code": null, "e": 3838, "s": 3785, "text": "<delete> \n <query>city:Chennai</query> \n</delete>\n" }, { "code": null, "e": 3954, "s": 3838, "text": "Save it as delete_field.xml and perform the delete operation on the core named my_core using the post tool of Solr." }, { "code": null, "e": 4015, "s": 3954, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete_field.xml \n" }, { "code": null, "e": 4081, "s": 4015, "text": "On executing the above command, it produces the following output." }, { "code": null, "e": 4691, "s": 4081, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool delete_field.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,\nrtf,htm,html,txt,log \nPOSTing file delete_field.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.084 \n" }, { "code": null, "e": 4983, "s": 4691, "text": "Visit the homepage of the of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted." }, { "code": null, "e": 5163, "s": 4983, "text": "Just like deleting a specific field, if you want to delete all the documents from an index, you just need to pass the symbol “:” between the tags <query></ query>, as shown below." }, { "code": null, "e": 5207, "s": 5163, "text": "<delete> \n <query>*:*</query> \n</delete>\n" }, { "code": null, "e": 5321, "s": 5207, "text": "Save it as delete_all.xml and perform the delete operation on the core named my_core using the post tool of Solr." }, { "code": null, "e": 5379, "s": 5321, "text": "[Hadoop@localhost bin]$ ./post -c my_core delete_all.xml\n" }, { "code": null, "e": 5445, "s": 5379, "text": "On executing the above command, it produces the following output." }, { "code": null, "e": 6048, "s": 5445, "text": "/home/Hadoop/java/bin/java -classpath /home/Hadoop/Solr/dist/Solr-core\n6.2.0.jar -Dauto = yes -Dc = my_core -Ddata = files \norg.apache.Solr.util.SimplePostTool deleteAll.xml \nSimplePostTool version 5.0.0 \nPosting files to [base] url http://localhost:8983/Solr/my_core/update... \nEntering auto mode. File endings considered are \nxml,json,jsonl,csv,pdf,doc,docx,ppt,pptx,xls,xlsx,odt,odp,ods,ott,otp,ots,rtf,\nhtm,html,txt,log \nPOSTing file deleteAll.xml (application/xml) to [base] \n1 files indexed. \nCOMMITting Solr index changes to http://localhost:8983/Solr/my_core/update... \nTime spent: 0:00:00.138\n" }, { "code": null, "e": 6333, "s": 6048, "text": "Visit the homepage of Apache Solr web interface and select the core as my_core. Try to retrieve all the documents by passing the query “:” in the text area q and execute the query. On executing, you can observe that the documents containing the specified field value pair are deleted." }, { "code": null, "e": 6464, "s": 6333, "text": "Following is the Java program to add documents to Apache Solr index. Save this code in a file with the name UpdatingDocument.java." }, { "code": null, "e": 7317, "s": 6464, "text": "import java.io.IOException; \n\nimport org.apache.Solr.client.Solrj.SolrClient; \nimport org.apache.Solr.client.Solrj.SolrServerException; \nimport org.apache.Solr.client.Solrj.impl.HttpSolrClient; \nimport org.apache.Solr.common.SolrInputDocument; \n\npublic class DeletingAllDocuments { \n public static void main(String args[]) throws SolrServerException, IOException {\n //Preparing the Solr client \n String urlString = \"http://localhost:8983/Solr/my_core\"; \n SolrClient Solr = new HttpSolrClient.Builder(urlString).build(); \n \n //Preparing the Solr document \n SolrInputDocument doc = new SolrInputDocument(); \n \n //Deleting the documents from Solr \n Solr.deleteByQuery(\"*\"); \n \n //Saving the document \n Solr.commit(); \n System.out.println(\"Documents deleted\"); \n } \n}" }, { "code": null, "e": 7394, "s": 7317, "text": "Compile the above code by executing the following commands in the terminal −" }, { "code": null, "e": 7497, "s": 7394, "text": "[Hadoop@localhost bin]$ javac DeletingAllDocuments \n[Hadoop@localhost bin]$ java DeletingAllDocuments\n" }, { "code": null, "e": 7564, "s": 7497, "text": "On executing the above command, you will get the following output." }, { "code": null, "e": 7583, "s": 7564, "text": "Documents deleted\n" }, { "code": null, "e": 7618, "s": 7583, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7637, "s": 7618, "text": " Arnab Chakraborty" }, { "code": null, "e": 7672, "s": 7637, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7693, "s": 7672, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7726, "s": 7693, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7739, "s": 7726, "text": " Nilay Mehta" }, { "code": null, "e": 7774, "s": 7739, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7792, "s": 7774, "text": " Bigdata Engineer" }, { "code": null, "e": 7825, "s": 7792, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7843, "s": 7825, "text": " Bigdata Engineer" }, { "code": null, "e": 7876, "s": 7843, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7894, "s": 7876, "text": " Bigdata Engineer" }, { "code": null, "e": 7901, "s": 7894, "text": " Print" }, { "code": null, "e": 7912, "s": 7901, "text": " Add Notes" } ]
Simplified Forecasting with Facebook Prophet | by Josh Johnson | Towards Data Science
Timeseries forecasting is a complex art form. Many models are very sensitive to trends, cycles (called ‘seasons’) and changing magnitudes of fluctuations, and instead require stationary data, which lack these features. This devastating disease has killed hundreds of thousands in the US and millions around the world and at this time continues to spread ever faster. Forecasting the rate of future infections can help hospitals and aid organizations plan and prepare for future needs. A good example of data that not-stationary is the cumulative spread of COVID-19 in the United States over 2020. For this project I will be using data from the Coronavirus Government Response Tracker, which provides daily updated data on every country, including government interventions. If you want to take your forecasting further by including exogenous variables (variables outside of the data being modeled that may have an effect on it) you can find many relevant ones in this dataset. However, for this example we will only be using cumulative reported infections in the United States. You can see above that not only is there an upward trend, but the trend keeps changing. The seasonality is not apparent from the cumulative data, but when we do a first order differencing to transform cumulative cases to daily new cases, we see the seasonality appear. The weekly seasonality is probably because: People tend to get tested on weekends and their results tend to come back on Wednesdays, creating a peak of reported cases on Wednesdays and valleys on other days. Or,Labs report cases in bulk on certain days. People tend to get tested on weekends and their results tend to come back on Wednesdays, creating a peak of reported cases on Wednesdays and valleys on other days. Or, Labs report cases in bulk on certain days. Notice the dips on 12–07, 12–14, 12–21, etc. There are also a large dips on 12–25 and 01–01. I assume not many lab workers were working on Christmas and New Year’s day, so reports dipped. We must keep in mind that data is not reality, and cases charted are actually cases reported, not actual infections. The patterns of reporting create the seasonality in the data. An ARMA model is a combination of an autoregressive and a moving average model, and a crucial tool in predicting stationary time series data. I won’t explain it fully here, since this post is about a different technique, but you can read about it here. Extensions to the ARMA model, such as ARIMA can account for trends and SARIMA can take into account the seasonality of data. However, the accuracy of these models require carefully tuning several hyperparameters to determine how and to what degree past data effects the future. data scientists often make a series of transforms on the data, such as subtracting moving averages or standard deviations, or log scaling it to get good predictions. With enough effort and expertise these are powerful models. With effort and thorough data exploration I tuned mine to predict cases in the first 18 days of January at 99% accuracy. You can experience my adventures in SARIMA modeling through my Github repo predicting COVID case rates. The Facebook Prophet library for R and Python does a lot of that work for you. It allows for quick and easy time series forecasts, but also provides options for more seasoned forecasters to tune the internal settings. It can detect adjust to seasonality, trends and shifting standard deviations in the residuals. However, it is particular about how you implement it. Let’s see how to get started. We will use Pandas to manipulate the data and download the fbprophet library. It installs fine into Google Colab notebooks with !pip install fbprophet. On my local Windows machine running the Anaconda package manager, I had to install using in my bash terminal with conda install -c conda-forge fbprophet. Facebook has more guidance on installation here. import pandas as pd #!pip install fbprophet from fbprophet import Prophet division = 'country' #regional data is available for some countries region = 'United States' prediction = 'ConfirmedCases' #ConfirmedDeaths is also available for forecasting. #get the latest data from OxCGRT DATA_URL = 'https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv' full_df = pd.read_csv(DATA_URL, usecols=['Date','CountryName','RegionName','Jurisdiction', 'ConfirmedCases','ConfirmedDeaths'], parse_dates=['Date'], encoding="ISO-8859-1", dtype={"RegionName": str, "CountryName":str}) #Filter the region we want to predict if division == 'country': df = full_df[(full_df['Jurisdiction'] == 'NAT_TOTAL') & (full_df['CountryName'] == region)][:-1] elif division == 'state': df = full_df[(full_df['Jurisdiction'] == 'STATE_TOTAL') & (full_df['RegionName'] == region)][:-1] #Since we are not using exogenous variables, we just keep the dates and endogenous data df = df[['Date',prediction]].rename(columns = {'Date':'ds', prediction:'y'}) You may notice that the last line renames the ‘Date’ columns to ‘ds’ and the ‘CumulativeCases’ column to ‘y’. This is required by Facebook in order to use the dataframe for modeling. Many experienced Pandas users may be tempted to make the datetime column the index, but for Prophet, don’t do that. Our dataframe is ready for modeling. Creating and training the out-of-the-box model is very simple: m = Prophet()m.fit(df) But, here is the tricky part. You have to prepare a special dataframe to store the actual prediction. Luckily the model comes with a handy method to do it for you if you want. You can make it yourself if you want, you just need the values of the periods you want to predict in the ‘ds’ column and an empty ‘y’ column future = m.make_future_dataframe(periods=length_of_desired_forecast) Finally, to make the prediction, simply feed the future dataframe as an argument to the the model’s .predict() method, like so: forecast = m.predict(future) I love the variable name conventions that the folks at Facebook have created, where the model predicts the future to make forecast. It’s satisfying and just the right amount of on the nose for me. import pandas as pd #!pip install fbprophet from fbprophet import Prophet import matplotlib.pyplot as plt division = 'country' #regional data is available for some countries region = 'United States' prediction = 'ConfirmedCases' #ConfirmedDeaths is also available for forecasting. #get the latest data from OxCGRT DATA_URL = 'https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv' full_df = pd.read_csv(DATA_URL, usecols=['Date','CountryName','RegionName','Jurisdiction', 'ConfirmedCases','ConfirmedDeaths'], parse_dates=['Date'], encoding="ISO-8859-1", dtype={"RegionName": str, "CountryName":str}) #Filter the region we want to predict if division == 'country': df = full_df[(full_df['Jurisdiction'] == 'NAT_TOTAL') & (full_df['CountryName'] == region)][:-1] elif division == 'state': df = full_df[(full_df['Jurisdiction'] == 'STATE_TOTAL') & (full_df['RegionName'] == region)][:-1] #Since we are not using exogenous variables, we just keep the dates and endogenous data df = df[['Date',prediction]].rename(columns = {'Date':'ds', prediction:'y'}) # set how many days to forecast forecast_length = 30 # instantiate and fit the model m = Prophet() m.fit(df) # create the prediction dataframe 'forecast_length' days past the fit data future = m.make_future_dataframe(periods=forecast_length) # make the forecast to the end of the 'future' dataframe forecast = m.predict(future) to_plot = forecast[forecast.ds > '2020-12-01'].merge(df, how='left') plt.figure(figsize = (10,7)) plt.plot(to_plot['ds'], to_plot['yhat'], label='Forecasted Cases') plt.plot(to_plot['ds'], to_plot['y'], label='True Cases') plt.fill_between(to_plot['ds'], to_plot['yhat_upper'], to_plot['yhat_lower'], alpha=.2, label='Confidence') plt.title('Facebook Prophet Forecasted COVID-19 cases, 1-22-2021 to 2-20-2021') plt.legend() plt.savefig('prophet_forecast.png') plt.show() print('\n The "forecast" DataFrame \n') forecast forecast will be a dataframe that contains your prediction, out to the end of the ‘ds’ column in your future dataframe, as well as much more. It includes confidence intervals, and all the parameters the model used for each step of the prediction. This allows some lovely inspection the internal workings of the model and opportunity to do some fun graphs with confidence bands. As you can see above, this out of the box Prophet has made a very basic linear regression as a prediction. Further tuning of the model will improve the accuracy. If you run the code you will see warnings that indicate the Prophet has automatically identified weekly seasonality in the data, but that you can manually tell it to look for monthly or yearly seasonality. There are a number of other tweaks and refinements you can try including adding extra (exogenous) variables, such as holidays or the government interventions provided in the dataset we used. A much more comprehensive guide can by found in this awesome article by Greg Rafferty. But, the above should get you off the ground and give you something to get started with. If you want to see my full work on trying to predict COVID-19 cases for an Xprize competition, you can check it out here:(Spoiler, I ended up going with a more accurate SARIMA model) Facebook Prophet Quickstart Guide Forecasting in Python with Facebook Prophet by Greg Rafferty Data: Coronavirus Government Response TrackerThanks to the Blavatnic School of Government and the University of Oxford
[ { "code": null, "e": 391, "s": 172, "text": "Timeseries forecasting is a complex art form. Many models are very sensitive to trends, cycles (called ‘seasons’) and changing magnitudes of fluctuations, and instead require stationary data, which lack these features." }, { "code": null, "e": 657, "s": 391, "text": "This devastating disease has killed hundreds of thousands in the US and millions around the world and at this time continues to spread ever faster. Forecasting the rate of future infections can help hospitals and aid organizations plan and prepare for future needs." }, { "code": null, "e": 1249, "s": 657, "text": "A good example of data that not-stationary is the cumulative spread of COVID-19 in the United States over 2020. For this project I will be using data from the Coronavirus Government Response Tracker, which provides daily updated data on every country, including government interventions. If you want to take your forecasting further by including exogenous variables (variables outside of the data being modeled that may have an effect on it) you can find many relevant ones in this dataset. However, for this example we will only be using cumulative reported infections in the United States." }, { "code": null, "e": 1518, "s": 1249, "text": "You can see above that not only is there an upward trend, but the trend keeps changing. The seasonality is not apparent from the cumulative data, but when we do a first order differencing to transform cumulative cases to daily new cases, we see the seasonality appear." }, { "code": null, "e": 1562, "s": 1518, "text": "The weekly seasonality is probably because:" }, { "code": null, "e": 1772, "s": 1562, "text": "People tend to get tested on weekends and their results tend to come back on Wednesdays, creating a peak of reported cases on Wednesdays and valleys on other days. Or,Labs report cases in bulk on certain days." }, { "code": null, "e": 1940, "s": 1772, "text": "People tend to get tested on weekends and their results tend to come back on Wednesdays, creating a peak of reported cases on Wednesdays and valleys on other days. Or," }, { "code": null, "e": 1983, "s": 1940, "text": "Labs report cases in bulk on certain days." }, { "code": null, "e": 2171, "s": 1983, "text": "Notice the dips on 12–07, 12–14, 12–21, etc. There are also a large dips on 12–25 and 01–01. I assume not many lab workers were working on Christmas and New Year’s day, so reports dipped." }, { "code": null, "e": 2350, "s": 2171, "text": "We must keep in mind that data is not reality, and cases charted are actually cases reported, not actual infections. The patterns of reporting create the seasonality in the data." }, { "code": null, "e": 2603, "s": 2350, "text": "An ARMA model is a combination of an autoregressive and a moving average model, and a crucial tool in predicting stationary time series data. I won’t explain it fully here, since this post is about a different technique, but you can read about it here." }, { "code": null, "e": 3107, "s": 2603, "text": "Extensions to the ARMA model, such as ARIMA can account for trends and SARIMA can take into account the seasonality of data. However, the accuracy of these models require carefully tuning several hyperparameters to determine how and to what degree past data effects the future. data scientists often make a series of transforms on the data, such as subtracting moving averages or standard deviations, or log scaling it to get good predictions. With enough effort and expertise these are powerful models." }, { "code": null, "e": 3332, "s": 3107, "text": "With effort and thorough data exploration I tuned mine to predict cases in the first 18 days of January at 99% accuracy. You can experience my adventures in SARIMA modeling through my Github repo predicting COVID case rates." }, { "code": null, "e": 3729, "s": 3332, "text": "The Facebook Prophet library for R and Python does a lot of that work for you. It allows for quick and easy time series forecasts, but also provides options for more seasoned forecasters to tune the internal settings. It can detect adjust to seasonality, trends and shifting standard deviations in the residuals. However, it is particular about how you implement it. Let’s see how to get started." }, { "code": null, "e": 3881, "s": 3729, "text": "We will use Pandas to manipulate the data and download the fbprophet library. It installs fine into Google Colab notebooks with !pip install fbprophet." }, { "code": null, "e": 4084, "s": 3881, "text": "On my local Windows machine running the Anaconda package manager, I had to install using in my bash terminal with conda install -c conda-forge fbprophet. Facebook has more guidance on installation here." }, { "code": null, "e": 5269, "s": 4084, "text": "import pandas as pd\n#!pip install fbprophet\nfrom fbprophet import Prophet\n\ndivision = 'country' #regional data is available for some countries\nregion = 'United States'\nprediction = 'ConfirmedCases' #ConfirmedDeaths is also available for forecasting.\n\n#get the latest data from OxCGRT\nDATA_URL = 'https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv'\nfull_df = pd.read_csv(DATA_URL,\n usecols=['Date','CountryName','RegionName','Jurisdiction',\n 'ConfirmedCases','ConfirmedDeaths'],\n parse_dates=['Date'],\n encoding=\"ISO-8859-1\",\n dtype={\"RegionName\": str,\n \"CountryName\":str})\n\n#Filter the region we want to predict\nif division == 'country':\n df = full_df[(full_df['Jurisdiction'] == 'NAT_TOTAL') & (full_df['CountryName'] == region)][:-1]\nelif division == 'state':\n df = full_df[(full_df['Jurisdiction'] == 'STATE_TOTAL') & (full_df['RegionName'] == region)][:-1]\n\n#Since we are not using exogenous variables, we just keep the dates and endogenous data\ndf = df[['Date',prediction]].rename(columns = {'Date':'ds', prediction:'y'})\n" }, { "code": null, "e": 5568, "s": 5269, "text": "You may notice that the last line renames the ‘Date’ columns to ‘ds’ and the ‘CumulativeCases’ column to ‘y’. This is required by Facebook in order to use the dataframe for modeling. Many experienced Pandas users may be tempted to make the datetime column the index, but for Prophet, don’t do that." }, { "code": null, "e": 5668, "s": 5568, "text": "Our dataframe is ready for modeling. Creating and training the out-of-the-box model is very simple:" }, { "code": null, "e": 5691, "s": 5668, "text": "m = Prophet()m.fit(df)" }, { "code": null, "e": 6008, "s": 5691, "text": "But, here is the tricky part. You have to prepare a special dataframe to store the actual prediction. Luckily the model comes with a handy method to do it for you if you want. You can make it yourself if you want, you just need the values of the periods you want to predict in the ‘ds’ column and an empty ‘y’ column" }, { "code": null, "e": 6077, "s": 6008, "text": "future = m.make_future_dataframe(periods=length_of_desired_forecast)" }, { "code": null, "e": 6205, "s": 6077, "text": "Finally, to make the prediction, simply feed the future dataframe as an argument to the the model’s .predict() method, like so:" }, { "code": null, "e": 6234, "s": 6205, "text": "forecast = m.predict(future)" }, { "code": null, "e": 6431, "s": 6234, "text": "I love the variable name conventions that the folks at Facebook have created, where the model predicts the future to make forecast. It’s satisfying and just the right amount of on the nose for me." }, { "code": null, "e": 7658, "s": 6431, "text": "import pandas as pd\n#!pip install fbprophet\nfrom fbprophet import Prophet\nimport matplotlib.pyplot as plt\n\ndivision = 'country' #regional data is available for some countries\nregion = 'United States'\nprediction = 'ConfirmedCases' #ConfirmedDeaths is also available for forecasting.\n\n#get the latest data from OxCGRT\nDATA_URL = 'https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest.csv'\nfull_df = pd.read_csv(DATA_URL,\n usecols=['Date','CountryName','RegionName','Jurisdiction',\n 'ConfirmedCases','ConfirmedDeaths'],\n parse_dates=['Date'],\n encoding=\"ISO-8859-1\",\n dtype={\"RegionName\": str,\n \"CountryName\":str})\n\n#Filter the region we want to predict\nif division == 'country':\n df = full_df[(full_df['Jurisdiction'] == 'NAT_TOTAL') \n & (full_df['CountryName'] == region)][:-1]\nelif division == 'state':\n df = full_df[(full_df['Jurisdiction'] == 'STATE_TOTAL') \n & (full_df['RegionName'] == region)][:-1]\n\n#Since we are not using exogenous variables, we just keep the dates and endogenous data\ndf = df[['Date',prediction]].rename(columns = {'Date':'ds', prediction:'y'})\n" }, { "code": null, "e": 8526, "s": 7658, "text": "# set how many days to forecast\nforecast_length = 30\n# instantiate and fit the model\nm = Prophet()\nm.fit(df)\n# create the prediction dataframe 'forecast_length' days past the fit data\nfuture = m.make_future_dataframe(periods=forecast_length)\n# make the forecast to the end of the 'future' dataframe\nforecast = m.predict(future)\n\nto_plot = forecast[forecast.ds > '2020-12-01'].merge(df, how='left')\n\nplt.figure(figsize = (10,7))\nplt.plot(to_plot['ds'], to_plot['yhat'], label='Forecasted Cases')\nplt.plot(to_plot['ds'], to_plot['y'], label='True Cases')\nplt.fill_between(to_plot['ds'], to_plot['yhat_upper'], to_plot['yhat_lower'],\n alpha=.2, label='Confidence')\nplt.title('Facebook Prophet Forecasted COVID-19 cases, 1-22-2021 to 2-20-2021')\nplt.legend()\nplt.savefig('prophet_forecast.png')\nplt.show()\nprint('\\n The \"forecast\" DataFrame \\n')\nforecast\n" }, { "code": null, "e": 8904, "s": 8526, "text": "forecast will be a dataframe that contains your prediction, out to the end of the ‘ds’ column in your future dataframe, as well as much more. It includes confidence intervals, and all the parameters the model used for each step of the prediction. This allows some lovely inspection the internal workings of the model and opportunity to do some fun graphs with confidence bands." }, { "code": null, "e": 9463, "s": 8904, "text": "As you can see above, this out of the box Prophet has made a very basic linear regression as a prediction. Further tuning of the model will improve the accuracy. If you run the code you will see warnings that indicate the Prophet has automatically identified weekly seasonality in the data, but that you can manually tell it to look for monthly or yearly seasonality. There are a number of other tweaks and refinements you can try including adding extra (exogenous) variables, such as holidays or the government interventions provided in the dataset we used." }, { "code": null, "e": 9639, "s": 9463, "text": "A much more comprehensive guide can by found in this awesome article by Greg Rafferty. But, the above should get you off the ground and give you something to get started with." }, { "code": null, "e": 9822, "s": 9639, "text": "If you want to see my full work on trying to predict COVID-19 cases for an Xprize competition, you can check it out here:(Spoiler, I ended up going with a more accurate SARIMA model)" }, { "code": null, "e": 9856, "s": 9822, "text": "Facebook Prophet Quickstart Guide" }, { "code": null, "e": 9917, "s": 9856, "text": "Forecasting in Python with Facebook Prophet by Greg Rafferty" }, { "code": null, "e": 9923, "s": 9917, "text": "Data:" } ]
Crack SQL Interviews | Towards Data Science
SQL is one of the most essential programming languages for data analysis and data processing, and so SQL questions are always part of the interview process for data science-related jobs, such as data analysts, data scientists, and data engineers. SQL interviews are meant to evaluate candidates’ technical and problem-solving skills. Therefore, it is critical to not only write correct queries based on sample data but also consider various scenarios and edge cases as if working with real-world datasets. I’ve helped design and conduct SQL interview questions for data science candidates, and have undergone many SQL interviews for jobs in giant technology companies and startups myself. In this blog post, I will explain the common patterns seen in SQL interview questions and provide tips on how to neatly handle them in SQL queries. To nail an SQL interview, the most important thing is to make sure that you have all the details of the given task and data sample by asking as many questions as you need. Understanding the requirements will save you time from iterating on problems later and enable you to handle edge cases well. I noticed many candidates tend to jump right into the solution without having a good understanding of the SQL questions or the dataset. Later on, they had to repeatedly modify their queries after I pointed out problems in their solution. In the end, they wasted a lot of interview time in iteration and may not have even arrived at the right solution. I recommend treating SQL interviews as if you are working with a business partner at work. You would want to gather all the requirements on the data request before you provide a solution. Example Find the top 3 employees who have the highest salary. You should ask the interviewer(s) to clarify the “top 3”. Should I include exactly 3 employees in my results? How do you want me to handle ties? In addition, carefully review the sample employee data. What is the data type of the salary field? Do I need to clean the data before calculate? In SQL, JOIN is frequently used to combine information from multiple tables. There are four different types of JOIN, but in most cases, we only use INNER, LEFT and FULL JOIN, because the RIGHT JOIN is not very intuitive and can be easily rewritten using LEFT JOIN. In an SQL interview, you need to choose the right JOIN to use based on the specific requirement of the given question. Example Find the total number of classes taken by each student. (Provide student id, name and number of classes taken.) As you might have noticed, not all students appearing in theclass_history table are present in thestudent table, which might be because those students are no longer enrolled. (This is actually very typical in transactional databases, as records are often deleted once inactive.) There is also a student (student_id = 6) with no class history. Depending on whether the interviewer wants to include inactive students and students who didn’t register for any classes in the results, we need to use either LEFT JOIN or INNER JOIN or FULL OUTER JOIN to combine two tables: WITH class_count AS ( SELECT student_id, COUNT(*) AS num_of_class FROM class_history GROUP BY student_id)SELECT COALESCE(c.student_id, s.student_id) AS student_id, s.student_name, COALESCE(c.num_of_class, 0) AS num_of_classFROM class_count c-- CASE 1: include only active students who took at least 1 classJOIN student s ON c.student_id = s.student_id-- CASE 2: include all students who took at least 1 class-- LEFT JOIN student s ON c.student_id = s.student_id-- CASE 3: include all students-- FULL OUTER JOIN student s ON c.student_id = s.student_id GROUP BY is the most essential function in SQL since it is widely used for data aggregation. If you see keywords such as sum, average, minimum, or maximum in a SQL question, it is a big hint that you should probably use GROUP BY in your query. A common pitfall is mixing WHERE and HAVING when filtering data along with GROUP BY — I have seen many people make this mistake. Example Calculate the average required course GPA in each school year for each student and find students who are qualified for the Dean’s List (GPA ≥ 3.5) in each semester. Since we consider only required courses in our GPA calculation, we need to exclude optional courses using WHERE is_required = TRUE. We need the average GPA per student per year, so we will GROUP BY both thestudent_id and theschool_year columns and take the average of thegpa column. Lastly, we only keep rows where the student has an average GPA higher than 3.5, which can be implemented using HAVING. Let’s put everything together: SELECT student_id, school_year, AVG(gpa) AS avg_gpaFROM gpa_historyWHERE is_required = TRUEGROUP BY student_id, school_yearHAVING AVG(gpa) >= 3.5 Keep in mind that whenever GROUP BY is used in a query, you can only select group-by columns and aggregated columns because the row-level information in other columns has already been discarded. Some people might wonder what’s the difference between WHERE and HAVING, or why we don’t just write HAVING avg_gpa >= 3.5 instead of specifying the function. I will explain more in the next section. Most people write SQL queries from top to bottom starting from SELECT, but do you know that SELECT is one of the very last functions executed by the SQL engine? Below is the execution order of a SQL query: FROM, JOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BYLIMIT, OFFSET FROM, JOIN WHERE GROUP BY HAVING SELECT DISTINCT ORDER BY LIMIT, OFFSET Consider the previous example again. Because we want to filter out optional courses before computing average GPAs, I used WHERE is_required = TRUE instead HAVING, because WHERE is executed before GROUP BY and HAVING. The reason I can’t write HAVING avg_gpa >= 3.5 is thatavg_gpa is defined as part of SELECT, so it cannot be referred to in steps executed before SELECT. I recommend following the execution order when writing queries, which is helpful if you struggle with writing complicated queries. Window functions frequently appear in SQL interviews as well. There are five common window functions: RANK /DENSE_RANK /ROW_NUMBER: these assign a rank to each row by ordering specific columns. If any partition columns are given, rows are ranked within a partition group that it belongs to. LAG /LEAD: it retrieves column values from a preceding or following row based on a specified order and partition group. In SQL interviews, it is important to understand the differences between ranking functions and know when to use LAG/LEAD. Example Find the top 3 employees who have the highest salary in each department. When an SQL question asks for “TOP N”, we can use either ORDER BY or ranking functions to answer the question. However, in this example, it asks to calculate “TOP N X in each Y”, which is a strong hint that we should use ranking functions because we need to rank rows within each partition group. The query below finds exactly 3 highest-payed employees regardless of ties: WITH T AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_salary DESC) AS rank_in_depFROM employee_salary)SELECT * FROM TWHERE rank_in_dep <= 3-- Note: When using ROW_NUMBER, each row will have a unique rank number and ranks for tied records are assigned randomly. For exmaple, Rimsha and Tiah may be rank 2 or 3 in different query runs. Moreover, based on how ties should be handled, we could pick a different ranking function. Again, details matter! Another common pitfall in SQL interviews is ignoring data duplicates. Although some columns seem to have distinct values in the sample data, candidates are expected to consider all possibilities as if they are working with a real-world dataset. For example, in theemployee_salary table from the previous example, it is possible to have employees sharing the same name. One easy way to avoid potential problems caused by duplicates is to always use ID columns to uniquely identify distinct records. Example Find the total salary from all departments for each employee using the employee_salary table. The right solution is to GROUP BY employee_id and calculating the total salary using SUM(employee_salary). If employee names are needed, join with an employee table at the end to retrieve employee name information. The wrong approach is to GROUP BY employee_name. In SQL, any predicates can result in one of the three values: true, false, and NULL, a reserved keyword for unknown or missing data values. Handling NULL datasets can be unexpectedly tricky. In an SQL interview, the interviewer might pay extra attention to whether your solution has handled NULL values. Sometimes it is obvious if a column is not nullable (ID columns, for instance) but for most other columns it is very likely there will be NULL values. I suggest confirming whether key columns in the sample data are nullable and if so, utilize functions such as IS (NOT) NULL, IFNULL, and COALESCE to cover those edge cases. (Want to learn more about how to deal with NULL values? Check out my guide on working with NULL in SQL.) Last but not least — keep the communication going during SQL interviews. I have interviewed many candidates who barely talked except when they had questions, which would be okay if they came up with the perfect solution at the end. However, it is generally a good idea to keep up communication during technical interviews. For example, you can talk about your understanding of the question and data, how you plan to approach the problem, why you use some functions versus other alternatives, and what edge cases you are considering. TL;DR: Always ask questions to gather the required details first. Carefully choose between INNER, LEFT, and FULL JOIN. Use GROUP BY to aggregate data and properly use WHERE and HAVING. Understand the differences between the three ranking functions. Know when to use LAG/LEAD window functions. If you struggle with creating complicated queries, try following the SQL execution order. Consider potential data problems such as duplicates and NULL values. Communicate your thought process with the interviewers. To help you understand how to use these strategies in an actual SQL interview, I will walk you through a sample SQL interview question from end to end in the video below: I hope you find this guide helpful in preparing for your next data science interview. If you have any questions regarding SQL, feel free to leave a comment. Good luck! Want to learn more about Data Engineering? Check out my Data Engineering 101 column on Towards Data Science:
[ { "code": null, "e": 677, "s": 171, "text": "SQL is one of the most essential programming languages for data analysis and data processing, and so SQL questions are always part of the interview process for data science-related jobs, such as data analysts, data scientists, and data engineers. SQL interviews are meant to evaluate candidates’ technical and problem-solving skills. Therefore, it is critical to not only write correct queries based on sample data but also consider various scenarios and edge cases as if working with real-world datasets." }, { "code": null, "e": 1008, "s": 677, "text": "I’ve helped design and conduct SQL interview questions for data science candidates, and have undergone many SQL interviews for jobs in giant technology companies and startups myself. In this blog post, I will explain the common patterns seen in SQL interview questions and provide tips on how to neatly handle them in SQL queries." }, { "code": null, "e": 1305, "s": 1008, "text": "To nail an SQL interview, the most important thing is to make sure that you have all the details of the given task and data sample by asking as many questions as you need. Understanding the requirements will save you time from iterating on problems later and enable you to handle edge cases well." }, { "code": null, "e": 1657, "s": 1305, "text": "I noticed many candidates tend to jump right into the solution without having a good understanding of the SQL questions or the dataset. Later on, they had to repeatedly modify their queries after I pointed out problems in their solution. In the end, they wasted a lot of interview time in iteration and may not have even arrived at the right solution." }, { "code": null, "e": 1845, "s": 1657, "text": "I recommend treating SQL interviews as if you are working with a business partner at work. You would want to gather all the requirements on the data request before you provide a solution." }, { "code": null, "e": 1853, "s": 1845, "text": "Example" }, { "code": null, "e": 1907, "s": 1853, "text": "Find the top 3 employees who have the highest salary." }, { "code": null, "e": 2197, "s": 1907, "text": "You should ask the interviewer(s) to clarify the “top 3”. Should I include exactly 3 employees in my results? How do you want me to handle ties? In addition, carefully review the sample employee data. What is the data type of the salary field? Do I need to clean the data before calculate?" }, { "code": null, "e": 2581, "s": 2197, "text": "In SQL, JOIN is frequently used to combine information from multiple tables. There are four different types of JOIN, but in most cases, we only use INNER, LEFT and FULL JOIN, because the RIGHT JOIN is not very intuitive and can be easily rewritten using LEFT JOIN. In an SQL interview, you need to choose the right JOIN to use based on the specific requirement of the given question." }, { "code": null, "e": 2589, "s": 2581, "text": "Example" }, { "code": null, "e": 2701, "s": 2589, "text": "Find the total number of classes taken by each student. (Provide student id, name and number of classes taken.)" }, { "code": null, "e": 3269, "s": 2701, "text": "As you might have noticed, not all students appearing in theclass_history table are present in thestudent table, which might be because those students are no longer enrolled. (This is actually very typical in transactional databases, as records are often deleted once inactive.) There is also a student (student_id = 6) with no class history. Depending on whether the interviewer wants to include inactive students and students who didn’t register for any classes in the results, we need to use either LEFT JOIN or INNER JOIN or FULL OUTER JOIN to combine two tables:" }, { "code": null, "e": 3839, "s": 3269, "text": "WITH class_count AS ( SELECT student_id, COUNT(*) AS num_of_class FROM class_history GROUP BY student_id)SELECT COALESCE(c.student_id, s.student_id) AS student_id, s.student_name, COALESCE(c.num_of_class, 0) AS num_of_classFROM class_count c-- CASE 1: include only active students who took at least 1 classJOIN student s ON c.student_id = s.student_id-- CASE 2: include all students who took at least 1 class-- LEFT JOIN student s ON c.student_id = s.student_id-- CASE 3: include all students-- FULL OUTER JOIN student s ON c.student_id = s.student_id" }, { "code": null, "e": 4212, "s": 3839, "text": "GROUP BY is the most essential function in SQL since it is widely used for data aggregation. If you see keywords such as sum, average, minimum, or maximum in a SQL question, it is a big hint that you should probably use GROUP BY in your query. A common pitfall is mixing WHERE and HAVING when filtering data along with GROUP BY — I have seen many people make this mistake." }, { "code": null, "e": 4220, "s": 4212, "text": "Example" }, { "code": null, "e": 4385, "s": 4220, "text": "Calculate the average required course GPA in each school year for each student and find students who are qualified for the Dean’s List (GPA ≥ 3.5) in each semester." }, { "code": null, "e": 4818, "s": 4385, "text": "Since we consider only required courses in our GPA calculation, we need to exclude optional courses using WHERE is_required = TRUE. We need the average GPA per student per year, so we will GROUP BY both thestudent_id and theschool_year columns and take the average of thegpa column. Lastly, we only keep rows where the student has an average GPA higher than 3.5, which can be implemented using HAVING. Let’s put everything together:" }, { "code": null, "e": 4973, "s": 4818, "text": "SELECT student_id, school_year, AVG(gpa) AS avg_gpaFROM gpa_historyWHERE is_required = TRUEGROUP BY student_id, school_yearHAVING AVG(gpa) >= 3.5" }, { "code": null, "e": 5168, "s": 4973, "text": "Keep in mind that whenever GROUP BY is used in a query, you can only select group-by columns and aggregated columns because the row-level information in other columns has already been discarded." }, { "code": null, "e": 5367, "s": 5168, "text": "Some people might wonder what’s the difference between WHERE and HAVING, or why we don’t just write HAVING avg_gpa >= 3.5 instead of specifying the function. I will explain more in the next section." }, { "code": null, "e": 5573, "s": 5367, "text": "Most people write SQL queries from top to bottom starting from SELECT, but do you know that SELECT is one of the very last functions executed by the SQL engine? Below is the execution order of a SQL query:" }, { "code": null, "e": 5638, "s": 5573, "text": "FROM, JOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BYLIMIT, OFFSET" }, { "code": null, "e": 5649, "s": 5638, "text": "FROM, JOIN" }, { "code": null, "e": 5655, "s": 5649, "text": "WHERE" }, { "code": null, "e": 5664, "s": 5655, "text": "GROUP BY" }, { "code": null, "e": 5671, "s": 5664, "text": "HAVING" }, { "code": null, "e": 5678, "s": 5671, "text": "SELECT" }, { "code": null, "e": 5687, "s": 5678, "text": "DISTINCT" }, { "code": null, "e": 5696, "s": 5687, "text": "ORDER BY" }, { "code": null, "e": 5710, "s": 5696, "text": "LIMIT, OFFSET" }, { "code": null, "e": 6080, "s": 5710, "text": "Consider the previous example again. Because we want to filter out optional courses before computing average GPAs, I used WHERE is_required = TRUE instead HAVING, because WHERE is executed before GROUP BY and HAVING. The reason I can’t write HAVING avg_gpa >= 3.5 is thatavg_gpa is defined as part of SELECT, so it cannot be referred to in steps executed before SELECT." }, { "code": null, "e": 6211, "s": 6080, "text": "I recommend following the execution order when writing queries, which is helpful if you struggle with writing complicated queries." }, { "code": null, "e": 6313, "s": 6211, "text": "Window functions frequently appear in SQL interviews as well. There are five common window functions:" }, { "code": null, "e": 6502, "s": 6313, "text": "RANK /DENSE_RANK /ROW_NUMBER: these assign a rank to each row by ordering specific columns. If any partition columns are given, rows are ranked within a partition group that it belongs to." }, { "code": null, "e": 6622, "s": 6502, "text": "LAG /LEAD: it retrieves column values from a preceding or following row based on a specified order and partition group." }, { "code": null, "e": 6744, "s": 6622, "text": "In SQL interviews, it is important to understand the differences between ranking functions and know when to use LAG/LEAD." }, { "code": null, "e": 6752, "s": 6744, "text": "Example" }, { "code": null, "e": 6825, "s": 6752, "text": "Find the top 3 employees who have the highest salary in each department." }, { "code": null, "e": 7122, "s": 6825, "text": "When an SQL question asks for “TOP N”, we can use either ORDER BY or ranking functions to answer the question. However, in this example, it asks to calculate “TOP N X in each Y”, which is a strong hint that we should use ranking functions because we need to rank rows within each partition group." }, { "code": null, "e": 7198, "s": 7122, "text": "The query below finds exactly 3 highest-payed employees regardless of ties:" }, { "code": null, "e": 7569, "s": 7198, "text": "WITH T AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY employee_salary DESC) AS rank_in_depFROM employee_salary)SELECT * FROM TWHERE rank_in_dep <= 3-- Note: When using ROW_NUMBER, each row will have a unique rank number and ranks for tied records are assigned randomly. For exmaple, Rimsha and Tiah may be rank 2 or 3 in different query runs." }, { "code": null, "e": 7683, "s": 7569, "text": "Moreover, based on how ties should be handled, we could pick a different ranking function. Again, details matter!" }, { "code": null, "e": 8052, "s": 7683, "text": "Another common pitfall in SQL interviews is ignoring data duplicates. Although some columns seem to have distinct values in the sample data, candidates are expected to consider all possibilities as if they are working with a real-world dataset. For example, in theemployee_salary table from the previous example, it is possible to have employees sharing the same name." }, { "code": null, "e": 8181, "s": 8052, "text": "One easy way to avoid potential problems caused by duplicates is to always use ID columns to uniquely identify distinct records." }, { "code": null, "e": 8189, "s": 8181, "text": "Example" }, { "code": null, "e": 8283, "s": 8189, "text": "Find the total salary from all departments for each employee using the employee_salary table." }, { "code": null, "e": 8498, "s": 8283, "text": "The right solution is to GROUP BY employee_id and calculating the total salary using SUM(employee_salary). If employee names are needed, join with an employee table at the end to retrieve employee name information." }, { "code": null, "e": 8547, "s": 8498, "text": "The wrong approach is to GROUP BY employee_name." }, { "code": null, "e": 9002, "s": 8547, "text": "In SQL, any predicates can result in one of the three values: true, false, and NULL, a reserved keyword for unknown or missing data values. Handling NULL datasets can be unexpectedly tricky. In an SQL interview, the interviewer might pay extra attention to whether your solution has handled NULL values. Sometimes it is obvious if a column is not nullable (ID columns, for instance) but for most other columns it is very likely there will be NULL values." }, { "code": null, "e": 9175, "s": 9002, "text": "I suggest confirming whether key columns in the sample data are nullable and if so, utilize functions such as IS (NOT) NULL, IFNULL, and COALESCE to cover those edge cases." }, { "code": null, "e": 9280, "s": 9175, "text": "(Want to learn more about how to deal with NULL values? Check out my guide on working with NULL in SQL.)" }, { "code": null, "e": 9353, "s": 9280, "text": "Last but not least — keep the communication going during SQL interviews." }, { "code": null, "e": 9813, "s": 9353, "text": "I have interviewed many candidates who barely talked except when they had questions, which would be okay if they came up with the perfect solution at the end. However, it is generally a good idea to keep up communication during technical interviews. For example, you can talk about your understanding of the question and data, how you plan to approach the problem, why you use some functions versus other alternatives, and what edge cases you are considering." }, { "code": null, "e": 9820, "s": 9813, "text": "TL;DR:" }, { "code": null, "e": 9879, "s": 9820, "text": "Always ask questions to gather the required details first." }, { "code": null, "e": 9932, "s": 9879, "text": "Carefully choose between INNER, LEFT, and FULL JOIN." }, { "code": null, "e": 9998, "s": 9932, "text": "Use GROUP BY to aggregate data and properly use WHERE and HAVING." }, { "code": null, "e": 10062, "s": 9998, "text": "Understand the differences between the three ranking functions." }, { "code": null, "e": 10106, "s": 10062, "text": "Know when to use LAG/LEAD window functions." }, { "code": null, "e": 10196, "s": 10106, "text": "If you struggle with creating complicated queries, try following the SQL execution order." }, { "code": null, "e": 10265, "s": 10196, "text": "Consider potential data problems such as duplicates and NULL values." }, { "code": null, "e": 10321, "s": 10265, "text": "Communicate your thought process with the interviewers." }, { "code": null, "e": 10492, "s": 10321, "text": "To help you understand how to use these strategies in an actual SQL interview, I will walk you through a sample SQL interview question from end to end in the video below:" }, { "code": null, "e": 10660, "s": 10492, "text": "I hope you find this guide helpful in preparing for your next data science interview. If you have any questions regarding SQL, feel free to leave a comment. Good luck!" } ]
C# Program for Median of two sorted arrays of same size - GeeksforGeeks
11 Dec, 2018 There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n)). Note : Since size of the set for which we are looking for median is even (2n), we need take average of middle two numbers and return floor of the average. Method 1 (Simply count while Merging)Use merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation. C# // A Simple Merge based O(n) solution// to find median of two sorted arraysusing System;class GFG { // function to calculate median static int getMedian(int[] ar1, int[] ar2, int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; // Since there are 2n elements, // median will be average of // elements at index n-1 and n in // the array obtained after // merging ar1 and ar2 for (count = 0; count <= n; count++) { // Below is to handle case // where all elements of ar1[] // are smaller than smallest // (or first) element of ar2[] if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } if (ar1[i] < ar2[j]) { // Store the prev median m1 = m2; m2 = ar1[i]; i++; } else { // Store the prev median m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2) / 2; } // Driver Code public static void Main() { int[] ar1 = { 1, 12, 15, 26, 38 }; int[] ar2 = { 2, 13, 17, 30, 45 }; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 == n2) Console.Write("Median is " + getMedian(ar1, ar2, n1)); else Console.Write("arrays are of unequal size"); }} Median is 16 Method 2 (By comparing the medians of two arrays): This method works by first getting medians of the two sorted arrays and then comparing them. Please refer complete article on Median of two sorted arrays of same size for more details! 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 and Write a Byte Array to File using FileStream Class C# Program to Check a Specified Type is an Enum or Not How to Sort Object Array By Specific Property in C#? C# Program to Sort a List of Integers Using the LINQ OrderBy() Method C# Program to Sort a List of String Names Using the LINQ OrderBy() Method C# Program to Check a Specified Type is a Primitive Data Type or Not C# Program to Delete an Empty and a Non-Empty Directory C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method C# Program to Create a Directory How to Get a Comma Separated String From an Array in C#?
[ { "code": null, "e": 24971, "s": 24943, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25170, "s": 24971, "text": "There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median of the array obtained merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n))." }, { "code": null, "e": 25325, "s": 25170, "text": "Note : Since size of the set for which we are looking for median is even (2n), we need take average of middle two numbers and return floor of the average." }, { "code": null, "e": 25627, "s": 25325, "text": "Method 1 (Simply count while Merging)Use merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation." }, { "code": null, "e": 25630, "s": 25627, "text": "C#" }, { "code": "// A Simple Merge based O(n) solution// to find median of two sorted arraysusing System;class GFG { // function to calculate median static int getMedian(int[] ar1, int[] ar2, int n) { int i = 0; int j = 0; int count; int m1 = -1, m2 = -1; // Since there are 2n elements, // median will be average of // elements at index n-1 and n in // the array obtained after // merging ar1 and ar2 for (count = 0; count <= n; count++) { // Below is to handle case // where all elements of ar1[] // are smaller than smallest // (or first) element of ar2[] if (i == n) { m1 = m2; m2 = ar2[0]; break; } /* Below is to handle case where all elements of ar2[] are smaller than smallest(or first) element of ar1[] */ else if (j == n) { m1 = m2; m2 = ar1[0]; break; } if (ar1[i] < ar2[j]) { // Store the prev median m1 = m2; m2 = ar1[i]; i++; } else { // Store the prev median m1 = m2; m2 = ar2[j]; j++; } } return (m1 + m2) / 2; } // Driver Code public static void Main() { int[] ar1 = { 1, 12, 15, 26, 38 }; int[] ar2 = { 2, 13, 17, 30, 45 }; int n1 = ar1.Length; int n2 = ar2.Length; if (n1 == n2) Console.Write(\"Median is \" + getMedian(ar1, ar2, n1)); else Console.Write(\"arrays are of unequal size\"); }}", "e": 27428, "s": 25630, "text": null }, { "code": null, "e": 27442, "s": 27428, "text": "Median is 16\n" }, { "code": null, "e": 27586, "s": 27442, "text": "Method 2 (By comparing the medians of two arrays): This method works by first getting medians of the two sorted arrays and then comparing them." }, { "code": null, "e": 27678, "s": 27586, "text": "Please refer complete article on Median of two sorted arrays of same size for more details!" }, { "code": null, "e": 27690, "s": 27678, "text": "C# Programs" }, { "code": null, "e": 27788, "s": 27690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27797, "s": 27788, "text": "Comments" }, { "code": null, "e": 27810, "s": 27797, "text": "Old Comments" }, { "code": null, "e": 27883, "s": 27810, "text": "C# Program to Read and Write a Byte Array to File using FileStream Class" }, { "code": null, "e": 27938, "s": 27883, "text": "C# Program to Check a Specified Type is an Enum or Not" }, { "code": null, "e": 27991, "s": 27938, "text": "How to Sort Object Array By Specific Property in C#?" }, { "code": null, "e": 28061, "s": 27991, "text": "C# Program to Sort a List of Integers Using the LINQ OrderBy() Method" }, { "code": null, "e": 28135, "s": 28061, "text": "C# Program to Sort a List of String Names Using the LINQ OrderBy() Method" }, { "code": null, "e": 28204, "s": 28135, "text": "C# Program to Check a Specified Type is a Primitive Data Type or Not" }, { "code": null, "e": 28260, "s": 28204, "text": "C# Program to Delete an Empty and a Non-Empty Directory" }, { "code": null, "e": 28344, "s": 28260, "text": "C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method" }, { "code": null, "e": 28377, "s": 28344, "text": "C# Program to Create a Directory" } ]
Setting up your own Data Science workspace with Visual Studio Code and Anaconda (Python) | by Christiaan Dollen | Towards Data Science
If you’re just starting out in the field of data science, creating a personal workspace will help you keeping your projects organized. There are lots of different tools to use and if you’re just like me, starting out in the field, you might find it daunting to dive right in. In this post I’ll show you the basics of how you can set up your own workspace on macOS with some of the most commonly used tools in the trade. While I use macOS in this guide, the steps are almost identically for Windows platforms and I expect you should have no trouble using this guide on Windows. At the end of this guide you’ll be able to: Set up a Python environment with Anaconda. Create a Visual Studio Code workspace and run Python scripts. Install packages and managing different Anaconda environments. Let’s get you started! Anaconda is a free distribution of Python and R, mostly used for the application of data science, machine learning, data processing, analytics et cetera. It lets you manage your own environments and packages that you would use in your projects. We’ll be using Anaconda for our package management and deployment. To build our workspace, we need to install and configure Anaconda. We will be following these steps: Install Anaconda.Create a new environment with the latest version of python.Installing packages into your environment. Install Anaconda. Create a new environment with the latest version of python. Installing packages into your environment. Go to the Anaconda website and download the latest version of Anaconda for your platform. You will be able to download Anaconda with Python 3.7 and Python 2.7. Although I personally prefer to get the latest version of Python, sometimes Python packages require a specific version of Python — hence the reason why I will show you how to set up multiple Python environments. We will use Python 3.7 for now, just to be sure. After installing Anaconda, start Anaconda Navigator. Upon opening the Anaconda Navigator, you see Anaconda has already set up some tools and packages like Jupyter, Spyder. Notice there’s an option to install VS Code. Click to Install. In the meantime, navigate to Environments in the menu on your left. In here you will see that Anaconda has already configured a base (root) environment for you to work with out of the box. From here you can select the environment you want to run. You can also directly run bash commands from the Terminal. There are a lot of packages already installed for you, but what if you want to install new packages? Or maybe you want to install different packages for different versions of Python? This is why you want to work with environments. Notice in the screenshot above I’ve already set up an environment like this called python37. Click on Create and configure a new Python environment.Select the latest version of Python and confirm by clicking on Create again. Click on Create and configure a new Python environment. Select the latest version of Python and confirm by clicking on Create again. It will take a couple of seconds before the environment is configured. In a couple of minutes you’ll notice a new environment is available with a handful of default packages installed. Once you have set up your Python environment, you’ll mostly use the Terminal for installing packages on the go (which I’ll show you later on) and you will probably use the Anaconda Navigator less. Great! Essentially, this is al you need to start to start using Python on your machine with Anaconda. Now all we need is a workspace to actually use our Python environment, so we can run our scripts with our packages. You can use Jupyter Notebook which comes with Anaconda, but I like to use VS Code and I’ll explain shortly why. Visual Studio Code is a free code editor that you can tailer to your needs. Using packages like the Python Extension for VS Code, GitHub and other useful packages, it’s a lightweight IDE that provides excellent support for running Python in your own custom workspace. In the previous chapter we’ve set up Anaconda and installed VS code. Open VS Code. Visual Studio Code is a powerful, lightweight code editor that lets you configure your own workspaces for each of your projects. I’ve created a dummy folder called DataScienceProject for testing purposes. Click on Open Folder and select the folder.Go to the menu and select File > Save Workspace asSave your Workspace-file within the folder Click on Open Folder and select the folder. Go to the menu and select File > Save Workspace as Save your Workspace-file within the folder You now have set up a custom Workspace in VS Code. The great thing about a Workspace, is that you can customize the settings for each individual Workspace. Now, create a new file called helloworld.py within your Workspace.Open helloworld.py.Copy the code below into your file and save it. Now, create a new file called helloworld.py within your Workspace. Open helloworld.py. Copy the code below into your file and save it. #%%# This is the first cell of our Python codeprint('Hello world!')#%%# This is another cellprint('Another cell for the world to see!') Around this time you might get all sorts of messages like ‘Pylint package not installed’, upon opening your file. This is because VS Code will automatically recognize you are editing a Python file. We’ll get into packages in a bit, but first let’s see if we can run that Python file of ours. You can run it directly in the Terminal or from the Interactive Python Window. The Interactive Python Window is extremely useful, since it gives you more feedback on debugging your code, but also allows you to run different bits of codes called cells in your Python script. To run your script, press shift-enter. You can also right-click the file and select ‘Run Python File in Terminal’ or ‘Run Python File in Interactive Python Window’. After running your first script, your should see the Interactive Python Window on the right of your code and return something like this. [1] # This is the first cell of our Python code...Hello world![2] # This is another cell...Another cell for the world to see! Congratulations! You’ve just set up a Workspace in Visual Studio Code to run Python projects! Now let’s dig a little deeper and see if we can install new packages into our environment. Now that we ran our first script, you might want to add a new package. Let’s say your project requires you to connect to one of the Google API’s. Google provides us with a package to do this, but these are not installed in your default environment. Luckily, there are a lot of packages available to us. Anaconda has its own package repository and there are many more repositories for us to find our packages. The package we are looking for in our example is the Google API Python Client. Go ahead and follow these steps. Open the Terminal. Make sure you are working in your base environment. The Terminal should tell us so by showing you something like this: (base) myMac:DataScienceProject myUser$ Check whether the package already is installed by entering the following command in the Terminal: conda list This will return a list of packages that are currently installed in your base (root) environment. Now install the package by running the following command into your Terminal: conda install -c conda-forge google-api-python-client The package will now be installed on your base environment. If all goes well, you should see the following message in your Terminal. I didn’t copy all of the message, but this should give you an idea. Collecting package metadata (current_repodata.json): doneSolving environment: done## Package Plan ##environment location: /Users/myUser/anaconda3added / updated specs: - google-api-python-clientThe following packages will be downloaded.........Proceed ([y]/n)? y...Preparing transaction: doneVerifying transaction: doneExecuting transaction: done Awesome! We’ve successfully installed a new package within our environment. This will allow you to import the package libraries and use the Google API Python Client from within your scripts. But what if you already have package running in the base environment and you don’t want to risk messing up your current environment settings? You can use a new environment and install different packages for that environment as well. We now know how to install a package, but let me show you how to change your Python environment from within VS code as well. Besides from working in your own custom Workspace, you can manage your Anaconda environment from within the editor itself. This way you don’t have to run Anaconda Navigator over and over again, but simply run a Python environment straight out of the editor so you can keep on coding. Have you noticed the blue bar in the bottom of the editor? This bar gives you information on the code you’re working on. On the far left of the bar, you see the interpreter you are currently using. In my case it uses: Python 3.7.3 64-bit ('base':conda) As you can figure, I’m running Python 3.7.3 in the base (root) environment from Anaconda. It also shows you if there are any problems in your code, how many lines, columns, spaces there are, which encoding you currently have selected and which language your are programming in. By clicking on the interpreter you can select other interpreters. For example, the Python environment we’ve created earlier in Anaconda. Click on your interpreter and select the interpreter we created earlier. Now, when you switch from your Base-interpreter to a new interpreter, sometimes the Jupyter-server has trouble starting. The Jupyter-server runs on a kernel which is somewhat of an engine for your Python environment. The Jupyter-kernel is vital to running your code inside VS Code, especially running code in the Interactive Python Window. If you happen to get these errors, try the following in the Terminal: For macOS: source activate <environmentnamehere>pip install ipykernelpython -m ipykernel install --user For Windows: activate <environmentnamehere>pip install ipykernelpython -m ipykernel install --user This will install a kernel within your environment specifically. Restart your VS Code editor and try running your code in the newly selected interpreter (python37:conda). If all goes well, then congratulations are in order! You’ve successfully set up your own Workspace in Visual Studio Code which you can now use for your Python projects! Managing your Python environments can be a pain in the butt. To understand how to manage your environments and your packages gives you a lot of flexibility and prevents a lot of stress when one of your environments suddenly stops working. This is why I wanted to show you how to switch environments and install packages, because these are the types of errors you are prone of getting. Of course I haven’t shown you everything you can do with Visual Studio Code or Anaconda, which is why I would suggest you also read up on the following articles: Best packages for data science with Python An extensive list of extensions for Visual Studio Code Using Version Control with GitHub for Visual Studio Code I hope you have found this guide to be of help to you. Happy coding!
[ { "code": null, "e": 792, "s": 171, "text": "If you’re just starting out in the field of data science, creating a personal workspace will help you keeping your projects organized. There are lots of different tools to use and if you’re just like me, starting out in the field, you might find it daunting to dive right in. In this post I’ll show you the basics of how you can set up your own workspace on macOS with some of the most commonly used tools in the trade. While I use macOS in this guide, the steps are almost identically for Windows platforms and I expect you should have no trouble using this guide on Windows. At the end of this guide you’ll be able to:" }, { "code": null, "e": 835, "s": 792, "text": "Set up a Python environment with Anaconda." }, { "code": null, "e": 897, "s": 835, "text": "Create a Visual Studio Code workspace and run Python scripts." }, { "code": null, "e": 960, "s": 897, "text": "Install packages and managing different Anaconda environments." }, { "code": null, "e": 983, "s": 960, "text": "Let’s get you started!" }, { "code": null, "e": 1396, "s": 983, "text": "Anaconda is a free distribution of Python and R, mostly used for the application of data science, machine learning, data processing, analytics et cetera. It lets you manage your own environments and packages that you would use in your projects. We’ll be using Anaconda for our package management and deployment. To build our workspace, we need to install and configure Anaconda. We will be following these steps:" }, { "code": null, "e": 1515, "s": 1396, "text": "Install Anaconda.Create a new environment with the latest version of python.Installing packages into your environment." }, { "code": null, "e": 1533, "s": 1515, "text": "Install Anaconda." }, { "code": null, "e": 1593, "s": 1533, "text": "Create a new environment with the latest version of python." }, { "code": null, "e": 1636, "s": 1593, "text": "Installing packages into your environment." }, { "code": null, "e": 2110, "s": 1636, "text": "Go to the Anaconda website and download the latest version of Anaconda for your platform. You will be able to download Anaconda with Python 3.7 and Python 2.7. Although I personally prefer to get the latest version of Python, sometimes Python packages require a specific version of Python — hence the reason why I will show you how to set up multiple Python environments. We will use Python 3.7 for now, just to be sure. After installing Anaconda, start Anaconda Navigator." }, { "code": null, "e": 2274, "s": 2110, "text": "Upon opening the Anaconda Navigator, you see Anaconda has already set up some tools and packages like Jupyter, Spyder. Notice there’s an option to install VS Code." }, { "code": null, "e": 2292, "s": 2274, "text": "Click to Install." }, { "code": null, "e": 2481, "s": 2292, "text": "In the meantime, navigate to Environments in the menu on your left. In here you will see that Anaconda has already configured a base (root) environment for you to work with out of the box." }, { "code": null, "e": 2598, "s": 2481, "text": "From here you can select the environment you want to run. You can also directly run bash commands from the Terminal." }, { "code": null, "e": 2922, "s": 2598, "text": "There are a lot of packages already installed for you, but what if you want to install new packages? Or maybe you want to install different packages for different versions of Python? This is why you want to work with environments. Notice in the screenshot above I’ve already set up an environment like this called python37." }, { "code": null, "e": 3054, "s": 2922, "text": "Click on Create and configure a new Python environment.Select the latest version of Python and confirm by clicking on Create again." }, { "code": null, "e": 3110, "s": 3054, "text": "Click on Create and configure a new Python environment." }, { "code": null, "e": 3187, "s": 3110, "text": "Select the latest version of Python and confirm by clicking on Create again." }, { "code": null, "e": 3569, "s": 3187, "text": "It will take a couple of seconds before the environment is configured. In a couple of minutes you’ll notice a new environment is available with a handful of default packages installed. Once you have set up your Python environment, you’ll mostly use the Terminal for installing packages on the go (which I’ll show you later on) and you will probably use the Anaconda Navigator less." }, { "code": null, "e": 3899, "s": 3569, "text": "Great! Essentially, this is al you need to start to start using Python on your machine with Anaconda. Now all we need is a workspace to actually use our Python environment, so we can run our scripts with our packages. You can use Jupyter Notebook which comes with Anaconda, but I like to use VS Code and I’ll explain shortly why." }, { "code": null, "e": 4236, "s": 3899, "text": "Visual Studio Code is a free code editor that you can tailer to your needs. Using packages like the Python Extension for VS Code, GitHub and other useful packages, it’s a lightweight IDE that provides excellent support for running Python in your own custom workspace. In the previous chapter we’ve set up Anaconda and installed VS code." }, { "code": null, "e": 4250, "s": 4236, "text": "Open VS Code." }, { "code": null, "e": 4455, "s": 4250, "text": "Visual Studio Code is a powerful, lightweight code editor that lets you configure your own workspaces for each of your projects. I’ve created a dummy folder called DataScienceProject for testing purposes." }, { "code": null, "e": 4591, "s": 4455, "text": "Click on Open Folder and select the folder.Go to the menu and select File > Save Workspace asSave your Workspace-file within the folder" }, { "code": null, "e": 4635, "s": 4591, "text": "Click on Open Folder and select the folder." }, { "code": null, "e": 4686, "s": 4635, "text": "Go to the menu and select File > Save Workspace as" }, { "code": null, "e": 4729, "s": 4686, "text": "Save your Workspace-file within the folder" }, { "code": null, "e": 4885, "s": 4729, "text": "You now have set up a custom Workspace in VS Code. The great thing about a Workspace, is that you can customize the settings for each individual Workspace." }, { "code": null, "e": 5018, "s": 4885, "text": "Now, create a new file called helloworld.py within your Workspace.Open helloworld.py.Copy the code below into your file and save it." }, { "code": null, "e": 5085, "s": 5018, "text": "Now, create a new file called helloworld.py within your Workspace." }, { "code": null, "e": 5105, "s": 5085, "text": "Open helloworld.py." }, { "code": null, "e": 5153, "s": 5105, "text": "Copy the code below into your file and save it." }, { "code": null, "e": 5289, "s": 5153, "text": "#%%# This is the first cell of our Python codeprint('Hello world!')#%%# This is another cellprint('Another cell for the world to see!')" }, { "code": null, "e": 5855, "s": 5289, "text": "Around this time you might get all sorts of messages like ‘Pylint package not installed’, upon opening your file. This is because VS Code will automatically recognize you are editing a Python file. We’ll get into packages in a bit, but first let’s see if we can run that Python file of ours. You can run it directly in the Terminal or from the Interactive Python Window. The Interactive Python Window is extremely useful, since it gives you more feedback on debugging your code, but also allows you to run different bits of codes called cells in your Python script." }, { "code": null, "e": 6020, "s": 5855, "text": "To run your script, press shift-enter. You can also right-click the file and select ‘Run Python File in Terminal’ or ‘Run Python File in Interactive Python Window’." }, { "code": null, "e": 6157, "s": 6020, "text": "After running your first script, your should see the Interactive Python Window on the right of your code and return something like this." }, { "code": null, "e": 6283, "s": 6157, "text": "[1] # This is the first cell of our Python code...Hello world![2] # This is another cell...Another cell for the world to see!" }, { "code": null, "e": 6468, "s": 6283, "text": "Congratulations! You’ve just set up a Workspace in Visual Studio Code to run Python projects! Now let’s dig a little deeper and see if we can install new packages into our environment." }, { "code": null, "e": 6989, "s": 6468, "text": "Now that we ran our first script, you might want to add a new package. Let’s say your project requires you to connect to one of the Google API’s. Google provides us with a package to do this, but these are not installed in your default environment. Luckily, there are a lot of packages available to us. Anaconda has its own package repository and there are many more repositories for us to find our packages. The package we are looking for in our example is the Google API Python Client. Go ahead and follow these steps." }, { "code": null, "e": 7127, "s": 6989, "text": "Open the Terminal. Make sure you are working in your base environment. The Terminal should tell us so by showing you something like this:" }, { "code": null, "e": 7167, "s": 7127, "text": "(base) myMac:DataScienceProject myUser$" }, { "code": null, "e": 7265, "s": 7167, "text": "Check whether the package already is installed by entering the following command in the Terminal:" }, { "code": null, "e": 7276, "s": 7265, "text": "conda list" }, { "code": null, "e": 7451, "s": 7276, "text": "This will return a list of packages that are currently installed in your base (root) environment. Now install the package by running the following command into your Terminal:" }, { "code": null, "e": 7506, "s": 7451, "text": "conda install -c conda-forge google-api-python-client " }, { "code": null, "e": 7707, "s": 7506, "text": "The package will now be installed on your base environment. If all goes well, you should see the following message in your Terminal. I didn’t copy all of the message, but this should give you an idea." }, { "code": null, "e": 8057, "s": 7707, "text": "Collecting package metadata (current_repodata.json): doneSolving environment: done## Package Plan ##environment location: /Users/myUser/anaconda3added / updated specs: - google-api-python-clientThe following packages will be downloaded.........Proceed ([y]/n)? y...Preparing transaction: doneVerifying transaction: doneExecuting transaction: done" }, { "code": null, "e": 8248, "s": 8057, "text": "Awesome! We’ve successfully installed a new package within our environment. This will allow you to import the package libraries and use the Google API Python Client from within your scripts." }, { "code": null, "e": 8606, "s": 8248, "text": "But what if you already have package running in the base environment and you don’t want to risk messing up your current environment settings? You can use a new environment and install different packages for that environment as well. We now know how to install a package, but let me show you how to change your Python environment from within VS code as well." }, { "code": null, "e": 8890, "s": 8606, "text": "Besides from working in your own custom Workspace, you can manage your Anaconda environment from within the editor itself. This way you don’t have to run Anaconda Navigator over and over again, but simply run a Python environment straight out of the editor so you can keep on coding." }, { "code": null, "e": 9108, "s": 8890, "text": "Have you noticed the blue bar in the bottom of the editor? This bar gives you information on the code you’re working on. On the far left of the bar, you see the interpreter you are currently using. In my case it uses:" }, { "code": null, "e": 9143, "s": 9108, "text": "Python 3.7.3 64-bit ('base':conda)" }, { "code": null, "e": 9421, "s": 9143, "text": "As you can figure, I’m running Python 3.7.3 in the base (root) environment from Anaconda. It also shows you if there are any problems in your code, how many lines, columns, spaces there are, which encoding you currently have selected and which language your are programming in." }, { "code": null, "e": 9558, "s": 9421, "text": "By clicking on the interpreter you can select other interpreters. For example, the Python environment we’ve created earlier in Anaconda." }, { "code": null, "e": 9631, "s": 9558, "text": "Click on your interpreter and select the interpreter we created earlier." }, { "code": null, "e": 10041, "s": 9631, "text": "Now, when you switch from your Base-interpreter to a new interpreter, sometimes the Jupyter-server has trouble starting. The Jupyter-server runs on a kernel which is somewhat of an engine for your Python environment. The Jupyter-kernel is vital to running your code inside VS Code, especially running code in the Interactive Python Window. If you happen to get these errors, try the following in the Terminal:" }, { "code": null, "e": 10052, "s": 10041, "text": "For macOS:" }, { "code": null, "e": 10145, "s": 10052, "text": "source activate <environmentnamehere>pip install ipykernelpython -m ipykernel install --user" }, { "code": null, "e": 10158, "s": 10145, "text": "For Windows:" }, { "code": null, "e": 10244, "s": 10158, "text": "activate <environmentnamehere>pip install ipykernelpython -m ipykernel install --user" }, { "code": null, "e": 10415, "s": 10244, "text": "This will install a kernel within your environment specifically. Restart your VS Code editor and try running your code in the newly selected interpreter (python37:conda)." }, { "code": null, "e": 10584, "s": 10415, "text": "If all goes well, then congratulations are in order! You’ve successfully set up your own Workspace in Visual Studio Code which you can now use for your Python projects!" }, { "code": null, "e": 10969, "s": 10584, "text": "Managing your Python environments can be a pain in the butt. To understand how to manage your environments and your packages gives you a lot of flexibility and prevents a lot of stress when one of your environments suddenly stops working. This is why I wanted to show you how to switch environments and install packages, because these are the types of errors you are prone of getting." }, { "code": null, "e": 11131, "s": 10969, "text": "Of course I haven’t shown you everything you can do with Visual Studio Code or Anaconda, which is why I would suggest you also read up on the following articles:" }, { "code": null, "e": 11174, "s": 11131, "text": "Best packages for data science with Python" }, { "code": null, "e": 11229, "s": 11174, "text": "An extensive list of extensions for Visual Studio Code" }, { "code": null, "e": 11286, "s": 11229, "text": "Using Version Control with GitHub for Visual Studio Code" } ]