title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python – Convert HTML Characters To Strings
08 Dec, 2020 Prerequisites: html module Given a string with HTML characters, the task is to convert HTML characters to a string. This can be achieved with the help of html.escape() method(for Python 3.4+), we can convert the ASCII string into HTML script by replacing ASCII characters with special characters by using html.escape() method. By this method we can decode the HTML entities into text. Syntax: html.unescape(String) We can also use Beautiful Soup which handles entity conversion. In Beautiful Soup 4, entities get decoded automatically. Example 1: Python 3.6+ Python3 # import htmlimport html # Create Texttext = 'Γeeks for Γeeks' # It Converts given text To Stringprint(html.unescape(text)) # It Converts given text to HTML Entities print(html.escape(text)) Output: Γeeks for Γeeks Γeeks for Γeeks Example 2: Python 2.6-3.3 We can use HTMLParser.unescape() from the standard library: For Python 2.6-2.7 it’s in HtmlParser. For Python 3 it’s in html.parser Python3 #import htmlimport html try: # Python 2.6-2.7 from HTMLParser import HTMLParserexcept ImportError: # Python 3 from html.parser import HTMLParser # for python 3h = html.parserprint(h.unescape('Γeeks for Γeeks')) Output: Γeeks for Γeeks Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 55, "s": 28, "text": "Prerequisites: html module" }, { "code": null, "e": 355, "s": 55, "text": "Given a string with HTML characters, the task is to convert HTML characters to a string. This can be achieved with the help of html.escape() method(for Python 3.4+), we can convert the ASCII string into HTML script by replacing ASCII characters with special characters by using html.escape() method." }, { "code": null, "e": 413, "s": 355, "text": "By this method we can decode the HTML entities into text." }, { "code": null, "e": 421, "s": 413, "text": "Syntax:" }, { "code": null, "e": 443, "s": 421, "text": "html.unescape(String)" }, { "code": null, "e": 564, "s": 443, "text": "We can also use Beautiful Soup which handles entity conversion. In Beautiful Soup 4, entities get decoded automatically." }, { "code": null, "e": 587, "s": 564, "text": "Example 1: Python 3.6+" }, { "code": null, "e": 595, "s": 587, "text": "Python3" }, { "code": "# import htmlimport html # Create Texttext = 'Γeeks for Γeeks' # It Converts given text To Stringprint(html.unescape(text)) # It Converts given text to HTML Entities print(html.escape(text)) ", "e": 791, "s": 595, "text": null }, { "code": null, "e": 799, "s": 791, "text": "Output:" }, { "code": null, "e": 815, "s": 799, "text": "Γeeks for Γeeks" }, { "code": null, "e": 843, "s": 815, "text": "Γeeks for Γeeks" }, { "code": null, "e": 869, "s": 843, "text": "Example 2: Python 2.6-3.3" }, { "code": null, "e": 929, "s": 869, "text": "We can use HTMLParser.unescape() from the standard library:" }, { "code": null, "e": 968, "s": 929, "text": "For Python 2.6-2.7 it’s in HtmlParser." }, { "code": null, "e": 1001, "s": 968, "text": "For Python 3 it’s in html.parser" }, { "code": null, "e": 1009, "s": 1001, "text": "Python3" }, { "code": "#import htmlimport html try: # Python 2.6-2.7 from HTMLParser import HTMLParserexcept ImportError: # Python 3 from html.parser import HTMLParser # for python 3h = html.parserprint(h.unescape('Γeeks for Γeeks')) ", "e": 1236, "s": 1009, "text": null }, { "code": null, "e": 1244, "s": 1236, "text": "Output:" }, { "code": null, "e": 1260, "s": 1244, "text": "Γeeks for Γeeks" }, { "code": null, "e": 1283, "s": 1260, "text": "Python string-programs" }, { "code": null, "e": 1290, "s": 1283, "text": "Python" }, { "code": null, "e": 1306, "s": 1290, "text": "Python Programs" }, { "code": null, "e": 1404, "s": 1306, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1436, "s": 1404, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1463, "s": 1436, "text": "Python Classes and Objects" }, { "code": null, "e": 1484, "s": 1463, "text": "Python OOPs Concepts" }, { "code": null, "e": 1507, "s": 1484, "text": "Introduction To PYTHON" }, { "code": null, "e": 1538, "s": 1507, "text": "Python | os.path.join() method" }, { "code": null, "e": 1560, "s": 1538, "text": "Defaultdict in Python" }, { "code": null, "e": 1599, "s": 1560, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1637, "s": 1599, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1686, "s": 1637, "text": "Python | Convert string dictionary to dictionary" } ]
Types of Routing
20 Oct, 2021 Routing is a process that is performed by layer 3 (or network layer) devices in order to deliver the packet by choosing an optimal path from one network to another. There are 3 types of routing: 1. Static routing – Static routing is a process in which we have to manually add routes to the routing table. Advantages – No routing overhead for router CPU which means a cheaper router can be used to do routing. It adds security because an only administrator can allow routing to particular networks only. No bandwidth usage between routers. Disadvantage – For a large network, it is a hectic task for administrators to manually add each route for the network in the routing table on each router. The administrator should have good knowledge of the topology. If a new administrator comes, then he has to manually add each route so he should have very good knowledge of the routes of the topology. Configuration – R1 having IP address 172.16.10.6/30 on s0/0/1, 192.168.10.1/24 on fa0/0. R2 having IP address 172.16.10.2/30 on s0/0/0, 192.168.20.1/24 on fa0/0. R3 having IP address 172.16.10.5/30 on s0/1, 172.16.10.1/30 on s0/0, 10.10.10.1/24 on fa0/0. Now configuring static routes for router R3: R3(config)#ip route 192.168.10.0 255.255.255.0 172.16.10.2 R3(config)#ip route 192.168.20.0 255.255.255.0 172.16.10.6 Here, provided the route for 192.168.10.0 network where 192.168.10.0 is its network I’d and 172.16.10.2 and 172.16.10.6 are the next-hop address. Now, configuring for R2: R2(config)#ip route 192.168.20.0 255.255.255.0 172.16.10.1 R2(config)#ip route 10.10.10.0 255.255.255.0 172.16.10.1 R2(config)#ip route 172.16.10.0 255.255.255.0 172.16.10.1 Similarly for R1: R1(config)#ip route 192.168.10.0 255.255.255.0 172.16.10.5 R1(config)#ip route 10.10.10.0 255.255.255.0 172.16.10.5 R1(config)#ip route 172.16.10.0 255.255.255.0 172.16.10.5 2. Default Routing – This is the method where the router is configured to send all packets towards a single router (next hop). It doesn’t matter to which network the packet belongs, it is forwarded out to the router which is configured for default routing. It is generally used with stub routers. A stub router is a router that has only one route to reach all other networks. Configuration – Using the same topology which we have used for the static routing before. In this topology, R1 and R2 are stub routers so we can configure default routing for both these routers. Configuring default routing for R1: R1(config)#ip route 0.0.0.0 0.0.0.0 172.16.10.5 Now configuring default routing for R2: R2(config)#ip route 0.0.0.0 0.0.0.0 172.16.10.1 3. Dynamic Routing – Dynamic routing makes automatic adjustments of the routes according to the current state of the route in the routing table. Dynamic routing uses protocols to discover network destinations and the routes to reach them. RIP and OSPF are the best examples of dynamic routing protocols. Automatic adjustments will be made to reach the network destination if one route goes down. A dynamic protocol has the following features: The routers should have the same dynamic protocol running in order to exchange routes. When a router finds a change in the topology then the router advertises it to all other routers. The routers should have the same dynamic protocol running in order to exchange routes. When a router finds a change in the topology then the router advertises it to all other routers. Advantages – Easy to configure. More effective at selecting the best route to a destination remote network and also for discovering remote network. Disadvantage – Consumes more bandwidth for communicating with other neighbors. Less secure than static routing. nidhi_biet mjn2k18 tanwarsinghvaibhav 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": 52, "s": 24, "text": "\n20 Oct, 2021" }, { "code": null, "e": 218, "s": 52, "text": "Routing is a process that is performed by layer 3 (or network layer) devices in order to deliver the packet by choosing an optimal path from one network to another. " }, { "code": null, "e": 250, "s": 218, "text": "There are 3 types of routing: " }, { "code": null, "e": 361, "s": 250, "text": "1. Static routing – Static routing is a process in which we have to manually add routes to the routing table. " }, { "code": null, "e": 375, "s": 361, "text": "Advantages – " }, { "code": null, "e": 467, "s": 375, "text": "No routing overhead for router CPU which means a cheaper router can be used to do routing. " }, { "code": null, "e": 562, "s": 467, "text": "It adds security because an only administrator can allow routing to particular networks only. " }, { "code": null, "e": 599, "s": 562, "text": "No bandwidth usage between routers. " }, { "code": null, "e": 615, "s": 599, "text": "Disadvantage – " }, { "code": null, "e": 756, "s": 615, "text": "For a large network, it is a hectic task for administrators to manually add each route for the network in the routing table on each router. " }, { "code": null, "e": 957, "s": 756, "text": "The administrator should have good knowledge of the topology. If a new administrator comes, then he has to manually add each route so he should have very good knowledge of the routes of the topology. " }, { "code": null, "e": 974, "s": 957, "text": "Configuration – " }, { "code": null, "e": 1216, "s": 976, "text": "R1 having IP address 172.16.10.6/30 on s0/0/1, 192.168.10.1/24 on fa0/0. R2 having IP address 172.16.10.2/30 on s0/0/0, 192.168.20.1/24 on fa0/0. R3 having IP address 172.16.10.5/30 on s0/1, 172.16.10.1/30 on s0/0, 10.10.10.1/24 on fa0/0. " }, { "code": null, "e": 1262, "s": 1216, "text": "Now configuring static routes for router R3: " }, { "code": null, "e": 1380, "s": 1262, "text": "R3(config)#ip route 192.168.10.0 255.255.255.0 172.16.10.2\nR3(config)#ip route 192.168.20.0 255.255.255.0 172.16.10.6" }, { "code": null, "e": 1528, "s": 1380, "text": "Here, provided the route for 192.168.10.0 network where 192.168.10.0 is its network I’d and 172.16.10.2 and 172.16.10.6 are the next-hop address. " }, { "code": null, "e": 1554, "s": 1528, "text": "Now, configuring for R2: " }, { "code": null, "e": 1728, "s": 1554, "text": "R2(config)#ip route 192.168.20.0 255.255.255.0 172.16.10.1\nR2(config)#ip route 10.10.10.0 255.255.255.0 172.16.10.1\nR2(config)#ip route 172.16.10.0 255.255.255.0 172.16.10.1" }, { "code": null, "e": 1747, "s": 1728, "text": "Similarly for R1: " }, { "code": null, "e": 1921, "s": 1747, "text": "R1(config)#ip route 192.168.10.0 255.255.255.0 172.16.10.5\nR1(config)#ip route 10.10.10.0 255.255.255.0 172.16.10.5\nR1(config)#ip route 172.16.10.0 255.255.255.0 172.16.10.5" }, { "code": null, "e": 2299, "s": 1921, "text": "2. Default Routing – This is the method where the router is configured to send all packets towards a single router (next hop). It doesn’t matter to which network the packet belongs, it is forwarded out to the router which is configured for default routing. It is generally used with stub routers. A stub router is a router that has only one route to reach all other networks. " }, { "code": null, "e": 2390, "s": 2299, "text": "Configuration – Using the same topology which we have used for the static routing before. " }, { "code": null, "e": 2499, "s": 2392, "text": "In this topology, R1 and R2 are stub routers so we can configure default routing for both these routers. " }, { "code": null, "e": 2536, "s": 2499, "text": "Configuring default routing for R1: " }, { "code": null, "e": 2585, "s": 2536, "text": "R1(config)#ip route 0.0.0.0 0.0.0.0 172.16.10.5" }, { "code": null, "e": 2626, "s": 2585, "text": "Now configuring default routing for R2: " }, { "code": null, "e": 2675, "s": 2626, "text": "R2(config)#ip route 0.0.0.0 0.0.0.0 172.16.10.1" }, { "code": null, "e": 3072, "s": 2675, "text": "3. Dynamic Routing – Dynamic routing makes automatic adjustments of the routes according to the current state of the route in the routing table. Dynamic routing uses protocols to discover network destinations and the routes to reach them. RIP and OSPF are the best examples of dynamic routing protocols. Automatic adjustments will be made to reach the network destination if one route goes down. " }, { "code": null, "e": 3120, "s": 3072, "text": "A dynamic protocol has the following features: " }, { "code": null, "e": 3305, "s": 3120, "text": "The routers should have the same dynamic protocol running in order to exchange routes. When a router finds a change in the topology then the router advertises it to all other routers. " }, { "code": null, "e": 3393, "s": 3305, "text": "The routers should have the same dynamic protocol running in order to exchange routes. " }, { "code": null, "e": 3491, "s": 3393, "text": "When a router finds a change in the topology then the router advertises it to all other routers. " }, { "code": null, "e": 3505, "s": 3491, "text": "Advantages – " }, { "code": null, "e": 3525, "s": 3505, "text": "Easy to configure. " }, { "code": null, "e": 3642, "s": 3525, "text": "More effective at selecting the best route to a destination remote network and also for discovering remote network. " }, { "code": null, "e": 3658, "s": 3642, "text": "Disadvantage – " }, { "code": null, "e": 3723, "s": 3658, "text": "Consumes more bandwidth for communicating with other neighbors. " }, { "code": null, "e": 3757, "s": 3723, "text": "Less secure than static routing. " }, { "code": null, "e": 3768, "s": 3757, "text": "nidhi_biet" }, { "code": null, "e": 3776, "s": 3768, "text": "mjn2k18" }, { "code": null, "e": 3795, "s": 3776, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 3813, "s": 3795, "text": "Computer Networks" }, { "code": null, "e": 3821, "s": 3813, "text": "GATE CS" }, { "code": null, "e": 3839, "s": 3821, "text": "Computer Networks" } ]
Object Detection with Detection Transformer (DETR) by Facebook
14 Feb, 2022 Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection models such as the RCNN family, YOLO(You Look Only Once) and SSD(Single Shot Detection) but none of them have ever used a transformer to achieve this task. The best part of this model is that due to the fact that it is using a transformer, it makes the architecture very simple unlike all the other techniques mentioned with has all kinds of hyperparameters and layers. So without further adieu, let’s get started.What is object detection? Given a photo if you need to determine if the photo has a single particular object you can do it by classification. but if you want to get the location of that object as well inside the image ....well even that is not an object detection task ....its called classification and localization. But if there are multiple objects in an image and you want the location of each and every location of every object, then that is object detection. Some of the previous techniques try to get an RPN(Region Proposal Network) to come up with potential regions that may contain the object and then we can use the concept of anchor boxes, NMS(non-max-suppression)and IOU to generate relevant boxes and identify the object. Although these concepts work it takes some time for inferencing so real-time use with high accuracy is not achieved due to its complexity. On a high level, this uses CNN and then a transformer to detect an object and it does so via a bipartite matching training object. This is the main reason why it is so simple. Source – https://arxiv.org/pdf/2005.12872.pdf Step 1: We put the image through a convolution Neural Network Encoder because CNN works best with images. So after passing through CNN the image features are conserved. This is the higher-order representation of an image with many more feature channels. Step 2: This enriched feature map of the image is given to a transformer encoder-decoder, which outputs the set of box prediction. Each of these boxes is consisting of a tuple. The tuple will be a class and a bounding box. Note: this also includes the class NULL or Nothing class and its position as well.Now, this is a real problem as in the annotation there is no object class annotated as nothing. Comparing and dealing with similar objects next to each other is another major issue and in this paper, it is tackled by using bipartite matching loss. The loss is compared by comparing each class and bounding box there is with its corresponding class and box including the none class, which are let’s say N, with the annotation including the part added that contains nothing to make the total boxes N. The assignment of the predicted to the actual is a one to one assignment such that the total loss is minimized. There is a very famous algorithm called the Hungarian method to compute these minimum matching. The main components: source – https://arxiv.org/pdf/2005.12872.pdf The backbone – Features extracted from a Convolutional Neural Network and a positional encoding are passed The transformer Encoder – A transformer is naturally a sequence processing unit and for the same reason, we the incoming tensors are flattened. It transforms the sequence into an equally long sequence of features.The Transformer Decoder – takes in Object queries So its a decoder as a side input for conditioning information. Prediction Feed-Forward Network (FFN) – The output for this is going through a classifier which outputs the class labels and bounding box output discussed earlierEvaluator: The evaluation is done on COCO dataset and its primary competitor was the RCNN family that has ruled this category for quiet some time and is considered to be the most classic technique for object detection. Source – https://arxiv.org/pdf/2005.12872.pdf Pros: This new model is quite simple and you don’t have to install any library to use it. DETR demonstrates significantly better performance on large objects and not on a small object which can be further improved. A good thing is that they have even provided the code in the paper so now we will also implement it to know what its really capable of doing. Code: Python3 # Write Python3 code hereimport torchfrom torch import nnfrom torchvision.models import resnet50 class DETR(nn.Module): def __init__(self, num_classes, hidden_dim, nheads,num_encoder_layers, num_decoder_layers): super().__init__() # We take only convolutional layers from ResNet-50 model self.backbone = nn.Sequential(*list(resnet50(pretrained=True).children())[:-2]) self.conv = nn.Conv2d(2048, hidden_dim, 1) self.transformer = nn.Transformer(hidden_dim, heads, num_encoder_layers, num_decoder_layers) self.linear_class = nn.Linear(hidden_dim, num_classes + 1) self.linear_bbox = nn.Linear(hidden_dim, 4) self.query_pos = nn.Parameter(torch.rand(100, hidden_dim)) self.row_embed = nn.Parameter(torch.rand(50, hidden_dim // 2)) self.col_embed = nn.Parameter(torch.rand(50, hidden_dim // 2)) def forward(self, inputs): x = self.backbone(inputs) h = self.conv(x) H , W = h.shape[-2:] pos = torch.cat([ self.col_embed[:W].unsqueeze(0).repeat(H, 1, 1), self.row_embed[:H].unsqueeze(1).repeat(1, W, 1),], dim=-1).flatten(0, 1).unsqueeze(1) h = self.transformer(pos + h.flatten(2).permute(2, 0, 1), self.query_pos.unsqueeze(1)) return self.linear_class(h), self.linear_bbox(h).sigmoid()detr = DETR(num_classes=91, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6)detr.eval()inputs = torch.randn(1, 3, 800, 1200)logits, bboxes = detr(inputs) <strong>Listing 1: </strong>DETR PyTorch inference code. For clarity, it uses learned positional encodings in the encoder instead of fixed, and positional encodings are added to the inputonly instead of at each transformer layer. Making these changes requires going beyondPyTorch implementation of transformers, which hampers readability. The entire codeto reproduce the experiments will be made available before the conference. We take only convolutional layers from ResNet-50 model Code taken from the paper Code: Try running this code on colab or just go to this link, copy and run the complete file. Python3 import torch as thimport torchvision.transforms as Timport requestsfrom PIL import Image, ImageDraw, ImageFont We will be using ResNet 101 as the backbone architecture and we will be loading this architecture directly from the Pytorch Hub. Code: Python3 model = th.hub.load('facebookresearch/detr', 'detr_resnet101', pretrained=True)model.eval()model = model.cuda() Python3 # standard PyTorch mean-std input image normalizationtransform = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) CLASSES = [ 'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'] Enter the URL of an image here. The one I have used is https://i.ytimg.com/vi/vrlX3cwr3ww/maxresdefault.jpg Code: Python3 url = input() Displaying the image Python3 img = Image.open(requests.get(url, stream=True).raw).resize((800,600)).convert('RGB')img Code: Python3 img_tens = transform(img).unsqueeze(0).cuda()with th.no_grad(): output = model(img_tens) draw = ImageDraw.Draw(img)pred_logits=output['pred_logits'][0][:, :len(CLASSES)]pred_boxes=output['pred_boxes'][0] max_output = pred_logits.softmax(-1).max(-1)topk = max_output.values.topk(15) pred_logits = pred_logits[topk.indices]pred_boxes = pred_boxes[topk.indices]pred_logits.shape Code: Python3 for logits, box in zip(pred_logits, pred_boxes): cls = logits.argmax() if cls >= len(CLASSES): continue label = CLASSES[cls] print(label) box = box.cpu() * th.Tensor([800, 600, 800, 600]) x, y, w, h = box x0, x1 = x-w//2, x+w//2 y0, y1 = y-h//2, y+h//2 draw.rectangle([x0, y0, x1, y1], outline='red', width=5) draw.text((x, y), label, fill='white') Code: Displaying the detected image Python3 img Here is the link to the colab notebook and github code. Also, feel free to check out the official GitHub for the same Drawbacks: It takes forever to train. It trained for six days on 8 GPUs. It’s not that much when you compare it with the language model at this scale as they use a transformer but still. 291087211 varshagumber28 Image-Processing Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Feb, 2022" }, { "code": null, "e": 1863, "s": 52, "text": "Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection models such as the RCNN family, YOLO(You Look Only Once) and SSD(Single Shot Detection) but none of them have ever used a transformer to achieve this task. The best part of this model is that due to the fact that it is using a transformer, it makes the architecture very simple unlike all the other techniques mentioned with has all kinds of hyperparameters and layers. So without further adieu, let’s get started.What is object detection? Given a photo if you need to determine if the photo has a single particular object you can do it by classification. but if you want to get the location of that object as well inside the image ....well even that is not an object detection task ....its called classification and localization. But if there are multiple objects in an image and you want the location of each and every location of every object, then that is object detection. Some of the previous techniques try to get an RPN(Region Proposal Network) to come up with potential regions that may contain the object and then we can use the concept of anchor boxes, NMS(non-max-suppression)and IOU to generate relevant boxes and identify the object. Although these concepts work it takes some time for inferencing so real-time use with high accuracy is not achieved due to its complexity. On a high level, this uses CNN and then a transformer to detect an object and it does so via a bipartite matching training object. This is the main reason why it is so simple. " }, { "code": null, "e": 1909, "s": 1863, "text": "Source – https://arxiv.org/pdf/2005.12872.pdf" }, { "code": null, "e": 3198, "s": 1909, "text": "Step 1: We put the image through a convolution Neural Network Encoder because CNN works best with images. So after passing through CNN the image features are conserved. This is the higher-order representation of an image with many more feature channels. Step 2: This enriched feature map of the image is given to a transformer encoder-decoder, which outputs the set of box prediction. Each of these boxes is consisting of a tuple. The tuple will be a class and a bounding box. Note: this also includes the class NULL or Nothing class and its position as well.Now, this is a real problem as in the annotation there is no object class annotated as nothing. Comparing and dealing with similar objects next to each other is another major issue and in this paper, it is tackled by using bipartite matching loss. The loss is compared by comparing each class and bounding box there is with its corresponding class and box including the none class, which are let’s say N, with the annotation including the part added that contains nothing to make the total boxes N. The assignment of the predicted to the actual is a one to one assignment such that the total loss is minimized. There is a very famous algorithm called the Hungarian method to compute these minimum matching. The main components: " }, { "code": null, "e": 3244, "s": 3198, "text": "source – https://arxiv.org/pdf/2005.12872.pdf" }, { "code": null, "e": 4060, "s": 3244, "text": "The backbone – Features extracted from a Convolutional Neural Network and a positional encoding are passed The transformer Encoder – A transformer is naturally a sequence processing unit and for the same reason, we the incoming tensors are flattened. It transforms the sequence into an equally long sequence of features.The Transformer Decoder – takes in Object queries So its a decoder as a side input for conditioning information. Prediction Feed-Forward Network (FFN) – The output for this is going through a classifier which outputs the class labels and bounding box output discussed earlierEvaluator: The evaluation is done on COCO dataset and its primary competitor was the RCNN family that has ruled this category for quiet some time and is considered to be the most classic technique for object detection. " }, { "code": null, "e": 4106, "s": 4060, "text": "Source – https://arxiv.org/pdf/2005.12872.pdf" }, { "code": null, "e": 4114, "s": 4106, "text": "Pros: " }, { "code": null, "e": 4198, "s": 4114, "text": "This new model is quite simple and you don’t have to install any library to use it." }, { "code": null, "e": 4323, "s": 4198, "text": "DETR demonstrates significantly better performance on large objects and not on a small object which can be further improved." }, { "code": null, "e": 4465, "s": 4323, "text": "A good thing is that they have even provided the code in the paper so now we will also implement it to know what its really capable of doing." }, { "code": null, "e": 4473, "s": 4465, "text": "Code: " }, { "code": null, "e": 4481, "s": 4473, "text": "Python3" }, { "code": "# Write Python3 code hereimport torchfrom torch import nnfrom torchvision.models import resnet50 class DETR(nn.Module): def __init__(self, num_classes, hidden_dim, nheads,num_encoder_layers, num_decoder_layers): super().__init__() # We take only convolutional layers from ResNet-50 model self.backbone = nn.Sequential(*list(resnet50(pretrained=True).children())[:-2]) self.conv = nn.Conv2d(2048, hidden_dim, 1) self.transformer = nn.Transformer(hidden_dim, heads, num_encoder_layers, num_decoder_layers) self.linear_class = nn.Linear(hidden_dim, num_classes + 1) self.linear_bbox = nn.Linear(hidden_dim, 4) self.query_pos = nn.Parameter(torch.rand(100, hidden_dim)) self.row_embed = nn.Parameter(torch.rand(50, hidden_dim // 2)) self.col_embed = nn.Parameter(torch.rand(50, hidden_dim // 2)) def forward(self, inputs): x = self.backbone(inputs) h = self.conv(x) H , W = h.shape[-2:] pos = torch.cat([ self.col_embed[:W].unsqueeze(0).repeat(H, 1, 1), self.row_embed[:H].unsqueeze(1).repeat(1, W, 1),], dim=-1).flatten(0, 1).unsqueeze(1) h = self.transformer(pos + h.flatten(2).permute(2, 0, 1), self.query_pos.unsqueeze(1)) return self.linear_class(h), self.linear_bbox(h).sigmoid()detr = DETR(num_classes=91, hidden_dim=256, nheads=8, num_encoder_layers=6, num_decoder_layers=6)detr.eval()inputs = torch.randn(1, 3, 800, 1200)logits, bboxes = detr(inputs) <strong>Listing 1: </strong>DETR PyTorch inference code. For clarity, it uses learned positional encodings in the encoder instead of fixed, and positional encodings are added to the inputonly instead of at each transformer layer. Making these changes requires going beyondPyTorch implementation of transformers, which hampers readability. The entire codeto reproduce the experiments will be made available before the conference.", "e": 6288, "s": 4481, "text": null }, { "code": null, "e": 6465, "s": 6288, "text": "We take only convolutional layers from ResNet-50 model Code taken from the paper Code: Try running this code on colab or just go to this link, copy and run the complete file. " }, { "code": null, "e": 6473, "s": 6465, "text": "Python3" }, { "code": "import torch as thimport torchvision.transforms as Timport requestsfrom PIL import Image, ImageDraw, ImageFont", "e": 6584, "s": 6473, "text": null }, { "code": null, "e": 6721, "s": 6584, "text": "We will be using ResNet 101 as the backbone architecture and we will be loading this architecture directly from the Pytorch Hub. Code: " }, { "code": null, "e": 6729, "s": 6721, "text": "Python3" }, { "code": "model = th.hub.load('facebookresearch/detr', 'detr_resnet101', pretrained=True)model.eval()model = model.cuda()", "e": 6841, "s": 6729, "text": null }, { "code": null, "e": 6849, "s": 6841, "text": "Python3" }, { "code": "# standard PyTorch mean-std input image normalizationtransform = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) CLASSES = [ 'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']", "e": 7998, "s": 6849, "text": null }, { "code": null, "e": 8114, "s": 7998, "text": "Enter the URL of an image here. The one I have used is https://i.ytimg.com/vi/vrlX3cwr3ww/maxresdefault.jpg Code: " }, { "code": null, "e": 8122, "s": 8114, "text": "Python3" }, { "code": "url = input()", "e": 8136, "s": 8122, "text": null }, { "code": null, "e": 8159, "s": 8136, "text": "Displaying the image " }, { "code": null, "e": 8167, "s": 8159, "text": "Python3" }, { "code": "img = Image.open(requests.get(url, stream=True).raw).resize((800,600)).convert('RGB')img", "e": 8256, "s": 8167, "text": null }, { "code": null, "e": 8264, "s": 8256, "text": "Code: " }, { "code": null, "e": 8272, "s": 8264, "text": "Python3" }, { "code": "img_tens = transform(img).unsqueeze(0).cuda()with th.no_grad(): output = model(img_tens) draw = ImageDraw.Draw(img)pred_logits=output['pred_logits'][0][:, :len(CLASSES)]pred_boxes=output['pred_boxes'][0] max_output = pred_logits.softmax(-1).max(-1)topk = max_output.values.topk(15) pred_logits = pred_logits[topk.indices]pred_boxes = pred_boxes[topk.indices]pred_logits.shape", "e": 8649, "s": 8272, "text": null }, { "code": null, "e": 8657, "s": 8649, "text": "Code: " }, { "code": null, "e": 8665, "s": 8657, "text": "Python3" }, { "code": "for logits, box in zip(pred_logits, pred_boxes): cls = logits.argmax() if cls >= len(CLASSES): continue label = CLASSES[cls] print(label) box = box.cpu() * th.Tensor([800, 600, 800, 600]) x, y, w, h = box x0, x1 = x-w//2, x+w//2 y0, y1 = y-h//2, y+h//2 draw.rectangle([x0, y0, x1, y1], outline='red', width=5) draw.text((x, y), label, fill='white')", "e": 9027, "s": 8665, "text": null }, { "code": null, "e": 9065, "s": 9027, "text": "Code: Displaying the detected image " }, { "code": null, "e": 9073, "s": 9065, "text": "Python3" }, { "code": "img", "e": 9077, "s": 9073, "text": null }, { "code": null, "e": 9383, "s": 9077, "text": "Here is the link to the colab notebook and github code. Also, feel free to check out the official GitHub for the same Drawbacks: It takes forever to train. It trained for six days on 8 GPUs. It’s not that much when you compare it with the language model at this scale as they use a transformer but still. " }, { "code": null, "e": 9393, "s": 9383, "text": "291087211" }, { "code": null, "e": 9408, "s": 9393, "text": "varshagumber28" }, { "code": null, "e": 9425, "s": 9408, "text": "Image-Processing" }, { "code": null, "e": 9442, "s": 9425, "text": "Machine Learning" }, { "code": null, "e": 9449, "s": 9442, "text": "Python" }, { "code": null, "e": 9466, "s": 9449, "text": "Machine Learning" }, { "code": null, "e": 9564, "s": 9466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9605, "s": 9564, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 9638, "s": 9605, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 9674, "s": 9638, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 9698, "s": 9674, "text": "Markov Decision Process" }, { "code": null, "e": 9749, "s": 9698, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 9777, "s": 9749, "text": "Read JSON file using Python" }, { "code": null, "e": 9827, "s": 9777, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 9849, "s": 9827, "text": "Python map() function" }, { "code": null, "e": 9867, "s": 9849, "text": "Python Dictionary" } ]
Python | numpy.isin() method
27 Sep, 2019 With the help of numpy.isin() method, we can see that one array having values are checked in a different numpy array having different elements with different sizes. Syntax : numpy.isin(target_array, list) Return : Return boolean array having same size as of target_array. Example #1 : In this example we can see that by using numpy.isin() method, we are able to get the boolean array if elements are matched with the target array. # import numpyimport numpy as np # using numpy.isin() methodgfg1 = np.array([1, 2, 3, 4, 5])lis = [1, 3, 5]gfg = np.isin(gfg1, lis) print(gfg) Output : [ True False True False True] Example #2 : # import numpyimport numpy as np # using numpy.isin() methodgfg1 = np.array([[1, 3], [5, 7], [9, 11]])lis = [1, 3, 11, 9]gfg = np.isin(gfg1, lis) print(gfg) Output : [[ True True][False False][ True True]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 193, "s": 28, "text": "With the help of numpy.isin() method, we can see that one array having values are checked in a different numpy array having different elements with different sizes." }, { "code": null, "e": 233, "s": 193, "text": "Syntax : numpy.isin(target_array, list)" }, { "code": null, "e": 300, "s": 233, "text": "Return : Return boolean array having same size as of target_array." }, { "code": null, "e": 313, "s": 300, "text": "Example #1 :" }, { "code": null, "e": 459, "s": 313, "text": "In this example we can see that by using numpy.isin() method, we are able to get the boolean array if elements are matched with the target array." }, { "code": "# import numpyimport numpy as np # using numpy.isin() methodgfg1 = np.array([1, 2, 3, 4, 5])lis = [1, 3, 5]gfg = np.isin(gfg1, lis) print(gfg)", "e": 604, "s": 459, "text": null }, { "code": null, "e": 613, "s": 604, "text": "Output :" }, { "code": null, "e": 643, "s": 613, "text": "[ True False True False True]" }, { "code": null, "e": 656, "s": 643, "text": "Example #2 :" }, { "code": "# import numpyimport numpy as np # using numpy.isin() methodgfg1 = np.array([[1, 3], [5, 7], [9, 11]])lis = [1, 3, 11, 9]gfg = np.isin(gfg1, lis) print(gfg)", "e": 815, "s": 656, "text": null }, { "code": null, "e": 824, "s": 815, "text": "Output :" }, { "code": null, "e": 864, "s": 824, "text": "[[ True True][False False][ True True]]" }, { "code": null, "e": 877, "s": 864, "text": "Python-numpy" }, { "code": null, "e": 884, "s": 877, "text": "Python" }, { "code": null, "e": 982, "s": 884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1000, "s": 982, "text": "Python Dictionary" }, { "code": null, "e": 1042, "s": 1000, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1064, "s": 1042, "text": "Enumerate() in Python" }, { "code": null, "e": 1099, "s": 1064, "text": "Read a file line by line in Python" }, { "code": null, "e": 1125, "s": 1099, "text": "Python String | replace()" }, { "code": null, "e": 1157, "s": 1125, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1186, "s": 1157, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1213, "s": 1186, "text": "Python Classes and Objects" }, { "code": null, "e": 1243, "s": 1213, "text": "Iterate over a list in Python" } ]
Ruby | Array dig() operation
08 Jan, 2020 Array#dig() : dig() is a Array class method which extracts the specific element out of the high dimension sequences. Syntax: Array.dig() Parameter: element position. Return: element from a specific location in sequence, returning nil if any intermediate step is nil. Code #1 : Example for dig() method # Ruby code for dig() method # declaring arraya = [18, 22, 33, 23, 5, 6] # declaring arrayb = [[1, 4], [ 1, 1, 88, 9]] # digputs "dig : #{a.dig(1)}\n\n" # digputs "dig : #{b.dig(0, 1)}\n\n" # digputs "dig : #{b.dig(1, 2)}\n\n" Output : dig : 22 dig : 4 dig : 88 Code #2 : Example for dig() method # Ruby code for dig() method # declaring arraya = [["abc"], ["geeks", "dog"], ["1", "2"]] # declaring arrayb = [["cow"], ["1", "dog"]] # digputs "dig : #{a.dig(2, 1)}\n\n" # digputs "dig : #{a.dig(1, 1)}\n\n" # digputs "dig : #{b.dig(1, 0)}\n\n" Output : dig : 2 dig : dog dig : 1 Ruby Array-class Ruby Collections Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2020" }, { "code": null, "e": 145, "s": 28, "text": "Array#dig() : dig() is a Array class method which extracts the specific element out of the high dimension sequences." }, { "code": null, "e": 165, "s": 145, "text": "Syntax: Array.dig()" }, { "code": null, "e": 194, "s": 165, "text": "Parameter: element position." }, { "code": null, "e": 295, "s": 194, "text": "Return: element from a specific location in sequence, returning nil if any intermediate step is nil." }, { "code": null, "e": 330, "s": 295, "text": "Code #1 : Example for dig() method" }, { "code": "# Ruby code for dig() method # declaring arraya = [18, 22, 33, 23, 5, 6] # declaring arrayb = [[1, 4], [ 1, 1, 88, 9]] # digputs \"dig : #{a.dig(1)}\\n\\n\" # digputs \"dig : #{b.dig(0, 1)}\\n\\n\" # digputs \"dig : #{b.dig(1, 2)}\\n\\n\"", "e": 562, "s": 330, "text": null }, { "code": null, "e": 571, "s": 562, "text": "Output :" }, { "code": null, "e": 600, "s": 571, "text": "dig : 22\n\ndig : 4\n\ndig : 88\n" }, { "code": null, "e": 635, "s": 600, "text": "Code #2 : Example for dig() method" }, { "code": "# Ruby code for dig() method # declaring arraya = [[\"abc\"], [\"geeks\", \"dog\"], [\"1\", \"2\"]] # declaring arrayb = [[\"cow\"], [\"1\", \"dog\"]] # digputs \"dig : #{a.dig(2, 1)}\\n\\n\" # digputs \"dig : #{a.dig(1, 1)}\\n\\n\" # digputs \"dig : #{b.dig(1, 0)}\\n\\n\"", "e": 894, "s": 635, "text": null }, { "code": null, "e": 903, "s": 894, "text": "Output :" }, { "code": null, "e": 932, "s": 903, "text": "dig : 2\n\ndig : dog\n\ndig : 1\n" }, { "code": null, "e": 949, "s": 932, "text": "Ruby Array-class" }, { "code": null, "e": 966, "s": 949, "text": "Ruby Collections" }, { "code": null, "e": 979, "s": 966, "text": "Ruby-Methods" }, { "code": null, "e": 984, "s": 979, "text": "Ruby" } ]
Path resolve() method in Java with Examples
07 Apr, 2022 resolve() method of java.nio.file.Path used to resolve the given path against this path. There are two types of resolve() methods. resolve(String other) method of java.nio.file.Path used to converts a given path string to a Path and resolves it against this Path in the exact same manner as specified by the resolve method. For example, If the name separator is “/” and a path represents “c/drive/files”, then invoking this method with the path string “file1” will result in the Path “c/drive/files/file1”.Syntax:default Path resolve(String other) Parameters: This method accepts a single parameter other which is the path string to resolve against this path.Return value: This method returns the resulting path.Exception: This method throws InvalidPathException if the path string cannot be converted to a Path..Below programs illustrate resolve(String other) method:Program 1:// Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create a string object String passedPath = "drive"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println("Resolved Path:" + resolvedPath); }}Output:resolve(Path other) method of java.nio.file.Path used to resolve the given path against this path. This method will going to connect both paths together.If this path is “C/temp” and passed path is “drive/newFile” then this method will add passed path in the end of this path and use “/” as a separator. So resolved path will be “C/temp/drive/newFile”.If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified.Syntax:Path resolve(Path other) Parameters: This method accepts a single parameter other which is the path to resolve against this path.Return value: This method return the resulting path.Below programs illustrate resolve(Path other) method:Program 1:// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create an object of Path // to pass to resolve method Path path2 = Paths.get("programs\\workspace"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println("Resolved Path:" + resolvedPath); }}Output: resolve(String other) method of java.nio.file.Path used to converts a given path string to a Path and resolves it against this Path in the exact same manner as specified by the resolve method. For example, If the name separator is “/” and a path represents “c/drive/files”, then invoking this method with the path string “file1” will result in the Path “c/drive/files/file1”.Syntax:default Path resolve(String other) Parameters: This method accepts a single parameter other which is the path string to resolve against this path.Return value: This method returns the resulting path.Exception: This method throws InvalidPathException if the path string cannot be converted to a Path..Below programs illustrate resolve(String other) method:Program 1:// Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create a string object String passedPath = "drive"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println("Resolved Path:" + resolvedPath); }}Output: Syntax: default Path resolve(String other) Parameters: This method accepts a single parameter other which is the path string to resolve against this path. Return value: This method returns the resulting path. Exception: This method throws InvalidPathException if the path string cannot be converted to a Path.. Below programs illustrate resolve(String other) method:Program 1: // Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create a string object String passedPath = "drive"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println("Resolved Path:" + resolvedPath); }} resolve(Path other) method of java.nio.file.Path used to resolve the given path against this path. This method will going to connect both paths together.If this path is “C/temp” and passed path is “drive/newFile” then this method will add passed path in the end of this path and use “/” as a separator. So resolved path will be “C/temp/drive/newFile”.If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified.Syntax:Path resolve(Path other) Parameters: This method accepts a single parameter other which is the path to resolve against this path.Return value: This method return the resulting path.Below programs illustrate resolve(Path other) method:Program 1:// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create an object of Path // to pass to resolve method Path path2 = Paths.get("programs\\workspace"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println("Resolved Path:" + resolvedPath); }}Output: If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified. Syntax: Path resolve(Path other) Parameters: This method accepts a single parameter other which is the path to resolve against this path. Return value: This method return the resulting path. Below programs illustrate resolve(Path other) method:Program 1: // Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get("drive\\temp\\Spring"); // create an object of Path // to pass to resolve method Path path2 = Paths.get("programs\\workspace"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println("Resolved Path:" + resolvedPath); }} References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.lang.String) https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.nio.file.Path) sweetyty kashishsoda Java-Functions Java-Path java.nio.file package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Apr, 2022" }, { "code": null, "e": 142, "s": 53, "text": "resolve() method of java.nio.file.Path used to resolve the given path against this path." }, { "code": null, "e": 184, "s": 142, "text": "There are two types of resolve() methods." }, { "code": null, "e": 3319, "s": 184, "text": "resolve(String other) method of java.nio.file.Path used to converts a given path string to a Path and resolves it against this Path in the exact same manner as specified by the resolve method. For example, If the name separator is “/” and a path represents “c/drive/files”, then invoking this method with the path string “file1” will result in the Path “c/drive/files/file1”.Syntax:default Path resolve(String other)\nParameters: This method accepts a single parameter other which is the path string to resolve against this path.Return value: This method returns the resulting path.Exception: This method throws InvalidPathException if the path string cannot be converted to a Path..Below programs illustrate resolve(String other) method:Program 1:// Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create a string object String passedPath = \"drive\"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}Output:resolve(Path other) method of java.nio.file.Path used to resolve the given path against this path. This method will going to connect both paths together.If this path is “C/temp” and passed path is “drive/newFile” then this method will add passed path in the end of this path and use “/” as a separator. So resolved path will be “C/temp/drive/newFile”.If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified.Syntax:Path resolve(Path other)\nParameters: This method accepts a single parameter other which is the path to resolve against this path.Return value: This method return the resulting path.Below programs illustrate resolve(Path other) method:Program 1:// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create an object of Path // to pass to resolve method Path path2 = Paths.get(\"programs\\\\workspace\"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}Output:" }, { "code": null, "e": 4636, "s": 3319, "text": "resolve(String other) method of java.nio.file.Path used to converts a given path string to a Path and resolves it against this Path in the exact same manner as specified by the resolve method. For example, If the name separator is “/” and a path represents “c/drive/files”, then invoking this method with the path string “file1” will result in the Path “c/drive/files/file1”.Syntax:default Path resolve(String other)\nParameters: This method accepts a single parameter other which is the path string to resolve against this path.Return value: This method returns the resulting path.Exception: This method throws InvalidPathException if the path string cannot be converted to a Path..Below programs illustrate resolve(String other) method:Program 1:// Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create a string object String passedPath = \"drive\"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}Output:" }, { "code": null, "e": 4644, "s": 4636, "text": "Syntax:" }, { "code": null, "e": 4680, "s": 4644, "text": "default Path resolve(String other)\n" }, { "code": null, "e": 4792, "s": 4680, "text": "Parameters: This method accepts a single parameter other which is the path string to resolve against this path." }, { "code": null, "e": 4846, "s": 4792, "text": "Return value: This method returns the resulting path." }, { "code": null, "e": 4948, "s": 4846, "text": "Exception: This method throws InvalidPathException if the path string cannot be converted to a Path.." }, { "code": null, "e": 5014, "s": 4948, "text": "Below programs illustrate resolve(String other) method:Program 1:" }, { "code": "// Java program to demonstrate// Path.resolve(String other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create a string object String passedPath = \"drive\"; // call resolve() to create resolved Path Path resolvedPath = path.resolve(passedPath); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}", "e": 5577, "s": 5014, "text": null }, { "code": null, "e": 7396, "s": 5577, "text": "resolve(Path other) method of java.nio.file.Path used to resolve the given path against this path. This method will going to connect both paths together.If this path is “C/temp” and passed path is “drive/newFile” then this method will add passed path in the end of this path and use “/” as a separator. So resolved path will be “C/temp/drive/newFile”.If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified.Syntax:Path resolve(Path other)\nParameters: This method accepts a single parameter other which is the path to resolve against this path.Return value: This method return the resulting path.Below programs illustrate resolve(Path other) method:Program 1:// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create an object of Path // to pass to resolve method Path path2 = Paths.get(\"programs\\\\workspace\"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}Output:" }, { "code": null, "e": 7974, "s": 7396, "text": "If the other parameter is an absolute path then this method trivially returns other. If other is an empty path then this method trivially returns this path. Otherwise, this method considers this path to be a directory and resolves the given path against this path. In the simplest case, the given path does not have a root component, in which case this method joins the given path to this path and returns a resulting path that ends with the given path. Where the given path has a root component then the resolution is highly implementation dependent and therefore unspecified." }, { "code": null, "e": 7982, "s": 7974, "text": "Syntax:" }, { "code": null, "e": 8008, "s": 7982, "text": "Path resolve(Path other)\n" }, { "code": null, "e": 8113, "s": 8008, "text": "Parameters: This method accepts a single parameter other which is the path to resolve against this path." }, { "code": null, "e": 8166, "s": 8113, "text": "Return value: This method return the resulting path." }, { "code": null, "e": 8230, "s": 8166, "text": "Below programs illustrate resolve(Path other) method:Program 1:" }, { "code": "// Java program to demonstrate// Path.resolve(Path other) method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path path = Paths.get(\"drive\\\\temp\\\\Spring\"); // create an object of Path // to pass to resolve method Path path2 = Paths.get(\"programs\\\\workspace\"); // call resolve() // to create resolved Path Path resolvedPath = path.resolve(path2); // print result System.out.println(\"Resolved Path:\" + resolvedPath); }}", "e": 8863, "s": 8230, "text": null }, { "code": null, "e": 8875, "s": 8863, "text": "References:" }, { "code": null, "e": 8968, "s": 8875, "text": "https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.lang.String)" }, { "code": null, "e": 9063, "s": 8968, "text": "https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#resolve(java.nio.file.Path)" }, { "code": null, "e": 9072, "s": 9063, "text": "sweetyty" }, { "code": null, "e": 9084, "s": 9072, "text": "kashishsoda" }, { "code": null, "e": 9099, "s": 9084, "text": "Java-Functions" }, { "code": null, "e": 9109, "s": 9099, "text": "Java-Path" }, { "code": null, "e": 9131, "s": 9109, "text": "java.nio.file package" }, { "code": null, "e": 9136, "s": 9131, "text": "Java" }, { "code": null, "e": 9141, "s": 9136, "text": "Java" } ]
Compare sequences in Python using dfflib module
24 Feb, 2021 The dfflib Python module includes various features to evaluate the comparison of sequences, it can be used to compare files, and it can create information about file variations in different formats, including HTML and context and unified diffs. It contains various classes to perform various comparisons between sequences: It is a very flexible class for matching sequence pairs of any sort. This class contains various functions discussed below: The ratio() method of this class returns the similarity ratio between the two arguments passed. The similarity ratio is determined using the formula below. 2*X/Y Where X is the number of similar matches and Y is the total elements present in both the sequences. Example 1: Python3 # import required moduleimport difflib # assign parameterspar1 = ['g', 'f', 'g']par2 = 'gfg' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio()) Output: 1.0 Example 2: Python3 # import required moduleimport difflib # assign parameterspar1 = 'Geeks for geeks!'par2 = 'geeks' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio()) Output: 0.47619047619047616 Example 3: Python3 # import required moduleimport difflib # assign parameterspar1 = 'gfg'par2 = 'GFG' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio()) Output: 0.0 The get_matching_blocks() method of this class returns a list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. Example 1: Python3 # import required moduleimport difflib # assign parameterspar1 = 'Geeks for geeks!'par2 = 'geeks' # comparematches = difflib.SequenceMatcher( None, par1, par2).get_matching_blocks() for ele in matches: print(par1[ele.a:ele.a + ele.size]) Output: geeks Example 2: Python3 # import required moduleimport difflib # assign parameterspar1 = 'GFG'par2 = 'gfg' # comparematches = difflib.SequenceMatcher( None, par1, par2).get_matching_blocks() for ele in matches: print(par1[ele.a:ele.a + ele.size]) Output: As there are no matching subsequences between GFG and gfg. So no output is displayed. get_close_matches() method: This method returns the best character or group of character matches column. The term is a sequence in which close similarities are needed (usually a string) and possibilities are a set of sequences for matching terms (mostly a list of strings). Example : Python3 # import required moduleimport difflib # assign parametersstring = "Geeks4geeks"listOfStrings = ["for", "Gks", "G4g", "geeks"] # find common stringsprint(difflib.get_close_matches(string, listOfStrings)) Output: ['geeks'] This class is used for matching sequences in the form of lines of text and creating human-readable variations or deltas. Every line of the Differ delta starts with a two-letter code: Following are the functions contained within this class: The compare() method in this class, compares two sequences of lines, and generate the delta (a sequence of lines). Example 1: Python3 # import required modulefrom difflib import Differ # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in Differ().compare(par1, par2): print(ele) Output: - G + g e e k s + ! Example 2: Python3 # import required modulefrom difflib import Differ # assign parameterspar1 = ['Geeks','for','geeks!']par2 = 'geeks!' # compare parametersfor ele in Differ().compare(par1, par2): print(ele) Output: - G + g e e k s + ! ndiff() method: The above type of comparison can be performed using this method also. However, if lists are passed then the elements of the lists are compared first. Example 1: Python3 # import required moduleimport difflib # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in difflib.ndiff(par1, par2): print(ele) Output: - G + g e e k s + ! Example 2: Python3 # import required moduleimport difflib # assign parameterspar1 = ['Geeks','for','geeks!']par2 = 'geeks!' # compare parametersfor ele in difflib.ndiff(par1, par2): print(ele) Output: - Geeks - for - geeks! + g + e + e + k + s + ! context_diff() method: The Context diffs are a convenient way to display only the lines that have shifted, with a few lines of context. The improvements are seen in the style before/after. The number of background lines is set to n, which is set to three by default. Example 1: Python3 # import required moduleimport difflib # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in difflib.context_diff(par1, par2): print(ele) Output: *** — *************** *** 1,5 **** ! G e e k s — 1,6 —- ! g e e k s + ! Example 2: Python3 # import required moduleimport difflib # assign parameterspar1 = ['Geeks', 'for', 'geeks!']par2 = 'geeks!' # compare parametersfor ele in difflib.context_diff(par1, par2): print(ele) Output: *** — *************** *** 1,3 **** ! Geeks ! for ! geeks! — 1,6 —- ! g ! e ! e ! k ! s ! ! python-modules Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 273, "s": 28, "text": "The dfflib Python module includes various features to evaluate the comparison of sequences, it can be used to compare files, and it can create information about file variations in different formats, including HTML and context and unified diffs." }, { "code": null, "e": 351, "s": 273, "text": "It contains various classes to perform various comparisons between sequences:" }, { "code": null, "e": 475, "s": 351, "text": "It is a very flexible class for matching sequence pairs of any sort. This class contains various functions discussed below:" }, { "code": null, "e": 631, "s": 475, "text": "The ratio() method of this class returns the similarity ratio between the two arguments passed. The similarity ratio is determined using the formula below." }, { "code": null, "e": 638, "s": 631, "text": "2*X/Y " }, { "code": null, "e": 684, "s": 638, "text": "Where X is the number of similar matches and " }, { "code": null, "e": 739, "s": 684, "text": "Y is the total elements present in both the sequences." }, { "code": null, "e": 750, "s": 739, "text": "Example 1:" }, { "code": null, "e": 758, "s": 750, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = ['g', 'f', 'g']par2 = 'gfg' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio())", "e": 919, "s": 758, "text": null }, { "code": null, "e": 927, "s": 919, "text": "Output:" }, { "code": null, "e": 931, "s": 927, "text": "1.0" }, { "code": null, "e": 942, "s": 931, "text": "Example 2:" }, { "code": null, "e": 950, "s": 942, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'Geeks for geeks!'par2 = 'geeks' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio())", "e": 1116, "s": 950, "text": null }, { "code": null, "e": 1124, "s": 1116, "text": "Output:" }, { "code": null, "e": 1144, "s": 1124, "text": "0.47619047619047616" }, { "code": null, "e": 1155, "s": 1144, "text": "Example 3:" }, { "code": null, "e": 1163, "s": 1155, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'gfg'par2 = 'GFG' # compareprint(difflib.SequenceMatcher(None, par1, par2).ratio())", "e": 1314, "s": 1163, "text": null }, { "code": null, "e": 1322, "s": 1314, "text": "Output:" }, { "code": null, "e": 1326, "s": 1322, "text": "0.0" }, { "code": null, "e": 1508, "s": 1326, "text": "The get_matching_blocks() method of this class returns a list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]." }, { "code": null, "e": 1519, "s": 1508, "text": "Example 1:" }, { "code": null, "e": 1527, "s": 1519, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'Geeks for geeks!'par2 = 'geeks' # comparematches = difflib.SequenceMatcher( None, par1, par2).get_matching_blocks() for ele in matches: print(par1[ele.a:ele.a + ele.size])", "e": 1774, "s": 1527, "text": null }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1788, "s": 1782, "text": "geeks" }, { "code": null, "e": 1799, "s": 1788, "text": "Example 2:" }, { "code": null, "e": 1807, "s": 1799, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'GFG'par2 = 'gfg' # comparematches = difflib.SequenceMatcher( None, par1, par2).get_matching_blocks() for ele in matches: print(par1[ele.a:ele.a + ele.size])", "e": 2039, "s": 1807, "text": null }, { "code": null, "e": 2047, "s": 2039, "text": "Output:" }, { "code": null, "e": 2135, "s": 2049, "text": "As there are no matching subsequences between GFG and gfg. So no output is displayed." }, { "code": null, "e": 2409, "s": 2135, "text": "get_close_matches() method: This method returns the best character or group of character matches column. The term is a sequence in which close similarities are needed (usually a string) and possibilities are a set of sequences for matching terms (mostly a list of strings)." }, { "code": null, "e": 2419, "s": 2409, "text": "Example :" }, { "code": null, "e": 2427, "s": 2419, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parametersstring = \"Geeks4geeks\"listOfStrings = [\"for\", \"Gks\", \"G4g\", \"geeks\"] # find common stringsprint(difflib.get_close_matches(string, listOfStrings))", "e": 2633, "s": 2427, "text": null }, { "code": null, "e": 2641, "s": 2633, "text": "Output:" }, { "code": null, "e": 2651, "s": 2641, "text": "['geeks']" }, { "code": null, "e": 2834, "s": 2651, "text": "This class is used for matching sequences in the form of lines of text and creating human-readable variations or deltas. Every line of the Differ delta starts with a two-letter code:" }, { "code": null, "e": 2891, "s": 2834, "text": "Following are the functions contained within this class:" }, { "code": null, "e": 3006, "s": 2891, "text": "The compare() method in this class, compares two sequences of lines, and generate the delta (a sequence of lines)." }, { "code": null, "e": 3017, "s": 3006, "text": "Example 1:" }, { "code": null, "e": 3025, "s": 3017, "text": "Python3" }, { "code": "# import required modulefrom difflib import Differ # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in Differ().compare(par1, par2): print(ele)", "e": 3202, "s": 3025, "text": null }, { "code": null, "e": 3210, "s": 3202, "text": "Output:" }, { "code": null, "e": 3238, "s": 3210, "text": "- G\n+ g\n e\n e\n k\n s\n+ !" }, { "code": null, "e": 3249, "s": 3238, "text": "Example 2:" }, { "code": null, "e": 3257, "s": 3249, "text": "Python3" }, { "code": "# import required modulefrom difflib import Differ # assign parameterspar1 = ['Geeks','for','geeks!']par2 = 'geeks!' # compare parametersfor ele in Differ().compare(par1, par2): print(ele)", "e": 3451, "s": 3257, "text": null }, { "code": null, "e": 3459, "s": 3451, "text": "Output:" }, { "code": null, "e": 3487, "s": 3459, "text": "- G\n+ g\n e\n e\n k\n s\n+ !" }, { "code": null, "e": 3653, "s": 3487, "text": "ndiff() method: The above type of comparison can be performed using this method also. However, if lists are passed then the elements of the lists are compared first." }, { "code": null, "e": 3664, "s": 3653, "text": "Example 1:" }, { "code": null, "e": 3672, "s": 3664, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in difflib.ndiff(par1, par2): print(ele)", "e": 3834, "s": 3672, "text": null }, { "code": null, "e": 3842, "s": 3834, "text": "Output:" }, { "code": null, "e": 3870, "s": 3842, "text": "- G\n+ g\n e\n e\n k\n s\n+ !" }, { "code": null, "e": 3881, "s": 3870, "text": "Example 2:" }, { "code": null, "e": 3889, "s": 3881, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = ['Geeks','for','geeks!']par2 = 'geeks!' # compare parametersfor ele in difflib.ndiff(par1, par2): print(ele)", "e": 4068, "s": 3889, "text": null }, { "code": null, "e": 4076, "s": 4068, "text": "Output:" }, { "code": null, "e": 4123, "s": 4076, "text": "- Geeks\n- for\n- geeks!\n+ g\n+ e\n+ e\n+ k\n+ s\n+ !" }, { "code": null, "e": 4390, "s": 4123, "text": "context_diff() method: The Context diffs are a convenient way to display only the lines that have shifted, with a few lines of context. The improvements are seen in the style before/after. The number of background lines is set to n, which is set to three by default." }, { "code": null, "e": 4401, "s": 4390, "text": "Example 1:" }, { "code": null, "e": 4409, "s": 4401, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = 'Geeks'par2 = 'geeks!' # compare parametersfor ele in difflib.context_diff(par1, par2): print(ele)", "e": 4578, "s": 4409, "text": null }, { "code": null, "e": 4586, "s": 4578, "text": "Output:" }, { "code": null, "e": 4591, "s": 4586, "text": "*** " }, { "code": null, "e": 4594, "s": 4591, "text": "— " }, { "code": null, "e": 4610, "s": 4594, "text": "***************" }, { "code": null, "e": 4623, "s": 4610, "text": "*** 1,5 ****" }, { "code": null, "e": 4627, "s": 4623, "text": "! G" }, { "code": null, "e": 4631, "s": 4627, "text": " e" }, { "code": null, "e": 4635, "s": 4631, "text": " e" }, { "code": null, "e": 4639, "s": 4635, "text": " k" }, { "code": null, "e": 4643, "s": 4639, "text": " s" }, { "code": null, "e": 4652, "s": 4643, "text": "— 1,6 —-" }, { "code": null, "e": 4656, "s": 4652, "text": "! g" }, { "code": null, "e": 4660, "s": 4656, "text": " e" }, { "code": null, "e": 4664, "s": 4660, "text": " e" }, { "code": null, "e": 4668, "s": 4664, "text": " k" }, { "code": null, "e": 4672, "s": 4668, "text": " s" }, { "code": null, "e": 4676, "s": 4672, "text": "+ !" }, { "code": null, "e": 4687, "s": 4676, "text": "Example 2:" }, { "code": null, "e": 4695, "s": 4687, "text": "Python3" }, { "code": "# import required moduleimport difflib # assign parameterspar1 = ['Geeks', 'for', 'geeks!']par2 = 'geeks!' # compare parametersfor ele in difflib.context_diff(par1, par2): print(ele)", "e": 4883, "s": 4695, "text": null }, { "code": null, "e": 4891, "s": 4883, "text": "Output:" }, { "code": null, "e": 4896, "s": 4891, "text": "*** " }, { "code": null, "e": 4899, "s": 4896, "text": "— " }, { "code": null, "e": 4915, "s": 4899, "text": "***************" }, { "code": null, "e": 4928, "s": 4915, "text": "*** 1,3 ****" }, { "code": null, "e": 4936, "s": 4928, "text": "! Geeks" }, { "code": null, "e": 4942, "s": 4936, "text": "! for" }, { "code": null, "e": 4951, "s": 4942, "text": "! geeks!" }, { "code": null, "e": 4960, "s": 4951, "text": "— 1,6 —-" }, { "code": null, "e": 4964, "s": 4960, "text": "! g" }, { "code": null, "e": 4968, "s": 4964, "text": "! e" }, { "code": null, "e": 4972, "s": 4968, "text": "! e" }, { "code": null, "e": 4976, "s": 4972, "text": "! k" }, { "code": null, "e": 4980, "s": 4976, "text": "! s" }, { "code": null, "e": 4984, "s": 4980, "text": "! !" }, { "code": null, "e": 4999, "s": 4984, "text": "python-modules" }, { "code": null, "e": 5023, "s": 4999, "text": "Technical Scripter 2020" }, { "code": null, "e": 5030, "s": 5023, "text": "Python" }, { "code": null, "e": 5049, "s": 5030, "text": "Technical Scripter" } ]
Check whether the string can be printed using same row of qwerty keypad
11 Jun, 2021 Given a string S, the task is to check whether the string can be typed using only a single row of the qwerty keyboard. Examples: Input: S = “Dad” Output: Yes Explanation: Characters “D” and “a” are present in the same row of qwerty keypad. That is second Row.Input: S = “Mom” Output: No Explanation: Characters “M” and “o” are not present in the same row of qwerty keypad. Approach: The idea is to store the characters of the same row of the qwerty keypad into different hash-maps to check that all the characters of the string are from the same row.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to check whether// the string can be printed// using same row of qwerty keypad #include <bits/stdc++.h>using namespace std; // Function to find the row of the// character in the qwerty keypadint checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad set<char> first_row = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; set<char> second_row = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; set<char> third_row = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; set<char> fourth_row = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; // Condition to check the row of the // current character of the string if (first_row.count(x) > 0) { return 1; } else if (second_row.count(x) > 0) { return 2; } else if (third_row.count(x) > 0) { return 3; } else if (fourth_row.count(x) > 0) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadbool checkValidity(string str){ char x = str[0]; int row = checkQwertyRow(x); for (int i = 0; i < str.length(); i++) { x = str[i]; if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver Codeint main(){ string str = "GeeksforGeeks"; if (checkValidity(str)) cout << "Yes"; else cout << "No"; return (0);} // Java program to check whether// the string can be printed// using same row of qwerty keypadimport java.util.*; class GFG{ // Function to find the row of the// character in the qwerty keypadstatic int checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad Character[] first_row1 = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; Set<Character> first_row = new HashSet<>( Arrays.asList(first_row1)); Character[] second_row1 = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; Set<Character> second_row = new HashSet<>( Arrays.asList(second_row1)); Character[] third_row1 = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; Set<Character> third_row = new HashSet<>( Arrays.asList(third_row1)); Character[] fourth_row1 = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; Set<Character> fourth_row = new HashSet<>( Arrays.asList(fourth_row1)); // Condition to check the row of the // current character of the string if (first_row.contains(x)) { return 1; } else if (second_row.contains(x)) { return 2; } else if (third_row.contains(x)) { return 3; } else if (fourth_row.contains(x)) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadstatic boolean checkValidity(String str){ char x = str.charAt(0); int row = checkQwertyRow(x); for(int i = 0; i < str.length(); i++) { x = str.charAt(i); if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver codepublic static void main(String[] args){ String str = "GeeksforGeeks"; if (checkValidity(str)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by offbeat # Python3 program to check whether# the string can be printed# using same row of qwerty keypad # Function to find the row of the# character in the qwerty keypaddef checkQwertyRow(x): # Sets to include the # characters from the # same row of the qwerty keypad first_row = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='] second_row = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'] third_row = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'] fourth_row = ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm'] # Condition to check the # row of the current character # of the string if(first_row.count(x) > 0): return 1 elif(second_row.count(x) > 0): return 2 elif(third_row.count(x) > 0): return 3 elif(fourth_row.count(x) > 0): return 4 return 0 # Function to check the # characters are from the# same row of the qwerty keypaddef checkValidity(str): x = str[0] row = checkQwertyRow(x) for i in range(len(str)): x = str[i] if(row != checkQwertyRow(x)): return False return True # Driver Codestr = "GeeksforGeeks" if(checkValidity(str)): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155 // C# program to check whether// the string can be printed// using same row of qwerty keypadusing System;using System.Collections.Generic; class GFG{ // Function to find the row of the// character in the qwerty keypadstatic int checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad char[] first_row1 = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; HashSet<char> first_row = new HashSet<char>( first_row1); char[] second_row1 = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; HashSet<char> second_row = new HashSet<char>( second_row1); char[] third_row1 = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; HashSet<char> third_row = new HashSet<char>( third_row1); char[] fourth_row1 = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; HashSet<char> fourth_row = new HashSet<char>( fourth_row1); // Condition to check the row of the // current character of the string if (first_row.Contains(x)) { return 1; } else if (second_row.Contains(x)) { return 2; } else if (third_row.Contains(x)) { return 3; } else if (fourth_row.Contains(x)) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadstatic bool checkValidity(String str){ char x = str[0]; int row = checkQwertyRow(x); for(int i = 0; i < str.Length; i++) { x = str[i]; if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ String str = "GeeksforGeeks"; if (checkValidity(str)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Amit Katiyar <script> // JavaScript program to check whether // the string can be printed // using same row of qwerty keypad // Function to find the row of the // character in the qwerty keypad function checkQwertyRow(x) { // Sets to include the characters // from the same row of the qwerty keypad var first_row = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", ]; var second_row = [ "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", ]; var third_row = [ "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", ":", "a", "s", "d", "f", "g", "h", "j", "k", "l", ]; var fourth_row = [ "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "z", "x", "c", "v", "b", "n", "m", ]; // Condition to check the row of the // current character of the string if (first_row.includes(x)) { return 1; } else if (second_row.includes(x)) { return 2; } else if (third_row.includes(x)) { return 3; } else if (fourth_row.includes(x)) { return 4; } return 0; } // Function to check the characters are // from the same row of the qwerty keypad function checkValidity(str) { var x = str[0]; var row = checkQwertyRow(x); for (var i = 0; i < str.length; i++) { x = str[i]; if (row !== checkQwertyRow(x)) { return false; } } return true; } // Driver code var str = "GeeksforGeeks"; if (checkValidity(str)) document.write("Yes"); else document.write("No"); </script> No Time Complexity: O(N) offbeat amit143katiyar avanitrachhadiya2155 rdtank Pattern Searching School Programming Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 148, "s": 28, "text": "Given a string S, the task is to check whether the string can be typed using only a single row of the qwerty keyboard. " }, { "code": null, "e": 159, "s": 148, "text": "Examples: " }, { "code": null, "e": 404, "s": 159, "text": "Input: S = “Dad” Output: Yes Explanation: Characters “D” and “a” are present in the same row of qwerty keypad. That is second Row.Input: S = “Mom” Output: No Explanation: Characters “M” and “o” are not present in the same row of qwerty keypad. " }, { "code": null, "e": 634, "s": 404, "text": "Approach: The idea is to store the characters of the same row of the qwerty keypad into different hash-maps to check that all the characters of the string are from the same row.Below is the implementation of the above approach: " }, { "code": null, "e": 638, "s": 634, "text": "C++" }, { "code": null, "e": 643, "s": 638, "text": "Java" }, { "code": null, "e": 651, "s": 643, "text": "Python3" }, { "code": null, "e": 654, "s": 651, "text": "C#" }, { "code": null, "e": 665, "s": 654, "text": "Javascript" }, { "code": "// C++ Program to check whether// the string can be printed// using same row of qwerty keypad #include <bits/stdc++.h>using namespace std; // Function to find the row of the// character in the qwerty keypadint checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad set<char> first_row = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; set<char> second_row = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; set<char> third_row = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; set<char> fourth_row = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; // Condition to check the row of the // current character of the string if (first_row.count(x) > 0) { return 1; } else if (second_row.count(x) > 0) { return 2; } else if (third_row.count(x) > 0) { return 3; } else if (fourth_row.count(x) > 0) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadbool checkValidity(string str){ char x = str[0]; int row = checkQwertyRow(x); for (int i = 0; i < str.length(); i++) { x = str[i]; if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver Codeint main(){ string str = \"GeeksforGeeks\"; if (checkValidity(str)) cout << \"Yes\"; else cout << \"No\"; return (0);}", "e": 2422, "s": 665, "text": null }, { "code": "// Java program to check whether// the string can be printed// using same row of qwerty keypadimport java.util.*; class GFG{ // Function to find the row of the// character in the qwerty keypadstatic int checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad Character[] first_row1 = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; Set<Character> first_row = new HashSet<>( Arrays.asList(first_row1)); Character[] second_row1 = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; Set<Character> second_row = new HashSet<>( Arrays.asList(second_row1)); Character[] third_row1 = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; Set<Character> third_row = new HashSet<>( Arrays.asList(third_row1)); Character[] fourth_row1 = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; Set<Character> fourth_row = new HashSet<>( Arrays.asList(fourth_row1)); // Condition to check the row of the // current character of the string if (first_row.contains(x)) { return 1; } else if (second_row.contains(x)) { return 2; } else if (third_row.contains(x)) { return 3; } else if (fourth_row.contains(x)) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadstatic boolean checkValidity(String str){ char x = str.charAt(0); int row = checkQwertyRow(x); for(int i = 0; i < str.length(); i++) { x = str.charAt(i); if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver codepublic static void main(String[] args){ String str = \"GeeksforGeeks\"; if (checkValidity(str)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by offbeat", "e": 4847, "s": 2422, "text": null }, { "code": "# Python3 program to check whether# the string can be printed# using same row of qwerty keypad # Function to find the row of the# character in the qwerty keypaddef checkQwertyRow(x): # Sets to include the # characters from the # same row of the qwerty keypad first_row = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '='] second_row = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'] third_row = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'] fourth_row = ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm'] # Condition to check the # row of the current character # of the string if(first_row.count(x) > 0): return 1 elif(second_row.count(x) > 0): return 2 elif(third_row.count(x) > 0): return 3 elif(fourth_row.count(x) > 0): return 4 return 0 # Function to check the # characters are from the# same row of the qwerty keypaddef checkValidity(str): x = str[0] row = checkQwertyRow(x) for i in range(len(str)): x = str[i] if(row != checkQwertyRow(x)): return False return True # Driver Codestr = \"GeeksforGeeks\" if(checkValidity(str)): print(\"Yes\")else: print(\"No\") # This code is contributed by avanitrachhadiya2155", "e": 6478, "s": 4847, "text": null }, { "code": "// C# program to check whether// the string can be printed// using same row of qwerty keypadusing System;using System.Collections.Generic; class GFG{ // Function to find the row of the// character in the qwerty keypadstatic int checkQwertyRow(char x){ // Sets to include the characters // from the same row of the qwerty keypad char[] first_row1 = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=' }; HashSet<char> first_row = new HashSet<char>( first_row1); char[] second_row1 = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; HashSet<char> second_row = new HashSet<char>( second_row1); char[] third_row1 = { 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; HashSet<char> third_row = new HashSet<char>( third_row1); char[] fourth_row1 = { 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; HashSet<char> fourth_row = new HashSet<char>( fourth_row1); // Condition to check the row of the // current character of the string if (first_row.Contains(x)) { return 1; } else if (second_row.Contains(x)) { return 2; } else if (third_row.Contains(x)) { return 3; } else if (fourth_row.Contains(x)) { return 4; } return 0;} // Function to check the characters are// from the same row of the qwerty keypadstatic bool checkValidity(String str){ char x = str[0]; int row = checkQwertyRow(x); for(int i = 0; i < str.Length; i++) { x = str[i]; if (row != checkQwertyRow(x)) { return false; } } return true;} // Driver codepublic static void Main(String[] args){ String str = \"GeeksforGeeks\"; if (checkValidity(str)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Amit Katiyar", "e": 8883, "s": 6478, "text": null }, { "code": "<script> // JavaScript program to check whether // the string can be printed // using same row of qwerty keypad // Function to find the row of the // character in the qwerty keypad function checkQwertyRow(x) { // Sets to include the characters // from the same row of the qwerty keypad var first_row = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\", \"-\", \"=\", ]; var second_row = [ \"Q\", \"W\", \"E\", \"R\", \"T\", \"Y\", \"U\", \"I\", \"O\", \"P\", \"[\", \"]\", \"q\", \"w\", \"e\", \"r\", \"t\", \"y\", \"u\", \"i\", \"o\", \"p\", ]; var third_row = [ \"A\", \"S\", \"D\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \";\", \":\", \"a\", \"s\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", ]; var fourth_row = [ \"Z\", \"X\", \"C\", \"V\", \"B\", \"N\", \"M\", \",\", \".\", \"/\", \"z\", \"x\", \"c\", \"v\", \"b\", \"n\", \"m\", ]; // Condition to check the row of the // current character of the string if (first_row.includes(x)) { return 1; } else if (second_row.includes(x)) { return 2; } else if (third_row.includes(x)) { return 3; } else if (fourth_row.includes(x)) { return 4; } return 0; } // Function to check the characters are // from the same row of the qwerty keypad function checkValidity(str) { var x = str[0]; var row = checkQwertyRow(x); for (var i = 0; i < str.length; i++) { x = str[i]; if (row !== checkQwertyRow(x)) { return false; } } return true; } // Driver code var str = \"GeeksforGeeks\"; if (checkValidity(str)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 11244, "s": 8883, "text": null }, { "code": null, "e": 11247, "s": 11244, "text": "No" }, { "code": null, "e": 11271, "s": 11249, "text": "Time Complexity: O(N)" }, { "code": null, "e": 11279, "s": 11271, "text": "offbeat" }, { "code": null, "e": 11294, "s": 11279, "text": "amit143katiyar" }, { "code": null, "e": 11315, "s": 11294, "text": "avanitrachhadiya2155" }, { "code": null, "e": 11322, "s": 11315, "text": "rdtank" }, { "code": null, "e": 11340, "s": 11322, "text": "Pattern Searching" }, { "code": null, "e": 11359, "s": 11340, "text": "School Programming" }, { "code": null, "e": 11367, "s": 11359, "text": "Strings" }, { "code": null, "e": 11375, "s": 11367, "text": "Strings" }, { "code": null, "e": 11393, "s": 11375, "text": "Pattern Searching" } ]
How to Set Column Names within the aggregate Function in R
14 Sep, 2021 In this article we will discuss how to set column names with the aggregate function in R programming language. The aggregate method in base R is used to divide the data frame into smaller subsets and compute a summary statistics for each of the formed groups. The function to be applied can be sum, mean, mode or any of the pre-defined aggregate methods available. This method gives a better clarity about the data. Syntax: aggregate(formula, data, function) Parameters: formula: the variable(s) of the input data frame we want to apply functions on. data: the data that we want to use for group by operation. function: the function or calculation to be applied. The setNames() method is used to specify the name of an object and then return the object. In case of data frame, the columns can be renamed with new names, using the c() method. Syntax: setNames(data, col-name-vec) Parameter : data – The data frame to be applied the function onto col-name-vec – The column name vector containing the names of the columns. Example: Set column names with aggregate function R # creating a data frame data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print("Original DataFrame")print(data_frame) # using aggregate methoddata_agg <- aggregate(col1 ~ col2, data_frame, sum) # using setnames methoddata_mod <- setNames(data_agg, c("C1", "C2")) print("Modified DataFrame")print(data_mod) Output [1] "Original DataFrame" col1 col2 1 1 A 2 2 B 3 3 C 4 4 A 5 5 B 6 6 C 7 7 A 8 8 B 9 9 C > [1] "Modified DataFrame" C1 C2 1 A 12 2 B 15 3 C 18 The data frame columns can be explicitly mapped to lists using the list() method in R. As a result of this a generic list object with a custom name can be specified within the aggregate function usage. Syntax: list(new-col-name = df$old-col-name) Example: Set column names with aggregate function R # creating a data frame data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print("Original DataFrame")print(data_frame) # using aggregate methoddata_mod <- aggregate( list(mean = data_frame$col1), list(letter = data_frame$col2), mean) # printing the modified dataframe print("Modified DataFrame")print(data_mod) Output [1] "Original DataFrame" col1 col2 1 1 A 2 2 B 3 3 C 4 4 A 5 5 B 6 6 C 7 7 A 8 8 B 9 9 C [1] "Modified DataFrame" letter mean 1 A 4 2 B 5 3 C 6 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": "\n14 Sep, 2021" }, { "code": null, "e": 139, "s": 28, "text": "In this article we will discuss how to set column names with the aggregate function in R programming language." }, { "code": null, "e": 445, "s": 139, "text": "The aggregate method in base R is used to divide the data frame into smaller subsets and compute a summary statistics for each of the formed groups. The function to be applied can be sum, mean, mode or any of the pre-defined aggregate methods available. This method gives a better clarity about the data. " }, { "code": null, "e": 488, "s": 445, "text": "Syntax: aggregate(formula, data, function)" }, { "code": null, "e": 500, "s": 488, "text": "Parameters:" }, { "code": null, "e": 581, "s": 500, "text": "formula: the variable(s) of the input data frame we want to apply functions on. " }, { "code": null, "e": 640, "s": 581, "text": "data: the data that we want to use for group by operation." }, { "code": null, "e": 694, "s": 640, "text": "function: the function or calculation to be applied. " }, { "code": null, "e": 874, "s": 694, "text": "The setNames() method is used to specify the name of an object and then return the object. In case of data frame, the columns can be renamed with new names, using the c() method. " }, { "code": null, "e": 911, "s": 874, "text": "Syntax: setNames(data, col-name-vec)" }, { "code": null, "e": 924, "s": 911, "text": "Parameter : " }, { "code": null, "e": 978, "s": 924, "text": "data – The data frame to be applied the function onto" }, { "code": null, "e": 1054, "s": 978, "text": "col-name-vec – The column name vector containing the names of the columns. " }, { "code": null, "e": 1104, "s": 1054, "text": "Example: Set column names with aggregate function" }, { "code": null, "e": 1106, "s": 1104, "text": "R" }, { "code": "# creating a data frame data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print(\"Original DataFrame\")print(data_frame) # using aggregate methoddata_agg <- aggregate(col1 ~ col2, data_frame, sum) # using setnames methoddata_mod <- setNames(data_agg, c(\"C1\", \"C2\")) print(\"Modified DataFrame\")print(data_mod)", "e": 1476, "s": 1106, "text": null }, { "code": null, "e": 1483, "s": 1476, "text": "Output" }, { "code": null, "e": 1701, "s": 1483, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 1 A \n2 2 B \n3 3 C \n4 4 A \n5 5 B \n6 6 C \n7 7 A \n8 8 B \n9 9 C >\n[1] \"Modified DataFrame\" \n C1 C2 \n1 A 12 \n2 B 15 \n3 C 18" }, { "code": null, "e": 1904, "s": 1701, "text": "The data frame columns can be explicitly mapped to lists using the list() method in R. As a result of this a generic list object with a custom name can be specified within the aggregate function usage. " }, { "code": null, "e": 1912, "s": 1904, "text": "Syntax:" }, { "code": null, "e": 1949, "s": 1912, "text": "list(new-col-name = df$old-col-name)" }, { "code": null, "e": 1999, "s": 1949, "text": "Example: Set column names with aggregate function" }, { "code": null, "e": 2001, "s": 1999, "text": "R" }, { "code": "# creating a data frame data_frame <- data.frame(col1 = c(1:9), col2 = LETTERS[1:3]) print(\"Original DataFrame\")print(data_frame) # using aggregate methoddata_mod <- aggregate( list(mean = data_frame$col1), list(letter = data_frame$col2), mean) # printing the modified dataframe print(\"Modified DataFrame\")print(data_mod)", "e": 2461, "s": 2001, "text": null }, { "code": null, "e": 2468, "s": 2461, "text": "Output" }, { "code": null, "e": 2709, "s": 2468, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 1 A \n2 2 B \n3 3 C \n4 4 A \n5 5 B \n6 6 C \n7 7 A \n8 8 B \n9 9 C \n[1] \"Modified DataFrame\" \n letter mean \n1 A 4 \n2 B 5 \n3 C 6" }, { "code": null, "e": 2716, "s": 2709, "text": "Picked" }, { "code": null, "e": 2737, "s": 2716, "text": "R DataFrame-Programs" }, { "code": null, "e": 2749, "s": 2737, "text": "R-DataFrame" }, { "code": null, "e": 2760, "s": 2749, "text": "R Language" }, { "code": null, "e": 2771, "s": 2760, "text": "R Programs" } ]
Introduction of Virtual Router Redundancy Protocol (VRRP) and its configuration
25 May, 2022 VRRP is an open standard protocol, which is used to provide redundancy in a network. It is a network layer protocol (protocol number-112). The number of routers (group members) in a group acts as a virtual logical router which will be the default gateway of all the local hosts. If one router goes down, one of the other group members can take place for the responsibilities for forwarding the traffic. Some important terms related to VRRP : virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts.Virtual MAC address : A virtual MAC address is automatically generated by taking the last 8 bytes as the VRRP group number in hexadecimal. In VRRP, Mac address used is 0000.5e00.01xx. Here, xx is the VRRP group number in hexadecimal.Master router : One of the VRRP group member is elected as master router which takes up the responsibility of forwarding the local traffic. The router is elected on the basis of priority. If some group member of VRRP group has higher priority than others then it will be elected as master router. If the priority is same(by default 100) then the router having the highest IP address will become the master router.Backup routers: Only one of the VRRP group member will become the master router while others will be back up routers. In case the master router fails then one of the backup routers will become master router.Master advertisement timer : The master router multicast the keep-alive messages at 224.0.0.18 in every 1 second.Master dead timer: The time in which the backup router will take up the responsibilities of Master router if the master advertisement message is not received. It is, by default, 3.69 seconds.Preempt : It is a state in which one of the backup routers becomes the master router (when the master router goes down). Also, when the master router comes up again, it will become the master router as its priority is still higher.Object tracking: The VRRP object tracking provides a way in which the best router will become the master router. The current master router continuously polls the tracked object state (such as line protocol is up or down). Suppose if the master router line protocol is down then the priority of backup router will be increased dynamically i.e it will become the master router.Authentication : VRRP supports 3 types of authentication – 1. No authentication 2. Plain text authentication 3. MD5 authentication virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts. Virtual MAC address : A virtual MAC address is automatically generated by taking the last 8 bytes as the VRRP group number in hexadecimal. In VRRP, Mac address used is 0000.5e00.01xx. Here, xx is the VRRP group number in hexadecimal. Master router : One of the VRRP group member is elected as master router which takes up the responsibility of forwarding the local traffic. The router is elected on the basis of priority. If some group member of VRRP group has higher priority than others then it will be elected as master router. If the priority is same(by default 100) then the router having the highest IP address will become the master router. Backup routers: Only one of the VRRP group member will become the master router while others will be back up routers. In case the master router fails then one of the backup routers will become master router. Master advertisement timer : The master router multicast the keep-alive messages at 224.0.0.18 in every 1 second. Master dead timer: The time in which the backup router will take up the responsibilities of Master router if the master advertisement message is not received. It is, by default, 3.69 seconds. Preempt : It is a state in which one of the backup routers becomes the master router (when the master router goes down). Also, when the master router comes up again, it will become the master router as its priority is still higher. Object tracking: The VRRP object tracking provides a way in which the best router will become the master router. The current master router continuously polls the tracked object state (such as line protocol is up or down). Suppose if the master router line protocol is down then the priority of backup router will be increased dynamically i.e it will become the master router. Authentication : VRRP supports 3 types of authentication – 1. No authentication 2. Plain text authentication 3. MD5 authentication VRRP rejects packet in any of the following cases : 1. The authentication schemes differ on the routers and the incoming packet. 2. MD5 digest differs on the router and the incoming packet. 3. Text authentication strings are different on the router and the incoming packet. Configuration : In above given topology, there are 2-routers named R1 and R2, where R1 fa 0/0 ip address is 10.1.1.1/24 and R2 fa0/0 ip address is 10.1.1.2/24. Assigning IP address to router R1 : r1# int fa0/0 r1# ip add 10.1.1.1 255.255.255.0 Assigning IP address to router r2. r2# int fa0/0 r2# ip address 10.1.1.2 255.255.255.0 Now, let’s provide virtual IP address(10.1.1.100), group name VRRP_TEST, group number 10 and priority 110. Also, here preempt has been enabled by default i.e. if the master router goes down then the backup router automatically becomes the master router. r1# int fa0/0 r1# vrrp 10 ip 10.1.1.100 r1# vrrp 10 name VRRP_TEST r1# vrrp 10 priority 110 Now, provide virtual IP address(10.1.1.100), group name VRRP_TEST and priority 100. Also, group number 10 is assigned. r2# int fa0/0 r2# vrrp 10 ip 10.1.1.100 r2# vrrp 10 name VRRP_TEST r2# vrrp 10 priority 100 Note : As provided priority 110 to r1, therefore, it will become the master router. vaibhavsinghtanwar surinderdawra388 Computer Networks-Network Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Data encryption standard (DES) | Set 1
[ { "code": null, "e": 28, "s": 0, "text": "\n25 May, 2022" }, { "code": null, "e": 432, "s": 28, "text": "VRRP is an open standard protocol, which is used to provide redundancy in a network. It is a network layer protocol (protocol number-112). The number of routers (group members) in a group acts as a virtual logical router which will be the default gateway of all the local hosts. If one router goes down, one of the other group members can take place for the responsibilities for forwarding the traffic. " }, { "code": null, "e": 471, "s": 432, "text": "Some important terms related to VRRP :" }, { "code": null, "e": 2523, "s": 471, "text": "virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts.Virtual MAC address : A virtual MAC address is automatically generated by taking the last 8 bytes as the VRRP group number in hexadecimal. In VRRP, Mac address used is 0000.5e00.01xx. Here, xx is the VRRP group number in hexadecimal.Master router : One of the VRRP group member is elected as master router which takes up the responsibility of forwarding the local traffic. The router is elected on the basis of priority. If some group member of VRRP group has higher priority than others then it will be elected as master router. If the priority is same(by default 100) then the router having the highest IP address will become the master router.Backup routers: Only one of the VRRP group member will become the master router while others will be back up routers. In case the master router fails then one of the backup routers will become master router.Master advertisement timer : The master router multicast the keep-alive messages at 224.0.0.18 in every 1 second.Master dead timer: The time in which the backup router will take up the responsibilities of Master router if the master advertisement message is not received. It is, by default, 3.69 seconds.Preempt : It is a state in which one of the backup routers becomes the master router (when the master router goes down). Also, when the master router comes up again, it will become the master router as its priority is still higher.Object tracking: The VRRP object tracking provides a way in which the best router will become the master router. The current master router continuously polls the tracked object state (such as line protocol is up or down). Suppose if the master router line protocol is down then the priority of backup router will be increased dynamically i.e it will become the master router.Authentication : VRRP supports 3 types of authentication – 1. No authentication 2. Plain text authentication 3. MD5 authentication" }, { "code": null, "e": 2682, "s": 2523, "text": "virtual IP address : An IP address is assigned as a virtual IP address from the local subnet which is configured as a default gateway for all the local hosts." }, { "code": null, "e": 2916, "s": 2682, "text": "Virtual MAC address : A virtual MAC address is automatically generated by taking the last 8 bytes as the VRRP group number in hexadecimal. In VRRP, Mac address used is 0000.5e00.01xx. Here, xx is the VRRP group number in hexadecimal." }, { "code": null, "e": 3330, "s": 2916, "text": "Master router : One of the VRRP group member is elected as master router which takes up the responsibility of forwarding the local traffic. The router is elected on the basis of priority. If some group member of VRRP group has higher priority than others then it will be elected as master router. If the priority is same(by default 100) then the router having the highest IP address will become the master router." }, { "code": null, "e": 3538, "s": 3330, "text": "Backup routers: Only one of the VRRP group member will become the master router while others will be back up routers. In case the master router fails then one of the backup routers will become master router." }, { "code": null, "e": 3652, "s": 3538, "text": "Master advertisement timer : The master router multicast the keep-alive messages at 224.0.0.18 in every 1 second." }, { "code": null, "e": 3844, "s": 3652, "text": "Master dead timer: The time in which the backup router will take up the responsibilities of Master router if the master advertisement message is not received. It is, by default, 3.69 seconds." }, { "code": null, "e": 4076, "s": 3844, "text": "Preempt : It is a state in which one of the backup routers becomes the master router (when the master router goes down). Also, when the master router comes up again, it will become the master router as its priority is still higher." }, { "code": null, "e": 4452, "s": 4076, "text": "Object tracking: The VRRP object tracking provides a way in which the best router will become the master router. The current master router continuously polls the tracked object state (such as line protocol is up or down). Suppose if the master router line protocol is down then the priority of backup router will be increased dynamically i.e it will become the master router." }, { "code": null, "e": 4583, "s": 4452, "text": "Authentication : VRRP supports 3 types of authentication – 1. No authentication 2. Plain text authentication 3. MD5 authentication" }, { "code": null, "e": 4857, "s": 4583, "text": "VRRP rejects packet in any of the following cases : 1. The authentication schemes differ on the routers and the incoming packet. 2. MD5 digest differs on the router and the incoming packet. 3. Text authentication strings are different on the router and the incoming packet." }, { "code": null, "e": 4875, "s": 4857, "text": " Configuration :" }, { "code": null, "e": 5060, "s": 4878, "text": "In above given topology, there are 2-routers named R1 and R2, where R1 fa 0/0 ip address is 10.1.1.1/24 and R2 fa0/0 ip address is 10.1.1.2/24. Assigning IP address to router R1 :" }, { "code": null, "e": 5108, "s": 5060, "text": "r1# int fa0/0\nr1# ip add 10.1.1.1 255.255.255.0" }, { "code": null, "e": 5143, "s": 5108, "text": "Assigning IP address to router r2." }, { "code": null, "e": 5195, "s": 5143, "text": "r2# int fa0/0\nr2# ip address 10.1.1.2 255.255.255.0" }, { "code": null, "e": 5449, "s": 5195, "text": "Now, let’s provide virtual IP address(10.1.1.100), group name VRRP_TEST, group number 10 and priority 110. Also, here preempt has been enabled by default i.e. if the master router goes down then the backup router automatically becomes the master router." }, { "code": null, "e": 5541, "s": 5449, "text": "r1# int fa0/0\nr1# vrrp 10 ip 10.1.1.100\nr1# vrrp 10 name VRRP_TEST\nr1# vrrp 10 priority 110" }, { "code": null, "e": 5660, "s": 5541, "text": "Now, provide virtual IP address(10.1.1.100), group name VRRP_TEST and priority 100. Also, group number 10 is assigned." }, { "code": null, "e": 5752, "s": 5660, "text": "r2# int fa0/0\nr2# vrrp 10 ip 10.1.1.100\nr2# vrrp 10 name VRRP_TEST\nr2# vrrp 10 priority 100" }, { "code": null, "e": 5836, "s": 5752, "text": "Note : As provided priority 110 to r1, therefore, it will become the master router." }, { "code": null, "e": 5855, "s": 5836, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 5872, "s": 5855, "text": "surinderdawra388" }, { "code": null, "e": 5904, "s": 5872, "text": "Computer Networks-Network Layer" }, { "code": null, "e": 5922, "s": 5904, "text": "Computer Networks" }, { "code": null, "e": 5940, "s": 5922, "text": "Computer Networks" }, { "code": null, "e": 6038, "s": 5940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6070, "s": 6038, "text": "Differences between TCP and UDP" }, { "code": null, "e": 6096, "s": 6070, "text": "Types of Network Topology" }, { "code": null, "e": 6126, "s": 6096, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 6156, "s": 6126, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6185, "s": 6156, "text": "Socket Programming in Python" }, { "code": null, "e": 6219, "s": 6185, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 6245, "s": 6219, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 6275, "s": 6245, "text": "Wireless Application Protocol" }, { "code": null, "e": 6315, "s": 6275, "text": "Mobile Internet Protocol (or Mobile IP)" } ]
Sum of the series 1.2.3 + 2.3.4 + ... + n(n+1)(n+2)
20 Apr, 2021 Find the sum up to n terms of the series: 1.2.3 + 2.3.4 + ... + n(n+1)(n+2). In this 1.2.3 represent the first term and 2.3.4 represent the second term .Examples : Input : 2 Output : 30 1.2.3 + 2.3.4 = 6 + 24 = 30 Input : 3 Output : 90 Simple Approach We run a loop for i = 1 to n, and find the sum of (i)*(i+1)*(i+2). And at the end display the sum . C++ Java Python3 C# PHP Javascript // CPP program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...#include <bits/stdc++.h>using namespace std; int sumofseries(int n){ int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res;} // Driver Codeint main(){ cout << sumofseries(3) << endl; return 0;} // Java program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...import java.io.*;import java.math.*; class GFG{ static int sumofseries(int n) { int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code public static void main(String[] args) { System.out.println(sumofseries(3)); }} # Python 3 program to find sum of the series# 1.2.3 + 2.3.4 + 3.4.5 + ... def sumofseries(n): res = 0 for i in range(1, n+1): res += (i) * (i + 1) * (i + 2) return res # Driver Programprint(sumofseries(3)) # This code is contributed# by Smitha Dinesh Semwal // Java program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...using System; class GFG{ static int sumofseries(int n) { int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code public static void Main() { Console.WriteLine(sumofseries(3)); }} // This code is contributed by vt_m. <?php// PHP program to find// sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ... function sumofseries($n){ $res = 0; for ($i = 1; $i <= $n; $i++) $res += ($i) * ($i + 1) * ($i + 2); return $res;} // Driver Code echo sumofseries(3); //This code is contributed by anuj_67.?> <script>// JavaScript program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ... function sumofseries(n) { let res = 0; for (let i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code document.write(sumofseries(3)); // This code is contributed by code_hunt.</script> 90 Complexity : O(N) Using Efficient Approach we know that we have to find = summation of( (n)*(n+1)*(n+2) ) Sn = summation[ (n)*(n+1)*(n+2) ] Sn = summation [n3 + 2*n2 + n2 + 2*n]We know sum of cubes of natural numbers is (n*(n+1))/2)2, sum of squares of natural numbers is n * (n + 1) * (2n + 1) / 6 and sum of first n natural numbers is n(n+1)/2Sn = ((n*(n+1))/2)2 + 3((n)*(n+1)*(2*n+1)/6) + 2*((n)*(n+1)/2) So by evaluating the above we get, Sn = (n*(n+1)*(n+2)*(n+3)/4) Hence it has a O(1) complexity. C++ Java Python3 C# PHP Javascript // Efficient CPP program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...#include <bits/stdc++.h>using namespace std; // function to calculate// sum of seriesint sumofseries(int n){ return (n * (n + 1) * (n + 2) * (n + 3) / 4);} // Driver Codeint main(){ cout << sumofseries(3) << endl; return 0;} // Efficient Java program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ..import java.io.*;import java.math.*; class GFG{ static int sumofseries(int n) { return (n * (n + 1) * (n + 2) * (n + 3) / 4); } // Driver Code public static void main(String[] args) { System.out.println(sumofseries(3)); }} # Efficient CPP program to find sum of the# series 1.2.3 + 2.3.4 + 3.4.5 + ... # function to calculate sum of seriesdef sumofseries(n): return int(n * (n + 1) * (n + 2) * (n + 3) / 4) # Driver programprint(sumofseries(3)) # This code is contributed# by Smitha Dinesh Semwal // Efficient C# program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ..using System; class GFG{ static int sumofseries(int n) { return (n * (n + 1) * (n + 2) * (n + 3) / 4); } // Driver Code public static void Main() { Console.WriteLine(sumofseries(3)); }} // This code is contributed by anuj_67. <?php// Efficient CPP program// to find sum of the// series 1.2.3 + 2.3.4// + 3.4.5 + ... // function to calculate// sum of seriesfunction sumofseries($n){ return ($n * ($n + 1) * ($n + 2) * ($n + 3) / 4);} // Driver Code echo sumofseries(3); // This code is contributed by anuj_67.?> <script>// Efficient Javascript program// to find sum of the// series 1.2.3 + 2.3.4// + 3.4.5 + ... // function to calculate// sum of seriesfunction sumofseries(n){ return (n * (n + 1) * (n + 2) * (n + 3) / 4);} // Driver Code document.write(sumofseries(3)); // This code is contributed by gfgking </script> 90 Time Complexity : O(1) vt_m code_hunt gfgking number-theory series series-sum Mathematical number-theory Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Count all possible paths from top left to bottom right of a mXn matrix Product of Array except itself
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2021" }, { "code": null, "e": 218, "s": 52, "text": "Find the sum up to n terms of the series: 1.2.3 + 2.3.4 + ... + n(n+1)(n+2). In this 1.2.3 represent the first term and 2.3.4 represent the second term .Examples : " }, { "code": null, "e": 291, "s": 218, "text": "Input : 2\nOutput : 30\n1.2.3 + 2.3.4 = 6 + 24 = 30\n\nInput : 3\nOutput : 90" }, { "code": null, "e": 410, "s": 293, "text": "Simple Approach We run a loop for i = 1 to n, and find the sum of (i)*(i+1)*(i+2). And at the end display the sum . " }, { "code": null, "e": 414, "s": 410, "text": "C++" }, { "code": null, "e": 419, "s": 414, "text": "Java" }, { "code": null, "e": 427, "s": 419, "text": "Python3" }, { "code": null, "e": 430, "s": 427, "text": "C#" }, { "code": null, "e": 434, "s": 430, "text": "PHP" }, { "code": null, "e": 445, "s": 434, "text": "Javascript" }, { "code": "// CPP program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...#include <bits/stdc++.h>using namespace std; int sumofseries(int n){ int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res;} // Driver Codeint main(){ cout << sumofseries(3) << endl; return 0;}", "e": 765, "s": 445, "text": null }, { "code": "// Java program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...import java.io.*;import java.math.*; class GFG{ static int sumofseries(int n) { int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code public static void main(String[] args) { System.out.println(sumofseries(3)); }}", "e": 1145, "s": 765, "text": null }, { "code": "# Python 3 program to find sum of the series# 1.2.3 + 2.3.4 + 3.4.5 + ... def sumofseries(n): res = 0 for i in range(1, n+1): res += (i) * (i + 1) * (i + 2) return res # Driver Programprint(sumofseries(3)) # This code is contributed# by Smitha Dinesh Semwal", "e": 1420, "s": 1145, "text": null }, { "code": "// Java program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...using System; class GFG{ static int sumofseries(int n) { int res = 0; for (int i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code public static void Main() { Console.WriteLine(sumofseries(3)); }} // This code is contributed by vt_m.", "e": 1816, "s": 1420, "text": null }, { "code": "<?php// PHP program to find// sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ... function sumofseries($n){ $res = 0; for ($i = 1; $i <= $n; $i++) $res += ($i) * ($i + 1) * ($i + 2); return $res;} // Driver Code echo sumofseries(3); //This code is contributed by anuj_67.?>", "e": 2131, "s": 1816, "text": null }, { "code": "<script>// JavaScript program to find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ... function sumofseries(n) { let res = 0; for (let i = 1; i <= n; i++) res += (i) * (i + 1) * (i + 2); return res; } // Driver Code document.write(sumofseries(3)); // This code is contributed by code_hunt.</script>", "e": 2459, "s": 2131, "text": null }, { "code": null, "e": 2462, "s": 2459, "text": "90" }, { "code": null, "e": 2482, "s": 2464, "text": "Complexity : O(N)" }, { "code": null, "e": 2571, "s": 2482, "text": "Using Efficient Approach we know that we have to find = summation of( (n)*(n+1)*(n+2) ) " }, { "code": null, "e": 2969, "s": 2571, "text": "Sn = summation[ (n)*(n+1)*(n+2) ] Sn = summation [n3 + 2*n2 + n2 + 2*n]We know sum of cubes of natural numbers is (n*(n+1))/2)2, sum of squares of natural numbers is n * (n + 1) * (2n + 1) / 6 and sum of first n natural numbers is n(n+1)/2Sn = ((n*(n+1))/2)2 + 3((n)*(n+1)*(2*n+1)/6) + 2*((n)*(n+1)/2) So by evaluating the above we get, Sn = (n*(n+1)*(n+2)*(n+3)/4) Hence it has a O(1) complexity." }, { "code": null, "e": 2975, "s": 2971, "text": "C++" }, { "code": null, "e": 2980, "s": 2975, "text": "Java" }, { "code": null, "e": 2988, "s": 2980, "text": "Python3" }, { "code": null, "e": 2991, "s": 2988, "text": "C#" }, { "code": null, "e": 2995, "s": 2991, "text": "PHP" }, { "code": null, "e": 3006, "s": 2995, "text": "Javascript" }, { "code": "// Efficient CPP program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ...#include <bits/stdc++.h>using namespace std; // function to calculate// sum of seriesint sumofseries(int n){ return (n * (n + 1) * (n + 2) * (n + 3) / 4);} // Driver Codeint main(){ cout << sumofseries(3) << endl; return 0;}", "e": 3332, "s": 3006, "text": null }, { "code": "// Efficient Java program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ..import java.io.*;import java.math.*; class GFG{ static int sumofseries(int n) { return (n * (n + 1) * (n + 2) * (n + 3) / 4); } // Driver Code public static void main(String[] args) { System.out.println(sumofseries(3)); }}", "e": 3679, "s": 3332, "text": null }, { "code": "# Efficient CPP program to find sum of the# series 1.2.3 + 2.3.4 + 3.4.5 + ... # function to calculate sum of seriesdef sumofseries(n): return int(n * (n + 1) * (n + 2) * (n + 3) / 4) # Driver programprint(sumofseries(3)) # This code is contributed# by Smitha Dinesh Semwal", "e": 3963, "s": 3679, "text": null }, { "code": "// Efficient C# program to// find sum of the series// 1.2.3 + 2.3.4 + 3.4.5 + ..using System; class GFG{ static int sumofseries(int n) { return (n * (n + 1) * (n + 2) * (n + 3) / 4); } // Driver Code public static void Main() { Console.WriteLine(sumofseries(3)); }} // This code is contributed by anuj_67.", "e": 4311, "s": 3963, "text": null }, { "code": "<?php// Efficient CPP program// to find sum of the// series 1.2.3 + 2.3.4// + 3.4.5 + ... // function to calculate// sum of seriesfunction sumofseries($n){ return ($n * ($n + 1) * ($n + 2) * ($n + 3) / 4);} // Driver Code echo sumofseries(3); // This code is contributed by anuj_67.?>", "e": 4616, "s": 4311, "text": null }, { "code": "<script>// Efficient Javascript program// to find sum of the// series 1.2.3 + 2.3.4// + 3.4.5 + ... // function to calculate// sum of seriesfunction sumofseries(n){ return (n * (n + 1) * (n + 2) * (n + 3) / 4);} // Driver Code document.write(sumofseries(3)); // This code is contributed by gfgking </script>", "e": 4941, "s": 4616, "text": null }, { "code": null, "e": 4944, "s": 4941, "text": "90" }, { "code": null, "e": 4970, "s": 4946, "text": "Time Complexity : O(1) " }, { "code": null, "e": 4975, "s": 4970, "text": "vt_m" }, { "code": null, "e": 4985, "s": 4975, "text": "code_hunt" }, { "code": null, "e": 4993, "s": 4985, "text": "gfgking" }, { "code": null, "e": 5007, "s": 4993, "text": "number-theory" }, { "code": null, "e": 5014, "s": 5007, "text": "series" }, { "code": null, "e": 5025, "s": 5014, "text": "series-sum" }, { "code": null, "e": 5038, "s": 5025, "text": "Mathematical" }, { "code": null, "e": 5052, "s": 5038, "text": "number-theory" }, { "code": null, "e": 5065, "s": 5052, "text": "Mathematical" }, { "code": null, "e": 5072, "s": 5065, "text": "series" }, { "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": 5202, "s": 5170, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5248, "s": 5202, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 5292, "s": 5248, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 5341, "s": 5292, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 5383, "s": 5341, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 5415, "s": 5383, "text": "Check if a number is Palindrome" }, { "code": null, "e": 5450, "s": 5415, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 5475, "s": 5450, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 5546, "s": 5475, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Multivariate Regression
12 Feb, 2018 Prerequisite Article-Machine Learning The goal in any data analysis is to extract from raw information the accurate estimation. One of the most important and common question concerning if there is statistical relationship between a response variable (Y) and explanatory variables (Xi). An option to answer this question is to employ regression analysis in order to model its relationship. Further it can be used to predict the response variable for any arbitrary set of explanatory variables. The Problem: Multivariate Regression is one of the simplest Machine Learning Algorithm. It comes under the class of Supervised Learning Algorithms i.e, when we are provided with training dataset. Some of the problems that can be solved using this model are: A researcher has collected data on three psychological variables, four academic variables (standardized test scores), and the type of educational program the student is in for 600 high school students. She is interested in how the set of psychological variables is related to the academic variables and the type of program the student is in. A doctor has collected data on cholesterol, blood pressure, and weight. She also collected data on the eating habits of the subjects (e.g., how many ounces of red meat, fish, dairy products, and chocolate consumed per week). She wants to investigate the relationship between the three measures of health and eating habits. A property dealer wants to set housing prices which are based various factors like Size of house, No of bedrooms, Age of house, etc. We shall discuss the algorithm further using this example. The Solution: The solution is divided into various parts. Selecting the features: Finding the features on which a response variable depends (or not) is one of the most important steps in Multivariate Regression. To make our analysis simple, we assume that the features on which the response variable is dependent are already selected. Normalizing the features: The features are then scaled in order to bring them in range of (0,1) to make better analysis. This can be done by changing the value of each feature by: Selecting Hypothesis and Cost function: A hypothesis is a predicted value of the response variable represented by h(x). Cost function defines the cost for wrongly predicting hypothesis. It should be as small as possible. We choose hypothesis function as linear combination of features X. Minimizing the Cost function: Next some Cost minimization algorithm runs over the datasets which adjusts the parameters of the hypothesis. Once the cost function is minimized for the training dataset, it should also be minimized for an arbitrary dataset if the relation is universal. Gradient descent algorithm is a good choice for minimizing the cost function in case of multivariate regression. Testing the hypothesis: The hypothesis function is then tested over the test set to check its correctness and efficiency. Implementation: Multivariate regression technique can be implemented efficiently with the help of matrix operations. With python, it can be implemented using “numpy” library which contains definitions and operations for matrix object. The code requires “numpy” library for python (www.numpy.org/) which is not installed on GfG servers and thus the code is unable to run on gfg IDE. However link to the code is: Code: https://ide.geeksforgeeks.org/WxxMIg References: [1]http://cs229.stanford.edu(For more information on Multivariate Regression) [2]http://docs.scipy.org (For using “numpy” library with python) [3] Some examples are taken from http://www.ats.ucla.edu/stat/stata/dae/mvreg.htm This article is contributed by Abhishek Sharma. 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. Advanced Computer Subject Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Docker - COPY Instruction Getting started with Machine Learning How to Run a Python Script using Docker? ML | Underfitting and Overfitting Overview of Data Structures | Set 1 (Linear Data Structures) vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions Virtualization In Cloud Computing and Types Program for nth Catalan Number
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Feb, 2018" }, { "code": null, "e": 92, "s": 54, "text": "Prerequisite Article-Machine Learning" }, { "code": null, "e": 547, "s": 92, "text": "The goal in any data analysis is to extract from raw information the accurate estimation. One of the most important and common question concerning if there is statistical relationship between a response variable (Y) and explanatory variables (Xi). An option to answer this question is to employ regression analysis in order to model its relationship. Further it can be used to predict the response variable for any arbitrary set of explanatory variables." }, { "code": null, "e": 561, "s": 547, "text": " The Problem:" }, { "code": null, "e": 806, "s": 561, "text": "Multivariate Regression is one of the simplest Machine Learning Algorithm. It comes under the class of Supervised Learning Algorithms i.e, when we are provided with training dataset. Some of the problems that can be solved using this model are:" }, { "code": null, "e": 1148, "s": 806, "text": "A researcher has collected data on three psychological variables, four academic variables (standardized test scores), and the type of educational program the student is in for 600 high school students. She is interested in how the set of psychological variables is related to the academic variables and the type of program the student is in." }, { "code": null, "e": 1473, "s": 1148, "text": "A doctor has collected data on cholesterol, blood pressure, and weight. She also collected data on the eating habits of the subjects (e.g., how many ounces of red meat, fish, dairy products, and chocolate consumed per week). She wants to investigate the relationship between the three measures of health and eating habits." }, { "code": null, "e": 1665, "s": 1473, "text": "A property dealer wants to set housing prices which are based various factors like Size of house, No of bedrooms, Age of house, etc. We shall discuss the algorithm further using this example." }, { "code": null, "e": 1679, "s": 1665, "text": "The Solution:" }, { "code": null, "e": 1733, "s": 1679, "text": " The solution is divided into various parts." }, { "code": null, "e": 2010, "s": 1733, "text": "Selecting the features: Finding the features on which a response variable depends (or not) is one of the most important steps in Multivariate Regression. To make our analysis simple, we assume that the features on which the response variable is dependent are already selected." }, { "code": null, "e": 2190, "s": 2010, "text": "Normalizing the features: The features are then scaled in order to bring them in range of (0,1) to make better analysis. This can be done by changing the value of each feature by:" }, { "code": null, "e": 2478, "s": 2190, "text": "Selecting Hypothesis and Cost function: A hypothesis is a predicted value of the response variable represented by h(x). Cost function defines the cost for wrongly predicting hypothesis. It should be as small as possible. We choose hypothesis function as linear combination of features X." }, { "code": null, "e": 2875, "s": 2478, "text": "Minimizing the Cost function: Next some Cost minimization algorithm runs over the datasets which adjusts the parameters of the hypothesis. Once the cost function is minimized for the training dataset, it should also be minimized for an arbitrary dataset if the relation is universal. Gradient descent algorithm is a good choice for minimizing the cost function in case of multivariate regression." }, { "code": null, "e": 2997, "s": 2875, "text": "Testing the hypothesis: The hypothesis function is then tested over the test set to check its correctness and efficiency." }, { "code": null, "e": 3013, "s": 2997, "text": "Implementation:" }, { "code": null, "e": 3232, "s": 3013, "text": "Multivariate regression technique can be implemented efficiently with the help of matrix operations. With python, it can be implemented using “numpy” library which contains definitions and operations for matrix object." }, { "code": null, "e": 3408, "s": 3232, "text": "The code requires “numpy” library for python (www.numpy.org/) which is not installed on GfG servers and thus the code is unable to run on gfg IDE. However link to the code is:" }, { "code": null, "e": 3451, "s": 3408, "text": "Code: https://ide.geeksforgeeks.org/WxxMIg" }, { "code": null, "e": 3463, "s": 3451, "text": "References:" }, { "code": null, "e": 3551, "s": 3463, "text": " [1]http://cs229.stanford.edu(For more information on Multivariate Regression)" }, { "code": null, "e": 3626, "s": 3551, "text": " [2]http://docs.scipy.org (For using “numpy” library with python)" }, { "code": null, "e": 3669, "s": 3626, "text": " [3] Some examples are taken from" }, { "code": null, "e": 3730, "s": 3669, "text": " http://www.ats.ucla.edu/stat/stata/dae/mvreg.htm" }, { "code": null, "e": 3999, "s": 3730, "text": "This article is contributed by Abhishek Sharma. 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": 4025, "s": 3999, "text": "Advanced Computer Subject" }, { "code": null, "e": 4030, "s": 4025, "text": "Misc" }, { "code": null, "e": 4035, "s": 4030, "text": "Misc" }, { "code": null, "e": 4040, "s": 4035, "text": "Misc" }, { "code": null, "e": 4138, "s": 4040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4161, "s": 4138, "text": "System Design Tutorial" }, { "code": null, "e": 4187, "s": 4161, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4225, "s": 4187, "text": "Getting started with Machine Learning" }, { "code": null, "e": 4266, "s": 4225, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 4300, "s": 4266, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 4361, "s": 4300, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 4415, "s": 4361, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 4456, "s": 4415, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 4500, "s": 4456, "text": "Virtualization In Cloud Computing and Types" } ]
Ripple Effect on Android Button
19 Feb, 2021 The touch feedback in Android is a must whenever the user clicks on the item or button ripple effect when clicking on the same, gives confidence to the user that the button has been clicked so that they can wait for the next interaction of the app. So in this article, we are going to discuss what type of ripples can be implemented and where it can be used. Have a look at the following image to get an idea about the discussion. Step 1: Create an empty activity project Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Step 2: Working with the activity_main.xml file In the main layout of the application, there are 4 TextViews that have been implemented. one for the default touch feedback with border, the second is for default touch feedback without border, the third is for custom touch feedback with border, fourth is for the custom touch feedback without border. Invoke the following code to implement the UI. 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--default touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--default touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:focusable="true" android:foregroundGravity="bottom" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> </LinearLayout> Output UI: Step 3: Default Ripples in Android The default ripple in the android for the buttons or the text buttons can be achieved with the tags: android:background=”?android:attr/selectableItemBackground”: this creates ripple effect with border. android:background=”?android:attr/selectableItemBackgroundBorderless”: this creates ripple effect without border. Note: These tags are need to be set under the TextView. To implement both of the default ripple effects in android invoke the following code inside 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--default touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:background="?android:attr/selectableItemBackground" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--default touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackgroundBorderless" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:focusable="true" android:foregroundGravity="bottom" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> </LinearLayout> Step 4: Adding custom layouts These are needed to be implemented under the drawable folder. After implementing they need to set as the background for these text buttons. To add the layouts right click on the drawable folder > new > Drawable Resource File. The first layout is custom_bordered_ripple.xml and invoke the following code inside it. XML <?xml version="1.0" encoding="utf-8"?><ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/colorAccent"> <!--this creates the mask with the ripple effect--> <item android:id="@+id/mask" android:drawable="@android:color/white" /> </ripple> The second layout is custom_borderless_ripple.xml and invoke the following code. XML <?xml version="1.0" encoding="utf-8"?><ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/colorAccent"></ripple> The next step is to invoke these custom layouts as the background for the Custom Ripple With Border and Custom Ripple Without Border buttons inside 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--default touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="64dp" android:background="?android:attr/selectableItemBackground" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--default touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackgroundBorderless" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback with border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/custom_bordered_ripple" android:clickable="true" android:focusable="true" android:foregroundGravity="bottom" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple With Border" android:textColor="@android:color/black" android:textSize="18sp" /> <!--custom touch feedback without border--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/custom_borderless_ripple" android:clickable="true" android:focusable="true" android:gravity="center|start" android:padding="24dp" android:text="Custom Ripple Without Border" android:textColor="@android:color/black" android:textSize="18sp" /> </LinearLayout> Android-Button Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Navigation Drawer in Android How to Communicate Between Fragments in Android? How to Create and Add Data to SQLite Database in Android? Flutter - Custom Bottom Navigation Bar Content Providers in Android with Example Android Projects - From Basic to Advanced Level
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Feb, 2021" }, { "code": null, "e": 483, "s": 52, "text": "The touch feedback in Android is a must whenever the user clicks on the item or button ripple effect when clicking on the same, gives confidence to the user that the button has been clicked so that they can wait for the next interaction of the app. So in this article, we are going to discuss what type of ripples can be implemented and where it can be used. Have a look at the following image to get an idea about the discussion." }, { "code": null, "e": 524, "s": 483, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 709, "s": 524, "text": "Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project." }, { "code": null, "e": 757, "s": 709, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1059, "s": 757, "text": "In the main layout of the application, there are 4 TextViews that have been implemented. one for the default touch feedback with border, the second is for default touch feedback without border, the third is for custom touch feedback with border, fourth is for the custom touch feedback without border." }, { "code": null, "e": 1106, "s": 1059, "text": "Invoke the following code to implement the UI." }, { "code": null, "e": 1110, "s": 1106, "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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--default touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"64dp\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--default touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"true\" android:focusable=\"true\" android:foregroundGravity=\"bottom\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> </LinearLayout>", "e": 3184, "s": 1110, "text": null }, { "code": null, "e": 3196, "s": 3184, "text": "Output UI: " }, { "code": null, "e": 3231, "s": 3196, "text": "Step 3: Default Ripples in Android" }, { "code": null, "e": 3332, "s": 3231, "text": "The default ripple in the android for the buttons or the text buttons can be achieved with the tags:" }, { "code": null, "e": 3433, "s": 3332, "text": "android:background=”?android:attr/selectableItemBackground”: this creates ripple effect with border." }, { "code": null, "e": 3547, "s": 3433, "text": "android:background=”?android:attr/selectableItemBackgroundBorderless”: this creates ripple effect without border." }, { "code": null, "e": 3603, "s": 3547, "text": "Note: These tags are need to be set under the TextView." }, { "code": null, "e": 3723, "s": 3603, "text": "To implement both of the default ripple effects in android invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 3727, "s": 3723, "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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--default touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"64dp\" android:background=\"?android:attr/selectableItemBackground\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--default touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"?android:attr/selectableItemBackgroundBorderless\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"true\" android:focusable=\"true\" android:foregroundGravity=\"bottom\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> </LinearLayout>", "e": 5945, "s": 3727, "text": null }, { "code": null, "e": 5975, "s": 5945, "text": "Step 4: Adding custom layouts" }, { "code": null, "e": 6115, "s": 5975, "text": "These are needed to be implemented under the drawable folder. After implementing they need to set as the background for these text buttons." }, { "code": null, "e": 6201, "s": 6115, "text": "To add the layouts right click on the drawable folder > new > Drawable Resource File." }, { "code": null, "e": 6289, "s": 6201, "text": "The first layout is custom_bordered_ripple.xml and invoke the following code inside it." }, { "code": null, "e": 6293, "s": 6289, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ripple xmlns:android=\"http://schemas.android.com/apk/res/android\" android:color=\"@color/colorAccent\"> <!--this creates the mask with the ripple effect--> <item android:id=\"@+id/mask\" android:drawable=\"@android:color/white\" /> </ripple>", "e": 6594, "s": 6293, "text": null }, { "code": null, "e": 6675, "s": 6594, "text": "The second layout is custom_borderless_ripple.xml and invoke the following code." }, { "code": null, "e": 6679, "s": 6675, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ripple xmlns:android=\"http://schemas.android.com/apk/res/android\" android:color=\"@color/colorAccent\"></ripple>", "e": 6832, "s": 6679, "text": null }, { "code": null, "e": 7008, "s": 6832, "text": "The next step is to invoke these custom layouts as the background for the Custom Ripple With Border and Custom Ripple Without Border buttons inside the activity_main.xml file." }, { "code": null, "e": 7012, "s": 7008, "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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--default touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"64dp\" android:background=\"?android:attr/selectableItemBackground\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--default touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"?android:attr/selectableItemBackgroundBorderless\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback with border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@drawable/custom_bordered_ripple\" android:clickable=\"true\" android:focusable=\"true\" android:foregroundGravity=\"bottom\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple With Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> <!--custom touch feedback without border--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@drawable/custom_borderless_ripple\" android:clickable=\"true\" android:focusable=\"true\" android:gravity=\"center|start\" android:padding=\"24dp\" android:text=\"Custom Ripple Without Border\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" /> </LinearLayout>", "e": 9354, "s": 7012, "text": null }, { "code": null, "e": 9369, "s": 9354, "text": "Android-Button" }, { "code": null, "e": 9393, "s": 9369, "text": "Technical Scripter 2020" }, { "code": null, "e": 9401, "s": 9393, "text": "Android" }, { "code": null, "e": 9420, "s": 9401, "text": "Technical Scripter" }, { "code": null, "e": 9428, "s": 9420, "text": "Android" }, { "code": null, "e": 9526, "s": 9428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9595, "s": 9526, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 9626, "s": 9595, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 9669, "s": 9626, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 9701, "s": 9669, "text": "Android SDK and it's Components" }, { "code": null, "e": 9730, "s": 9701, "text": "Navigation Drawer in Android" }, { "code": null, "e": 9779, "s": 9730, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 9837, "s": 9779, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 9876, "s": 9837, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 9918, "s": 9876, "text": "Content Providers in Android with Example" } ]
How to use Checkboxes in ReactJS?
18 Jan, 2021 A Checkbox is a GUI widget that allows the user to make a binary choice from the given options. It is very useful when the user can select from the given options only. Material UI for React has this component available for us and it is very easy to integrate. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/lab npm install @material-ui/icons Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';import Checkbox from '@material-ui/core/Checkbox';import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';import CheckBoxIcon from '@material-ui/icons/CheckBox'; const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;const checkedIcon = <CheckBoxIcon fontSize="small" />; const App = () => { // Our sample dropdown options const options = ['Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete multiple id="checkboxes-tags-demo" options={options} renderOption={(option, { selected }) => ( <React.Fragment> <Checkbox icon={icon} checkedIcon={checkedIcon} style={{ marginRight: 8 }} checked={selected} /> {option} </React.Fragment> )} style={{ width: 500 }} renderInput={(params) => ( <TextField {...params} variant="outlined" label="Checkboxes" placeholder="Favorites" /> )} /> </div> );} 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: JavaScript ReactJS Technical Scripter 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": "\n18 Jan, 2021" }, { "code": null, "e": 288, "s": 28, "text": "A Checkbox is a GUI widget that allows the user to make a binary choice from the given options. It is very useful when the user can select from the given options only. Material UI for React has this component available for us and it is very easy to integrate." }, { "code": null, "e": 338, "s": 288, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 402, "s": 338, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 434, "s": 402, "text": "npx create-react-app foldername" }, { "code": null, "e": 534, "s": 434, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 548, "s": 534, "text": "cd foldername" }, { "code": null, "e": 657, "s": 548, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 747, "s": 657, "text": "npm install @material-ui/core\nnpm install @material-ui/lab\nnpm install @material-ui/icons" }, { "code": null, "e": 799, "s": 747, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 817, "s": 799, "text": "Project Structure" }, { "code": null, "e": 946, "s": 817, "text": "App.js: 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": 957, "s": 946, "text": "Javascript" }, { "code": "import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';import Checkbox from '@material-ui/core/Checkbox';import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';import CheckBoxIcon from '@material-ui/icons/CheckBox'; const icon = <CheckBoxOutlineBlankIcon fontSize=\"small\" />;const checkedIcon = <CheckBoxIcon fontSize=\"small\" />; const App = () => { // Our sample dropdown options const options = ['Monday', 'Tuesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete multiple id=\"checkboxes-tags-demo\" options={options} renderOption={(option, { selected }) => ( <React.Fragment> <Checkbox icon={icon} checkedIcon={checkedIcon} style={{ marginRight: 8 }} checked={selected} /> {option} </React.Fragment> )} style={{ width: 500 }} renderInput={(params) => ( <TextField {...params} variant=\"outlined\" label=\"Checkboxes\" placeholder=\"Favorites\" /> )} /> </div> );} export default App", "e": 2277, "s": 957, "text": null }, { "code": null, "e": 2390, "s": 2277, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2400, "s": 2390, "text": "npm start" }, { "code": null, "e": 2499, "s": 2400, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2510, "s": 2499, "text": "JavaScript" }, { "code": null, "e": 2518, "s": 2510, "text": "ReactJS" }, { "code": null, "e": 2537, "s": 2518, "text": "Technical Scripter" }, { "code": null, "e": 2554, "s": 2537, "text": "Web Technologies" } ]
Level of Each node in a Tree from source node (using BFS)
11 Nov, 2021 Given a tree with v vertices, find the level of each node in a tree from the source node.Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Approach: BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first and then the neighbours of neighbours. In simple terms, it traverses level-wise from the source. First, it traverses level 1 nodes (direct neighbours of source node) and then level 2 nodes (neighbours of source node) and so on. The BFS can be used to determine the level of each node from a given source node.Algorithm: Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array.Run a loop while size of queue is greater than 0.Mark the current node as visited.Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1.Print all the node and its level. Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array. Run a loop while size of queue is greater than 0. Mark the current node as visited. Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1. Print all the node and its level. Implementation: C++ Java Python3 C# Javascript // CPP Program to determine level of each node// and print level#include <bits/stdc++.h>using namespace std; // function to determine level of each node starting// from x using BFSvoid printLevels(vector<int> graph[], int V, int x){ // array to store level of each node int level[V]; bool marked[V]; // create a queue queue<int> que; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (!que.empty()) { // get the first element of queue x = que.front(); // dequeue element que.pop(); // traverse neighbors of node x for (int i = 0; i < graph[x].size(); i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels cout << "Nodes" << " " << "Level" << endl; for (int i = 0; i < V; i++) cout << " " << i << " --> " << level[i] << endl;} // Driver Codeint main(){ // adjacency graph for tree int V = 8; vector<int> graph[V]; graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); graph[1].push_back(5); graph[2].push_back(5); graph[2].push_back(6); graph[6].push_back(7); // call levels function with source as 0 printLevels(graph, V, 0); return 0;} // Java Program to determine level of each node // and print level import java.util.*; class GFG{ // function to determine level of each node starting // from x using BFS static void printLevels(Vector<Vector<Integer>> graph, int V, int x) { // array to store level of each node int level[] = new int[V]; boolean marked[] = new boolean[V]; // create a queue Queue<Integer> que = new LinkedList<Integer>(); // enqueue element x que.add(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.size() > 0) { // get the first element of queue x = que.peek(); // dequeue element que.remove(); // traverse neighbors of node x for (int i = 0; i < graph.get(x).size(); i++) { // b is neighbor of node x int b = graph.get(x).get(i); // if b is not marked already if (!marked[b]) { // enqueue b in queue que.add(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels System.out.println( "Nodes" + " " + "Level"); for (int i = 0; i < V; i++) System.out.println(" " + i +" --> " + level[i] ); } // Driver Code public static void main(String args[]){ // adjacency graph for tree int V = 8; Vector<Vector<Integer>> graph=new Vector<Vector<Integer>>(); for(int i = 0; i < V + 1; i++) graph.add(new Vector<Integer>()); graph.get(0).add(1); graph.get(0).add(2); graph.get(1).add(3); graph.get(1).add(4); graph.get(1).add(5); graph.get(2).add(5); graph.get(2).add(6); graph.get(6).add(7); // call levels function with source as 0 printLevels(graph, V, 0); } } // This code is contributed by Arnab Kundu # Python3 Program to determine level # of each node and print level import queue # function to determine level of # each node starting from x using BFS def printLevels(graph, V, x): # array to store level of each node level = [None] * V marked = [False] * V # create a queue que = queue.Queue() # enqueue element x que.put(x) # initialize level of source # node to 0 level[x] = 0 # marked it as visited marked[x] = True # do until queue is empty while (not que.empty()): # get the first element of queue x = que.get() # traverse neighbors of node x for i in range(len(graph[x])): # b is neighbor of node x b = graph[x][i] # if b is not marked already if (not marked[b]): # enqueue b in queue que.put(b) # level of b is level of x + 1 level[b] = level[x] + 1 # mark b marked[b] = True # display all nodes and their levels print("Nodes", " ", "Level") for i in range(V): print(" ",i, " --> ", level[i]) # Driver Code if __name__ == '__main__': # adjacency graph for tree V = 8 graph = [[] for i in range(V)] graph[0].append(1) graph[0].append(2) graph[1].append(3) graph[1].append(4) graph[1].append(5) graph[2].append(5) graph[2].append(6) graph[6].append(7) # call levels function with source as 0 printLevels(graph, V, 0) # This code is contributed by PranchalK // C# Program to determine level of each node // and print level using System;using System.Collections.Generic; class GFG{ // function to determine level of each node starting // from x using BFS static void printLevels(List<List<int>> graph, int V, int x) { // array to store level of each node int []level = new int[V]; Boolean []marked = new Boolean[V]; // create a queue Queue<int> que = new Queue<int>(); // enqueue element x que.Enqueue(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.Count > 0) { // get the first element of queue x = que.Peek(); // dequeue element que.Dequeue(); // traverse neighbors of node x for (int i = 0; i < graph[x].Count; i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.Enqueue(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels Console.WriteLine("Nodes" + " " + "Level"); for (int i = 0; i < V; i++) Console.WriteLine(" " + i +" --> " + level[i]); } // Driver Code public static void Main(String []args){ // adjacency graph for tree int V = 8; List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < V + 1; i++) graph.Add(new List<int>()); graph[0].Add(1); graph[0].Add(2); graph[1].Add(3); graph[1].Add(4); graph[1].Add(5); graph[2].Add(5); graph[2].Add(6); graph[6].Add(7); // call levels function with source as 0 printLevels(graph, V, 0); } } // This code is contributed by Princi Singh <script> // Javascript Program to determine level of each node // and print level // function to determine level of each node starting // from x using BFS function printLevels(graph, V, x) { // array to store level of each node var level = Array(V); var marked = Array(V).fill(false); // create a queue var que = []; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.length > 0) { // get the first element of queue x = que[0]; // dequeue element que.shift(); // traverse neighbors of node x for (var i = 0; i < graph[x].length; i++) { // b is neighbor of node x var b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels document.write("Nodes" + " " + "Level<br>"); for (var i = 0; i < V; i++) document.write(" " + i +" --> " + level[i]+"<br>"); } // Driver Code // adjacency graph for tree var V = 8; var graph = Array.from(Array(V+1), ()=>Array()); graph[0].push(1); graph[0].push(2); graph[1].push(3); graph[1].push(4); graph[1].push(5); graph[2].push(5); graph[2].push(6); graph[6].push(7); // call levels function with source as 0 printLevels(graph, V, 0); // This code is contributed by importantly. </script> Output: Nodes Level 0 --> 0 1 --> 1 2 --> 1 3 --> 2 4 --> 2 5 --> 2 6 --> 2 7 --> 3 Complexity Analysis: Time Complexity: O(n). In BFS traversal every node is visited only once, so Time Complexity is O(n). Space Complexity: O(n). The space is required to store the nodes in a queue. Level of Each node in a Tree from source node (using BFS) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLevel of Each node in a Tree from source node (using BFS) | 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:10•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=teTH3Vmv7A0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> PranchalKatiyar andrew1234 princi singh nidhi_biet importantly BFS Graph Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Find if there is a path between two vertices in a directed graph Introduction to Data Structures Floyd Warshall Algorithm | DP-16 What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Nov, 2021" }, { "code": null, "e": 153, "s": 52, "text": "Given a tree with v vertices, find the level of each node in a tree from the source node.Examples: " }, { "code": null, "e": 164, "s": 153, "text": "Input : " }, { "code": null, "e": 398, "s": 164, "text": "Output : Node Level\n 0 0\n 1 1\n 2 1\n 3 2\n 4 2\n 5 2\n 6 2\n 7 3\n\nExplanation : " }, { "code": null, "e": 405, "s": 398, "text": "Input:" }, { "code": null, "e": 564, "s": 405, "text": "Output : Node Level\n 0 0\n 1 1\n 2 1\n 3 2\n 4 2\nExplanation:" }, { "code": null, "e": 573, "s": 564, "text": "Chapters" }, { "code": null, "e": 600, "s": 573, "text": "descriptions off, selected" }, { "code": null, "e": 650, "s": 600, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 673, "s": 650, "text": "captions off, selected" }, { "code": null, "e": 681, "s": 673, "text": "English" }, { "code": null, "e": 699, "s": 681, "text": "default, selected" }, { "code": null, "e": 723, "s": 699, "text": "This is a modal window." }, { "code": null, "e": 792, "s": 723, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 814, "s": 792, "text": "End of dialog window." }, { "code": null, "e": 1255, "s": 816, "text": "Approach: BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first and then the neighbours of neighbours. In simple terms, it traverses level-wise from the source. First, it traverses level 1 nodes (direct neighbours of source node) and then level 2 nodes (neighbours of source node) and so on. The BFS can be used to determine the level of each node from a given source node.Algorithm: " }, { "code": null, "e": 1693, "s": 1255, "text": "Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array.Run a loop while size of queue is greater than 0.Mark the current node as visited.Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1.Print all the node and its level." }, { "code": null, "e": 1875, "s": 1693, "text": "Create the tree, a queue to store the nodes and insert the root or starting node in the queue. Create an extra array level of size v (number of vertices) and create a visited array." }, { "code": null, "e": 1925, "s": 1875, "text": "Run a loop while size of queue is greater than 0." }, { "code": null, "e": 1959, "s": 1925, "text": "Mark the current node as visited." }, { "code": null, "e": 2101, "s": 1959, "text": "Pop one node from the queue and insert its childrens (if present) and update the size of the inserted node as level[child] = level[node] + 1." }, { "code": null, "e": 2135, "s": 2101, "text": "Print all the node and its level." }, { "code": null, "e": 2153, "s": 2135, "text": "Implementation: " }, { "code": null, "e": 2157, "s": 2153, "text": "C++" }, { "code": null, "e": 2162, "s": 2157, "text": "Java" }, { "code": null, "e": 2170, "s": 2162, "text": "Python3" }, { "code": null, "e": 2173, "s": 2170, "text": "C#" }, { "code": null, "e": 2184, "s": 2173, "text": "Javascript" }, { "code": "// CPP Program to determine level of each node// and print level#include <bits/stdc++.h>using namespace std; // function to determine level of each node starting// from x using BFSvoid printLevels(vector<int> graph[], int V, int x){ // array to store level of each node int level[V]; bool marked[V]; // create a queue queue<int> que; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (!que.empty()) { // get the first element of queue x = que.front(); // dequeue element que.pop(); // traverse neighbors of node x for (int i = 0; i < graph[x].size(); i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels cout << \"Nodes\" << \" \" << \"Level\" << endl; for (int i = 0; i < V; i++) cout << \" \" << i << \" --> \" << level[i] << endl;} // Driver Codeint main(){ // adjacency graph for tree int V = 8; vector<int> graph[V]; graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); graph[1].push_back(5); graph[2].push_back(5); graph[2].push_back(6); graph[6].push_back(7); // call levels function with source as 0 printLevels(graph, V, 0); return 0;}", "e": 3936, "s": 2184, "text": null }, { "code": "// Java Program to determine level of each node // and print level import java.util.*; class GFG{ // function to determine level of each node starting // from x using BFS static void printLevels(Vector<Vector<Integer>> graph, int V, int x) { // array to store level of each node int level[] = new int[V]; boolean marked[] = new boolean[V]; // create a queue Queue<Integer> que = new LinkedList<Integer>(); // enqueue element x que.add(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.size() > 0) { // get the first element of queue x = que.peek(); // dequeue element que.remove(); // traverse neighbors of node x for (int i = 0; i < graph.get(x).size(); i++) { // b is neighbor of node x int b = graph.get(x).get(i); // if b is not marked already if (!marked[b]) { // enqueue b in queue que.add(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels System.out.println( \"Nodes\" + \" \" + \"Level\"); for (int i = 0; i < V; i++) System.out.println(\" \" + i +\" --> \" + level[i] ); } // Driver Code public static void main(String args[]){ // adjacency graph for tree int V = 8; Vector<Vector<Integer>> graph=new Vector<Vector<Integer>>(); for(int i = 0; i < V + 1; i++) graph.add(new Vector<Integer>()); graph.get(0).add(1); graph.get(0).add(2); graph.get(1).add(3); graph.get(1).add(4); graph.get(1).add(5); graph.get(2).add(5); graph.get(2).add(6); graph.get(6).add(7); // call levels function with source as 0 printLevels(graph, V, 0); } } // This code is contributed by Arnab Kundu", "e": 6042, "s": 3936, "text": null }, { "code": "# Python3 Program to determine level # of each node and print level import queue # function to determine level of # each node starting from x using BFS def printLevels(graph, V, x): # array to store level of each node level = [None] * V marked = [False] * V # create a queue que = queue.Queue() # enqueue element x que.put(x) # initialize level of source # node to 0 level[x] = 0 # marked it as visited marked[x] = True # do until queue is empty while (not que.empty()): # get the first element of queue x = que.get() # traverse neighbors of node x for i in range(len(graph[x])): # b is neighbor of node x b = graph[x][i] # if b is not marked already if (not marked[b]): # enqueue b in queue que.put(b) # level of b is level of x + 1 level[b] = level[x] + 1 # mark b marked[b] = True # display all nodes and their levels print(\"Nodes\", \" \", \"Level\") for i in range(V): print(\" \",i, \" --> \", level[i]) # Driver Code if __name__ == '__main__': # adjacency graph for tree V = 8 graph = [[] for i in range(V)] graph[0].append(1) graph[0].append(2) graph[1].append(3) graph[1].append(4) graph[1].append(5) graph[2].append(5) graph[2].append(6) graph[6].append(7) # call levels function with source as 0 printLevels(graph, V, 0) # This code is contributed by PranchalK", "e": 7650, "s": 6042, "text": null }, { "code": "// C# Program to determine level of each node // and print level using System;using System.Collections.Generic; class GFG{ // function to determine level of each node starting // from x using BFS static void printLevels(List<List<int>> graph, int V, int x) { // array to store level of each node int []level = new int[V]; Boolean []marked = new Boolean[V]; // create a queue Queue<int> que = new Queue<int>(); // enqueue element x que.Enqueue(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.Count > 0) { // get the first element of queue x = que.Peek(); // dequeue element que.Dequeue(); // traverse neighbors of node x for (int i = 0; i < graph[x].Count; i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.Enqueue(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels Console.WriteLine(\"Nodes\" + \" \" + \"Level\"); for (int i = 0; i < V; i++) Console.WriteLine(\" \" + i +\" --> \" + level[i]); } // Driver Code public static void Main(String []args){ // adjacency graph for tree int V = 8; List<List<int>> graph = new List<List<int>>(); for(int i = 0; i < V + 1; i++) graph.Add(new List<int>()); graph[0].Add(1); graph[0].Add(2); graph[1].Add(3); graph[1].Add(4); graph[1].Add(5); graph[2].Add(5); graph[2].Add(6); graph[6].Add(7); // call levels function with source as 0 printLevels(graph, V, 0); } } // This code is contributed by Princi Singh", "e": 9691, "s": 7650, "text": null }, { "code": "<script> // Javascript Program to determine level of each node // and print level // function to determine level of each node starting // from x using BFS function printLevels(graph, V, x) { // array to store level of each node var level = Array(V); var marked = Array(V).fill(false); // create a queue var que = []; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (que.length > 0) { // get the first element of queue x = que[0]; // dequeue element que.shift(); // traverse neighbors of node x for (var i = 0; i < graph[x].length; i++) { // b is neighbor of node x var b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels document.write(\"Nodes\" + \" \" + \"Level<br>\"); for (var i = 0; i < V; i++) document.write(\" \" + i +\" --> \" + level[i]+\"<br>\"); } // Driver Code // adjacency graph for tree var V = 8; var graph = Array.from(Array(V+1), ()=>Array()); graph[0].push(1); graph[0].push(2); graph[1].push(3); graph[1].push(4); graph[1].push(5); graph[2].push(5); graph[2].push(6); graph[6].push(7); // call levels function with source as 0 printLevels(graph, V, 0); // This code is contributed by importantly. </script>", "e": 11448, "s": 9691, "text": null }, { "code": null, "e": 11458, "s": 11448, "text": "Output: " }, { "code": null, "e": 11577, "s": 11458, "text": "Nodes Level\n 0 --> 0\n 1 --> 1\n 2 --> 1\n 3 --> 2\n 4 --> 2\n 5 --> 2\n 6 --> 2\n 7 --> 3" }, { "code": null, "e": 11600, "s": 11577, "text": "Complexity Analysis: " }, { "code": null, "e": 11701, "s": 11600, "text": "Time Complexity: O(n). In BFS traversal every node is visited only once, so Time Complexity is O(n)." }, { "code": null, "e": 11778, "s": 11701, "text": "Space Complexity: O(n). The space is required to store the nodes in a queue." }, { "code": null, "e": 12712, "s": 11780, "text": "Level of Each node in a Tree from source node (using BFS) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersLevel of Each node in a Tree from source node (using BFS) | 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:10•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=teTH3Vmv7A0\" 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": 12730, "s": 12714, "text": "PranchalKatiyar" }, { "code": null, "e": 12741, "s": 12730, "text": "andrew1234" }, { "code": null, "e": 12754, "s": 12741, "text": "princi singh" }, { "code": null, "e": 12765, "s": 12754, "text": "nidhi_biet" }, { "code": null, "e": 12777, "s": 12765, "text": "importantly" }, { "code": null, "e": 12781, "s": 12777, "text": "BFS" }, { "code": null, "e": 12787, "s": 12781, "text": "Graph" }, { "code": null, "e": 12793, "s": 12787, "text": "Graph" }, { "code": null, "e": 12797, "s": 12793, "text": "BFS" }, { "code": null, "e": 12895, "s": 12797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12935, "s": 12895, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 12973, "s": 12935, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 13024, "s": 12973, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 13075, "s": 13024, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 13105, "s": 13075, "text": "Graph and its representations" }, { "code": null, "e": 13163, "s": 13105, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 13228, "s": 13163, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 13260, "s": 13228, "text": "Introduction to Data Structures" }, { "code": null, "e": 13293, "s": 13260, "text": "Floyd Warshall Algorithm | DP-16" } ]
p5.js | lerp() Function
25 Mar, 2020 The lerp() function is used to find a number between two numbers. The amt parameter can be used to specify the amount to interpolate between the two values. An amount nearer to 0.1 would mean that the final value is nearer to the first value, and nearer to 0.9 means that the value is nearer to the second value. If the value is less or more than these, then the final value would be calculated on the basis of the ratio of the two numbers. It can be used for drawing dotted lines or creating motion along a path by finding all the intermediate points in a line. Syntax: lerp( start, stop, amt ) Parameters: This function accept three parameters as mentioned above and described below: start: It is a number which denotes the first value of the two numbers. stop: It is a number which denotes the second value of the two numbers.. amt: It is a number which denotes the amount by which a number is to be interpolated between the two numbers. Return Value: It returns a number with the lerped value. Below examples illustrate the lerp() function in p5.js: Example 1: function setup() { createCanvas(600, 200); textSize(20); inputElemA = createInput(10); inputElemA.position(30, 40); inputElemB = createInput(100); inputElemB.position(30, 60); sliderElem = createSlider(0, 1, 0.5, 0.1); sliderElem.position(30, 120);} function draw() { clear(); text("Enter two values between which new " + "number would be lerped", 20, 20); text("Move the slider to observe the amount" + " of lerping", 20, 100); // Convert the string value to a number // value for lerping inputValA = Number(inputElemA.value()); inputValB = Number(inputElemB.value()); sliderVal = sliderElem.value(); text("The amount of lerping is: " + sliderVal, 20, 160); text("The lerped value is: " + lerp(inputValA, inputValB, sliderVal), 20, 180);} Output: Example 2: function setup() { createCanvas(600, 300); textSize(20); sliderElem = createSlider(0, 1, 0.5, 0.1); sliderElem.position(30, 180); circleApos = 50; circleBpos = 500;} function draw() { clear(); text("Move the slider to observe the x position " + "of the middle circle", 20, 160); circle(circleApos, 50, 80); circle(circleBpos, 50, 80); sliderVal = sliderElem.value(); lerpedVal = lerp(circleApos, circleBpos, sliderVal); // Draw the circle at the lerped x coordinate circle(lerpedVal, 50, 80); text("The amount of lerping is: " + sliderVal, 20, 220);} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/lerp JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Mar, 2020" }, { "code": null, "e": 469, "s": 28, "text": "The lerp() function is used to find a number between two numbers. The amt parameter can be used to specify the amount to interpolate between the two values. An amount nearer to 0.1 would mean that the final value is nearer to the first value, and nearer to 0.9 means that the value is nearer to the second value. If the value is less or more than these, then the final value would be calculated on the basis of the ratio of the two numbers." }, { "code": null, "e": 591, "s": 469, "text": "It can be used for drawing dotted lines or creating motion along a path by finding all the intermediate points in a line." }, { "code": null, "e": 599, "s": 591, "text": "Syntax:" }, { "code": null, "e": 624, "s": 599, "text": "lerp( start, stop, amt )" }, { "code": null, "e": 714, "s": 624, "text": "Parameters: This function accept three parameters as mentioned above and described below:" }, { "code": null, "e": 786, "s": 714, "text": "start: It is a number which denotes the first value of the two numbers." }, { "code": null, "e": 859, "s": 786, "text": "stop: It is a number which denotes the second value of the two numbers.." }, { "code": null, "e": 969, "s": 859, "text": "amt: It is a number which denotes the amount by which a number is to be interpolated between the two numbers." }, { "code": null, "e": 1026, "s": 969, "text": "Return Value: It returns a number with the lerped value." }, { "code": null, "e": 1082, "s": 1026, "text": "Below examples illustrate the lerp() function in p5.js:" }, { "code": null, "e": 1093, "s": 1082, "text": "Example 1:" }, { "code": "function setup() { createCanvas(600, 200); textSize(20); inputElemA = createInput(10); inputElemA.position(30, 40); inputElemB = createInput(100); inputElemB.position(30, 60); sliderElem = createSlider(0, 1, 0.5, 0.1); sliderElem.position(30, 120);} function draw() { clear(); text(\"Enter two values between which new \" + \"number would be lerped\", 20, 20); text(\"Move the slider to observe the amount\" + \" of lerping\", 20, 100); // Convert the string value to a number // value for lerping inputValA = Number(inputElemA.value()); inputValB = Number(inputElemB.value()); sliderVal = sliderElem.value(); text(\"The amount of lerping is: \" + sliderVal, 20, 160); text(\"The lerped value is: \" + lerp(inputValA, inputValB, sliderVal), 20, 180);}", "e": 1914, "s": 1093, "text": null }, { "code": null, "e": 1922, "s": 1914, "text": "Output:" }, { "code": null, "e": 1933, "s": 1922, "text": "Example 2:" }, { "code": "function setup() { createCanvas(600, 300); textSize(20); sliderElem = createSlider(0, 1, 0.5, 0.1); sliderElem.position(30, 180); circleApos = 50; circleBpos = 500;} function draw() { clear(); text(\"Move the slider to observe the x position \" + \"of the middle circle\", 20, 160); circle(circleApos, 50, 80); circle(circleBpos, 50, 80); sliderVal = sliderElem.value(); lerpedVal = lerp(circleApos, circleBpos, sliderVal); // Draw the circle at the lerped x coordinate circle(lerpedVal, 50, 80); text(\"The amount of lerping is: \" + sliderVal, 20, 220);}", "e": 2521, "s": 1933, "text": null }, { "code": null, "e": 2529, "s": 2521, "text": "Output:" }, { "code": null, "e": 2569, "s": 2529, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 2667, "s": 2569, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 2715, "s": 2667, "text": "Reference: https://p5js.org/reference/#/p5/lerp" }, { "code": null, "e": 2732, "s": 2715, "text": "JavaScript-p5.js" }, { "code": null, "e": 2743, "s": 2732, "text": "JavaScript" }, { "code": null, "e": 2760, "s": 2743, "text": "Web Technologies" } ]
Switch Case in Python (Replacement)
13 Jun, 2022 What is the replacement of Switch Case in Python? Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping. Python3 # Function to convert number into string# Switcher is dictionary data type heredef numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } # get() method of dictionary data type returns # value of passed argument if it is present # in dictionary otherwise second argument will # be assigned as default value of passed argument return switcher.get(argument, "nothing") # Driver programif __name__ == "__main__": argument=0 print (numbers_to_strings(argument)) This code is analogous to the given code in C++ : CPP #include<bits/stdc++.h>using namespace std; // Function to convert number into stringstring numbers_to_strings(int argument){ switch(argument) { case 0: return "zero"; case 1: return "one"; case 2: return "two"; default: return "nothing"; };}; // Driver programint main(){ int argument = 0; cout << numbers_to_strings(argument); return 0;} Output: Zero But In Python 3.10 and after that, Python will support this: it’s my example code: Python3 def number_to_string(argument): match argument: case 0: return "zero" case 1: return "one" case 2: return "two" case default: return "something" if __name__ = "__main__": argument = 0 number_to_string(argument) It is similar to that of switch cases in C++, Java, etc. This article is contributed by Shashank Mishra (Gullu). 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 if you want to share more information about the topic discussed above. ddeevviissaavviittaa nhatphuc2021b rishabsaini261 harshmaster07705 varshagumber28 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 102, "s": 52, "text": "What is the replacement of Switch Case in Python?" }, { "code": null, "e": 264, "s": 102, "text": "Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping." }, { "code": null, "e": 272, "s": 264, "text": "Python3" }, { "code": "# Function to convert number into string# Switcher is dictionary data type heredef numbers_to_strings(argument): switcher = { 0: \"zero\", 1: \"one\", 2: \"two\", } # get() method of dictionary data type returns # value of passed argument if it is present # in dictionary otherwise second argument will # be assigned as default value of passed argument return switcher.get(argument, \"nothing\") # Driver programif __name__ == \"__main__\": argument=0 print (numbers_to_strings(argument))", "e": 800, "s": 272, "text": null }, { "code": null, "e": 851, "s": 800, "text": "This code is analogous to the given code in C++ : " }, { "code": null, "e": 855, "s": 851, "text": "CPP" }, { "code": "#include<bits/stdc++.h>using namespace std; // Function to convert number into stringstring numbers_to_strings(int argument){ switch(argument) { case 0: return \"zero\"; case 1: return \"one\"; case 2: return \"two\"; default: return \"nothing\"; };}; // Driver programint main(){ int argument = 0; cout << numbers_to_strings(argument); return 0;}", "e": 1282, "s": 855, "text": null }, { "code": null, "e": 1291, "s": 1282, "text": "Output: " }, { "code": null, "e": 1296, "s": 1291, "text": "Zero" }, { "code": null, "e": 1357, "s": 1296, "text": "But In Python 3.10 and after that, Python will support this:" }, { "code": null, "e": 1380, "s": 1357, "text": " it’s my example code:" }, { "code": null, "e": 1388, "s": 1380, "text": "Python3" }, { "code": "def number_to_string(argument): match argument: case 0: return \"zero\" case 1: return \"one\" case 2: return \"two\" case default: return \"something\" if __name__ = \"__main__\": argument = 0 number_to_string(argument)", "e": 1681, "s": 1388, "text": null }, { "code": null, "e": 1738, "s": 1681, "text": "It is similar to that of switch cases in C++, Java, etc." }, { "code": null, "e": 2173, "s": 1738, "text": "This article is contributed by Shashank Mishra (Gullu). 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 if you want to share more information about the topic discussed above. " }, { "code": null, "e": 2194, "s": 2173, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 2208, "s": 2194, "text": "nhatphuc2021b" }, { "code": null, "e": 2223, "s": 2208, "text": "rishabsaini261" }, { "code": null, "e": 2240, "s": 2223, "text": "harshmaster07705" }, { "code": null, "e": 2255, "s": 2240, "text": "varshagumber28" }, { "code": null, "e": 2262, "s": 2255, "text": "Python" } ]
Find the Mobile Number formed using first digits of arrays of absolute differences of consecutive numbers
21 Jun, 2022 Given a String ph[], the task is to find a new number for the user, based on following conditions: The new number will also start from the same digit as of original number.The digits of the new number will be the first digits of a series of arrays of absolute differences of the consecutive elements. The new number will also start from the same digit as of original number. The digits of the new number will be the first digits of a series of arrays of absolute differences of the consecutive elements. Examples: Input: ph = “9827218706”Output: 9154301011Explanation: Input: ph =”9647253846′′Output: 9310100011 Approach: Consider the following steps to solve this problem: Convert every character from the string into integer and store it into the array ph1[] using list comprehension.Declare an empty string ph2.Convert first element of array ph1[ ] into a string and add it to ph2.Using List comprehension create an array by storing the absolute difference of consecutive elements.Assign this array to ph1.Repeat step 3-5, ten times as the phone number have ten digits. Convert every character from the string into integer and store it into the array ph1[] using list comprehension. Declare an empty string ph2. Convert first element of array ph1[ ] into a string and add it to ph2. Using List comprehension create an array by storing the absolute difference of consecutive elements. Assign this array to ph1. Repeat step 3-5, ten times as the phone number have ten digits. Below is the implementation of the above approach. Java Python3 Javascript // Java program for above approachpublic class Mobile{ // Function to find lucky phone number static String phone(String ph, int n) { // Converting char to int and storing into array. int[] ph1 = new int[n]; for (int i = 0; i < n; i++) ph1[i] = ph.charAt(i) - '0'; // Empty string to store lucky number. String ph2 = ""; // Loop for performing action // and adding digit to ph2. for (int i = 0; i < n; i++) { // Convert first element into // string and adding to ph2. ph2 += ph1[0]; // Creating new ph1 by subtracting // consecutive element. int ph3[] = new int[ph1.length - 1]; for (int j = 0; j < ph1.length - 1; j++) ph3[j] = Math.abs(ph1[j] - ph1[j + 1]); ph1 = ph3; } // Return lucky number ph2 return ph2; } // Driver code public static void main(String[] args) { // Original number String ph = "9827218706"; // Calling phone function. String num = phone(ph, ph.length()); // Print the lucky number System.out.println(num); }} // This code is contributed by Lovely Jain # Function to find lucky phone numberdef phone(ph, n): # Converting char to int and storing into array. ph1 = [int(i) for i in ph] # Empty string to store lucky number. ph2 = "" # Loop for performing action # and adding digit to ph2. for _ in range(n): # Convert first element into # string and adding to ph2. ph2 += str(ph1[0]) # Creating new ph1 by subtracting # consecutive element. ph1 = [abs(ph1[j]-ph1[j + 1]) \ for j in range(len(ph1)-1)] # Return lucky number ph2 return ph2 # Original numberph = "9827218706" # Calling phone function.num = phone(ph, len(ph)) # Print the lucky numberprint(num) <script>// Function to find lucky phone numberfunction phone(ph, n) { // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = "" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let temp = [] for (let j = 0; j < ph1.length - 1; j++) { temp.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = temp } // Return lucky number ph2 return ph2} // Original numberlet ph = "9827218706" // Calling phone function.let num = phone(ph, ph.length) // Print the lucky numberdocument.write(num) // This code is contributed by gfgking.</script> 9154301011 Time Complexity: O(N*N)Auxiliary Space: O(N) Efficient Approach: In this approach, no extra space is required for storing elements in the array. First, declare an empty string ph2 in which lucky number will be stored, now create a for loop in which the first character of the string will be added to ph2 and again another for loop to find the absolute difference of consecutive element. Now the string of absolute difference will be assigned to ph1 which is the original number and the same steps will be followed. Follow the steps below to solve the problem: Initialize a string variable ph2[] as an empty string. Iterate over the range [0, N) using the variable i and perform the following tasks:Add ph[0] to the variable ph2[].Initialize a string variable S[] as an empty string.Iterate over the range [0, N-1) using the variable j and perform the following tasks:Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[].Set the value of ph as S[]. Add ph[0] to the variable ph2[]. Initialize a string variable S[] as an empty string. Iterate over the range [0, N-1) using the variable j and perform the following tasks:Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[]. Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[]. Set the value of ph as S[]. After performing the above steps, print the value of ph2[] as the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find lucky number.string phone(string ph, int n){ // ph2 is empty string to store lucky number. string ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.length(); j++) { int x = abs(int(ph[j]) - int(ph[j + 1])); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2;} // Driver Codeint main(){ // Original number string ph = "9827218706"; // Call phone function string num = phone(ph, ph.length()); // Printing lucky number cout << (num);} // This code is contributed by Potta Lokesh // Java program for the above approachimport java.util.*; class GFG { // Function to find lucky number. static String phone(String ph, int n) { // ph2 is empty string to store lucky number. String ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph.charAt(0); // S for storing the difference String S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.length()-1; j++) { int x = Math.abs(ph.charAt(j) - ph.charAt(j+1)); S += (char)(x + '0'); } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void main(String args[]) { // Original number String ph = "9827218706"; // Call phone function String num = phone(ph, ph.length()); // Printing lucky number System.out.println(num); }} // This code is contributed by avijitmondal1998 # Function to find lucky number.def phone(ph, n): # ph2 is empty string to store lucky number. ph2 = "" # For loop for finding lucky number for i in range(len(ph)): # Add first element of ph to ph2 ph2 += ph[0] # S for storing the difference S = "" # Loop to calculate the absolute difference for j in range(len(ph)-1): x = abs(int(ph[j])-int(ph[j + 1])) S += str(x) # Assigning S to ph. ph = S # Return the lucky number return ph2 # Original numberph = "9827218706" # Call phone functionnum = phone(ph, len(ph)) # Printing lucky numberprint(num) // C# code for the above approachusing System;class GFG{ // Function to find lucky number. static string phone(string ph, int n) { // ph2 is empty string to store lucky number. string ph2 = ""; // For loop for finding lucky number for (int i = 0; i < ph.Length; i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = ""; // Loop to calculate the absolute difference for (int j = 0; j < ph.Length; j++) { int x = Math.Abs(ph[j] - ph[j + 1]); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void Main() { // Original number string ph = "9827218706"; // Call phone function string num = phone(ph, ph.Length); // Printing lucky number Console.WriteLine (num); }} // This code is contributed by ukasp. <script>// javascript program for the above approach // Function to find lucky number. function phone( ph , n) { // ph2 is empty string to store lucky number. // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = "" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let S = [] for (let j = 0; j < ph1.length - 1; j++) { S.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = S } // Return the lucky number return ph2; } // Driver Code // Original number var ph = "9827218706"; // Call phone function var num = phone(ph, ph.length); // Printing lucky number document.write(num); // This code is contributed by umadevi9616</script> 9154301011 Time Complexity: O(N*N)Auxiliary Space: O(N) lokeshpotta20 ukasp gfgking avijitmondal1998 umadevi9616 jainlovely450 Algo-Geek 2021 Algo Geek Mathematical Pattern Searching Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 155, "s": 54, "text": "Given a String ph[], the task is to find a new number for the user, based on following conditions: " }, { "code": null, "e": 357, "s": 155, "text": "The new number will also start from the same digit as of original number.The digits of the new number will be the first digits of a series of arrays of absolute differences of the consecutive elements." }, { "code": null, "e": 431, "s": 357, "text": "The new number will also start from the same digit as of original number." }, { "code": null, "e": 560, "s": 431, "text": "The digits of the new number will be the first digits of a series of arrays of absolute differences of the consecutive elements." }, { "code": null, "e": 570, "s": 560, "text": "Examples:" }, { "code": null, "e": 625, "s": 570, "text": "Input: ph = “9827218706”Output: 9154301011Explanation:" }, { "code": null, "e": 668, "s": 625, "text": "Input: ph =”9647253846′′Output: 9310100011" }, { "code": null, "e": 732, "s": 668, "text": "Approach: Consider the following steps to solve this problem: " }, { "code": null, "e": 1131, "s": 732, "text": "Convert every character from the string into integer and store it into the array ph1[] using list comprehension.Declare an empty string ph2.Convert first element of array ph1[ ] into a string and add it to ph2.Using List comprehension create an array by storing the absolute difference of consecutive elements.Assign this array to ph1.Repeat step 3-5, ten times as the phone number have ten digits." }, { "code": null, "e": 1244, "s": 1131, "text": "Convert every character from the string into integer and store it into the array ph1[] using list comprehension." }, { "code": null, "e": 1273, "s": 1244, "text": "Declare an empty string ph2." }, { "code": null, "e": 1344, "s": 1273, "text": "Convert first element of array ph1[ ] into a string and add it to ph2." }, { "code": null, "e": 1445, "s": 1344, "text": "Using List comprehension create an array by storing the absolute difference of consecutive elements." }, { "code": null, "e": 1471, "s": 1445, "text": "Assign this array to ph1." }, { "code": null, "e": 1535, "s": 1471, "text": "Repeat step 3-5, ten times as the phone number have ten digits." }, { "code": null, "e": 1586, "s": 1535, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1591, "s": 1586, "text": "Java" }, { "code": null, "e": 1599, "s": 1591, "text": "Python3" }, { "code": null, "e": 1610, "s": 1599, "text": "Javascript" }, { "code": "// Java program for above approachpublic class Mobile{ // Function to find lucky phone number static String phone(String ph, int n) { // Converting char to int and storing into array. int[] ph1 = new int[n]; for (int i = 0; i < n; i++) ph1[i] = ph.charAt(i) - '0'; // Empty string to store lucky number. String ph2 = \"\"; // Loop for performing action // and adding digit to ph2. for (int i = 0; i < n; i++) { // Convert first element into // string and adding to ph2. ph2 += ph1[0]; // Creating new ph1 by subtracting // consecutive element. int ph3[] = new int[ph1.length - 1]; for (int j = 0; j < ph1.length - 1; j++) ph3[j] = Math.abs(ph1[j] - ph1[j + 1]); ph1 = ph3; } // Return lucky number ph2 return ph2; } // Driver code public static void main(String[] args) { // Original number String ph = \"9827218706\"; // Calling phone function. String num = phone(ph, ph.length()); // Print the lucky number System.out.println(num); }} // This code is contributed by Lovely Jain", "e": 2706, "s": 1610, "text": null }, { "code": "# Function to find lucky phone numberdef phone(ph, n): # Converting char to int and storing into array. ph1 = [int(i) for i in ph] # Empty string to store lucky number. ph2 = \"\" # Loop for performing action # and adding digit to ph2. for _ in range(n): # Convert first element into # string and adding to ph2. ph2 += str(ph1[0]) # Creating new ph1 by subtracting # consecutive element. ph1 = [abs(ph1[j]-ph1[j + 1]) \\ for j in range(len(ph1)-1)] # Return lucky number ph2 return ph2 # Original numberph = \"9827218706\" # Calling phone function.num = phone(ph, len(ph)) # Print the lucky numberprint(num)", "e": 3398, "s": 2706, "text": null }, { "code": "<script>// Function to find lucky phone numberfunction phone(ph, n) { // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = \"\" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let temp = [] for (let j = 0; j < ph1.length - 1; j++) { temp.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = temp } // Return lucky number ph2 return ph2} // Original numberlet ph = \"9827218706\" // Calling phone function.let num = phone(ph, ph.length) // Print the lucky numberdocument.write(num) // This code is contributed by gfgking.</script>", "e": 4305, "s": 3398, "text": null }, { "code": null, "e": 4316, "s": 4305, "text": "9154301011" }, { "code": null, "e": 4361, "s": 4316, "text": "Time Complexity: O(N*N)Auxiliary Space: O(N)" }, { "code": null, "e": 4876, "s": 4361, "text": "Efficient Approach: In this approach, no extra space is required for storing elements in the array. First, declare an empty string ph2 in which lucky number will be stored, now create a for loop in which the first character of the string will be added to ph2 and again another for loop to find the absolute difference of consecutive element. Now the string of absolute difference will be assigned to ph1 which is the original number and the same steps will be followed. Follow the steps below to solve the problem:" }, { "code": null, "e": 4931, "s": 4876, "text": "Initialize a string variable ph2[] as an empty string." }, { "code": null, "e": 5282, "s": 4931, "text": "Iterate over the range [0, N) using the variable i and perform the following tasks:Add ph[0] to the variable ph2[].Initialize a string variable S[] as an empty string.Iterate over the range [0, N-1) using the variable j and perform the following tasks:Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[].Set the value of ph as S[]." }, { "code": null, "e": 5315, "s": 5282, "text": "Add ph[0] to the variable ph2[]." }, { "code": null, "e": 5368, "s": 5315, "text": "Initialize a string variable S[] as an empty string." }, { "code": null, "e": 5525, "s": 5368, "text": "Iterate over the range [0, N-1) using the variable j and perform the following tasks:Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[]." }, { "code": null, "e": 5597, "s": 5525, "text": "Add the value of str(abs(int(ph[j])-int(ph[j+1]))) to the variable S[]." }, { "code": null, "e": 5625, "s": 5597, "text": "Set the value of ph as S[]." }, { "code": null, "e": 5699, "s": 5625, "text": "After performing the above steps, print the value of ph2[] as the answer." }, { "code": null, "e": 5750, "s": 5699, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 5754, "s": 5750, "text": "C++" }, { "code": null, "e": 5759, "s": 5754, "text": "Java" }, { "code": null, "e": 5767, "s": 5759, "text": "Python3" }, { "code": null, "e": 5770, "s": 5767, "text": "C#" }, { "code": null, "e": 5781, "s": 5770, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find lucky number.string phone(string ph, int n){ // ph2 is empty string to store lucky number. string ph2 = \"\"; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = \"\"; // Loop to calculate the absolute difference for (int j = 0; j < ph.length(); j++) { int x = abs(int(ph[j]) - int(ph[j + 1])); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2;} // Driver Codeint main(){ // Original number string ph = \"9827218706\"; // Call phone function string num = phone(ph, ph.length()); // Printing lucky number cout << (num);} // This code is contributed by Potta Lokesh", "e": 6725, "s": 5781, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find lucky number. static String phone(String ph, int n) { // ph2 is empty string to store lucky number. String ph2 = \"\"; // For loop for finding lucky number for (int i = 0; i < ph.length(); i++) { // Add first element of ph to ph2 ph2 += ph.charAt(0); // S for storing the difference String S = \"\"; // Loop to calculate the absolute difference for (int j = 0; j < ph.length()-1; j++) { int x = Math.abs(ph.charAt(j) - ph.charAt(j+1)); S += (char)(x + '0'); } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void main(String args[]) { // Original number String ph = \"9827218706\"; // Call phone function String num = phone(ph, ph.length()); // Printing lucky number System.out.println(num); }} // This code is contributed by avijitmondal1998", "e": 7736, "s": 6725, "text": null }, { "code": "# Function to find lucky number.def phone(ph, n): # ph2 is empty string to store lucky number. ph2 = \"\" # For loop for finding lucky number for i in range(len(ph)): # Add first element of ph to ph2 ph2 += ph[0] # S for storing the difference S = \"\" # Loop to calculate the absolute difference for j in range(len(ph)-1): x = abs(int(ph[j])-int(ph[j + 1])) S += str(x) # Assigning S to ph. ph = S # Return the lucky number return ph2 # Original numberph = \"9827218706\" # Call phone functionnum = phone(ph, len(ph)) # Printing lucky numberprint(num)", "e": 8387, "s": 7736, "text": null }, { "code": "// C# code for the above approachusing System;class GFG{ // Function to find lucky number. static string phone(string ph, int n) { // ph2 is empty string to store lucky number. string ph2 = \"\"; // For loop for finding lucky number for (int i = 0; i < ph.Length; i++) { // Add first element of ph to ph2 ph2 += ph[0]; // S for storing the difference string S = \"\"; // Loop to calculate the absolute difference for (int j = 0; j < ph.Length; j++) { int x = Math.Abs(ph[j] - ph[j + 1]); S += x + '0'; } // Assigning S to ph. ph = S; } // Return the lucky number return ph2; } // Driver Code public static void Main() { // Original number string ph = \"9827218706\"; // Call phone function string num = phone(ph, ph.Length); // Printing lucky number Console.WriteLine (num); }} // This code is contributed by ukasp.", "e": 9323, "s": 8387, "text": null }, { "code": "<script>// javascript program for the above approach // Function to find lucky number. function phone( ph , n) { // ph2 is empty string to store lucky number. // Converting char to int and storing into array. let ph1 = []; for (i of ph) ph1.push(i) // Empty string to store lucky number. let ph2 = \"\" // Loop for performing action // and adding digit to ph2. for (let _ = 0; _ < n; _++) { // Convert first element into // string and adding to ph2. ph2 += new String(ph1[0]) // Creating new ph1 by subtracting // consecutive element. let S = [] for (let j = 0; j < ph1.length - 1; j++) { S.push(Math.abs(ph1[j] - ph1[j + 1])) } ph1 = S } // Return the lucky number return ph2; } // Driver Code // Original number var ph = \"9827218706\"; // Call phone function var num = phone(ph, ph.length); // Printing lucky number document.write(num); // This code is contributed by umadevi9616</script>", "e": 10424, "s": 9323, "text": null }, { "code": null, "e": 10435, "s": 10424, "text": "9154301011" }, { "code": null, "e": 10480, "s": 10435, "text": "Time Complexity: O(N*N)Auxiliary Space: O(N)" }, { "code": null, "e": 10494, "s": 10480, "text": "lokeshpotta20" }, { "code": null, "e": 10500, "s": 10494, "text": "ukasp" }, { "code": null, "e": 10508, "s": 10500, "text": "gfgking" }, { "code": null, "e": 10525, "s": 10508, "text": "avijitmondal1998" }, { "code": null, "e": 10537, "s": 10525, "text": "umadevi9616" }, { "code": null, "e": 10551, "s": 10537, "text": "jainlovely450" }, { "code": null, "e": 10566, "s": 10551, "text": "Algo-Geek 2021" }, { "code": null, "e": 10576, "s": 10566, "text": "Algo Geek" }, { "code": null, "e": 10589, "s": 10576, "text": "Mathematical" }, { "code": null, "e": 10607, "s": 10589, "text": "Pattern Searching" }, { "code": null, "e": 10620, "s": 10607, "text": "Mathematical" }, { "code": null, "e": 10638, "s": 10620, "text": "Pattern Searching" } ]
Function that takes an interface type as value and pointer in Golang
17 May, 2020 Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything. Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.). In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type. Now you can create a function that takes interface type as a value and pointer. To understand this concept see the below example: // Golang Function that takes an interface// type as value and pointerpackage main import "fmt" // taking an interfacetype CoursePrice interface { show(int)} // taking a function that accept// CoursePrice interface as an valuefunc show(cp CoursePrice, fee int) { cp.show(fee)} // taking a structtype Dsa struct { Price int} func (c Dsa) show(fee int) { c.Price = fee} // taking a structtype Placement struct { Price int} // function accepting a pointerfunc (p *Placement) show(fee int) { p.Price = fee} // main functionfunc main() { first := Dsa{Price: 2499} second := Placement{Price: 9999} // calling the function show(first, 1999) // calling the function // by passing the address show(&second, 7999) fmt.Println("DSA Course Fee:", first.Price) fmt.Println("Placement100 Course Fee:", second.Price)} Output: DSA Course Fee: 2499 Placement100 Course Fee: 7999 Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? How to iterate over an Array using for loop in Golang? Structures in Golang Loops in Go Language Time Durations in Golang Constants- Go Language Strings in Golang time.Parse() Function in Golang With Examples Go Variables Class and Object in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2020" }, { "code": null, "e": 488, "s": 28, "text": "Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything." }, { "code": null, "e": 853, "s": 488, "text": "Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.)." }, { "code": null, "e": 1317, "s": 853, "text": "In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type." }, { "code": null, "e": 1447, "s": 1317, "text": "Now you can create a function that takes interface type as a value and pointer. To understand this concept see the below example:" }, { "code": "// Golang Function that takes an interface// type as value and pointerpackage main import \"fmt\" // taking an interfacetype CoursePrice interface { show(int)} // taking a function that accept// CoursePrice interface as an valuefunc show(cp CoursePrice, fee int) { cp.show(fee)} // taking a structtype Dsa struct { Price int} func (c Dsa) show(fee int) { c.Price = fee} // taking a structtype Placement struct { Price int} // function accepting a pointerfunc (p *Placement) show(fee int) { p.Price = fee} // main functionfunc main() { first := Dsa{Price: 2499} second := Placement{Price: 9999} // calling the function show(first, 1999) // calling the function // by passing the address show(&second, 7999) fmt.Println(\"DSA Course Fee:\", first.Price) fmt.Println(\"Placement100 Course Fee:\", second.Price)}", "e": 2311, "s": 1447, "text": null }, { "code": null, "e": 2319, "s": 2311, "text": "Output:" }, { "code": null, "e": 2371, "s": 2319, "text": "DSA Course Fee: 2499\nPlacement100 Course Fee: 7999\n" }, { "code": null, "e": 2386, "s": 2371, "text": "Golang-Program" }, { "code": null, "e": 2393, "s": 2386, "text": "Picked" }, { "code": null, "e": 2405, "s": 2393, "text": "Go Language" }, { "code": null, "e": 2503, "s": 2405, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2532, "s": 2503, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2587, "s": 2532, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 2608, "s": 2587, "text": "Structures in Golang" }, { "code": null, "e": 2629, "s": 2608, "text": "Loops in Go Language" }, { "code": null, "e": 2654, "s": 2629, "text": "Time Durations in Golang" }, { "code": null, "e": 2677, "s": 2654, "text": "Constants- Go Language" }, { "code": null, "e": 2695, "s": 2677, "text": "Strings in Golang" }, { "code": null, "e": 2741, "s": 2695, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 2754, "s": 2741, "text": "Go Variables" } ]
gcc command in Linux with examples
21 Nov, 2021 GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++. The most important option required while compiling a source code file is the name of the source program, rest every argument is optional like a warning, debugging, linking libraries, object file etc. The different options of gcc command allow the user to stop the compilation process at different stages. Syntax: gcc [-c|-S|-E] [-std=standard] Example: This will compile the source.c file and give the output file as a.out file which is default name of output file given by gcc compiler, which can be executed using ./a.out gcc source.c Most Useful Options with Examples: Here source.c is the C program code file. -o opt: This will compile the source.c file but instead of giving default name hence executed using ./opt, it will give output file as opt. -o is for output file option. gcc source.c -o opt -Werror: This will compile the source and show the warning if any error is there in the program, -W is for giving warnings. gcc source.c -Werror -o opt -Wall: This will check not only for errors but also for all kinds warning like unused variables errors, it is good practice to use this flag while compiling the code. gcc source.c -Wall -o opt -ggdb3: This command give us permissions to debug the program using gdb which will be described later, -g option is for debugging. gcc -ggdb3 source.c -Wall -o opt -lm : This command link math.h library to our source file, -l option is used for linking particular library, for math.h we use -lm. gcc -Wall source.c -o opt -lm -std=c11 :This command will use the c11 version of standards for compiling the source.c program, which allows to define variable under loop initializations also using newer standards version is preferred. gcc -Wall -std=c11 source.c -o opt -c : This command compile the program and give the object file as output, which is used to make libraries. -v : This option is used for the verbose purpose. sagar0719kumar linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples TCP Server-Client implementation in C 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Docker - COPY Instruction scp command in Linux with Examples Cat command in Linux with examples
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Nov, 2021" }, { "code": null, "e": 512, "s": 52, "text": "GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++. The most important option required while compiling a source code file is the name of the source program, rest every argument is optional like a warning, debugging, linking libraries, object file etc. The different options of gcc command allow the user to stop the compilation process at different stages. " }, { "code": null, "e": 522, "s": 512, "text": "Syntax: " }, { "code": null, "e": 553, "s": 522, "text": "gcc [-c|-S|-E] [-std=standard]" }, { "code": null, "e": 735, "s": 553, "text": "Example: This will compile the source.c file and give the output file as a.out file which is default name of output file given by gcc compiler, which can be executed using ./a.out " }, { "code": null, "e": 748, "s": 735, "text": "gcc source.c" }, { "code": null, "e": 826, "s": 748, "text": "Most Useful Options with Examples: Here source.c is the C program code file. " }, { "code": null, "e": 997, "s": 826, "text": "-o opt: This will compile the source.c file but instead of giving default name hence executed using ./opt, it will give output file as opt. -o is for output file option. " }, { "code": null, "e": 1017, "s": 997, "text": "gcc source.c -o opt" }, { "code": null, "e": 1142, "s": 1017, "text": "-Werror: This will compile the source and show the warning if any error is there in the program, -W is for giving warnings. " }, { "code": null, "e": 1170, "s": 1142, "text": "gcc source.c -Werror -o opt" }, { "code": null, "e": 1338, "s": 1170, "text": "-Wall: This will check not only for errors but also for all kinds warning like unused variables errors, it is good practice to use this flag while compiling the code. " }, { "code": null, "e": 1364, "s": 1338, "text": "gcc source.c -Wall -o opt" }, { "code": null, "e": 1496, "s": 1364, "text": "-ggdb3: This command give us permissions to debug the program using gdb which will be described later, -g option is for debugging. " }, { "code": null, "e": 1529, "s": 1496, "text": "gcc -ggdb3 source.c -Wall -o opt" }, { "code": null, "e": 1662, "s": 1529, "text": "-lm : This command link math.h library to our source file, -l option is used for linking particular library, for math.h we use -lm. " }, { "code": null, "e": 1692, "s": 1662, "text": "gcc -Wall source.c -o opt -lm" }, { "code": null, "e": 1898, "s": 1692, "text": "-std=c11 :This command will use the c11 version of standards for compiling the source.c program, which allows to define variable under loop initializations also using newer standards version is preferred. " }, { "code": null, "e": 1933, "s": 1898, "text": "gcc -Wall -std=c11 source.c -o opt" }, { "code": null, "e": 2041, "s": 1933, "text": "-c : This command compile the program and give the object file as output, which is used to make libraries. " }, { "code": null, "e": 2092, "s": 2041, "text": "-v : This option is used for the verbose purpose. " }, { "code": null, "e": 2107, "s": 2092, "text": "sagar0719kumar" }, { "code": null, "e": 2121, "s": 2107, "text": "linux-command" }, { "code": null, "e": 2141, "s": 2121, "text": "Linux-misc-commands" }, { "code": null, "e": 2148, "s": 2141, "text": "Picked" }, { "code": null, "e": 2159, "s": 2148, "text": "Linux-Unix" }, { "code": null, "e": 2257, "s": 2159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2292, "s": 2257, "text": "tar command in Linux with examples" }, { "code": null, "e": 2328, "s": 2292, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2366, "s": 2328, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2399, "s": 2366, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2437, "s": 2399, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2473, "s": 2437, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2511, "s": 2473, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2537, "s": 2511, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2572, "s": 2537, "text": "scp command in Linux with Examples" } ]
jQuery querySelector() Vs querySelectorAll() Methods
23 Dec, 2020 querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors (‘id’, ‘class’) can be selected. querySelector() Method: The querySelector() method returns the first element within the document which matches a specified CSS selector(s). If multiple elements occurs, then it returns the result for only the first matching element. Syntax: document.querySelector(selectors); It returns the first element which matches the selector. querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s). It returns all the elements that matches with the selector in the form of a static NodeList object which is a collection of nodes. To access each element, we usually use a loop. Each element can be accessed via an index. The index starts with 0. The property length can be used to get the number of elements that matches the specified selector. Syntax: document.querySelectorAll(selectors); It returns all the elements which match the selector. document.querySelectorAll(selectors)[i]; It returns the element at index i in the list. Difference between querySelector() and querySelectorAll() Method: HTML code: HTML <!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:#006600"> GeeksforGeeks </h1> <div class="test-btn">text</div> <div class="test-btn">text</div> <div class="test-btn">text</div> <div class="test-btn">text</div> <button onClick="qselector()"> querySelector </button> <button onClick="qselectorall()"> querySelectorAll </button> <script> function qselector() { document.querySelector(".test-btn") .style.color = "#006600"; } function qselectorall() { var x = document .querySelectorAll(".test-btn"); for (var i = 0; i < x.length; i++) { x[i].style.color = "#006600"; } } </script></body> </html> Output: Before clicking any button: After clicking querySelector button: After clicking querySelectorAll button: Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used. HTML-Misc jQuery-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2020" }, { "code": null, "e": 206, "s": 28, "text": "querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors (‘id’, ‘class’) can be selected." }, { "code": null, "e": 439, "s": 206, "text": "querySelector() Method: The querySelector() method returns the first element within the document which matches a specified CSS selector(s). If multiple elements occurs, then it returns the result for only the first matching element." }, { "code": null, "e": 447, "s": 439, "text": "Syntax:" }, { "code": null, "e": 482, "s": 447, "text": "document.querySelector(selectors);" }, { "code": null, "e": 539, "s": 482, "text": "It returns the first element which matches the selector." }, { "code": null, "e": 1031, "s": 539, "text": "querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s). It returns all the elements that matches with the selector in the form of a static NodeList object which is a collection of nodes. To access each element, we usually use a loop. Each element can be accessed via an index. The index starts with 0. The property length can be used to get the number of elements that matches the specified selector." }, { "code": null, "e": 1039, "s": 1031, "text": "Syntax:" }, { "code": null, "e": 1077, "s": 1039, "text": "document.querySelectorAll(selectors);" }, { "code": null, "e": 1131, "s": 1077, "text": "It returns all the elements which match the selector." }, { "code": null, "e": 1172, "s": 1131, "text": "document.querySelectorAll(selectors)[i];" }, { "code": null, "e": 1219, "s": 1172, "text": "It returns the element at index i in the list." }, { "code": null, "e": 1285, "s": 1219, "text": "Difference between querySelector() and querySelectorAll() Method:" }, { "code": null, "e": 1296, "s": 1285, "text": "HTML code:" }, { "code": null, "e": 1301, "s": 1296, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:#006600\"> GeeksforGeeks </h1> <div class=\"test-btn\">text</div> <div class=\"test-btn\">text</div> <div class=\"test-btn\">text</div> <div class=\"test-btn\">text</div> <button onClick=\"qselector()\"> querySelector </button> <button onClick=\"qselectorall()\"> querySelectorAll </button> <script> function qselector() { document.querySelector(\".test-btn\") .style.color = \"#006600\"; } function qselectorall() { var x = document .querySelectorAll(\".test-btn\"); for (var i = 0; i < x.length; i++) { x[i].style.color = \"#006600\"; } } </script></body> </html>", "e": 2110, "s": 1301, "text": null }, { "code": null, "e": 2118, "s": 2110, "text": "Output:" }, { "code": null, "e": 2146, "s": 2118, "text": "Before clicking any button:" }, { "code": null, "e": 2183, "s": 2146, "text": "After clicking querySelector button:" }, { "code": null, "e": 2223, "s": 2183, "text": "After clicking querySelectorAll button:" }, { "code": null, "e": 2538, "s": 2223, "text": "Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used." }, { "code": null, "e": 2548, "s": 2538, "text": "HTML-Misc" }, { "code": null, "e": 2560, "s": 2548, "text": "jQuery-Misc" }, { "code": null, "e": 2564, "s": 2560, "text": "CSS" }, { "code": null, "e": 2569, "s": 2564, "text": "HTML" }, { "code": null, "e": 2580, "s": 2569, "text": "JavaScript" }, { "code": null, "e": 2597, "s": 2580, "text": "Web Technologies" }, { "code": null, "e": 2602, "s": 2597, "text": "HTML" } ]
K’th Smallest/Largest Element using STL
14 Jun, 2022 Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. Examples: Input : arr[] = {7, 10, 4, 3, 20, 15} k = 2 Output : 4 Smallest element is 3. Second smallest is 4. Input : arr[] = {7, 10, 4, 3, 3, 15} k = 2 Output : 4 Even if there are more than one occurrences of 3, answer should be 4. Input :arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output : 10 We use set in C++ STL. 1) Insert all elements into a set. 2) Traverse the set and print k-th element. CPP // STL based C++ program to find k-th smallest// element.#include <bits/stdc++.h>using namespace std; int kthSmallest(int arr[], int n, int k){ // Insert all elements into the set set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); // Traverse set and print k-th element auto it = s.begin(); for (int i = 0; i < k - 1; i++) it++; return *it;} int main(){ int arr[] = { 12, 3, 5, 7, 3, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << "K'th smallest element is " << kthSmallest(arr, n, k); return 0;} Output: K'th smallest element is 5 Time complexity: O(n Log n). Note that set in STL uses a self-balancing BST internally and therefore time complexity of search and insert operations is O(log n). Auxiliary Space: O(n) where n is size of array Related Posts : K’th Smallest/Largest Element in Unsorted Array | Set 1K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) This article is contributed by Roshan Halwai. 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. technophpfij Order-Statistics STL Arrays Arrays STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 193, "s": 52, "text": "Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. Examples:" }, { "code": null, "e": 508, "s": 193, "text": "Input : arr[] = {7, 10, 4, 3, 20, 15}\n k = 2\nOutput : 4\nSmallest element is 3. Second smallest\nis 4.\n\nInput : arr[] = {7, 10, 4, 3, 3, 15}\n k = 2\nOutput : 4\nEven if there are more than one occurrences\nof 3, answer should be 4.\n\nInput :arr[] = {7, 10, 4, 3, 20, 15}\n k = 4\nOutput : 10" }, { "code": null, "e": 611, "s": 508, "text": "We use set in C++ STL. 1) Insert all elements into a set. 2) Traverse the set and print k-th element. " }, { "code": null, "e": 615, "s": 611, "text": "CPP" }, { "code": "// STL based C++ program to find k-th smallest// element.#include <bits/stdc++.h>using namespace std; int kthSmallest(int arr[], int n, int k){ // Insert all elements into the set set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); // Traverse set and print k-th element auto it = s.begin(); for (int i = 0; i < k - 1; i++) it++; return *it;} int main(){ int arr[] = { 12, 3, 5, 7, 3, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << \"K'th smallest element is \" << kthSmallest(arr, n, k); return 0;}", "e": 1135, "s": 615, "text": null }, { "code": null, "e": 1143, "s": 1135, "text": "Output:" }, { "code": null, "e": 1171, "s": 1143, "text": "K'th smallest element is 5 " }, { "code": null, "e": 1334, "s": 1171, "text": "Time complexity: O(n Log n). Note that set in STL uses a self-balancing BST internally and therefore time complexity of search and insert operations is O(log n). " }, { "code": null, "e": 1381, "s": 1334, "text": "Auxiliary Space: O(n) where n is size of array" }, { "code": null, "e": 1398, "s": 1381, "text": "Related Posts : " }, { "code": null, "e": 2034, "s": 1398, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 1K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) This article is contributed by Roshan Halwai. 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": 2047, "s": 2034, "text": "technophpfij" }, { "code": null, "e": 2064, "s": 2047, "text": "Order-Statistics" }, { "code": null, "e": 2068, "s": 2064, "text": "STL" }, { "code": null, "e": 2075, "s": 2068, "text": "Arrays" }, { "code": null, "e": 2082, "s": 2075, "text": "Arrays" }, { "code": null, "e": 2086, "s": 2082, "text": "STL" } ]
Sort an Array which contain 1 to N values in O(N) using Cycle Sort
01 Aug, 2021 Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] – 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct position, then swap arr[2] with arr[arr[2] – 1] Now the array becomes: arr[] = {1, 2, 3, 4, 5} Now the array is sorted.Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 1 2 3 4 5 6 Explanation: The array is already sorted. Approach: This problem can be solved using Greedy Approach. Below are the steps: Traverse the given array arr[]. If the current element is not at the correct position i.e., arr[i] is not equal to i+1 then, swap the current element with the element with its correct position. For Example: Let arr[] = {2, 1, 4, 5, 3} Since, arr[0] = 2, which is not at it’s correct position 1. Then swap this element with it’s correct position, i.e., swap(arr[0], arr[2-1]) Then array becomes: arr[] = {1, 2, 4, 5, 3} If the current element is at the correct position then check for the next element. Repeat the above steps until we reach the end of the array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include "bits/stdc++.h"using namespace std; // Function to swap two a & b valuevoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to print array elementvoid printArray(int arr[], int N){ // Traverse the array for (int i = 0; i < N; i++) { cout << arr[i] << ' '; }} // Function to sort the array in O(N)void sortArray(int arr[], int N){ // Traverse the array for (int i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { swap(&arr[i], &arr[arr[i] - 1]); } }} // Driver Codeint main(){ int arr[] = { 2, 1, 5, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N); return 0;} // Java program for the above approachclass Main{ // Function to print array elementpublic static void printArray(int arr[], int N){ // Traverse the array for(int i = 0; i < N; i++) { System.out.print(arr[i] + " "); }} // Function to sort the array in O(N)public static void sortArray(int arr[], int N){ // Traverse the array for(int i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { // Swap the value of // arr[i] and arr[arr[i]-1] int temp1 = arr[i]; int temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Code public static void main(String[] args){ int arr[] = { 2, 1, 5, 3, 4 }; int N = arr.length; // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N);}} // This code is contributed by divyeshrabadiya07 # Python3 program for the above approach # Function to print array elementdef printArray(arr, N): # Traverse the array for i in range(N): print(arr[i], end = ' ') # Function to sort the array in O(N)def sortArray(arr, N): i = 0 # Traverse the array while i < N: # If the current element is # at correct position if arr[i] == i + 1: i += 1 # Else swap the current element # with it's correct position else: # Swap the value of # arr[i] and arr[arr[i]-1] temp1 = arr[i] temp2 = arr[arr[i] - 1] arr[i] = temp2 arr[temp1 - 1] = temp1 # Driver codeif __name__=='__main__': arr = [ 2, 1, 5, 3, 4 ] N = len(arr) # Function call to sort the array sortArray(arr, N) # Function call to print the array printArray(arr, N) # This code is contributed by rutvik_56 // C# program for the above approachusing System;class GFG{ // Function to print array elementpublic static void printArray(int []arr, int N){ // Traverse the array for(int i = 0; i < N; i++) { Console.Write(arr[i] + " "); }} // Function to sort the array in O(N)public static void sortArray(int []arr, int N){ // Traverse the array for(int i = 0; i < N; ) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { // Swap the value of // arr[i] and arr[arr[i]-1] int temp1 = arr[i]; int temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Code public static void Main(String[] args){ int []arr = {2, 1, 5, 3, 4}; int N = arr.Length; // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N);}} // This code is contributed by shikhasingrajput <script> // Javascript program for the above approach // Function to print array elementfunction printArray(arr, N){ // Traverse the array for (var i = 0; i < N; i++) { document.write( arr[i] + ' '); }} // Function to sort the array in O(N)function sortArray(arr, N){ // Traverse the array for (var i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { var temp1 = arr[i]; var temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Codevar arr = [ 2, 1, 5, 3, 4 ];var N = arr.length; // Function call to sort the arraysortArray(arr, N); // Function call to print the arrayprintArray(arr, N); // This code is contributed by noob2000.</script> 1 2 3 4 5 Time Complexity: O(N), where N is the length of the array. Auxiliary Space: O(1) divyeshrabadiya07 rutvik_56 shikhasingrajput noob2000 parthsikkah704 Natural Numbers Algorithms Arrays Sorting Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Hash Functions and list/types of Hash functions How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Minimum cost to reach the top of the floor by climbing stairs Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Aug, 2021" }, { "code": null, "e": 183, "s": 52, "text": "Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: " }, { "code": null, "e": 621, "s": 183, "text": "Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] – 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct position, then swap arr[2] with arr[arr[2] – 1] Now the array becomes: arr[] = {1, 2, 3, 4, 5} Now the array is sorted.Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 1 2 3 4 5 6 Explanation: The array is already sorted. " }, { "code": null, "e": 704, "s": 621, "text": "Approach: This problem can be solved using Greedy Approach. Below are the steps: " }, { "code": null, "e": 736, "s": 704, "text": "Traverse the given array arr[]." }, { "code": null, "e": 913, "s": 736, "text": "If the current element is not at the correct position i.e., arr[i] is not equal to i+1 then, swap the current element with the element with its correct position. For Example: " }, { "code": null, "e": 1127, "s": 913, "text": "Let arr[] = {2, 1, 4, 5, 3} Since, arr[0] = 2, which is not at it’s correct position 1. Then swap this element with it’s correct position, i.e., swap(arr[0], arr[2-1]) Then array becomes: arr[] = {1, 2, 4, 5, 3} " }, { "code": null, "e": 1210, "s": 1127, "text": "If the current element is at the correct position then check for the next element." }, { "code": null, "e": 1270, "s": 1210, "text": "Repeat the above steps until we reach the end of the array." }, { "code": null, "e": 1322, "s": 1270, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1326, "s": 1322, "text": "C++" }, { "code": null, "e": 1331, "s": 1326, "text": "Java" }, { "code": null, "e": 1339, "s": 1331, "text": "Python3" }, { "code": null, "e": 1342, "s": 1339, "text": "C#" }, { "code": null, "e": 1353, "s": 1342, "text": "Javascript" }, { "code": "// C++ program for the above approach #include \"bits/stdc++.h\"using namespace std; // Function to swap two a & b valuevoid swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} // Function to print array elementvoid printArray(int arr[], int N){ // Traverse the array for (int i = 0; i < N; i++) { cout << arr[i] << ' '; }} // Function to sort the array in O(N)void sortArray(int arr[], int N){ // Traverse the array for (int i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { swap(&arr[i], &arr[arr[i] - 1]); } }} // Driver Codeint main(){ int arr[] = { 2, 1, 5, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N); return 0;}", "e": 2346, "s": 1353, "text": null }, { "code": "// Java program for the above approachclass Main{ // Function to print array elementpublic static void printArray(int arr[], int N){ // Traverse the array for(int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); }} // Function to sort the array in O(N)public static void sortArray(int arr[], int N){ // Traverse the array for(int i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { // Swap the value of // arr[i] and arr[arr[i]-1] int temp1 = arr[i]; int temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Code public static void main(String[] args){ int arr[] = { 2, 1, 5, 3, 4 }; int N = arr.length; // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N);}} // This code is contributed by divyeshrabadiya07", "e": 3464, "s": 2346, "text": null }, { "code": "# Python3 program for the above approach # Function to print array elementdef printArray(arr, N): # Traverse the array for i in range(N): print(arr[i], end = ' ') # Function to sort the array in O(N)def sortArray(arr, N): i = 0 # Traverse the array while i < N: # If the current element is # at correct position if arr[i] == i + 1: i += 1 # Else swap the current element # with it's correct position else: # Swap the value of # arr[i] and arr[arr[i]-1] temp1 = arr[i] temp2 = arr[arr[i] - 1] arr[i] = temp2 arr[temp1 - 1] = temp1 # Driver codeif __name__=='__main__': arr = [ 2, 1, 5, 3, 4 ] N = len(arr) # Function call to sort the array sortArray(arr, N) # Function call to print the array printArray(arr, N) # This code is contributed by rutvik_56 ", "e": 4450, "s": 3464, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to print array elementpublic static void printArray(int []arr, int N){ // Traverse the array for(int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); }} // Function to sort the array in O(N)public static void sortArray(int []arr, int N){ // Traverse the array for(int i = 0; i < N; ) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { // Swap the value of // arr[i] and arr[arr[i]-1] int temp1 = arr[i]; int temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Code public static void Main(String[] args){ int []arr = {2, 1, 5, 3, 4}; int N = arr.Length; // Function call to sort the array sortArray(arr, N); // Function call to print the array printArray(arr, N);}} // This code is contributed by shikhasingrajput", "e": 5569, "s": 4450, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to print array elementfunction printArray(arr, N){ // Traverse the array for (var i = 0; i < N; i++) { document.write( arr[i] + ' '); }} // Function to sort the array in O(N)function sortArray(arr, N){ // Traverse the array for (var i = 0; i < N;) { // If the current element is // at correct position if (arr[i] == i + 1) { i++; } // Else swap the current element // with it's correct position else { var temp1 = arr[i]; var temp2 = arr[arr[i] - 1]; arr[i] = temp2; arr[temp1 - 1] = temp1; } }} // Driver Codevar arr = [ 2, 1, 5, 3, 4 ];var N = arr.length; // Function call to sort the arraysortArray(arr, N); // Function call to print the arrayprintArray(arr, N); // This code is contributed by noob2000.</script>", "e": 6489, "s": 5569, "text": null }, { "code": null, "e": 6499, "s": 6489, "text": "1 2 3 4 5" }, { "code": null, "e": 6583, "s": 6501, "text": "Time Complexity: O(N), where N is the length of the array. Auxiliary Space: O(1) " }, { "code": null, "e": 6601, "s": 6583, "text": "divyeshrabadiya07" }, { "code": null, "e": 6611, "s": 6601, "text": "rutvik_56" }, { "code": null, "e": 6628, "s": 6611, "text": "shikhasingrajput" }, { "code": null, "e": 6637, "s": 6628, "text": "noob2000" }, { "code": null, "e": 6652, "s": 6637, "text": "parthsikkah704" }, { "code": null, "e": 6668, "s": 6652, "text": "Natural Numbers" }, { "code": null, "e": 6679, "s": 6668, "text": "Algorithms" }, { "code": null, "e": 6686, "s": 6679, "text": "Arrays" }, { "code": null, "e": 6694, "s": 6686, "text": "Sorting" }, { "code": null, "e": 6701, "s": 6694, "text": "Arrays" }, { "code": null, "e": 6709, "s": 6701, "text": "Sorting" }, { "code": null, "e": 6720, "s": 6709, "text": "Algorithms" }, { "code": null, "e": 6818, "s": 6720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6885, "s": 6818, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 6933, "s": 6885, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 6960, "s": 6933, "text": "How to Start Learning DSA?" }, { "code": null, "e": 7003, "s": 6960, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 7065, "s": 7003, "text": "Minimum cost to reach the top of the floor by climbing stairs" }, { "code": null, "e": 7080, "s": 7065, "text": "Arrays in Java" }, { "code": null, "e": 7096, "s": 7080, "text": "Arrays in C/C++" }, { "code": null, "e": 7142, "s": 7096, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7210, "s": 7142, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
Python assert keyword
03 Mar, 2022 Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code, so that failure of these doesn’t allow the code to execute further. In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error. Let us look at the flowchart of the assertion. In python, assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. Syntax : assert condition, error_message(optional) Parameters : condition : The boolean condition returning true or false. error_message : The optional argument to be printed in console in case of AssertionError Returns : Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. Python3 # Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print("The value of a / b is : ")assert b != 0print(a / b) Output : AssertionError: Python3 # Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print("The value of a / b is : ")assert b != 0, "Zero Division Error"print(a / b) Output: AssertionError: Zero Division Error This has a much greater utility in Testing and Quality Assurance role in any development domain. Different types of assertions are used depending upon the application. Below is the simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch. Python3 # Python 3 code to demonstrate# working of assert# Application # initializing list of foods temperaturesbatch = [ 40, 26, 39, 30, 25, 21] # initializing cut temperaturecut = 26 # using assert to check for temperature greater than cutfor i in batch: assert i >= 26, "Batch is Rejected" print (str(i) + " is O.K" ) Output : 40 is O.K 26 is O.K 39 is O.K 30 is O.K Runtime Exception : AssertionError: Batch is Rejected nikhilaggarwal3 ignorantadventurer python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Mar, 2022" }, { "code": null, "e": 338, "s": 54, "text": "Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code, so that failure of these doesn’t allow the code to execute further. " }, { "code": null, "e": 624, "s": 338, "text": "In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error." }, { "code": null, "e": 671, "s": 624, "text": "Let us look at the flowchart of the assertion." }, { "code": null, "e": 977, "s": 671, "text": "In python, assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. " }, { "code": null, "e": 1029, "s": 977, "text": "Syntax : assert condition, error_message(optional) " }, { "code": null, "e": 1190, "s": 1029, "text": "Parameters : condition : The boolean condition returning true or false. error_message : The optional argument to be printed in console in case of AssertionError" }, { "code": null, "e": 1316, "s": 1190, "text": "Returns : Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. " }, { "code": null, "e": 1324, "s": 1316, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print(\"The value of a / b is : \")assert b != 0print(a / b)", "e": 1494, "s": 1324, "text": null }, { "code": null, "e": 1504, "s": 1494, "text": "Output : " }, { "code": null, "e": 1521, "s": 1504, "text": "AssertionError: " }, { "code": null, "e": 1529, "s": 1521, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print(\"The value of a / b is : \")assert b != 0, \"Zero Division Error\"print(a / b)", "e": 1722, "s": 1529, "text": null }, { "code": null, "e": 1730, "s": 1722, "text": "Output:" }, { "code": null, "e": 1766, "s": 1730, "text": "AssertionError: Zero Division Error" }, { "code": null, "e": 2080, "s": 1766, "text": "This has a much greater utility in Testing and Quality Assurance role in any development domain. Different types of assertions are used depending upon the application. Below is the simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch." }, { "code": null, "e": 2088, "s": 2080, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# working of assert# Application # initializing list of foods temperaturesbatch = [ 40, 26, 39, 30, 25, 21] # initializing cut temperaturecut = 26 # using assert to check for temperature greater than cutfor i in batch: assert i >= 26, \"Batch is Rejected\" print (str(i) + \" is O.K\" )", "e": 2407, "s": 2088, "text": null }, { "code": null, "e": 2417, "s": 2407, "text": "Output : " }, { "code": null, "e": 2457, "s": 2417, "text": "40 is O.K\n26 is O.K\n39 is O.K\n30 is O.K" }, { "code": null, "e": 2478, "s": 2457, "text": "Runtime Exception : " }, { "code": null, "e": 2512, "s": 2478, "text": "AssertionError: Batch is Rejected" }, { "code": null, "e": 2528, "s": 2512, "text": "nikhilaggarwal3" }, { "code": null, "e": 2547, "s": 2528, "text": "ignorantadventurer" }, { "code": null, "e": 2561, "s": 2547, "text": "python-basics" }, { "code": null, "e": 2568, "s": 2561, "text": "Python" }, { "code": null, "e": 2666, "s": 2568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2684, "s": 2666, "text": "Python Dictionary" }, { "code": null, "e": 2726, "s": 2684, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2748, "s": 2726, "text": "Enumerate() in Python" }, { "code": null, "e": 2774, "s": 2748, "text": "Python String | replace()" }, { "code": null, "e": 2806, "s": 2774, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2835, "s": 2806, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2862, "s": 2835, "text": "Python Classes and Objects" }, { "code": null, "e": 2898, "s": 2862, "text": "Convert integer to string in Python" }, { "code": null, "e": 2929, "s": 2898, "text": "Python | os.path.join() method" } ]
How to add column sum as new column in PySpark dataframe ?
25 Aug, 2021 In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let’s discuss the various methods how we add sum as new columns But first, let’s create Dataframe for Demonstration Python3 # import SparkSession from the pysparkfrom pyspark.sql import SparkSession # build and create the SparkSession# with name "sum as new_col"spark = SparkSession.builder.appName("sum as new_col").getOrCreate() # Creating the Spark DataFramedata = spark.createDataFrame([('x', 5, 3, 7), ('Y', 3, 3, 6), ('Z', 5, 2, 6)], ['A', 'B', 'C', 'D']) # Print the schema of the DataFrame by# printSchema()data.printSchema() # Showing the DataFramedata.show() Output: Now we will see the different methods about how to add new columns in spark Dataframe . In this method, we will define the function which will take the column name as arguments and return the total sum of rows. By using UDF(User-defined Functions) Method which is used to make reusable function in spark. This function allows us to create the new function as per our requirements that’s why this is also called a used defined function. Now we define the datatype of the udf function and create the functions which will return the values which is the sum of all values in the row. Python3 # import the functions as F from pyspark.sqlimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType # define the sum_coldef sum_col(b, c, d): col_sum = b+c+d return col_sum # integer datatype is definednew_f = F.udf(sum_col, IntegerType()) # calling and creating the new# col as udf_method_sumdf_col1 = data.withColumn("Udf_method_sum", new_f("B", "C", "D")) # Showing and printing the schema of the Dataframedf_col1.printSchema()df_col1.show() Output: By using expr(str) the function which will take expressions argument as a string. There is another function in pyspark that will take mathematical expression as an argument in the form of string. For example, if you want the sum of rows then pass the arguments as ‘n1+n2+n3+n4.......’ where n1,n2,n3... are the column names Python3 # import expr from the functionsfrom pyspark.sql.functions import expr # create the new column as by withcolumn# by giving argument as# col_name ='expression_method_sum'# and expr() function which# will take expressions argument as stringdf_col1 = df_col1.withColumn('expression_method_sum', expr("B+C + D")) # Showing and printing the schema of# the Dataframedf_col1.printSchema()df_col1.show() Output: In this method first, we have to create the temp view of the table with the help of createTempView we can create the temporary view. The life of this temp is upto the life of the sparkSession Then after creating the table select the table by SQL clause which will take all the values as a string Python3 # Creating the temporary view# of the DataFrame as temp.df_col1 = df_col1.createTempView("temp") # By using sql clause creating# new columns as sql_methoddf_col1=spark.sql('select *, B+C+D as sql_method from temp') # Printing the schema of the dataFrame# and showing the DataFramedf_col1.printScheam()df_col1.show() Output: Select table by using select() method and pass the arguments first one is the column name , or “*” for selecting the whole table and the second argument pass the names of the columns for the addition, and alias() function is used to give the name of the newly created column. Python3 # select everything from table df_col1 and# create new sum column as " select_method_sum".df_col1 = df_col1.select('*', (df_col1["B"]+df_col1["C"]+df_col1['D']). alias("select_method_sum")) # Showing the schema and tabledf_col1.printSchema()df_col1.show() Output: WithColumn() is a transformation function of the dataframe which is used for changing values, change datatypes, and creating new columns from existing ones. This function will arguments as new column name and column name for the summation. Python3 # by using withcolumn functiondf_col1 = df_col1.withColumn('withcolum_Sum', data['B']+data['C']+data['D']) # Showing and printing the schema# of the Dataframedf_col1.printSchema()df_col1.show() Output: arorakashish0911 simranarora5sos Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Aug, 2021" }, { "code": null, "e": 353, "s": 52, "text": "In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let’s discuss the various methods how we add sum as new columns " }, { "code": null, "e": 405, "s": 353, "text": "But first, let’s create Dataframe for Demonstration" }, { "code": null, "e": 413, "s": 405, "text": "Python3" }, { "code": "# import SparkSession from the pysparkfrom pyspark.sql import SparkSession # build and create the SparkSession# with name \"sum as new_col\"spark = SparkSession.builder.appName(\"sum as new_col\").getOrCreate() # Creating the Spark DataFramedata = spark.createDataFrame([('x', 5, 3, 7), ('Y', 3, 3, 6), ('Z', 5, 2, 6)], ['A', 'B', 'C', 'D']) # Print the schema of the DataFrame by# printSchema()data.printSchema() # Showing the DataFramedata.show()", "e": 945, "s": 413, "text": null }, { "code": null, "e": 953, "s": 945, "text": "Output:" }, { "code": null, "e": 1041, "s": 953, "text": "Now we will see the different methods about how to add new columns in spark Dataframe ." }, { "code": null, "e": 1389, "s": 1041, "text": "In this method, we will define the function which will take the column name as arguments and return the total sum of rows. By using UDF(User-defined Functions) Method which is used to make reusable function in spark. This function allows us to create the new function as per our requirements that’s why this is also called a used defined function." }, { "code": null, "e": 1533, "s": 1389, "text": "Now we define the datatype of the udf function and create the functions which will return the values which is the sum of all values in the row." }, { "code": null, "e": 1541, "s": 1533, "text": "Python3" }, { "code": "# import the functions as F from pyspark.sqlimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType # define the sum_coldef sum_col(b, c, d): col_sum = b+c+d return col_sum # integer datatype is definednew_f = F.udf(sum_col, IntegerType()) # calling and creating the new# col as udf_method_sumdf_col1 = data.withColumn(\"Udf_method_sum\", new_f(\"B\", \"C\", \"D\")) # Showing and printing the schema of the Dataframedf_col1.printSchema()df_col1.show()", "e": 2038, "s": 1541, "text": null }, { "code": null, "e": 2046, "s": 2038, "text": "Output:" }, { "code": null, "e": 2370, "s": 2046, "text": "By using expr(str) the function which will take expressions argument as a string. There is another function in pyspark that will take mathematical expression as an argument in the form of string. For example, if you want the sum of rows then pass the arguments as ‘n1+n2+n3+n4.......’ where n1,n2,n3... are the column names" }, { "code": null, "e": 2378, "s": 2370, "text": "Python3" }, { "code": "# import expr from the functionsfrom pyspark.sql.functions import expr # create the new column as by withcolumn# by giving argument as# col_name ='expression_method_sum'# and expr() function which# will take expressions argument as stringdf_col1 = df_col1.withColumn('expression_method_sum', expr(\"B+C + D\")) # Showing and printing the schema of# the Dataframedf_col1.printSchema()df_col1.show()", "e": 2805, "s": 2378, "text": null }, { "code": null, "e": 2814, "s": 2805, "text": "Output: " }, { "code": null, "e": 3006, "s": 2814, "text": "In this method first, we have to create the temp view of the table with the help of createTempView we can create the temporary view. The life of this temp is upto the life of the sparkSession" }, { "code": null, "e": 3112, "s": 3006, "text": "Then after creating the table select the table by SQL clause which will take all the values as a string " }, { "code": null, "e": 3120, "s": 3112, "text": "Python3" }, { "code": "# Creating the temporary view# of the DataFrame as temp.df_col1 = df_col1.createTempView(\"temp\") # By using sql clause creating# new columns as sql_methoddf_col1=spark.sql('select *, B+C+D as sql_method from temp') # Printing the schema of the dataFrame# and showing the DataFramedf_col1.printScheam()df_col1.show()", "e": 3436, "s": 3120, "text": null }, { "code": null, "e": 3445, "s": 3436, "text": "Output: " }, { "code": null, "e": 3721, "s": 3445, "text": "Select table by using select() method and pass the arguments first one is the column name , or “*” for selecting the whole table and the second argument pass the names of the columns for the addition, and alias() function is used to give the name of the newly created column." }, { "code": null, "e": 3729, "s": 3721, "text": "Python3" }, { "code": "# select everything from table df_col1 and# create new sum column as \" select_method_sum\".df_col1 = df_col1.select('*', (df_col1[\"B\"]+df_col1[\"C\"]+df_col1['D']). alias(\"select_method_sum\")) # Showing the schema and tabledf_col1.printSchema()df_col1.show()", "e": 4034, "s": 3729, "text": null }, { "code": null, "e": 4042, "s": 4034, "text": "Output:" }, { "code": null, "e": 4200, "s": 4042, "text": " WithColumn() is a transformation function of the dataframe which is used for changing values, change datatypes, and creating new columns from existing ones." }, { "code": null, "e": 4283, "s": 4200, "text": "This function will arguments as new column name and column name for the summation." }, { "code": null, "e": 4291, "s": 4283, "text": "Python3" }, { "code": "# by using withcolumn functiondf_col1 = df_col1.withColumn('withcolum_Sum', data['B']+data['C']+data['D']) # Showing and printing the schema# of the Dataframedf_col1.printSchema()df_col1.show()", "e": 4513, "s": 4291, "text": null }, { "code": null, "e": 4522, "s": 4513, "text": "Output: " }, { "code": null, "e": 4541, "s": 4524, "text": "arorakashish0911" }, { "code": null, "e": 4557, "s": 4541, "text": "simranarora5sos" }, { "code": null, "e": 4564, "s": 4557, "text": "Picked" }, { "code": null, "e": 4579, "s": 4564, "text": "Python-Pyspark" }, { "code": null, "e": 4586, "s": 4579, "text": "Python" }, { "code": null, "e": 4684, "s": 4586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4726, "s": 4684, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4748, "s": 4726, "text": "Enumerate() in Python" }, { "code": null, "e": 4783, "s": 4748, "text": "Read a file line by line in Python" }, { "code": null, "e": 4809, "s": 4783, "text": "Python String | replace()" }, { "code": null, "e": 4841, "s": 4809, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4870, "s": 4841, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4897, "s": 4870, "text": "Python Classes and Objects" }, { "code": null, "e": 4918, "s": 4897, "text": "Python OOPs Concepts" }, { "code": null, "e": 4948, "s": 4918, "text": "Iterate over a list in Python" } ]
Find the concentration of a solution using given Mass and Volume
17 Mar, 2021 Given two values M and V representing the mass of solute and volume of a solution, the task is to calculate the concentration of the solution.Examples: Input: M = 100.00, V = 500.00 Output: 200 Explaination: C = 1000 * (100 / 500) The concentration of solution is 200Input: M = 1.00 V = 1000.00 Output: 1 Approach: The concentration of a solution is defined as the mass of solute in (gram) per liter of solution. Mathematically: C = 1000 * (M / V) Where M = Mass of solute and V = Volume of solution. Hence, in order to solve the problem, follow the steps below: Calculate the concentration of solution using the formula C = 1000* (M / V).Print the result. Calculate the concentration of solution using the formula C = 1000* (M / V). Print the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find// concentration of a solution// using given Mass and Volume #include <bits/stdc++.h>using namespace std; // Function to calculate// concentration from the// given mass of solute and// volume of a solutiondouble get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver Programint main(){ double mass, volume; mass = 100.00; volume = 500.00; cout << get_concentration(mass, volume); return 0;} // Java program to find concentration// of a solution using given Mass// and Volumeclass GFG{ // Function to calculate// concentration from the// given mass of solute and// volume of a solutionstatic double get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver codepublic static void main(String[] args){ double mass, volume; mass = 100.00; volume = 500.00; System.out.println(get_concentration(mass, volume));}} // This code is contributed by Ritik Bansal # Python3 program to find# concentration of a solution# using given Mass and Volume # Function to calculate# concentration from the# given mass of solute and# volume of a solutiondef get_concentration(mass, volume): if (volume == 0): return -1; else: return (mass / volume) * 1000; # Driver codemass = 100.00;volume = 500.00; print(get_concentration(mass, volume)) # This code is contributed by Pratima Pandey // C# program to find concentration// of a solution using given Mass// and Volumeusing System;class GFG{ // Function to calculate// concentration from the// given mass of solute and// volume of a solutionstatic double get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver codepublic static void Main(){ double mass, volume; mass = 100.00; volume = 500.00; Console.Write(get_concentration(mass, volume));}} // This code is contributed by rock_cool <script>// javascript program to find// concentration of a solution// using given Mass and Volume // Function to calculate// concentration from the// given mass of solute and// volume of a solutionfunction get_concentration( mass, volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver Program let mass, volume; mass = 100.00; volume = 500.00; document.write(get_concentration(mass, volume)); // This code is contributed by todaysgaurav </script> 200 Time Complexity: O(1) Auxiliary Space: O(1) bansal_rtk_ rock_cool dewantipandeydp todaysgaurav Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Mar, 2021" }, { "code": null, "e": 182, "s": 28, "text": "Given two values M and V representing the mass of solute and volume of a solution, the task is to calculate the concentration of the solution.Examples: " }, { "code": null, "e": 337, "s": 182, "text": "Input: M = 100.00, V = 500.00 Output: 200 Explaination: C = 1000 * (100 / 500) The concentration of solution is 200Input: M = 1.00 V = 1000.00 Output: 1 " }, { "code": null, "e": 465, "s": 339, "text": "Approach: The concentration of a solution is defined as the mass of solute in (gram) per liter of solution. Mathematically: " }, { "code": null, "e": 537, "s": 465, "text": "C = 1000 * (M / V) Where M = Mass of solute and V = Volume of solution." }, { "code": null, "e": 602, "s": 537, "text": " Hence, in order to solve the problem, follow the steps below: " }, { "code": null, "e": 696, "s": 602, "text": "Calculate the concentration of solution using the formula C = 1000* (M / V).Print the result." }, { "code": null, "e": 773, "s": 696, "text": "Calculate the concentration of solution using the formula C = 1000* (M / V)." }, { "code": null, "e": 791, "s": 773, "text": "Print the result." }, { "code": null, "e": 844, "s": 791, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 848, "s": 844, "text": "C++" }, { "code": null, "e": 853, "s": 848, "text": "Java" }, { "code": null, "e": 861, "s": 853, "text": "Python3" }, { "code": null, "e": 864, "s": 861, "text": "C#" }, { "code": null, "e": 875, "s": 864, "text": "Javascript" }, { "code": "// C++ program to find// concentration of a solution// using given Mass and Volume #include <bits/stdc++.h>using namespace std; // Function to calculate// concentration from the// given mass of solute and// volume of a solutiondouble get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver Programint main(){ double mass, volume; mass = 100.00; volume = 500.00; cout << get_concentration(mass, volume); return 0;}", "e": 1457, "s": 875, "text": null }, { "code": "// Java program to find concentration// of a solution using given Mass// and Volumeclass GFG{ // Function to calculate// concentration from the// given mass of solute and// volume of a solutionstatic double get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver codepublic static void main(String[] args){ double mass, volume; mass = 100.00; volume = 500.00; System.out.println(get_concentration(mass, volume));}} // This code is contributed by Ritik Bansal", "e": 2090, "s": 1457, "text": null }, { "code": "# Python3 program to find# concentration of a solution# using given Mass and Volume # Function to calculate# concentration from the# given mass of solute and# volume of a solutiondef get_concentration(mass, volume): if (volume == 0): return -1; else: return (mass / volume) * 1000; # Driver codemass = 100.00;volume = 500.00; print(get_concentration(mass, volume)) # This code is contributed by Pratima Pandey", "e": 2529, "s": 2090, "text": null }, { "code": "// C# program to find concentration// of a solution using given Mass// and Volumeusing System;class GFG{ // Function to calculate// concentration from the// given mass of solute and// volume of a solutionstatic double get_concentration(double mass, double volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver codepublic static void Main(){ double mass, volume; mass = 100.00; volume = 500.00; Console.Write(get_concentration(mass, volume));}} // This code is contributed by rock_cool", "e": 3147, "s": 2529, "text": null }, { "code": "<script>// javascript program to find// concentration of a solution// using given Mass and Volume // Function to calculate// concentration from the// given mass of solute and// volume of a solutionfunction get_concentration( mass, volume){ if (volume == 0) return -1; else return (mass / volume) * 1000;} // Driver Program let mass, volume; mass = 100.00; volume = 500.00; document.write(get_concentration(mass, volume)); // This code is contributed by todaysgaurav </script>", "e": 3700, "s": 3147, "text": null }, { "code": null, "e": 3704, "s": 3700, "text": "200" }, { "code": null, "e": 3751, "s": 3706, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 3763, "s": 3751, "text": "bansal_rtk_" }, { "code": null, "e": 3773, "s": 3763, "text": "rock_cool" }, { "code": null, "e": 3789, "s": 3773, "text": "dewantipandeydp" }, { "code": null, "e": 3802, "s": 3789, "text": "todaysgaurav" }, { "code": null, "e": 3815, "s": 3802, "text": "Mathematical" }, { "code": null, "e": 3834, "s": 3815, "text": "School Programming" }, { "code": null, "e": 3847, "s": 3834, "text": "Mathematical" } ]
Interactive Charts using Pywedge package
29 Jun, 2021 In Machine Learning and Data Science, one of the toughest jobs is to understand the raw data and make it fit for applying different models over it to make predictions. For understanding purpose, we make use of different processes like checking statistical figures such as mean, median, mode, finding the relation between features, looking at the distribution of certain features, etc. This all things are often clubbed under the term Exploratory Data Analysis (EDA). According to experienced ML and DS practitioners, EDA is one of the most valuable tasks and its importance cannot be overlooked when it comes to analyzing the dataset. It helps the practitioners to choose the appropriate data pre-processing techniques. Checking the statistical figures is well and good but what’s better than visualizing these stats pictorially, it often said that pictures are a more powerful tool for understanding rather than just numerical figures. We can come up with the clearer understanding of the data visually by making different charts. In machine learning and data science, we use different types of charts/plots in order to visualize different patterns among the features some of which are: Histogram, Bar plots, Box plots, Pair plots, Pie charts, Violin plots, etc. But writing codes manually for all these plots/graphs can seem to be a tiring process and also we are more prone to inaccuracies and errors/bugs in the code. So, here comes our lifesaver, a python package that does the tasks of plotting these graphs easily and efficiently without any such bugs in the code. In this article, we will be reading about making interactive plots/charts using pywedge python package. Pywedge is an open-source python package that can be used for automating most of the machine learning problem-solving task. It also offers us features to plot interactive graphs using just a few lines of code. Pywedge library has a make_charts method that offers us to make 8 different types of charts which are named as follows: Scatter plot Pie chart Bar Plot Violin plot Box plot Distribution plot Histogram Correlation plot Let’s see an example of how can we use pywedge library to draw interactive plots: Python import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings("ignore") df = pd.read_csv("https://www.shortto.com/WineDataset",sep=";") After loading the dataset, we will look at how the dataset looks like, this can be seen using the head method to print the top 5 rows in the dataset: Python df.head() Python print("Shape of our dataframe is: ",df.shape) Shape of our dataframe is: (1599, 12) So, as we can notice we have in total 1599 rows and 11 features in the dataset along with one target feature named ‘quality’. It is always better to check out some stats about our dataset and we can do it using the describe() method as: Python df.describe() Statistics about the dataset By looking just at the stats, we can infer The mean value is greater than the median value in each of the columns, for example, mean value of pH is 3.311113 whereas median value is 3.310000. Similarly, the mean of alcohol is 10.422 as compared to median which is 10.20. We can notice a large difference between 75th percentile value and max values of predictors “residual sugar”, “free sulfur dioxide”, “total sulfur dioxide”. This indicates that some values of these 3 variables lie much farther from the general range of values( up to 75th %tile). Thus, we can conclude that there are extreme values i.e., Outliers in our dataset. Python df.rename(columns={'ficxed acidity':'fixed_acidity','citric acid':'citric_acid', 'volatile acidity':'volatile_acidity','residual sugar':'residual_sugar', 'free sulphur dioxide':'free_sulphur_dioxide', 'total sulphur dioxide': 'total_sulphur_dioxide'},inplace=True) # Splitting data into features and labels setX = df.iloc[:,:11]y = df.iloc[:,-1] Python import pywedge as pwcharts = pw.Pywedge_Charts(df, c=None, y = 'quality')# Calling the make_charts methodplots = charts.make_charts() The ‘make_charts’ method on execution yields out a window giving us 8 different types of chart options and we can select our required features to plot the graph and visualize the results. Making a scatter plot: Scatter Plot Violin plot Distribution plot Histogram Correlation plot Thus, we can see how efficiently we can plot these several graphs using just a few lines of code using the pywedge package without explicitly writing codes for all these graphs. surindertarika1234 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2021" }, { "code": null, "e": 748, "s": 28, "text": "In Machine Learning and Data Science, one of the toughest jobs is to understand the raw data and make it fit for applying different models over it to make predictions. For understanding purpose, we make use of different processes like checking statistical figures such as mean, median, mode, finding the relation between features, looking at the distribution of certain features, etc. This all things are often clubbed under the term Exploratory Data Analysis (EDA). According to experienced ML and DS practitioners, EDA is one of the most valuable tasks and its importance cannot be overlooked when it comes to analyzing the dataset. It helps the practitioners to choose the appropriate data pre-processing techniques." }, { "code": null, "e": 1600, "s": 748, "text": "Checking the statistical figures is well and good but what’s better than visualizing these stats pictorially, it often said that pictures are a more powerful tool for understanding rather than just numerical figures. We can come up with the clearer understanding of the data visually by making different charts. In machine learning and data science, we use different types of charts/plots in order to visualize different patterns among the features some of which are: Histogram, Bar plots, Box plots, Pair plots, Pie charts, Violin plots, etc. But writing codes manually for all these plots/graphs can seem to be a tiring process and also we are more prone to inaccuracies and errors/bugs in the code. So, here comes our lifesaver, a python package that does the tasks of plotting these graphs easily and efficiently without any such bugs in the code." }, { "code": null, "e": 1914, "s": 1600, "text": "In this article, we will be reading about making interactive plots/charts using pywedge python package. Pywedge is an open-source python package that can be used for automating most of the machine learning problem-solving task. It also offers us features to plot interactive graphs using just a few lines of code." }, { "code": null, "e": 2034, "s": 1914, "text": "Pywedge library has a make_charts method that offers us to make 8 different types of charts which are named as follows:" }, { "code": null, "e": 2047, "s": 2034, "text": "Scatter plot" }, { "code": null, "e": 2057, "s": 2047, "text": "Pie chart" }, { "code": null, "e": 2066, "s": 2057, "text": "Bar Plot" }, { "code": null, "e": 2078, "s": 2066, "text": "Violin plot" }, { "code": null, "e": 2087, "s": 2078, "text": "Box plot" }, { "code": null, "e": 2105, "s": 2087, "text": "Distribution plot" }, { "code": null, "e": 2115, "s": 2105, "text": "Histogram" }, { "code": null, "e": 2132, "s": 2115, "text": "Correlation plot" }, { "code": null, "e": 2214, "s": 2132, "text": "Let’s see an example of how can we use pywedge library to draw interactive plots:" }, { "code": null, "e": 2221, "s": 2214, "text": "Python" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings(\"ignore\") df = pd.read_csv(\"https://www.shortto.com/WineDataset\",sep=\";\")", "e": 2423, "s": 2221, "text": null }, { "code": null, "e": 2573, "s": 2423, "text": "After loading the dataset, we will look at how the dataset looks like, this can be seen using the head method to print the top 5 rows in the dataset:" }, { "code": null, "e": 2580, "s": 2573, "text": "Python" }, { "code": "df.head()", "e": 2590, "s": 2580, "text": null }, { "code": null, "e": 2602, "s": 2595, "text": "Python" }, { "code": "print(\"Shape of our dataframe is: \",df.shape)", "e": 2648, "s": 2602, "text": null }, { "code": null, "e": 2690, "s": 2651, "text": "Shape of our dataframe is: (1599, 12)" }, { "code": null, "e": 2818, "s": 2692, "text": "So, as we can notice we have in total 1599 rows and 11 features in the dataset along with one target feature named ‘quality’." }, { "code": null, "e": 2931, "s": 2820, "text": "It is always better to check out some stats about our dataset and we can do it using the describe() method as:" }, { "code": null, "e": 2940, "s": 2933, "text": "Python" }, { "code": "df.describe()", "e": 2954, "s": 2940, "text": null }, { "code": null, "e": 2986, "s": 2957, "text": "Statistics about the dataset" }, { "code": null, "e": 3031, "s": 2988, "text": "By looking just at the stats, we can infer" }, { "code": null, "e": 3260, "s": 3033, "text": "The mean value is greater than the median value in each of the columns, for example, mean value of pH is 3.311113 whereas median value is 3.310000. Similarly, the mean of alcohol is 10.422 as compared to median which is 10.20." }, { "code": null, "e": 3624, "s": 3260, "text": "We can notice a large difference between 75th percentile value and max values of predictors “residual sugar”, “free sulfur dioxide”, “total sulfur dioxide”. This indicates that some values of these 3 variables lie much farther from the general range of values( up to 75th %tile). Thus, we can conclude that there are extreme values i.e., Outliers in our dataset." }, { "code": null, "e": 3633, "s": 3626, "text": "Python" }, { "code": "df.rename(columns={'ficxed acidity':'fixed_acidity','citric acid':'citric_acid', 'volatile acidity':'volatile_acidity','residual sugar':'residual_sugar', 'free sulphur dioxide':'free_sulphur_dioxide', 'total sulphur dioxide': 'total_sulphur_dioxide'},inplace=True) # Splitting data into features and labels setX = df.iloc[:,:11]y = df.iloc[:,-1]", "e": 4033, "s": 3633, "text": null }, { "code": null, "e": 4045, "s": 4038, "text": "Python" }, { "code": "import pywedge as pwcharts = pw.Pywedge_Charts(df, c=None, y = 'quality')# Calling the make_charts methodplots = charts.make_charts()", "e": 4179, "s": 4045, "text": null }, { "code": null, "e": 4371, "s": 4183, "text": "The ‘make_charts’ method on execution yields out a window giving us 8 different types of chart options and we can select our required features to plot the graph and visualize the results." }, { "code": null, "e": 4396, "s": 4373, "text": "Making a scatter plot:" }, { "code": null, "e": 4411, "s": 4398, "text": "Scatter Plot" }, { "code": null, "e": 4423, "s": 4411, "text": "Violin plot" }, { "code": null, "e": 4441, "s": 4423, "text": "Distribution plot" }, { "code": null, "e": 4451, "s": 4441, "text": "Histogram" }, { "code": null, "e": 4468, "s": 4451, "text": "Correlation plot" }, { "code": null, "e": 4648, "s": 4470, "text": "Thus, we can see how efficiently we can plot these several graphs using just a few lines of code using the pywedge package without explicitly writing codes for all these graphs." }, { "code": null, "e": 4669, "s": 4650, "text": "surindertarika1234" }, { "code": null, "e": 4686, "s": 4669, "text": "Machine Learning" }, { "code": null, "e": 4693, "s": 4686, "text": "Python" }, { "code": null, "e": 4710, "s": 4693, "text": "Machine Learning" } ]
Java Program to Round a Number to n Decimal Places
10 May, 2022 Floating-point numbers are decimal values, which can be rounded to n number of decimal places. There are 3 different ways to Round a Number to n Decimal Places in Java as follows: Using format MethodUsing DecimalFormat ClassMultiply and Divide the number by 10n (n decimal places) Using format Method Using DecimalFormat Class Multiply and Divide the number by 10n (n decimal places) Example: Input: number = 1.41421356237, round = 3 Output:1.414 Input: number = 0.70710678118, round = 2 Output:0.71 The decimal number can be rounded by the inbuilt format() method supported by Java. Syntax: System.out.format("%.df", number); Parameters: The first parameter accepts d digits to round off the number, the second argument accepts a number that is to be rounded. Example: Java // Java Program to Round a Number to n Decimal Places// using format() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing a double number double number = 3.141341435; // Rounding number to 2 decimal places // using format method System.out.format("%.2f", number); }} 3.14 DecimalFormat is a child class of the NumberFormat which is used to perform formatting of decimal numbers in java. We create an object of this class and pass in as arguments the format specified in form of #, with the number of # after decimal point indicating the number of digits we wish to output. By default, the number is rounded off to the ceiling value itself. The object of the DecimalFormat class invokes a method format() which takes as argument the number to be formatted. Example 1: Java // Java Program to Round a Number to n Decimal Places// Using DecimalFormat Class // Importing required classesimport java.text.DecimalFormat; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing a double number double number = 145.34567; // Creating an object of DecimalFormat class DecimalFormat df_obj = new DecimalFormat("#.###"); // format() method is used to // print the desired number System.out.println(df_obj.format(number)); }} 145.346 Note: In case we wish to round off the number to the floor, we invoke the Java in-built class RoundingMode. It has the following values for attributes as follows: FLOOR – for next nearest floor value CEILING – for next nearest ceiling value Also do remember, this method can be invoked on the DecimalFormat class supported in-built method setRoundingMode(), which takes as an argument either RoundingMode.FLOOR or CEILING, and accordingly gives us the result. Example 2: Java // Java Program to Round a Number to N Decimal Places// Using DecimalFormat Class // Importing required classesimport java.math.RoundingMode;import java.text.DecimalFormat; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double double number = 9.97869896; // Creating an object of DecimalFormat class DecimalFormat df_obj = new DecimalFormat("#.####"); // Rounding number to the next lowest value // using setRoundingMode() df_obj.setRoundingMode(RoundingMode.FLOOR); // Printing the number in desired format // using format() method System.out.println(df_obj.format(number)); }} 9.9786 In this approach, we first Multiply the number by 10n using the pow() function of the Math class. Then the number is rounded to the nearest integer. At last, we divide the number by 10n. By doing this, we get the decimal number up to n decimal places. Syntax: number = Math.round(number*Math.pow(10,n))/Math.pow(10,n); Example: Java // Java Program to Round a Number to n Decimal Places// Via Multiply and Divide the number with 10^n // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double number double number = 12.983665; // Getting the number of decimal places required int n = 3; // Rounding off the number // using pow() and round() method of Math class number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n); // Printing the rounded number System.out.println(number); }} Output 12.984 manavsarkar07 solankimayank sumitgumber28 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2022" }, { "code": null, "e": 209, "s": 28, "text": "Floating-point numbers are decimal values, which can be rounded to n number of decimal places. There are 3 different ways to Round a Number to n Decimal Places in Java as follows: " }, { "code": null, "e": 310, "s": 209, "text": "Using format MethodUsing DecimalFormat ClassMultiply and Divide the number by 10n (n decimal places)" }, { "code": null, "e": 330, "s": 310, "text": "Using format Method" }, { "code": null, "e": 356, "s": 330, "text": "Using DecimalFormat Class" }, { "code": null, "e": 413, "s": 356, "text": "Multiply and Divide the number by 10n (n decimal places)" }, { "code": null, "e": 422, "s": 413, "text": "Example:" }, { "code": null, "e": 477, "s": 422, "text": "Input: number = 1.41421356237, round = 3 \nOutput:1.414" }, { "code": null, "e": 531, "s": 477, "text": "Input: number = 0.70710678118, round = 2 \nOutput:0.71" }, { "code": null, "e": 616, "s": 531, "text": "The decimal number can be rounded by the inbuilt format() method supported by Java. " }, { "code": null, "e": 625, "s": 616, "text": "Syntax: " }, { "code": null, "e": 660, "s": 625, "text": "System.out.format(\"%.df\", number);" }, { "code": null, "e": 794, "s": 660, "text": "Parameters: The first parameter accepts d digits to round off the number, the second argument accepts a number that is to be rounded." }, { "code": null, "e": 803, "s": 794, "text": "Example:" }, { "code": null, "e": 808, "s": 803, "text": "Java" }, { "code": "// Java Program to Round a Number to n Decimal Places// using format() Method // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing a double number double number = 3.141341435; // Rounding number to 2 decimal places // using format method System.out.format(\"%.2f\", number); }}", "e": 1245, "s": 808, "text": null }, { "code": null, "e": 1250, "s": 1245, "text": "3.14" }, { "code": null, "e": 1734, "s": 1250, "text": "DecimalFormat is a child class of the NumberFormat which is used to perform formatting of decimal numbers in java. We create an object of this class and pass in as arguments the format specified in form of #, with the number of # after decimal point indicating the number of digits we wish to output. By default, the number is rounded off to the ceiling value itself. The object of the DecimalFormat class invokes a method format() which takes as argument the number to be formatted." }, { "code": null, "e": 1745, "s": 1734, "text": "Example 1:" }, { "code": null, "e": 1750, "s": 1745, "text": "Java" }, { "code": "// Java Program to Round a Number to n Decimal Places// Using DecimalFormat Class // Importing required classesimport java.text.DecimalFormat; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing a double number double number = 145.34567; // Creating an object of DecimalFormat class DecimalFormat df_obj = new DecimalFormat(\"#.###\"); // format() method is used to // print the desired number System.out.println(df_obj.format(number)); }}", "e": 2325, "s": 1750, "text": null }, { "code": null, "e": 2333, "s": 2325, "text": "145.346" }, { "code": null, "e": 2496, "s": 2333, "text": "Note: In case we wish to round off the number to the floor, we invoke the Java in-built class RoundingMode. It has the following values for attributes as follows:" }, { "code": null, "e": 2533, "s": 2496, "text": "FLOOR – for next nearest floor value" }, { "code": null, "e": 2574, "s": 2533, "text": "CEILING – for next nearest ceiling value" }, { "code": null, "e": 2793, "s": 2574, "text": "Also do remember, this method can be invoked on the DecimalFormat class supported in-built method setRoundingMode(), which takes as an argument either RoundingMode.FLOOR or CEILING, and accordingly gives us the result." }, { "code": null, "e": 2804, "s": 2793, "text": "Example 2:" }, { "code": null, "e": 2809, "s": 2804, "text": "Java" }, { "code": "// Java Program to Round a Number to N Decimal Places// Using DecimalFormat Class // Importing required classesimport java.math.RoundingMode;import java.text.DecimalFormat; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double double number = 9.97869896; // Creating an object of DecimalFormat class DecimalFormat df_obj = new DecimalFormat(\"#.####\"); // Rounding number to the next lowest value // using setRoundingMode() df_obj.setRoundingMode(RoundingMode.FLOOR); // Printing the number in desired format // using format() method System.out.println(df_obj.format(number)); }}", "e": 3553, "s": 2809, "text": null }, { "code": null, "e": 3560, "s": 3553, "text": "9.9786" }, { "code": null, "e": 3813, "s": 3560, "text": " In this approach, we first Multiply the number by 10n using the pow() function of the Math class. Then the number is rounded to the nearest integer. At last, we divide the number by 10n. By doing this, we get the decimal number up to n decimal places." }, { "code": null, "e": 3821, "s": 3813, "text": "Syntax:" }, { "code": null, "e": 3880, "s": 3821, "text": "number = Math.round(number*Math.pow(10,n))/Math.pow(10,n);" }, { "code": null, "e": 3889, "s": 3880, "text": "Example:" }, { "code": null, "e": 3894, "s": 3889, "text": "Java" }, { "code": "// Java Program to Round a Number to n Decimal Places// Via Multiply and Divide the number with 10^n // Importing required classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing double number double number = 12.983665; // Getting the number of decimal places required int n = 3; // Rounding off the number // using pow() and round() method of Math class number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n); // Printing the rounded number System.out.println(number); }}", "e": 4559, "s": 3894, "text": null }, { "code": null, "e": 4566, "s": 4559, "text": "Output" }, { "code": null, "e": 4573, "s": 4566, "text": "12.984" }, { "code": null, "e": 4587, "s": 4573, "text": "manavsarkar07" }, { "code": null, "e": 4601, "s": 4587, "text": "solankimayank" }, { "code": null, "e": 4615, "s": 4601, "text": "sumitgumber28" }, { "code": null, "e": 4620, "s": 4615, "text": "Java" }, { "code": null, "e": 4634, "s": 4620, "text": "Java Programs" }, { "code": null, "e": 4639, "s": 4634, "text": "Java" } ]
Find sum of even and odd nodes in a linked list
07 Jun, 2021 Given a linked list, the task is to find the sum of even and odd nodes in it separately.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 Output: Even Sum = 12 Odd Sum = 16Input: 5 -> 7 -> 8 -> 10 -> 15 Output: Even Sum = 18 Odd Sum = 27 Approach: Traverse the whole linked list and for each node:- If the element is even then we add that element to the variable which is holding the sum of even elements.If the element is odd then we add that element to the variable which is holding the sum of odd elements. If the element is even then we add that element to the variable which is holding the sum of even elements. If the element is odd then we add that element to the variable which is holding the sum of odd elements. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Represents node of the linked liststruct Node { int data; Node* next;}; // Function to insert a node at the// end of the linked listvoid insert(Node** root, int item){ Node *ptr = *root, *temp = new Node; temp->data = item; temp->next = NULL; if (*root == NULL) *root = temp; else { while (ptr->next != NULL) ptr = ptr->next; ptr->next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsvoid evenOdd(Node* root){ int odd = 0, even = 0; Node* ptr = root; while (ptr != NULL) { // If current node's data is even if (ptr->data % 2 == 0) even += ptr->data; // If current node's data is odd else odd += ptr->data; // ptr now points to the next node ptr = ptr->next; } cout << "Even Sum = " << even << endl; cout << "Odd Sum = " << odd << endl;} // Driver codeint main(){ Node* root = NULL; insert(&root, 1); insert(&root, 2); insert(&root, 3); insert(&root, 4); insert(&root, 5); insert(&root, 6); insert(&root, 7); evenOdd(root); return 0;} // Java implementation of the approachclass GfG{ // Represents node of the linked liststatic class Node{ int data; Node next;}static Node root; // Function to insert a node at the// end of the linked liststatic void insert(int item){ Node ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsstatic void evenOdd(Node root){ int odd = 0, even = 0; Node ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } System.out.println("Even Sum = " + even); System.out.println("Odd Sum = " + odd);} // Driver codepublic static void main(String[] args){ // Node* root = NULL; insert( 1); insert( 2); insert( 3); insert( 4); insert(5); insert(6); insert( 7); evenOdd(root);}} // This code is contributed by Prerna Saini # Python3 implementation of the approachimport math # Represents node of the linked listclass Node: def __init__(self, data): self.data = data self.next = None # Function to insert a node at the# end of the linked listdef insert(root, item): ptr = root temp = Node(item) temp.data = item temp.next = None if (root == None): root = temp else: while (ptr.next != None): ptr = ptr.next ptr.next = temp return root # Function to print the sum of even# and odd nodes of the linked listsdef evenOdd(root): odd = 0 even = 0 ptr = root while (ptr != None): # If current node's data is even if (ptr.data % 2 == 0): even = even + ptr.data # If current node's data is odd else: odd = odd + ptr.data # ptr now points to the next node ptr = ptr.next print( "Even Sum = ", even) print( "Odd Sum = ", odd) # Driver codeif __name__=='__main__': root = None root = insert(root, 1) root = insert(root, 2) root = insert(root, 3) root = insert(root, 4) root = insert(root, 5) root = insert(root, 6) root = insert(root, 7) evenOdd(root) # This code is contributed by AbhiThakur // C# implementation of the approachusing System; class GfG{ // Represents node of the linked listpublic class Node{ public int data; public Node next;}static Node root; // Function to insert a node at the// end of the linked liststatic void insert(int item){ Node ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsstatic void evenOdd(Node root){ int odd = 0, even = 0; Node ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } Console.WriteLine("Even Sum = " + even); Console.WriteLine("Odd Sum = " + odd);} // Driver codepublic static void Main(String []args){ // Node* root = NULL; insert( 1); insert( 2); insert( 3); insert( 4); insert(5); insert(6); insert( 7); evenOdd(root);}} // This code is contributed by Arnab Kundu <script> // Javascript implementation of the approach // Represents node of the linked listclass Node { constructor() { this.data = 0; this.next = null; } } // Function to insert a node at the// end of the linked listfunction insert( item){ var ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsfunction evenOdd( root){ let odd = 0, even = 0; let ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } document.write("Even Sum = " + even); document.write("</br>"); document.write("Odd Sum = " + odd);} // Driver Code var root = null;insert( 1);insert( 2);insert( 3);insert( 4);insert(5);insert(6);insert( 7); evenOdd(root); // This code is contributed by jana_sayantan.</script> Even Sum = 12 Odd Sum = 16 prerna saini andrew1234 abhaysingh290895 Akanksha_Rai jana_sayantan Traversal Linked List Linked List Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) What is Data Structure: Types, Classifications and Applications Linked List vs Array Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Queue - Linked List Implementation Function to check if a singly linked list is palindrome Write a function to get the intersection point of two Linked Lists
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2021" }, { "code": null, "e": 152, "s": 52, "text": "Given a linked list, the task is to find the sum of even and odd nodes in it separately.Examples: " }, { "code": null, "e": 293, "s": 152, "text": "Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 Output: Even Sum = 12 Odd Sum = 16Input: 5 -> 7 -> 8 -> 10 -> 15 Output: Even Sum = 18 Odd Sum = 27 " }, { "code": null, "e": 358, "s": 295, "text": "Approach: Traverse the whole linked list and for each node:- " }, { "code": null, "e": 569, "s": 358, "text": "If the element is even then we add that element to the variable which is holding the sum of even elements.If the element is odd then we add that element to the variable which is holding the sum of odd elements." }, { "code": null, "e": 676, "s": 569, "text": "If the element is even then we add that element to the variable which is holding the sum of even elements." }, { "code": null, "e": 781, "s": 676, "text": "If the element is odd then we add that element to the variable which is holding the sum of odd elements." }, { "code": null, "e": 834, "s": 781, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 838, "s": 834, "text": "C++" }, { "code": null, "e": 843, "s": 838, "text": "Java" }, { "code": null, "e": 851, "s": 843, "text": "Python3" }, { "code": null, "e": 854, "s": 851, "text": "C#" }, { "code": null, "e": 865, "s": 854, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Represents node of the linked liststruct Node { int data; Node* next;}; // Function to insert a node at the// end of the linked listvoid insert(Node** root, int item){ Node *ptr = *root, *temp = new Node; temp->data = item; temp->next = NULL; if (*root == NULL) *root = temp; else { while (ptr->next != NULL) ptr = ptr->next; ptr->next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsvoid evenOdd(Node* root){ int odd = 0, even = 0; Node* ptr = root; while (ptr != NULL) { // If current node's data is even if (ptr->data % 2 == 0) even += ptr->data; // If current node's data is odd else odd += ptr->data; // ptr now points to the next node ptr = ptr->next; } cout << \"Even Sum = \" << even << endl; cout << \"Odd Sum = \" << odd << endl;} // Driver codeint main(){ Node* root = NULL; insert(&root, 1); insert(&root, 2); insert(&root, 3); insert(&root, 4); insert(&root, 5); insert(&root, 6); insert(&root, 7); evenOdd(root); return 0;}", "e": 2089, "s": 865, "text": null }, { "code": "// Java implementation of the approachclass GfG{ // Represents node of the linked liststatic class Node{ int data; Node next;}static Node root; // Function to insert a node at the// end of the linked liststatic void insert(int item){ Node ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsstatic void evenOdd(Node root){ int odd = 0, even = 0; Node ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } System.out.println(\"Even Sum = \" + even); System.out.println(\"Odd Sum = \" + odd);} // Driver codepublic static void main(String[] args){ // Node* root = NULL; insert( 1); insert( 2); insert( 3); insert( 4); insert(5); insert(6); insert( 7); evenOdd(root);}} // This code is contributed by Prerna Saini", "e": 3322, "s": 2089, "text": null }, { "code": "# Python3 implementation of the approachimport math # Represents node of the linked listclass Node: def __init__(self, data): self.data = data self.next = None # Function to insert a node at the# end of the linked listdef insert(root, item): ptr = root temp = Node(item) temp.data = item temp.next = None if (root == None): root = temp else: while (ptr.next != None): ptr = ptr.next ptr.next = temp return root # Function to print the sum of even# and odd nodes of the linked listsdef evenOdd(root): odd = 0 even = 0 ptr = root while (ptr != None): # If current node's data is even if (ptr.data % 2 == 0): even = even + ptr.data # If current node's data is odd else: odd = odd + ptr.data # ptr now points to the next node ptr = ptr.next print( \"Even Sum = \", even) print( \"Odd Sum = \", odd) # Driver codeif __name__=='__main__': root = None root = insert(root, 1) root = insert(root, 2) root = insert(root, 3) root = insert(root, 4) root = insert(root, 5) root = insert(root, 6) root = insert(root, 7) evenOdd(root) # This code is contributed by AbhiThakur", "e": 4573, "s": 3322, "text": null }, { "code": "// C# implementation of the approachusing System; class GfG{ // Represents node of the linked listpublic class Node{ public int data; public Node next;}static Node root; // Function to insert a node at the// end of the linked liststatic void insert(int item){ Node ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsstatic void evenOdd(Node root){ int odd = 0, even = 0; Node ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } Console.WriteLine(\"Even Sum = \" + even); Console.WriteLine(\"Odd Sum = \" + odd);} // Driver codepublic static void Main(String []args){ // Node* root = NULL; insert( 1); insert( 2); insert( 3); insert( 4); insert(5); insert(6); insert( 7); evenOdd(root);}} // This code is contributed by Arnab Kundu", "e": 5829, "s": 4573, "text": null }, { "code": "<script> // Javascript implementation of the approach // Represents node of the linked listclass Node { constructor() { this.data = 0; this.next = null; } } // Function to insert a node at the// end of the linked listfunction insert( item){ var ptr = root, temp = new Node(); temp.data = item; temp.next = null; if (root == null) root = temp; else { while (ptr.next != null) ptr = ptr.next; ptr.next = temp; }} // Function to print the sum of even// and odd nodes of the linked listsfunction evenOdd( root){ let odd = 0, even = 0; let ptr = root; while (ptr != null) { // If current node's data is even if (ptr.data % 2 == 0) even += ptr.data; // If current node's data is odd else odd += ptr.data; // ptr now points to the next node ptr = ptr.next; } document.write(\"Even Sum = \" + even); document.write(\"</br>\"); document.write(\"Odd Sum = \" + odd);} // Driver Code var root = null;insert( 1);insert( 2);insert( 3);insert( 4);insert(5);insert(6);insert( 7); evenOdd(root); // This code is contributed by jana_sayantan.</script>", "e": 7078, "s": 5829, "text": null }, { "code": null, "e": 7105, "s": 7078, "text": "Even Sum = 12\nOdd Sum = 16" }, { "code": null, "e": 7120, "s": 7107, "text": "prerna saini" }, { "code": null, "e": 7131, "s": 7120, "text": "andrew1234" }, { "code": null, "e": 7148, "s": 7131, "text": "abhaysingh290895" }, { "code": null, "e": 7161, "s": 7148, "text": "Akanksha_Rai" }, { "code": null, "e": 7175, "s": 7161, "text": "jana_sayantan" }, { "code": null, "e": 7185, "s": 7175, "text": "Traversal" }, { "code": null, "e": 7197, "s": 7185, "text": "Linked List" }, { "code": null, "e": 7209, "s": 7197, "text": "Linked List" }, { "code": null, "e": 7219, "s": 7209, "text": "Traversal" }, { "code": null, "e": 7317, "s": 7219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7336, "s": 7317, "text": "LinkedList in Java" }, { "code": null, "e": 7368, "s": 7336, "text": "Introduction to Data Structures" }, { "code": null, "e": 7424, "s": 7368, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 7488, "s": 7424, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7509, "s": 7488, "text": "Linked List vs Array" }, { "code": null, "e": 7556, "s": 7509, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 7611, "s": 7556, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 7646, "s": 7611, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 7702, "s": 7646, "text": "Function to check if a singly linked list is palindrome" } ]
Python | time.localtime() method
12 Oct, 2021 Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.localtime() method of Time module is used to convert a time expressed in seconds since the epoch to a time.struct_time object in local time. To convert the given time in seconds since the epoch to a time.struct_time object in UTC, time.gmtime() method is used. This method returns a time.struct_time object with a named tuple interface. Following are the values present in time.struct_time object: Syntax: time.localtime([secs])Parameter: secs (optional): An integer or float value representing time in seconds. Fractions of specified seconds will be ignored. If secs parameter is not provided or None then the current time as returned by time.time() method is used. Return type: This method returns an object of class ‘time.struct_time’. Code #1: Use of time.localtime() method Python3 # Python program to explain time.localtime() method # importing time moduleimport time # If secs parameter# is not given then# the current time as# returned by time.time() method# is used # Convert the current time in seconds# since the epoch to a# time.struct_time object in Local timeobj = time.localtime() # Print the time.struct.time objectprint(obj) # We can change it to# Day Mon date Hour:Min:Sec year# format using time.asctime() methodt = time.asctime(obj)print(t) time.struct_time(tm_year=2019, tm_mon=8, tm_mday=22, tm_hour=10, tm_min=3, tm_sec=15, tm_wday=3, tm_yday=234, tm_isdst=0) Thu Aug 22 10:03:15 2019 Code #2: Use of time.localtime() method Python3 # Python program to explain time.localtime() method # importing time moduleimport time # Time in seconds# since the epochsecs = 950000000 # Convert the given time in seconds# since the epoch to a# time.struct_time object in local time# using time.localtime() methodobj = time.localtime(secs) # Print the time.struct_time objectprint("time.struct_time object for seconds =", secs)print(obj) # Time in seconds# since the epochsecs = 950000000.81956 # Convert the given time in seconds# since the epoch to a# time.struct_time object in local time# using time.localtime() methodobj = time.localtime(secs) # Print the time.struct_time objectprint("\ntime.struct_time object for seconds =", secs)print(obj) # Output for secs = 950000000# and secs = 950000000.81956# will be same because# fractions in 950000000.81956# i.e .81956 will be ignored time.struct_time object for seconds = 950000000 time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23, tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0) time.struct_time object for seconds = 950000000.81956 time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23, tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0) Reference: https://docs.python.org/3/library/time.html#time.localtime sooda367 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 555, "s": 28, "text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.localtime() method of Time module is used to convert a time expressed in seconds since the epoch to a time.struct_time object in local time. To convert the given time in seconds since the epoch to a time.struct_time object in UTC, time.gmtime() method is used. This method returns a time.struct_time object with a named tuple interface. Following are the values present in time.struct_time object: " }, { "code": null, "e": 900, "s": 557, "text": "Syntax: time.localtime([secs])Parameter: secs (optional): An integer or float value representing time in seconds. Fractions of specified seconds will be ignored. If secs parameter is not provided or None then the current time as returned by time.time() method is used. Return type: This method returns an object of class ‘time.struct_time’. " }, { "code": null, "e": 942, "s": 900, "text": "Code #1: Use of time.localtime() method " }, { "code": null, "e": 950, "s": 942, "text": "Python3" }, { "code": "# Python program to explain time.localtime() method # importing time moduleimport time # If secs parameter# is not given then# the current time as# returned by time.time() method# is used # Convert the current time in seconds# since the epoch to a# time.struct_time object in Local timeobj = time.localtime() # Print the time.struct.time objectprint(obj) # We can change it to# Day Mon date Hour:Min:Sec year# format using time.asctime() methodt = time.asctime(obj)print(t)", "e": 1424, "s": 950, "text": null }, { "code": null, "e": 1571, "s": 1424, "text": "time.struct_time(tm_year=2019, tm_mon=8, tm_mday=22, tm_hour=10, tm_min=3,\ntm_sec=15, tm_wday=3, tm_yday=234, tm_isdst=0)\nThu Aug 22 10:03:15 2019" }, { "code": null, "e": 1615, "s": 1573, "text": "Code #2: Use of time.localtime() method " }, { "code": null, "e": 1623, "s": 1615, "text": "Python3" }, { "code": "# Python program to explain time.localtime() method # importing time moduleimport time # Time in seconds# since the epochsecs = 950000000 # Convert the given time in seconds# since the epoch to a# time.struct_time object in local time# using time.localtime() methodobj = time.localtime(secs) # Print the time.struct_time objectprint(\"time.struct_time object for seconds =\", secs)print(obj) # Time in seconds# since the epochsecs = 950000000.81956 # Convert the given time in seconds# since the epoch to a# time.struct_time object in local time# using time.localtime() methodobj = time.localtime(secs) # Print the time.struct_time objectprint(\"\\ntime.struct_time object for seconds =\", secs)print(obj) # Output for secs = 950000000# and secs = 950000000.81956# will be same because# fractions in 950000000.81956# i.e .81956 will be ignored", "e": 2464, "s": 1623, "text": null }, { "code": null, "e": 2809, "s": 2464, "text": "time.struct_time object for seconds = 950000000\ntime.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23,\ntm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)\n\ntime.struct_time object for seconds = 950000000.81956\ntime.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23,\ntm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)" }, { "code": null, "e": 2882, "s": 2811, "text": "Reference: https://docs.python.org/3/library/time.html#time.localtime " }, { "code": null, "e": 2891, "s": 2882, "text": "sooda367" }, { "code": null, "e": 2906, "s": 2891, "text": "python-utility" }, { "code": null, "e": 2913, "s": 2906, "text": "Python" }, { "code": null, "e": 3011, "s": 2913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3029, "s": 3011, "text": "Python Dictionary" }, { "code": null, "e": 3071, "s": 3029, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3093, "s": 3071, "text": "Enumerate() in Python" }, { "code": null, "e": 3128, "s": 3093, "text": "Read a file line by line in Python" }, { "code": null, "e": 3160, "s": 3128, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3189, "s": 3160, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3216, "s": 3189, "text": "Python Classes and Objects" }, { "code": null, "e": 3237, "s": 3216, "text": "Python OOPs Concepts" }, { "code": null, "e": 3260, "s": 3237, "text": "Introduction To PYTHON" } ]
JasmineJS - Building Blocks of Test
In this chapter, we will discuss the building blocks of test by Jasmine. Jasmine is a testing framework for JavaScript. Suite is the basic building block of Jasmine framework. The collection of similar type test cases written for a specific file or function is known as one suite. It contains two other blocks, one is “Describe()” and another one is “It()”. One Suite block can have only two parameters, one “name of that suite” and another “Function declaration” that actually makes a call to our unit functionality that is to be tested. In the following example, we will create a suite that will unit test add function in add.js file. In this example, we have our JS file named “calculator.js” which will be tested through Jasmine, and the corresponding Jasmine spec file is “CalCulatorSpec.js”. window.Calculator = { currentVal:0, varAfterEachExmaple:0, add:function (num1) { this.currentVal += num1; return this.currentVal; }, addAny:function () { var sum = this.currentVal; for(var i = 0; i < arguments.length; i++) { sum += arguments[i]; } this.currentVal = sum; Return this.currentVal; }, }; describe("calculator",function() { //test case: 1 it("Should retain the current value of all time", function () { expect(Calculator.currentVal).toBeDefined(); expect(Calculator.currentVal).toEqual(0); }); //test case: 2 it("should add numbers",function() { expect(Calculator.add(5)).toEqual(5); expect(Calculator.add(5)).toEqual(10); }); //test case :3 it("Should add any number of numbers",function () { expect(Calculator.addAny(1,2,3)).toEqual(6); }); }); In the above function, we have declared two functions. Function add will add two numbers given as an argument to that function and another function addAny should add any numbers given as an argument. After creating this file, we need to add this file in “SpecRunner.html” inside the head section. On successful compilation, this will generate the following output as a result. Suite block can have many suite blocks inside another suite block. The following example will show you how we can create a different suite block inside another suite block. We will create two JavaScript files, one named as “NestedSpec.js” and another named as “nested.js”. describe("nested",function() { // Starting of first suite block // First block describe("Retaining values ",function () { //test case:1 it ("Should retain the current value of all time", function () { expect(nested.currentVal).toBeDefined(); expect(nested.currentVal).toEqual(0); }); }); //end of the suite block //second suite block describe("Adding single number ",function () { //test case:2 it("should add numbers",function() { expect(nested.add(5)).toEqual(5); expect(nested.add(5)).toEqual(10); }); }); //end of the suite block //third suite block describe("Adding Different Numbers",function () { //test case:3 it("Should add any number of numbers",function() { expect(nested.addAny(1,2,3)).toEqual(6); }); }); //end of the suite block }); window.nested = { currentVal: 0, add:function (num1) { this.currentVal += num1; return this.currentVal; }, addAny:function () { Var sum = this.currentVal; for(var i = 0;i < arguments.length; i++) { sum += arguments[i]; } this.currentVal = sum; return this.currentVal; } }; The above piece of code will generate the following output as a result of running specRunner.html file after adding this file inside the head section. As discussed earlier describe block is a part of Suite block. Like Suite block, it contains two parameters, one “the name of the describe block” and another “function declaration”. In our upcoming examples, we will go through many describe blocks to understand the working flow of Jasmine suite block. Following is an example of a complete describe block. describe("Adding single number ",function () { it("should add numbers",function() { expect(nested.add(5)).toEqual(5); expect(nested.add(5)).toEqual(10); }); } Like describe block we have been introduced to IT block too. It goes within a describe block. This is the block which actually contains each unit test case. In the following code, there are pieces of IT block inside one describe block. describe("Adding single number ",function () { // test case : 1 it("should add numbers",function() { expect(nested.add(5)).toEqual(5); expect(nested.add(5)).toEqual(10); }); //test case : 2 it("should add numbers",function() { expect(nested.addAny(1,2,3)).toEqual(6); }); } Jasmine Expect allows you to write your expectation from the required function or JavaScript file. It comes under IT block. One IT block can have more than one Expect block. Following is an example of Expect block. This expect block provides a wide variety of methods to unit test your JavaScript function or JavaScript file. Each of the Expect block is also known as a matcher. There are two different types of matchers, one inbuilt matcher and another user defined matchers. describe("Adding single number ",function () { // test case : 1 it("should add numbers",function() { expect(nested.add(5)).toEqual(5); expect(nested.add(5)).toEqual(10); }); //test case : 2 it("should add numbers",function() { expect(nested.addAny(1,2,3)).toEqual(6); }); } In the upcoming chapters, we will discuss various uses of different inbuilt methods of the Expect block. Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 2050, "text": "In this chapter, we will discuss the building blocks of test by Jasmine." }, { "code": null, "e": 2408, "s": 2123, "text": "Jasmine is a testing framework for JavaScript. Suite is the basic building block of Jasmine framework. The collection of similar type test cases written for a specific file or function is known as one suite. It contains two other blocks, one is “Describe()” and another one is “It()”." }, { "code": null, "e": 2589, "s": 2408, "text": "One Suite block can have only two parameters, one “name of that suite” and another “Function declaration” that actually makes a call to our unit functionality that is to be tested." }, { "code": null, "e": 2848, "s": 2589, "text": "In the following example, we will create a suite that will unit test add function in add.js file. In this example, we have our JS file named “calculator.js” which will be tested through Jasmine, and the corresponding Jasmine spec file is “CalCulatorSpec.js”." }, { "code": null, "e": 3267, "s": 2848, "text": "window.Calculator = { \n \n currentVal:0, \n varAfterEachExmaple:0, \n \n add:function (num1) { \n this.currentVal += num1; \n return this.currentVal; \n }, \n \n addAny:function () { \n var sum = this.currentVal; \n\t\t\n for(var i = 0; i < arguments.length; i++) { \n sum += arguments[i]; \n } \n \n this.currentVal = sum; \n Return this.currentVal; \n }, \n};" }, { "code": null, "e": 3821, "s": 3267, "text": "describe(\"calculator\",function() { \n \n //test case: 1 \n it(\"Should retain the current value of all time\", function () {\n expect(Calculator.currentVal).toBeDefined();\n expect(Calculator.currentVal).toEqual(0); \n }); \n \n //test case: 2 \n it(\"should add numbers\",function() {\n expect(Calculator.add(5)).toEqual(5); \n expect(Calculator.add(5)).toEqual(10); \n }); \n \n //test case :3 \n it(\"Should add any number of numbers\",function () {\n expect(Calculator.addAny(1,2,3)).toEqual(6); \n }); \n}); " }, { "code": null, "e": 4021, "s": 3821, "text": "In the above function, we have declared two functions. Function add will add two numbers given as an argument to that function and another function addAny should add any numbers given as an argument." }, { "code": null, "e": 4198, "s": 4021, "text": "After creating this file, we need to add this file in “SpecRunner.html” inside the head section. On successful compilation, this will generate the following output as a result." }, { "code": null, "e": 4471, "s": 4198, "text": "Suite block can have many suite blocks inside another suite block. The following example will show you how we can create a different suite block inside another suite block. We will create two JavaScript files, one named as “NestedSpec.js” and another named as “nested.js”." }, { "code": null, "e": 5426, "s": 4471, "text": "describe(\"nested\",function() { \n \n // Starting of first suite block \n // First block \n\t\n describe(\"Retaining values \",function () {\n \n //test case:1 \n it (\"Should retain the current value of all time\", function () { \n expect(nested.currentVal).toBeDefined(); \n expect(nested.currentVal).toEqual(0); \n }); \n }); //end of the suite block \n\n //second suite block \n describe(\"Adding single number \",function () { \n \n //test case:2 \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n }); //end of the suite block \n\n //third suite block \n describe(\"Adding Different Numbers\",function () { \n \n //test case:3 \n it(\"Should add any number of numbers\",function() { \n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n }); //end of the suite block \n});" }, { "code": null, "e": 5805, "s": 5426, "text": "window.nested = { \n \n currentVal: 0,\n\t\n add:function (num1) { \n this.currentVal += num1; \n return this.currentVal; \n },\n \n addAny:function () { \n Var sum = this.currentVal; \n\t\t\n for(var i = 0;i < arguments.length; i++) { \n sum += arguments[i]; \n } \n\t\t\n this.currentVal = sum; \n return this.currentVal; \n } \n};" }, { "code": null, "e": 5956, "s": 5805, "text": "The above piece of code will generate the following output as a result of running specRunner.html file after adding this file inside the head section." }, { "code": null, "e": 6312, "s": 5956, "text": "As discussed earlier describe block is a part of Suite block. Like Suite block, it contains two parameters, one “the name of the describe block” and another “function declaration”. In our upcoming examples, we will go through many describe blocks to understand the working flow of Jasmine suite block. Following is an example of a complete describe block." }, { "code": null, "e": 6502, "s": 6312, "text": "describe(\"Adding single number \",function () { \n \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n}" }, { "code": null, "e": 6738, "s": 6502, "text": "Like describe block we have been introduced to IT block too. It goes within a describe block. This is the block which actually contains each unit test case. In the following code, there are pieces of IT block inside one describe block." }, { "code": null, "e": 7082, "s": 6738, "text": "describe(\"Adding single number \",function () { \n \n // test case : 1 \n it(\"should add numbers\",function() { \n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10); \n }); \n \n //test case : 2 \n it(\"should add numbers\",function() { \n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n}" }, { "code": null, "e": 7256, "s": 7082, "text": "Jasmine Expect allows you to write your expectation from the required function or JavaScript file. It comes under IT block. One IT block can have more than one Expect block." }, { "code": null, "e": 7559, "s": 7256, "text": "Following is an example of Expect block. This expect block provides a wide variety of methods to unit test your JavaScript function or JavaScript file. Each of the Expect block is also known as a matcher. There are two different types of matchers, one inbuilt matcher and another user defined matchers." }, { "code": null, "e": 7899, "s": 7559, "text": "describe(\"Adding single number \",function () { \n \n // test case : 1 \n it(\"should add numbers\",function() {\n expect(nested.add(5)).toEqual(5); \n expect(nested.add(5)).toEqual(10);\n }); \n \n //test case : 2 \n it(\"should add numbers\",function() {\n expect(nested.addAny(1,2,3)).toEqual(6); \n }); \n}" }, { "code": null, "e": 8004, "s": 7899, "text": "In the upcoming chapters, we will discuss various uses of different inbuilt methods of the Expect block." }, { "code": null, "e": 8011, "s": 8004, "text": " Print" }, { "code": null, "e": 8022, "s": 8011, "text": " Add Notes" } ]
C Program to print numbers from 1 to N without using semicolon? - GeeksforGeeks
03 Mar, 2022 How to print numbers from 1 to N without using any semicolon in C. C #include<stdio.h>#define N 100 // Add your code here to print numbers from 1// to N without using any semicolon What code to add in above snippet such that it doesn’t contain semicolon and prints numbers from 1 to N?We strongly recommend you to minimize your browser and try this yourself firstMethod 1 (Recursive) C // A recursive C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num){ if (num <= N && printf("%d ", num) && main(num + 1)) { } } Output: 1 2 3 4 5 6 7 8 9 10 See this for complete run. Thanks to Utkarsh Trivedi for suggesting this solution.Method 2 (Iterative) C // An iterative C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num, char *argv[]){while (num <= N && printf("%d ", num) && num++){}} Output: 1 2 3 4 5 6 7 8 9 10 See this for complete run. Thanks to Rahul Huria for suggesting this solution.How do these solutions work? main() function can receive arguments. The first argument is argument count whose value is 1 if no argument is passed to it. The first argument is always program name. C #include<stdio.h> int main(int num, char *argv[]){ printf("num = %d\n", num); printf("argv[0] = %s ", argv[0]);} Output: num = 1 argv[0] = <file_name> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above maveriek simmytarika5 c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Core Dump (Segmentation fault) in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C Structures in C
[ { "code": null, "e": 24813, "s": 24785, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24881, "s": 24813, "text": "How to print numbers from 1 to N without using any semicolon in C. " }, { "code": null, "e": 24883, "s": 24881, "text": "C" }, { "code": "#include<stdio.h>#define N 100 // Add your code here to print numbers from 1// to N without using any semicolon", "e": 24995, "s": 24883, "text": null }, { "code": null, "e": 25199, "s": 24995, "text": "What code to add in above snippet such that it doesn’t contain semicolon and prints numbers from 1 to N?We strongly recommend you to minimize your browser and try this yourself firstMethod 1 (Recursive) " }, { "code": null, "e": 25201, "s": 25199, "text": "C" }, { "code": "// A recursive C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num){ if (num <= N && printf(\"%d \", num) && main(num + 1)) { } }", "e": 25398, "s": 25201, "text": null }, { "code": null, "e": 25407, "s": 25398, "text": "Output: " }, { "code": null, "e": 25429, "s": 25407, "text": "1 2 3 4 5 6 7 8 9 10 " }, { "code": null, "e": 25533, "s": 25429, "text": "See this for complete run. Thanks to Utkarsh Trivedi for suggesting this solution.Method 2 (Iterative) " }, { "code": null, "e": 25535, "s": 25533, "text": "C" }, { "code": "// An iterative C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num, char *argv[]){while (num <= N && printf(\"%d \", num) && num++){}}", "e": 25726, "s": 25535, "text": null }, { "code": null, "e": 25735, "s": 25726, "text": "Output: " }, { "code": null, "e": 25757, "s": 25735, "text": "1 2 3 4 5 6 7 8 9 10 " }, { "code": null, "e": 26034, "s": 25757, "text": "See this for complete run. Thanks to Rahul Huria for suggesting this solution.How do these solutions work? main() function can receive arguments. The first argument is argument count whose value is 1 if no argument is passed to it. The first argument is always program name. " }, { "code": null, "e": 26036, "s": 26034, "text": "C" }, { "code": "#include<stdio.h> int main(int num, char *argv[]){ printf(\"num = %d\\n\", num); printf(\"argv[0] = %s \", argv[0]);}", "e": 26153, "s": 26036, "text": null }, { "code": null, "e": 26162, "s": 26153, "text": "Output: " }, { "code": null, "e": 26193, "s": 26162, "text": "num = 1 \nargv[0] = <file_name>" }, { "code": null, "e": 26318, "s": 26193, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 26327, "s": 26318, "text": "maveriek" }, { "code": null, "e": 26340, "s": 26327, "text": "simmytarika5" }, { "code": null, "e": 26349, "s": 26340, "text": "c-puzzle" }, { "code": null, "e": 26360, "s": 26349, "text": "C Language" }, { "code": null, "e": 26458, "s": 26360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26467, "s": 26458, "text": "Comments" }, { "code": null, "e": 26480, "s": 26467, "text": "Old Comments" }, { "code": null, "e": 26515, "s": 26480, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26543, "s": 26515, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26589, "s": 26543, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26601, "s": 26589, "text": "fork() in C" }, { "code": null, "e": 26633, "s": 26601, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26673, "s": 26633, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 26690, "s": 26673, "text": "Substring in C++" }, { "code": null, "e": 26712, "s": 26690, "text": "Function Pointer in C" }, { "code": null, "e": 26750, "s": 26712, "text": "TCP Server-Client implementation in C" } ]
Nth Natural Number | Practice | GeeksforGeeks
Given a positive integer N. You have to find Nth natural number after removing all the numbers containing digit 9. Example 1: Input: N = 8 Output: 8 Explanation: After removing natural numbers which contains digit 9, first 8 numbers are 1,2,3,4,5,6,7,8 and 8th number is 8. Example 2: Input: N = 9 Output: 10 Explanation: After removing natural numbers which contains digit 9, first 9 numbers are 1,2,3,4,5,6,7,8,10 and 9th number is 10. Your Task: You don't need to read input or print anything. Complete the function findNth() which accepts an integer N as input parameter and return the Nth number after removing all the numbers containing digit 9. Expected Time Complexity: O(logN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 1012 0 nk01879122 weeks ago //simple one-line solution Java class Solution { long findNth(long N){ //convert to base 9, that's all there's to it.\ return Long.parseLong(Long.toString(N,9)); }} +2 akashmr10962 months ago class Solution { long findNth(long N) { String result = new String(); while(N >= 1) { result = (N % 9) + result; N = N/9; } return Long.parseLong(result); } } 0 abhinavsinghbiz2 months ago C++ Code,O(log9(N)),Run Time=0.0 long long findNth(long long N){ long long ans=0,rem,i=0; while(N!=0){ rem=N%9; ans+=rem*pow(10,i); N/=9; i++; } return ans; } 0 sunghunet2 months ago // C++ Version long long findNth(long long N, long long M=9) { long long alpha=0, beta=1; while( N > 0 ) { alpha += (beta * (N%M)); N/=M; beta*=10; } return alpha; } +3 sunghunet2 months ago # Python Version class Solution: def findNth(self, N, M:int=9): alpha, beta=0, 1 while( N>0 ): alpha += (beta * (int(N)%M)) N/=M beta*=10 return alpha -3 hemantsoni2 months ago +1 choudharymanojloul844 This comment was deleted. +3 manishbit233 months ago // TC O(N) , ASC O(1) long long number=0; long long curr=1; while(N){ number += curr*(N%9); N/=9; curr=curr*10 } return number; +2 cs21m0593 months ago convert to base 9. Thats all 0 keshariamanindian This comment was deleted. 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": 353, "s": 238, "text": "Given a positive integer N. You have to find Nth natural number after removing all the numbers containing digit 9." }, { "code": null, "e": 365, "s": 353, "text": "\nExample 1:" }, { "code": null, "e": 513, "s": 365, "text": "Input:\nN = 8\nOutput:\n8\nExplanation:\nAfter removing natural numbers which contains\ndigit 9, first 8 numbers are 1,2,3,4,5,6,7,8\nand 8th number is 8." }, { "code": null, "e": 524, "s": 513, "text": "Example 2:" }, { "code": null, "e": 678, "s": 524, "text": "Input:\nN = 9\nOutput:\n10\nExplanation:\nAfter removing natural numbers which contains\ndigit 9, first 9 numbers are 1,2,3,4,5,6,7,8,10\nand 9th number is 10.\n" }, { "code": null, "e": 894, "s": 680, "text": "Your Task:\nYou don't need to read input or print anything. Complete the function findNth() which accepts an integer N as input parameter and return the Nth number after removing all the numbers containing digit 9." }, { "code": null, "e": 960, "s": 894, "text": "\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 988, "s": 960, "text": "\nConstraints:\n1 ≤ N ≤ 1012 " }, { "code": null, "e": 990, "s": 988, "text": "0" }, { "code": null, "e": 1011, "s": 990, "text": "nk01879122 weeks ago" }, { "code": null, "e": 1043, "s": 1011, "text": "//simple one-line solution Java" }, { "code": null, "e": 1199, "s": 1043, "text": "class Solution { long findNth(long N){ //convert to base 9, that's all there's to it.\\ return Long.parseLong(Long.toString(N,9)); }}" }, { "code": null, "e": 1202, "s": 1199, "text": "+2" }, { "code": null, "e": 1226, "s": 1202, "text": "akashmr10962 months ago" }, { "code": null, "e": 1462, "s": 1226, "text": "class Solution {\n long findNth(long N)\n {\n String result = new String();\n while(N >= 1) {\n result = (N % 9) + result;\n N = N/9;\n }\n \n return Long.parseLong(result);\n }\n}" }, { "code": null, "e": 1464, "s": 1462, "text": "0" }, { "code": null, "e": 1492, "s": 1464, "text": "abhinavsinghbiz2 months ago" }, { "code": null, "e": 1525, "s": 1492, "text": "C++ Code,O(log9(N)),Run Time=0.0" }, { "code": null, "e": 1717, "s": 1525, "text": "long long findNth(long long N){ long long ans=0,rem,i=0; while(N!=0){ rem=N%9; ans+=rem*pow(10,i); N/=9; i++; } return ans; }" }, { "code": null, "e": 1719, "s": 1717, "text": "0" }, { "code": null, "e": 1741, "s": 1719, "text": "sunghunet2 months ago" }, { "code": null, "e": 1947, "s": 1741, "text": "// C++ Version\nlong long findNth(long long N, long long M=9) {\n long long alpha=0, beta=1;\n while( N > 0 ) {\n alpha += (beta * (N%M));\n N/=M;\n beta*=10;\n }\n return alpha;\n}" }, { "code": null, "e": 1952, "s": 1949, "text": "+3" }, { "code": null, "e": 1974, "s": 1952, "text": "sunghunet2 months ago" }, { "code": null, "e": 2198, "s": 1974, "text": "# Python Version\nclass Solution:\n def findNth(self, N, M:int=9):\n alpha, beta=0, 1\n while( N>0 ):\n alpha += (beta * (int(N)%M))\n N/=M\n beta*=10\n \n return alpha" }, { "code": null, "e": 2201, "s": 2198, "text": "-3" }, { "code": null, "e": 2224, "s": 2201, "text": "hemantsoni2 months ago" }, { "code": null, "e": 2227, "s": 2224, "text": "+1" }, { "code": null, "e": 2249, "s": 2227, "text": "choudharymanojloul844" }, { "code": null, "e": 2275, "s": 2249, "text": "This comment was deleted." }, { "code": null, "e": 2278, "s": 2275, "text": "+3" }, { "code": null, "e": 2302, "s": 2278, "text": "manishbit233 months ago" }, { "code": null, "e": 2439, "s": 2302, "text": "// TC O(N) , ASC O(1)\nlong long number=0;\nlong long curr=1;\nwhile(N){\n number += curr*(N%9);\n N/=9;\n curr=curr*10\n}\nreturn number;" }, { "code": null, "e": 2442, "s": 2439, "text": "+2" }, { "code": null, "e": 2463, "s": 2442, "text": "cs21m0593 months ago" }, { "code": null, "e": 2492, "s": 2463, "text": "convert to base 9. Thats all" }, { "code": null, "e": 2494, "s": 2492, "text": "0" }, { "code": null, "e": 2512, "s": 2494, "text": "keshariamanindian" }, { "code": null, "e": 2538, "s": 2512, "text": "This comment was deleted." }, { "code": null, "e": 2684, "s": 2538, "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": 2720, "s": 2684, "text": " Login to access your submissions. " }, { "code": null, "e": 2730, "s": 2720, "text": "\nProblem\n" }, { "code": null, "e": 2740, "s": 2730, "text": "\nContest\n" }, { "code": null, "e": 2803, "s": 2740, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2951, "s": 2803, "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": 3159, "s": 2951, "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": 3265, "s": 3159, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
MySQL LIMIT clause equivalent for SQL SERVER?
Firstly, we need to create a table to understand the limit clause (as we want for SQL server).We will create a table with the help of CREATE command. mysql> CREATE table limitDemo -> ( -> id int, -> primary key(id) -> ); Query OK, 0 rows affected (0.58 sec) After that, let us insert records into the table − mysql> INSERT into limitDemo values(1); Query OK, 1 row affected (0.16 sec) mysql> INSERT into limitDemo values(2); Query OK, 1 row affected (0.12 sec) mysql> INSERT into limitDemo values(3); Query OK, 1 row affected (0.11 sec) mysql> INSERT into limitDemo values(4); Query OK, 1 row affected (0.10 sec) mysql> INSERT into limitDemo values(5); Query OK, 1 row affected (0.12 sec) mysql> INSERT into limitDemo values(6); Query OK, 1 row affected (0.13 sec) mysql> INSERT into limitDemo values(7); Query OK, 1 row affected (0.15 sec) mysql> INSERT into limitDemo values(8); Query OK, 1 row affected (0.09 sec) mysql> INSERT into limitDemo values(9); Query OK, 1 row affected (0.14 sec) Displaying all the records with the help of SELECT statement − mysql> SELECT * from limitDemo; The following is the output +----+ | id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | +----+ 9 rows in set (0.00 sec) Let us see the query of limit clause and begin with the syntax − SELECT column_name1........N from yourTableName limit integervalue offset integervalue; Now, I am applying the above query − mysql> SELECT id from limitDemo limit 5 offset 2; The following is the output +----+ | id | +----+ | 3 | | 4 | | 5 | | 6 | | 7 | +----+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1212, "s": 1062, "text": "Firstly, we need to create a table to understand the limit clause (as we want for SQL server).We will create a table with the help of CREATE command." }, { "code": null, "e": 1320, "s": 1212, "text": "mysql> CREATE table limitDemo\n-> (\n-> id int,\n-> primary key(id)\n-> );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1371, "s": 1320, "text": "After that, let us insert records into the table −" }, { "code": null, "e": 2063, "s": 1371, "text": "mysql> INSERT into limitDemo values(1);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> INSERT into limitDemo values(2);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT into limitDemo values(3);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> INSERT into limitDemo values(4);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> INSERT into limitDemo values(5);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> INSERT into limitDemo values(6);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into limitDemo values(7);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> INSERT into limitDemo values(8);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> INSERT into limitDemo values(9);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2126, "s": 2063, "text": "Displaying all the records with the help of SELECT statement −" }, { "code": null, "e": 2159, "s": 2126, "text": "mysql> SELECT * from limitDemo;\n" }, { "code": null, "e": 2187, "s": 2159, "text": "The following is the output" }, { "code": null, "e": 2304, "s": 2187, "text": "+----+\n| id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 | \n| 7 |\n| 8 |\n| 9 |\n+----+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2369, "s": 2304, "text": "Let us see the query of limit clause and begin with the syntax −" }, { "code": null, "e": 2458, "s": 2369, "text": "SELECT column_name1........N from yourTableName limit integervalue offset integervalue;\n" }, { "code": null, "e": 2495, "s": 2458, "text": "Now, I am applying the above query −" }, { "code": null, "e": 2545, "s": 2495, "text": "mysql> SELECT id from limitDemo limit 5 offset 2;" }, { "code": null, "e": 2573, "s": 2545, "text": "The following is the output" }, { "code": null, "e": 2661, "s": 2573, "text": "+----+\n| id |\n+----+\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n+----+\n5 rows in set (0.00 sec)" } ]
C++ Program to Split the array and add the first part to the end?
Here we will see how to split an array, and add the first part after splitting at the end position. Suppose the array contents are {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. We want to cut this intro two parts. The first part is from index 0 to 3 (split size 4), and second part is rest. After adding the first part at the end, the array elements will be like this {4, 5, 6, 7, 8, 9, 0, 1, 2, 3}. To solve this problem, we will follow this algorithm. begin for i := 0 to k, do x := arr[0] for j := 0 to n-2, do arr[j] := arr[j+1] done arr[n-1] := x done end Live Demo #include<iostream> using namespace std; void splitArray(int arr[], int n, int k){ for(int i = 0; i<k; i++){ int x = arr[0]; //take the first number for(int j = 0; j<= n-2; j++){ arr[j] = arr[j+1]; } arr[n-1] = x; } } main() { int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(data)/sizeof(data[0]); int i; cout << "Enter split size: "; cin >> i; splitArray(data, n, i); for(int i = 0; i <n;i++){ cout << data[i] << " "; } } Enter split size: 4 4 5 6 7 8 9 0 1 2 3
[ { "code": null, "e": 1502, "s": 1062, "text": "Here we will see how to split an array, and add the first part after splitting at the end position. Suppose the array contents are {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. We want to cut this intro two parts. The first part is from index 0 to 3 (split size 4), and second part is rest. After adding the first part at the end, the array elements will be like this {4, 5, 6, 7, 8, 9, 0, 1, 2, 3}. To solve this problem, we will follow this algorithm." }, { "code": null, "e": 1648, "s": 1502, "text": "begin\n for i := 0 to k, do\n x := arr[0]\n for j := 0 to n-2, do\n arr[j] := arr[j+1]\n done\n arr[n-1] := x\n done\nend" }, { "code": null, "e": 1659, "s": 1648, "text": " Live Demo" }, { "code": null, "e": 2162, "s": 1659, "text": "#include<iostream>\nusing namespace std;\nvoid splitArray(int arr[], int n, int k){\n for(int i = 0; i<k; i++){\n int x = arr[0]; //take the first number\n for(int j = 0; j<= n-2; j++){\n arr[j] = arr[j+1];\n }\n arr[n-1] = x;\n }\n}\nmain() {\n int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n int n = sizeof(data)/sizeof(data[0]);\n int i;\n cout << \"Enter split size: \";\n cin >> i;\n splitArray(data, n, i);\n for(int i = 0; i <n;i++){\n cout << data[i] << \" \";\n }\n}" }, { "code": null, "e": 2202, "s": 2162, "text": "Enter split size: 4\n4 5 6 7 8 9 0 1 2 3" } ]
poll() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <poll.h> int poll(struct pollfd *fds, nfds_t nfds, int timeout); #define _GNU_SOURCE #include <poll.h> int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask); int poll(struct pollfd *fds, nfds_t nfds, int timeout); #define _GNU_SOURCE #include <poll.h> int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask); The set of file descriptors to be monitored is specified in the fds argument, which is an array of nfds structures of the following form: struct pollfd { int fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ }; struct pollfd { int fd; /* file descriptor */ short events; /* requested events */ short revents; /* returned events */ }; The field events is an input parameter, a bitmask specifying the events the application is interested in. The field revents is an output parameter, filled by the kernel with the events that actually occurred. The bits returned in revents can include any of those specified in events, or one of the values POLLERR, POLLHUP, or POLLNVAL. (These three bits are meaningless in the events field, and will be set in the revents field whenever the corresponding condition is true.) If none of the events requested (and no error) has occurred for any of the file descriptors, then poll() blocks until one of the events occurs. The timeout argument specifies an upper limit on the time for which poll() will block, in milliseconds. Specifying a negative value in timeout means an infinite timeout. The bits that may be set/returned in events and revents are defined in <poll.h>: When compiling with _XOPEN_SOURCE defined, one also has the following, which convey no further information beyond the bits listed above: Linux also knows about, but does not use POLLMSG. Other than the difference in the timeout argument, the following ppoll() call: ready = ppoll(&fds, nfds, timeout, &sigmask); ready = ppoll(&fds, nfds, timeout, &sigmask); sigset_t origmask; sigprocmask(SIG_SETMASK, &sigmask, &origmask); ready = ppoll(&fds, nfds, timeout); sigprocmask(SIG_SETMASK, &origmask, NULL); sigset_t origmask; sigprocmask(SIG_SETMASK, &sigmask, &origmask); ready = ppoll(&fds, nfds, timeout); sigprocmask(SIG_SETMASK, &origmask, NULL); See the description of pselect(2) for an explanation of why ppoll() is necessary. The timeout argument specifies an upper limit on the amount of time that ppoll() will block. This argument is a pointer to a structure of the following form: struct timespec { long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; struct timespec { long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; If timeout is specified as NULL, then ppoll() can block indefinitely. The ppoll() system call was added to Linux in kernel 2.6.16. The ppoll() library call was added in glibc 2.4. select (2) select (2) select_tut (2) select_tut (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2551, "s": 2319, "text": "#include <poll.h> \n\nint poll(struct pollfd *fds, nfds_t nfds, int timeout); \n\n#define _GNU_SOURCE \n#include <poll.h> \n\nint ppoll(struct pollfd *fds, nfds_t nfds, \n const struct timespec *timeout, const sigset_t *sigmask); \n" }, { "code": null, "e": 2610, "s": 2551, "text": "\nint poll(struct pollfd *fds, nfds_t nfds, int timeout); \n" }, { "code": null, "e": 2652, "s": 2610, "text": "\n#define _GNU_SOURCE \n#include <poll.h> \n" }, { "code": null, "e": 2766, "s": 2652, "text": "\nint ppoll(struct pollfd *fds, nfds_t nfds, \n const struct timespec *timeout, const sigset_t *sigmask); \n" }, { "code": null, "e": 2906, "s": 2766, "text": "\nThe set of file descriptors to be monitored is specified in the\nfds argument, which is an array of\nnfds structures of the following form:\n" }, { "code": null, "e": 3081, "s": 2906, "text": "\n struct pollfd {\n int fd; /* file descriptor */\n short events; /* requested events */\n short revents; /* returned events */\n };\n\n" }, { "code": null, "e": 3255, "s": 3081, "text": "\n struct pollfd {\n int fd; /* file descriptor */\n short events; /* requested events */\n short revents; /* returned events */\n };\n" }, { "code": null, "e": 3365, "s": 3257, "text": "\nThe field\nevents is an input parameter, a bitmask specifying the events the application\nis interested in.\n" }, { "code": null, "e": 3736, "s": 3365, "text": "\nThe field\nrevents is an output parameter, filled by the kernel with the events that\nactually occurred.\nThe bits returned in\nrevents can include any of those specified in\nevents, or one of the values\nPOLLERR, POLLHUP, or\nPOLLNVAL. (These three bits are meaningless in the\nevents field, and will be set in the\nrevents field whenever the corresponding condition is true.)\n" }, { "code": null, "e": 3882, "s": 3736, "text": "\nIf none of the events requested (and no error) has occurred for any\nof the file descriptors, then\npoll() blocks until one of the events occurs.\n" }, { "code": null, "e": 4054, "s": 3882, "text": "\nThe\ntimeout argument specifies an upper limit on the time for which\npoll() will block, in milliseconds.\nSpecifying a negative value in\ntimeout means an infinite timeout.\n" }, { "code": null, "e": 4137, "s": 4054, "text": "\nThe bits that may be set/returned in\nevents and\nrevents are defined in <poll.h>:\n" }, { "code": null, "e": 4276, "s": 4137, "text": "\nWhen compiling with\n_XOPEN_SOURCE defined, one also has the following,\nwhich convey no further information beyond the bits listed above:\n" }, { "code": null, "e": 4328, "s": 4276, "text": "\nLinux also knows about, but does not use\nPOLLMSG. " }, { "code": null, "e": 4411, "s": 4330, "text": "\nOther than the difference in the\ntimeout argument, the following\nppoll() call:\n" }, { "code": null, "e": 4464, "s": 4411, "text": "\n ready = ppoll(&fds, nfds, timeout, &sigmask);\n\n" }, { "code": null, "e": 4516, "s": 4464, "text": "\n ready = ppoll(&fds, nfds, timeout, &sigmask);\n" }, { "code": null, "e": 4682, "s": 4518, "text": "\n sigset_t origmask;\n\n sigprocmask(SIG_SETMASK, &sigmask, &origmask);\n ready = ppoll(&fds, nfds, timeout);\n sigprocmask(SIG_SETMASK, &origmask, NULL);\n" }, { "code": null, "e": 4707, "s": 4682, "text": "\n sigset_t origmask;\n" }, { "code": null, "e": 4847, "s": 4707, "text": "\n sigprocmask(SIG_SETMASK, &sigmask, &origmask);\n ready = ppoll(&fds, nfds, timeout);\n sigprocmask(SIG_SETMASK, &origmask, NULL);\n" }, { "code": null, "e": 4931, "s": 4847, "text": "\nSee the description of\npselect(2)\nfor an explanation of why\nppoll() is necessary.\n" }, { "code": null, "e": 5092, "s": 4931, "text": "\nThe\ntimeout argument specifies an upper limit on the amount of time that\nppoll() will block.\nThis argument is a pointer to a structure of the following form:\n\n" }, { "code": null, "e": 5203, "s": 5092, "text": "\nstruct timespec {\n long tv_sec; /* seconds */\n long tv_nsec; /* nanoseconds */\n};\n" }, { "code": null, "e": 5314, "s": 5203, "text": "\nstruct timespec {\n long tv_sec; /* seconds */\n long tv_nsec; /* nanoseconds */\n};\n" }, { "code": null, "e": 5386, "s": 5314, "text": "\nIf\ntimeout is specified as NULL, then\nppoll() can block indefinitely.\n" }, { "code": null, "e": 5498, "s": 5386, "text": "\nThe\nppoll() system call was added to Linux in kernel 2.6.16.\nThe\nppoll() library call was added in glibc 2.4.\n" }, { "code": null, "e": 5509, "s": 5498, "text": "select (2)" }, { "code": null, "e": 5520, "s": 5509, "text": "select (2)" }, { "code": null, "e": 5535, "s": 5520, "text": "select_tut (2)" }, { "code": null, "e": 5550, "s": 5535, "text": "select_tut (2)" }, { "code": null, "e": 5567, "s": 5550, "text": "\nAdvertisements\n" }, { "code": null, "e": 5602, "s": 5567, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 5630, "s": 5602, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5664, "s": 5630, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5681, "s": 5664, "text": " Frahaan Hussain" }, { "code": null, "e": 5714, "s": 5681, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 5725, "s": 5714, "text": " Pradeep D" }, { "code": null, "e": 5760, "s": 5725, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5776, "s": 5760, "text": " Musab Zayadneh" }, { "code": null, "e": 5809, "s": 5776, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 5821, "s": 5809, "text": " GUHARAJANM" }, { "code": null, "e": 5853, "s": 5821, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 5861, "s": 5853, "text": " Uplatz" }, { "code": null, "e": 5868, "s": 5861, "text": " Print" }, { "code": null, "e": 5879, "s": 5868, "text": " Add Notes" } ]
JSON Objects in Python. Introduction to JSON objects in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
Java Script Object Notation (JSON) is a light weight data format with many similarities to python dictionaries. JSON objects are useful because browsers can quickly parse them, which is ideal for transporting data between a client and a server. In this post, we will discuss how to use python’s JSON library to send and receive JSON data. Let’s get started! First, let’s inspect the following JSON packet with information about The Beatle’s album Yellow Submarine : { "album_title" : "Yellow Submarine", "release_year" : 1966, "won_grammy" : false, "band" : "The Beatles", "album_sale": null "musicians" : ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"], "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"} } In JSON objects, the keys are strings and the values can be strings, numbers (floats or ints), boolean values, lists, null, or another JSON object. There are a few differences between python dictionaries and JSON objects that can be discerned from this example. For example, boolean values are lower case and ‘None’ values are ‘null’. A python dictionary equivalent is: { "album_title" : "Yellow Submarine", "release_year" : 1966, "won_grammy" : False, "band" : "The Beatles", "album_sale": None "musicians" : ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"], "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"} } Now, let’s save the sample JSON data to a text file called ‘album.txt’. I did this using a terminal command line and the ‘vim’ text editor, but you can use any tool of you’d like. Next, in a python script, let’s import the JSON module: import json Let’s look at the methods available in this module using the ‘dir()’ method: print(dir(json)) We will be focusing on the load and dump methods. To proceed, let’s use the open method to open the file. In the open method, let’s specify the filename, ‘album.txt’, and the mode (read or write). We will be reading the file so the mode is ‘r’: album_json_file = open("album.txt", "r") Next, we can use the load method to load the JSON data from our file: album = json.load(album_json_file) After loading the JSON data, we close the file: album_json_file.close() We can now print our loaded JSON data: print(album) If we print the type of this object we see that it is a python dictionary: print(type(album)) Let’s look at the differences between the JSON object and the python dictionary. The ‘won_grammy’ value in the JSON object is ‘false’, while in the dictionary it is a capitalized ‘False’. Additionally, the ‘album_sale’ ‘value Null’ was parsed as ‘None’ in the python dictionary. Now that we've loaded our data as a dictionary, we can access the values in the parsed dictionary by key. For example, if we like to access the ‘album_title’ we do the following: print("Album Title: ", album['album_title']) Or if we’d like to access the year the album was released: print("Release Year: ", album['release_year']) In client server applications it is common for JSON objects to arrive in the form of strings. For example, our JSON object for album information can look something like this: album_string = """{"album_title" : "Yellow Submarine", "release_year" : 1966, "won_grammy" : false, "band" : "The Beatles", "album_sale": null, "musicians" : ["John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"], "studio" : {"studio_name": "Abbey Road Studios", "location": "London, England"} }""" To load this data using the JSON module, we use the ‘loads()’ method: album_s = json.loads(album_string)album_string.close()print(album_s) Now, suppose we start with dictionary formatted data and wish to send this data to a database in JSON format. We can use the dumps methods to convert dictionaries to string JSON objects. Let’s define our original dictionary: album2 = {'album_title': 'Yellow Submarine', 'release_year': 1966, 'won_grammy': False, 'band': 'The Beatles', 'album_sale': None, 'musicians': ['John Lennon', 'Paul McCartney', 'George Harrison', 'Ringo Starr'], 'studio': {'studio_name': 'Abbey Road Studios', 'location': 'London, England'}} Next, let’s print the string JSON object using the dumps method: print(json.dumps(album2))print(type(json.dumps(album2))) Our dictionary was correctly parsed as a string JSON object. We see that the ‘album_sale’ value, ‘None’, is now ‘null’ and the ‘won_grammy’ value, ‘False’, is now ‘false’. Finally, we can write this JSON object to a ‘.txt’ file using the dump method: file2 = open("album2.txt", "w")json.dump(album2, file2) I’ll stop here but feel free to play around with the code yourself. To summarize, in this post we discussed how to send and receive JSON data using the python JSON library. We discussed the load methods, which help us receive data and the dump methods which help us send data. If you are interested in learning more about working with JSON objects in python, I recommend Socratica’s YouTube tutorials. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 510, "s": 171, "text": "Java Script Object Notation (JSON) is a light weight data format with many similarities to python dictionaries. JSON objects are useful because browsers can quickly parse them, which is ideal for transporting data between a client and a server. In this post, we will discuss how to use python’s JSON library to send and receive JSON data." }, { "code": null, "e": 529, "s": 510, "text": "Let’s get started!" }, { "code": null, "e": 637, "s": 529, "text": "First, let’s inspect the following JSON packet with information about The Beatle’s album Yellow Submarine :" }, { "code": null, "e": 970, "s": 637, "text": "{ \"album_title\" : \"Yellow Submarine\", \"release_year\" : 1966, \"won_grammy\" : false, \"band\" : \"The Beatles\", \"album_sale\": null \"musicians\" : [\"John Lennon\", \"Paul McCartney\", \"George Harrison\", \"Ringo Starr\"], \"studio\" : {\"studio_name\": \"Abbey Road Studios\", \"location\": \"London, England\"} }" }, { "code": null, "e": 1340, "s": 970, "text": "In JSON objects, the keys are strings and the values can be strings, numbers (floats or ints), boolean values, lists, null, or another JSON object. There are a few differences between python dictionaries and JSON objects that can be discerned from this example. For example, boolean values are lower case and ‘None’ values are ‘null’. A python dictionary equivalent is:" }, { "code": null, "e": 1673, "s": 1340, "text": "{ \"album_title\" : \"Yellow Submarine\", \"release_year\" : 1966, \"won_grammy\" : False, \"band\" : \"The Beatles\", \"album_sale\": None \"musicians\" : [\"John Lennon\", \"Paul McCartney\", \"George Harrison\", \"Ringo Starr\"], \"studio\" : {\"studio_name\": \"Abbey Road Studios\", \"location\": \"London, England\"} }" }, { "code": null, "e": 1909, "s": 1673, "text": "Now, let’s save the sample JSON data to a text file called ‘album.txt’. I did this using a terminal command line and the ‘vim’ text editor, but you can use any tool of you’d like. Next, in a python script, let’s import the JSON module:" }, { "code": null, "e": 1921, "s": 1909, "text": "import json" }, { "code": null, "e": 1998, "s": 1921, "text": "Let’s look at the methods available in this module using the ‘dir()’ method:" }, { "code": null, "e": 2015, "s": 1998, "text": "print(dir(json))" }, { "code": null, "e": 2260, "s": 2015, "text": "We will be focusing on the load and dump methods. To proceed, let’s use the open method to open the file. In the open method, let’s specify the filename, ‘album.txt’, and the mode (read or write). We will be reading the file so the mode is ‘r’:" }, { "code": null, "e": 2301, "s": 2260, "text": "album_json_file = open(\"album.txt\", \"r\")" }, { "code": null, "e": 2371, "s": 2301, "text": "Next, we can use the load method to load the JSON data from our file:" }, { "code": null, "e": 2406, "s": 2371, "text": "album = json.load(album_json_file)" }, { "code": null, "e": 2454, "s": 2406, "text": "After loading the JSON data, we close the file:" }, { "code": null, "e": 2478, "s": 2454, "text": "album_json_file.close()" }, { "code": null, "e": 2517, "s": 2478, "text": "We can now print our loaded JSON data:" }, { "code": null, "e": 2530, "s": 2517, "text": "print(album)" }, { "code": null, "e": 2605, "s": 2530, "text": "If we print the type of this object we see that it is a python dictionary:" }, { "code": null, "e": 2624, "s": 2605, "text": "print(type(album))" }, { "code": null, "e": 2903, "s": 2624, "text": "Let’s look at the differences between the JSON object and the python dictionary. The ‘won_grammy’ value in the JSON object is ‘false’, while in the dictionary it is a capitalized ‘False’. Additionally, the ‘album_sale’ ‘value Null’ was parsed as ‘None’ in the python dictionary." }, { "code": null, "e": 3082, "s": 2903, "text": "Now that we've loaded our data as a dictionary, we can access the values in the parsed dictionary by key. For example, if we like to access the ‘album_title’ we do the following:" }, { "code": null, "e": 3127, "s": 3082, "text": "print(\"Album Title: \", album['album_title'])" }, { "code": null, "e": 3186, "s": 3127, "text": "Or if we’d like to access the year the album was released:" }, { "code": null, "e": 3233, "s": 3186, "text": "print(\"Release Year: \", album['release_year'])" }, { "code": null, "e": 3408, "s": 3233, "text": "In client server applications it is common for JSON objects to arrive in the form of strings. For example, our JSON object for album information can look something like this:" }, { "code": null, "e": 3750, "s": 3408, "text": "album_string = \"\"\"{\"album_title\" : \"Yellow Submarine\", \"release_year\" : 1966, \"won_grammy\" : false, \"band\" : \"The Beatles\", \"album_sale\": null, \"musicians\" : [\"John Lennon\", \"Paul McCartney\", \"George Harrison\", \"Ringo Starr\"], \"studio\" : {\"studio_name\": \"Abbey Road Studios\", \"location\": \"London, England\"} }\"\"\"" }, { "code": null, "e": 3820, "s": 3750, "text": "To load this data using the JSON module, we use the ‘loads()’ method:" }, { "code": null, "e": 3889, "s": 3820, "text": "album_s = json.loads(album_string)album_string.close()print(album_s)" }, { "code": null, "e": 4114, "s": 3889, "text": "Now, suppose we start with dictionary formatted data and wish to send this data to a database in JSON format. We can use the dumps methods to convert dictionaries to string JSON objects. Let’s define our original dictionary:" }, { "code": null, "e": 4411, "s": 4114, "text": "album2 = {'album_title': 'Yellow Submarine', 'release_year': 1966, 'won_grammy': False, 'band': 'The Beatles', 'album_sale': None, 'musicians': ['John Lennon', 'Paul McCartney', 'George Harrison', 'Ringo Starr'], 'studio': {'studio_name': 'Abbey Road Studios', 'location': 'London, England'}}" }, { "code": null, "e": 4476, "s": 4411, "text": "Next, let’s print the string JSON object using the dumps method:" }, { "code": null, "e": 4533, "s": 4476, "text": "print(json.dumps(album2))print(type(json.dumps(album2)))" }, { "code": null, "e": 4705, "s": 4533, "text": "Our dictionary was correctly parsed as a string JSON object. We see that the ‘album_sale’ value, ‘None’, is now ‘null’ and the ‘won_grammy’ value, ‘False’, is now ‘false’." }, { "code": null, "e": 4784, "s": 4705, "text": "Finally, we can write this JSON object to a ‘.txt’ file using the dump method:" }, { "code": null, "e": 4840, "s": 4784, "text": "file2 = open(\"album2.txt\", \"w\")json.dump(album2, file2)" }, { "code": null, "e": 4908, "s": 4840, "text": "I’ll stop here but feel free to play around with the code yourself." } ]
Understanding And Implementing Dropout In TensorFlow And Keras | by Richmond Alake | Towards Data Science
This article covers the concept of the dropout technique, a technique that is leveraged in deep neural networks such as recurrent neural networks and convolutional neural network. The Dropout technique involves the omission of neurons that act as feature detectors from the neural network during each training step. The exclusion of each neuron is determined randomly. G.E Hinton proposed this simple technique in 2012 in the published paper: “Improving neural networks by preventing co-adaptation of feature detectors”. In this article, we will uncover the concept of dropout in-depth and look at how this technique can be implemented within neural networks using TensorFlow and Keras. Neural networks have hidden layers in between their input and output layers, these hidden layers have neurons embedded within them, and it’s the weights within the neurons along with the interconnection between neurons is what enables the neural network system to simulate the process of what resembles learning. The general idea is that the more neurons and layers within a neural network architecture, the greater the representational power it has. This increase in representational power means that the neural network can fit more complex functions and generalize well to training data. Simply kept, there are more configurations for the interconnections between the neurons within the neural network layers. The disadvantage of utilizing deeper neural networks is that they are highly prone to overfitting. Overfitting is a common problem that is defined as the inability for a trained machine learning model to generalized well to unseen data, but the same model performs well on the data it was trained on. The primary purpose of dropout is to minimize the effect of overfitting within a trained network. Dropout technique works by randomly reducing the number of interconnecting neurons within a neural network. At every training step, each neuron has a chance of being left out, or rather, dropped out of the collated contribution from connected neurons. This technique minimizes overfitting because each neuron becomes independently sufficient, in the sense that the neurons within the layers learn weight values that are not based on the cooperation of its neighbouring neurons. Hence, we reduce the dependence on a large number of interconnecting neurons to generate a decent representational power from the trained neural network. Supposedly you trained 7,000 different neural network architecture, to select the best one you simply take the average of all 7,000 trained neural network. Well, the dropout technique actually mimics this scenario. If the probability of a neuron getting dropped out in a training step is set to 0.5; we are actually training a variety of different network at each training step as it’s highly impossible that the same neurons are excluded at any two training steps. Therefore a neural network that has been trained utilizing the dropout technique is an average of all the different neurons connection combinations that have occurred at each training step. In practical scenarios, or when testing the performance of the trained neural network that utilized dropout on unseen data, certain items are considered. The first being the fact that dropout technique is actually not implemented on every single layer within a neural network; it’s commonly leveraged within the neurons in the last few layers within the network. In the experiments conducted in the published paper, it was reported that when testing on the CIFAR-10 dataset, there was an error rate of 15.6% when dropout was utilized in the last hidden layer. This was an improvement from the error rate of 16.6% that was reported when the same dataset was tested on the same convolutional neural network but with no dropout technique included in any of the layers. The second item is that within practical scenarios dropout isn’t utilized when evaluating a trained neural network. As a result of dropout not used during the evaluation or testing phase, the full potential of the neural network is realized. This means that all neurons within the network are active, and each neuron has more input connections than it had been trained with. Therefore it’s expected to divide the weights of the neurons by one minus the dropout hyperparameter value(dropout rate that’s used during training). So if the dropout rate was 0.5 during training, then in test time the results of the weights from each neuron is halved. Using TensorFlow and Keras, we are equipped with the tools to implement a neural network that utilizes the dropout technique by including dropout layers within the neural network architecture. We only need to add one line to include a dropout layer within a more extensive neural network architecture. The Dropout class takes a few arguments, but for now, we are only concerned with the ‘rate’ argument. The dropout rate is a hyperparameter that represents the likelihood of a neuron activation been set to zero during a training step. The rate argument can take values between 0 and 1. keras.layers.Dropout(rate=0.2) From this point onwards, we will go through small steps taken to implement, train and evaluate a neural network. Load tools and libraries utilized, Keras and TensorFlow Load tools and libraries utilized, Keras and TensorFlow import tensorflow as tffrom tensorflow import keras 2. Load the FashionMNIST dataset, normalize images and partition dataset into test, training and validation data. (train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000] 3. Create a custom model that includes a dropout layer using the Keras Model Class API. class CustomModel(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) self.input_layer = keras.layers.Flatten(input_shape=(28,28)) self.hidden1 = keras.layers.Dense(200, activation='relu') self.hidden2 = keras.layers.Dense(100, activation='relu') self.hidden3 = keras.layers.Dense(60, activation='relu') self.output_layer = keras.layers.Dense(10, activation='softmax') self.dropout_layer = keras.layers.Dropout(rate=0.2) def call(self, input, training=None): input_layer = self.input_layer(input) input_layer = self.dropout_layer(input_layer) hidden1 = self.hidden1(input_layer) hidden1 = self.dropout_layer(hidden1, training=training) hidden2 = self.hidden2(hidden1) hidden2 = self.dropout_layer(hidden2, training=training) hidden3 = self.hidden3(hidden2) hidden3 = self.dropout_layer(hidden3, training=training) output_layer = self.output_layer(hidden3) return output_layer 4. Load the implemented model and initialize both optimizers and hyperparameters. model = CustomModel()sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss="sparse_categorical_crossentropy", optimizer=sgd, metrics=["accuracy"]) 5. Train the model for a total of 60 epochs model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels)) 6. Evaluate the model on the test dataset model.evaluate(test_images, test_labels) The result of the evaluation will look similar to the example evaluation result below: 10000/10000 [==============================] - 0s 34us/sample - loss: 0.3230 - accuracy: 0.8812[0.32301584649085996, 0.8812] The accuracy shown in the evaluation result example corresponds to the accuracy of our model of 88%. With some fine-tuning and training with more significant epoch numbers, the accuracy could be increased by a few percentages. Here’s a GitHub repository for the code presented in this article. Dropout is a common regularization technique that is leveraged within the state of the art solutions to computer vision tasks such as pose estimation, object detection or semantic segmentation. The concept is simple to understand and easier to implement through its inclusion in many standard machine/deep learning libraries such as PyTorch, TensorFlow and Keras. If you are interested in other regularization techniques and how they are implemented, have a read of the articles below. Thanks for reading.
[ { "code": null, "e": 227, "s": 47, "text": "This article covers the concept of the dropout technique, a technique that is leveraged in deep neural networks such as recurrent neural networks and convolutional neural network." }, { "code": null, "e": 416, "s": 227, "text": "The Dropout technique involves the omission of neurons that act as feature detectors from the neural network during each training step. The exclusion of each neuron is determined randomly." }, { "code": null, "e": 568, "s": 416, "text": "G.E Hinton proposed this simple technique in 2012 in the published paper: “Improving neural networks by preventing co-adaptation of feature detectors”." }, { "code": null, "e": 734, "s": 568, "text": "In this article, we will uncover the concept of dropout in-depth and look at how this technique can be implemented within neural networks using TensorFlow and Keras." }, { "code": null, "e": 1047, "s": 734, "text": "Neural networks have hidden layers in between their input and output layers, these hidden layers have neurons embedded within them, and it’s the weights within the neurons along with the interconnection between neurons is what enables the neural network system to simulate the process of what resembles learning." }, { "code": null, "e": 1324, "s": 1047, "text": "The general idea is that the more neurons and layers within a neural network architecture, the greater the representational power it has. This increase in representational power means that the neural network can fit more complex functions and generalize well to training data." }, { "code": null, "e": 1446, "s": 1324, "text": "Simply kept, there are more configurations for the interconnections between the neurons within the neural network layers." }, { "code": null, "e": 1545, "s": 1446, "text": "The disadvantage of utilizing deeper neural networks is that they are highly prone to overfitting." }, { "code": null, "e": 1747, "s": 1545, "text": "Overfitting is a common problem that is defined as the inability for a trained machine learning model to generalized well to unseen data, but the same model performs well on the data it was trained on." }, { "code": null, "e": 1845, "s": 1747, "text": "The primary purpose of dropout is to minimize the effect of overfitting within a trained network." }, { "code": null, "e": 2097, "s": 1845, "text": "Dropout technique works by randomly reducing the number of interconnecting neurons within a neural network. At every training step, each neuron has a chance of being left out, or rather, dropped out of the collated contribution from connected neurons." }, { "code": null, "e": 2323, "s": 2097, "text": "This technique minimizes overfitting because each neuron becomes independently sufficient, in the sense that the neurons within the layers learn weight values that are not based on the cooperation of its neighbouring neurons." }, { "code": null, "e": 2477, "s": 2323, "text": "Hence, we reduce the dependence on a large number of interconnecting neurons to generate a decent representational power from the trained neural network." }, { "code": null, "e": 2633, "s": 2477, "text": "Supposedly you trained 7,000 different neural network architecture, to select the best one you simply take the average of all 7,000 trained neural network." }, { "code": null, "e": 2692, "s": 2633, "text": "Well, the dropout technique actually mimics this scenario." }, { "code": null, "e": 3133, "s": 2692, "text": "If the probability of a neuron getting dropped out in a training step is set to 0.5; we are actually training a variety of different network at each training step as it’s highly impossible that the same neurons are excluded at any two training steps. Therefore a neural network that has been trained utilizing the dropout technique is an average of all the different neurons connection combinations that have occurred at each training step." }, { "code": null, "e": 3287, "s": 3133, "text": "In practical scenarios, or when testing the performance of the trained neural network that utilized dropout on unseen data, certain items are considered." }, { "code": null, "e": 3496, "s": 3287, "text": "The first being the fact that dropout technique is actually not implemented on every single layer within a neural network; it’s commonly leveraged within the neurons in the last few layers within the network." }, { "code": null, "e": 3899, "s": 3496, "text": "In the experiments conducted in the published paper, it was reported that when testing on the CIFAR-10 dataset, there was an error rate of 15.6% when dropout was utilized in the last hidden layer. This was an improvement from the error rate of 16.6% that was reported when the same dataset was tested on the same convolutional neural network but with no dropout technique included in any of the layers." }, { "code": null, "e": 4274, "s": 3899, "text": "The second item is that within practical scenarios dropout isn’t utilized when evaluating a trained neural network. As a result of dropout not used during the evaluation or testing phase, the full potential of the neural network is realized. This means that all neurons within the network are active, and each neuron has more input connections than it had been trained with." }, { "code": null, "e": 4545, "s": 4274, "text": "Therefore it’s expected to divide the weights of the neurons by one minus the dropout hyperparameter value(dropout rate that’s used during training). So if the dropout rate was 0.5 during training, then in test time the results of the weights from each neuron is halved." }, { "code": null, "e": 4738, "s": 4545, "text": "Using TensorFlow and Keras, we are equipped with the tools to implement a neural network that utilizes the dropout technique by including dropout layers within the neural network architecture." }, { "code": null, "e": 5132, "s": 4738, "text": "We only need to add one line to include a dropout layer within a more extensive neural network architecture. The Dropout class takes a few arguments, but for now, we are only concerned with the ‘rate’ argument. The dropout rate is a hyperparameter that represents the likelihood of a neuron activation been set to zero during a training step. The rate argument can take values between 0 and 1." }, { "code": null, "e": 5163, "s": 5132, "text": "keras.layers.Dropout(rate=0.2)" }, { "code": null, "e": 5276, "s": 5163, "text": "From this point onwards, we will go through small steps taken to implement, train and evaluate a neural network." }, { "code": null, "e": 5332, "s": 5276, "text": "Load tools and libraries utilized, Keras and TensorFlow" }, { "code": null, "e": 5388, "s": 5332, "text": "Load tools and libraries utilized, Keras and TensorFlow" }, { "code": null, "e": 5440, "s": 5388, "text": "import tensorflow as tffrom tensorflow import keras" }, { "code": null, "e": 5554, "s": 5440, "text": "2. Load the FashionMNIST dataset, normalize images and partition dataset into test, training and validation data." }, { "code": null, "e": 5800, "s": 5554, "text": "(train_images, train_labels),(test_images, test_labels) = keras.datasets.fashion_mnist.load_data()train_images = train_images / 255.0test_images = test_images / 255.0validation_images = train_images[:5000]validation_labels = train_labels[:5000]" }, { "code": null, "e": 5888, "s": 5800, "text": "3. Create a custom model that includes a dropout layer using the Keras Model Class API." }, { "code": null, "e": 6912, "s": 5888, "text": "class CustomModel(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) self.input_layer = keras.layers.Flatten(input_shape=(28,28)) self.hidden1 = keras.layers.Dense(200, activation='relu') self.hidden2 = keras.layers.Dense(100, activation='relu') self.hidden3 = keras.layers.Dense(60, activation='relu') self.output_layer = keras.layers.Dense(10, activation='softmax') self.dropout_layer = keras.layers.Dropout(rate=0.2) def call(self, input, training=None): input_layer = self.input_layer(input) input_layer = self.dropout_layer(input_layer) hidden1 = self.hidden1(input_layer) hidden1 = self.dropout_layer(hidden1, training=training) hidden2 = self.hidden2(hidden1) hidden2 = self.dropout_layer(hidden2, training=training) hidden3 = self.hidden3(hidden2) hidden3 = self.dropout_layer(hidden3, training=training) output_layer = self.output_layer(hidden3) return output_layer" }, { "code": null, "e": 6994, "s": 6912, "text": "4. Load the implemented model and initialize both optimizers and hyperparameters." }, { "code": null, "e": 7141, "s": 6994, "text": "model = CustomModel()sgd = keras.optimizers.SGD(lr=0.01)model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=sgd, metrics=[\"accuracy\"])" }, { "code": null, "e": 7185, "s": 7141, "text": "5. Train the model for a total of 60 epochs" }, { "code": null, "e": 7290, "s": 7185, "text": "model.fit(train_images, train_labels, epochs=60, validation_data=(validation_images, validation_labels))" }, { "code": null, "e": 7332, "s": 7290, "text": "6. Evaluate the model on the test dataset" }, { "code": null, "e": 7373, "s": 7332, "text": "model.evaluate(test_images, test_labels)" }, { "code": null, "e": 7460, "s": 7373, "text": "The result of the evaluation will look similar to the example evaluation result below:" }, { "code": null, "e": 7585, "s": 7460, "text": "10000/10000 [==============================] - 0s 34us/sample - loss: 0.3230 - accuracy: 0.8812[0.32301584649085996, 0.8812]" }, { "code": null, "e": 7686, "s": 7585, "text": "The accuracy shown in the evaluation result example corresponds to the accuracy of our model of 88%." }, { "code": null, "e": 7812, "s": 7686, "text": "With some fine-tuning and training with more significant epoch numbers, the accuracy could be increased by a few percentages." }, { "code": null, "e": 7879, "s": 7812, "text": "Here’s a GitHub repository for the code presented in this article." }, { "code": null, "e": 8243, "s": 7879, "text": "Dropout is a common regularization technique that is leveraged within the state of the art solutions to computer vision tasks such as pose estimation, object detection or semantic segmentation. The concept is simple to understand and easier to implement through its inclusion in many standard machine/deep learning libraries such as PyTorch, TensorFlow and Keras." }, { "code": null, "e": 8365, "s": 8243, "text": "If you are interested in other regularization techniques and how they are implemented, have a read of the articles below." } ]
How to check if a string is a valid keyword in C#?
To check if a string is a valid keyword, use the IsValidIdentifier method. The IsValidIdentifier method checks whether the entered value is an identifier or not. If it’s not an identifier, then it’s a keyword in C#. Let us see an example, wherein we have set the CodeDomProvider and worked with the IsValiddentifier method − CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); Let us see the complete codeL Live Demo using System; using System.IO; using System.CodeDom.Compiler; namespace Program { class Demo { static void Main(string[] args) { string str1 = "amit"; string str2 = "for"; CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); // checking for str1 if (provider.IsValidIdentifier(str1)) { Console.WriteLine("{0} is an identifier", str1); } else { Console.WriteLine("{0} is a Valid Keyword in C#", str1); } // checking for str2 if (provider.IsValidIdentifier(str2)) { Console.WriteLine("{0} is an identifier", str2); } else { Console.Write("{0} is a Valid Keyword in C#", str2); } } } } amit is an identifier for is a Valid Keyword in C#
[ { "code": null, "e": 1137, "s": 1062, "text": "To check if a string is a valid keyword, use the IsValidIdentifier method." }, { "code": null, "e": 1278, "s": 1137, "text": "The IsValidIdentifier method checks whether the entered value is an identifier or not. If it’s not an identifier, then it’s a keyword in C#." }, { "code": null, "e": 1387, "s": 1278, "text": "Let us see an example, wherein we have set the CodeDomProvider and worked with the IsValiddentifier method −" }, { "code": null, "e": 1452, "s": 1387, "text": "CodeDomProvider provider = CodeDomProvider.CreateProvider(\"C#\");" }, { "code": null, "e": 1482, "s": 1452, "text": "Let us see the complete codeL" }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 2261, "s": 1493, "text": "using System;\nusing System.IO;\nusing System.CodeDom.Compiler;\n\nnamespace Program {\n class Demo {\n static void Main(string[] args) {\n \n string str1 = \"amit\";\n string str2 = \"for\";\n\n CodeDomProvider provider = CodeDomProvider.CreateProvider(\"C#\");\n\n // checking for str1\n if (provider.IsValidIdentifier(str1)) {\n Console.WriteLine(\"{0} is an identifier\", str1);\n } else {\n Console.WriteLine(\"{0} is a Valid Keyword in C#\", str1);\n }\n\n // checking for str2\n if (provider.IsValidIdentifier(str2)) {\n Console.WriteLine(\"{0} is an identifier\", str2);\n } else {\n Console.Write(\"{0} is a Valid Keyword in C#\", str2);\n }\n }\n }\n}" }, { "code": null, "e": 2312, "s": 2261, "text": "amit is an identifier\nfor is a Valid Keyword in C#" } ]
DelayQueue Class in Java with Example - GeeksforGeeks
20 May, 2021 The DelayQueue class is a member of the Java Collections Framework. It belongs to java.util.concurrent package. DelayQueue implements the BlockingQueue interface. DelayQueue is a specialized Priority Queue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired. DelayQueue head contains the element that has expired in the least time. If no delay has expired, then there is no head and the poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed or those implement java.util.concurrent.Delayed interface. The DelayQueue blocks the elements internally until a certain delay has expired. DelayQueue implements the getDelay(TimeUnit.NANOSECONDS) method to return the remaining delay time. The TimeUnit instance passed to the getDelay() method is an Enum that tells which time unit the delay should be returned in. The TimeUnit enum can take DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS. This queue does not permit null elements. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the DelayQueue in any particular order. // Declaration of Delayed interface public interface Delayed extends Comparable<Delayed> { /** * Returns the remaining delay associated with this object, in the * given time unit. * * @param unit the time unit * * @return the remaining delay; zero or negative values indicate * that the delay has already elapsed */ long getDelay(TimeUnit unit); } The Hierarchy of DelayQueue It implements Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces. Class Declaration: public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E> Here, E is the type of element maintained by this collection. To construct a DelayQueue, we need to import it from java.util.concurrent.DelayQueue. 1. DelayQueue(): This constructor is used to construct an empty DelayQueue. DelayQueue<E> dq = new DelayQueue<E>(); 2. DelayQueue(Collection<E> c): This constructor is used to construct a DelayQueue with the elements of the Collection of Delayed instances passed as the parameter. DelayQueue<E> dq = new DelayQueue(Collection<E> c); Below is a sample program to illustrate DelayQueue in Java: Java // Java Program Demonstrate DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return "\n{" + "name=" + name + ", time=" + time + "}"; }} // Driver Classpublic class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue DQ.add(new DelayObject("A", 1)); DQ.add(new DelayObject("B", 2)); DQ.add(new DelayObject("C", 3)); DQ.add(new DelayObject("D", 4)); // print DelayQueue System.out.println("DelayQueue: " + DQ); // create object of DelayQueue // using DelayQueue(Collection c) // constructor BlockingQueue<DelayObject> DQ2 = new DelayQueue<DelayObject>(DQ); // print DelayQueue System.out.println("DelayQueue: " + DQ2); }} DelayQueue: [ {name=A, time=1543472836003}, {name=B, time=1543472836004}, {name=C, time=1543472836005}, {name=D, time=1543472836006}] DelayQueue: [ {name=A, time=1543472836003}, {name=B, time=1543472836004}, {name=C, time=1543472836005}, {name=D, time=1543472836006}] Below is a sample program to illustrate DelayQueue methods in Java: Java // Java Program Demonstrate DelayQueue methods import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() // method of Delayed @Override public String toString() { return "\n{" + "name=" + name + ", time=" + time + "}"; }} // Driver Classpublic class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject("A", 1)); DQ.add(new DelayObject("B", 2)); DQ.add(new DelayObject("C", 3)); DQ.add(new DelayObject("D", 4)); // print queue System.out.println("DelayQueue: " + DQ); // print the head using peek() method System.out.println("Head of DelayQueue: " + DQ.peek()); // print the size using size() method System.out.println("Size of DelayQueue: " + DQ.size()); // remove the head using poll() method System.out.println("Head of DelayQueue: " + DQ.poll()); // print the size using size() method System.out.println("Size of DelayQueue: " + DQ.size()); // clear the DelayQueue using clear() method DQ.clear(); System.out.println("Size of DelayQueue" + " after clear: " + DQ.size()); }} DelayQueue: [ {name=A, time=1543472845012}, {name=B, time=1543472845013}, {name=C, time=1543472845014}, {name=D, time=1543472845015}] Head of DelayQueue: {name=A, time=1543472845012} Size of DelayQueue: 4 Head of DelayQueue: {name=A, time=1543472845012} Size of DelayQueue: 3 Size of DelayQueue after clear: 0 1. Adding Elements The add(E e) method of DelayQueue class in Java is used to insert the given element into the delay queue and returns true if the element has been successfully inserted. Java // Java program to illustrate the adding// elements to the DelayQueue import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class AddingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an instance of Delayed Delayed obj = new Delayed() { public long getDelay(TimeUnit unit) { return 24; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this.getDelay(TimeUnit.DAYS)) return 1; else if (o.getDelay(TimeUnit.DAYS) == this.getDelay(TimeUnit.DAYS)) return 0; return -1; } }; // Use the add() method to add obj to // the empty DelayQueue instance queue.add(obj); // printing size of the queue to the console System.out.println("Size of the queue : " + queue.size()); }} Size of the queue : 1 2. Removing Elements The remove() method of DelayQueue class in Java is used to remove a single instance of the given object say obj from this DelayQueue if it is present. It returns true if the given element is removed successfully otherwise it returns false. Java // Java Program to illustrate the removing// elements of DelayQueue class import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class RemovingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an object of type Delayed Delayed ob = new Delayed() { public long getDelay(TimeUnit unit) { return 24; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this.getDelay(TimeUnit.DAYS)) return 1; else if (o.getDelay(TimeUnit.DAYS) == this.getDelay(TimeUnit.DAYS)) return 0; return -1; } }; // Add the object to DelayQueue queue.add(ob); // Print initial size of Queue System.out.println("Initial Size : " + queue.size()); // Remove the object ob from // this DelayQueue queue.remove(ob); // Print the final size of the DelayQueue System.out.println("Size after removing : " + queue.size()); }} Initial Size : 1 Size after removing : 0 3. Accessing Elements The peek() method of DelayQueue is used to retrieve the head of the DelayQueue, but does not remove it, as in the case of the poll() method where the head is removed from the DelayQueue. Java // Java Program Demonstrate accessing// elements of DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return "\n{" + " " + name + ", time=" + time + "}"; }} // Driver Classpublic class AccessingElementsExample { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject("A", 1)); DQ.add(new DelayObject("B", 2)); // Print delayqueue System.out.println("Original DelayQueue: " + DQ + "\n"); // removing all elements DQ.clear(); // peek() method for returning head of the // DelayQueue System.out.println("Head of the DelayQueue: " + DQ.peek()); }} Original DelayQueue: [ { A, time=1600770273132}, { B, time=1600770273134}] Head of the DelayQueue: null 4. Traversing The iterator() method of DelayQueue is used to return an iterator over all the elements in the DelayQueue. Java // Java Program Demonstrate iterating// over DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return "\n{" + " " + name + ", time=" + time + "}"; }} // Driver Classpublic class IteratingExample { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject("A", 1)); DQ.add(new DelayObject("B", 2)); DQ.add(new DelayObject("C", 3)); DQ.add(new DelayObject("D", 4)); // Creating an iterator Iterator val = DQ.iterator(); // print the value after iterating DelayQueue System.out.println("The iterator values are: "); while (val.hasNext()) { System.out.println(val.next()); } }} The iterator values are: { A, time=1600770415898} { B, time=1600770415900} { C, time=1600770415901} { D, time=1600770415902} METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html Ganeshchowdharysadanala arorakashish0911 Java-Collections java-DelayQueue Technical Scripter 2018 Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Set in Java LinkedList in Java Stream In Java
[ { "code": null, "e": 24254, "s": 24226, "text": "\n20 May, 2021" }, { "code": null, "e": 25568, "s": 24254, "text": "The DelayQueue class is a member of the Java Collections Framework. It belongs to java.util.concurrent package. DelayQueue implements the BlockingQueue interface. DelayQueue is a specialized Priority Queue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired. DelayQueue head contains the element that has expired in the least time. If no delay has expired, then there is no head and the poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed or those implement java.util.concurrent.Delayed interface. The DelayQueue blocks the elements internally until a certain delay has expired. DelayQueue implements the getDelay(TimeUnit.NANOSECONDS) method to return the remaining delay time. The TimeUnit instance passed to the getDelay() method is an Enum that tells which time unit the delay should be returned in. The TimeUnit enum can take DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS. This queue does not permit null elements. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the DelayQueue in any particular order. " }, { "code": null, "e": 25604, "s": 25568, "text": "// Declaration of Delayed interface" }, { "code": null, "e": 25657, "s": 25604, "text": "public interface Delayed extends Comparable<Delayed>" }, { "code": null, "e": 25659, "s": 25657, "text": "{" }, { "code": null, "e": 25663, "s": 25659, "text": "/**" }, { "code": null, "e": 25733, "s": 25663, "text": " * Returns the remaining delay associated with this object, in the" }, { "code": null, "e": 25756, "s": 25733, "text": " * given time unit." }, { "code": null, "e": 25762, "s": 25756, "text": " *" }, { "code": null, "e": 25794, "s": 25762, "text": " * @param unit the time unit" }, { "code": null, "e": 25800, "s": 25794, "text": " *" }, { "code": null, "e": 25868, "s": 25800, "text": " * @return the remaining delay; zero or negative values indicate" }, { "code": null, "e": 25909, "s": 25868, "text": " * that the delay has already elapsed" }, { "code": null, "e": 25916, "s": 25909, "text": " */" }, { "code": null, "e": 25949, "s": 25916, "text": " long getDelay(TimeUnit unit);" }, { "code": null, "e": 25951, "s": 25949, "text": "}" }, { "code": null, "e": 25979, "s": 25951, "text": "The Hierarchy of DelayQueue" }, { "code": null, "e": 26060, "s": 25979, "text": "It implements Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces." }, { "code": null, "e": 26081, "s": 26060, "text": "Class Declaration: " }, { "code": null, "e": 26178, "s": 26081, "text": "public class DelayQueue<E extends Delayed> extends AbstractQueue<E> implements BlockingQueue<E> " }, { "code": null, "e": 26240, "s": 26178, "text": "Here, E is the type of element maintained by this collection." }, { "code": null, "e": 26326, "s": 26240, "text": "To construct a DelayQueue, we need to import it from java.util.concurrent.DelayQueue." }, { "code": null, "e": 26402, "s": 26326, "text": "1. DelayQueue(): This constructor is used to construct an empty DelayQueue." }, { "code": null, "e": 26442, "s": 26402, "text": "DelayQueue<E> dq = new DelayQueue<E>();" }, { "code": null, "e": 26607, "s": 26442, "text": "2. DelayQueue(Collection<E> c): This constructor is used to construct a DelayQueue with the elements of the Collection of Delayed instances passed as the parameter." }, { "code": null, "e": 26659, "s": 26607, "text": "DelayQueue<E> dq = new DelayQueue(Collection<E> c);" }, { "code": null, "e": 26720, "s": 26659, "text": "Below is a sample program to illustrate DelayQueue in Java: " }, { "code": null, "e": 26725, "s": 26720, "text": "Java" }, { "code": "// Java Program Demonstrate DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return \"\\n{\" + \"name=\" + name + \", time=\" + time + \"}\"; }} // Driver Classpublic class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue DQ.add(new DelayObject(\"A\", 1)); DQ.add(new DelayObject(\"B\", 2)); DQ.add(new DelayObject(\"C\", 3)); DQ.add(new DelayObject(\"D\", 4)); // print DelayQueue System.out.println(\"DelayQueue: \" + DQ); // create object of DelayQueue // using DelayQueue(Collection c) // constructor BlockingQueue<DelayObject> DQ2 = new DelayQueue<DelayObject>(DQ); // print DelayQueue System.out.println(\"DelayQueue: \" + DQ2); }}", "e": 28790, "s": 26725, "text": null }, { "code": null, "e": 29064, "s": 28790, "text": "DelayQueue: [\n{name=A, time=1543472836003}, \n{name=B, time=1543472836004}, \n{name=C, time=1543472836005}, \n{name=D, time=1543472836006}]\nDelayQueue: [\n{name=A, time=1543472836003}, \n{name=B, time=1543472836004}, \n{name=C, time=1543472836005}, \n{name=D, time=1543472836006}]" }, { "code": null, "e": 29134, "s": 29066, "text": "Below is a sample program to illustrate DelayQueue methods in Java:" }, { "code": null, "e": 29139, "s": 29134, "text": "Java" }, { "code": "// Java Program Demonstrate DelayQueue methods import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() // method of Delayed @Override public String toString() { return \"\\n{\" + \"name=\" + name + \", time=\" + time + \"}\"; }} // Driver Classpublic class GFG { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject(\"A\", 1)); DQ.add(new DelayObject(\"B\", 2)); DQ.add(new DelayObject(\"C\", 3)); DQ.add(new DelayObject(\"D\", 4)); // print queue System.out.println(\"DelayQueue: \" + DQ); // print the head using peek() method System.out.println(\"Head of DelayQueue: \" + DQ.peek()); // print the size using size() method System.out.println(\"Size of DelayQueue: \" + DQ.size()); // remove the head using poll() method System.out.println(\"Head of DelayQueue: \" + DQ.poll()); // print the size using size() method System.out.println(\"Size of DelayQueue: \" + DQ.size()); // clear the DelayQueue using clear() method DQ.clear(); System.out.println(\"Size of DelayQueue\" + \" after clear: \" + DQ.size()); }}", "e": 31700, "s": 29139, "text": null }, { "code": null, "e": 32020, "s": 31700, "text": "DelayQueue: [\n{name=A, time=1543472845012}, \n{name=B, time=1543472845013}, \n{name=C, time=1543472845014}, \n{name=D, time=1543472845015}]\n\nHead of DelayQueue: \n{name=A, time=1543472845012}\n\nSize of DelayQueue: 4\n\nHead of DelayQueue: \n{name=A, time=1543472845012}\n\nSize of DelayQueue: 3\n\nSize of DelayQueue after clear: 0" }, { "code": null, "e": 32041, "s": 32022, "text": "1. Adding Elements" }, { "code": null, "e": 32211, "s": 32041, "text": "The add(E e) method of DelayQueue class in Java is used to insert the given element into the delay queue and returns true if the element has been successfully inserted. " }, { "code": null, "e": 32216, "s": 32211, "text": "Java" }, { "code": "// Java program to illustrate the adding// elements to the DelayQueue import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class AddingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an instance of Delayed Delayed obj = new Delayed() { public long getDelay(TimeUnit unit) { return 24; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this.getDelay(TimeUnit.DAYS)) return 1; else if (o.getDelay(TimeUnit.DAYS) == this.getDelay(TimeUnit.DAYS)) return 0; return -1; } }; // Use the add() method to add obj to // the empty DelayQueue instance queue.add(obj); // printing size of the queue to the console System.out.println(\"Size of the queue : \" + queue.size()); }}", "e": 33425, "s": 32216, "text": null }, { "code": null, "e": 33450, "s": 33428, "text": "Size of the queue : 1" }, { "code": null, "e": 33473, "s": 33452, "text": "2. Removing Elements" }, { "code": null, "e": 33717, "s": 33475, "text": "The remove() method of DelayQueue class in Java is used to remove a single instance of the given object say obj from this DelayQueue if it is present. It returns true if the given element is removed successfully otherwise it returns false. " }, { "code": null, "e": 33724, "s": 33719, "text": "Java" }, { "code": "// Java Program to illustrate the removing// elements of DelayQueue class import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; public class RemovingElementsExample { public static void main(String args[]) { // Create a DelayQueue instance DelayQueue<Delayed> queue = new DelayQueue<Delayed>(); // Create an object of type Delayed Delayed ob = new Delayed() { public long getDelay(TimeUnit unit) { return 24; // some value is returned } public int compareTo(Delayed o) { if (o.getDelay(TimeUnit.DAYS) > this.getDelay(TimeUnit.DAYS)) return 1; else if (o.getDelay(TimeUnit.DAYS) == this.getDelay(TimeUnit.DAYS)) return 0; return -1; } }; // Add the object to DelayQueue queue.add(ob); // Print initial size of Queue System.out.println(\"Initial Size : \" + queue.size()); // Remove the object ob from // this DelayQueue queue.remove(ob); // Print the final size of the DelayQueue System.out.println(\"Size after removing : \" + queue.size()); }}", "e": 35044, "s": 33724, "text": null }, { "code": null, "e": 35088, "s": 35047, "text": "Initial Size : 1\nSize after removing : 0" }, { "code": null, "e": 35112, "s": 35090, "text": "3. Accessing Elements" }, { "code": null, "e": 35301, "s": 35114, "text": "The peek() method of DelayQueue is used to retrieve the head of the DelayQueue, but does not remove it, as in the case of the poll() method where the head is removed from the DelayQueue." }, { "code": null, "e": 35308, "s": 35303, "text": "Java" }, { "code": "// Java Program Demonstrate accessing// elements of DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return \"\\n{\" + \" \" + name + \", time=\" + time + \"}\"; }} // Driver Classpublic class AccessingElementsExample { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject(\"A\", 1)); DQ.add(new DelayObject(\"B\", 2)); // Print delayqueue System.out.println(\"Original DelayQueue: \" + DQ + \"\\n\"); // removing all elements DQ.clear(); // peek() method for returning head of the // DelayQueue System.out.println(\"Head of the DelayQueue: \" + DQ.peek()); }}", "e": 37210, "s": 35308, "text": null }, { "code": null, "e": 37319, "s": 37213, "text": "Original DelayQueue: [\n{ A, time=1600770273132}, \n{ B, time=1600770273134}]\n\nHead of the DelayQueue: null" }, { "code": null, "e": 37335, "s": 37321, "text": "4. Traversing" }, { "code": null, "e": 37444, "s": 37337, "text": "The iterator() method of DelayQueue is used to return an iterator over all the elements in the DelayQueue." }, { "code": null, "e": 37451, "s": 37446, "text": "Java" }, { "code": "// Java Program Demonstrate iterating// over DelayQueue import java.util.concurrent.*;import java.util.*; // The DelayObject for DelayQueue// It must implement Delayed and// its getDelay() and compareTo() methodclass DelayObject implements Delayed { private String name; private long time; // Constructor of DelayObject public DelayObject(String name, long delayTime) { this.name = name; this.time = System.currentTimeMillis() + delayTime; } // Implementing getDelay() method of Delayed @Override public long getDelay(TimeUnit unit) { long diff = time - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } // Implementing compareTo() method of Delayed @Override public int compareTo(Delayed obj) { if (this.time < ((DelayObject)obj).time) { return -1; } if (this.time > ((DelayObject)obj).time) { return 1; } return 0; } // Implementing toString() method of Delayed @Override public String toString() { return \"\\n{\" + \" \" + name + \", time=\" + time + \"}\"; }} // Driver Classpublic class IteratingExample { public static void main(String[] args) throws InterruptedException { // create object of DelayQueue // using DelayQueue() constructor BlockingQueue<DelayObject> DQ = new DelayQueue<DelayObject>(); // Add numbers to end of DelayQueue // using add() method DQ.add(new DelayObject(\"A\", 1)); DQ.add(new DelayObject(\"B\", 2)); DQ.add(new DelayObject(\"C\", 3)); DQ.add(new DelayObject(\"D\", 4)); // Creating an iterator Iterator val = DQ.iterator(); // print the value after iterating DelayQueue System.out.println(\"The iterator values are: \"); while (val.hasNext()) { System.out.println(val.next()); } }}", "e": 39379, "s": 37451, "text": null }, { "code": null, "e": 39512, "s": 39382, "text": "The iterator values are: \n\n{ A, time=1600770415898}\n\n{ B, time=1600770415900}\n\n{ C, time=1600770415901}\n\n{ D, time=1600770415902}" }, { "code": null, "e": 39521, "s": 39514, "text": "METHOD" }, { "code": null, "e": 39533, "s": 39521, "text": "DESCRIPTION" }, { "code": null, "e": 39540, "s": 39533, "text": "METHOD" }, { "code": null, "e": 39552, "s": 39540, "text": "DESCRIPTION" }, { "code": null, "e": 39559, "s": 39552, "text": "METHOD" }, { "code": null, "e": 39571, "s": 39559, "text": "DESCRIPTION" }, { "code": null, "e": 39578, "s": 39571, "text": "METHOD" }, { "code": null, "e": 39590, "s": 39578, "text": "DESCRIPTION" }, { "code": null, "e": 39597, "s": 39590, "text": "METHOD" }, { "code": null, "e": 39609, "s": 39597, "text": "DESCRIPTION" }, { "code": null, "e": 39616, "s": 39609, "text": "METHOD" }, { "code": null, "e": 39628, "s": 39616, "text": "DESCRIPTION" }, { "code": null, "e": 39635, "s": 39628, "text": "METHOD" }, { "code": null, "e": 39647, "s": 39635, "text": "DESCRIPTION" }, { "code": null, "e": 39756, "s": 39647, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/DelayQueue.html" }, { "code": null, "e": 39782, "s": 39758, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 39799, "s": 39782, "text": "arorakashish0911" }, { "code": null, "e": 39816, "s": 39799, "text": "Java-Collections" }, { "code": null, "e": 39832, "s": 39816, "text": "java-DelayQueue" }, { "code": null, "e": 39856, "s": 39832, "text": "Technical Scripter 2018" }, { "code": null, "e": 39861, "s": 39856, "text": "Java" }, { "code": null, "e": 39880, "s": 39861, "text": "Technical Scripter" }, { "code": null, "e": 39885, "s": 39880, "text": "Java" }, { "code": null, "e": 39902, "s": 39885, "text": "Java-Collections" }, { "code": null, "e": 40000, "s": 39902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40009, "s": 40000, "text": "Comments" }, { "code": null, "e": 40022, "s": 40009, "text": "Old Comments" }, { "code": null, "e": 40052, "s": 40022, "text": "HashMap in Java with Examples" }, { "code": null, "e": 40071, "s": 40052, "text": "Interfaces in Java" }, { "code": null, "e": 40089, "s": 40071, "text": "ArrayList in Java" }, { "code": null, "e": 40121, "s": 40089, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 40145, "s": 40121, "text": "Singleton Class in Java" }, { "code": null, "e": 40164, "s": 40145, "text": "Overriding in Java" }, { "code": null, "e": 40184, "s": 40164, "text": "Collections in Java" }, { "code": null, "e": 40196, "s": 40184, "text": "Set in Java" }, { "code": null, "e": 40215, "s": 40196, "text": "LinkedList in Java" } ]
Find largest word in dictionary by deleting some characters of given string - GeeksforGeeks
14 Mar, 2022 Giving a dictionary and a string ‘str’, find the longest string in dictionary which can be formed by deleting some characters of the given ‘str’. Examples: Input : dict = {"ale", "apple", "monkey", "plea"} str = "abpcplea" Output : apple Input : dict = {"pintu", "geeksfor", "geeksgeeks", " forgeek"} str = "geeksforgeeks" Output : geeksgeeks Asked In: Google Interview This problem reduces to finding if a string is subsequence of another string or not. We traverse all dictionary words and for every word, we check if it is subsequence of given string and is largest of all such words. We finally return the longest word with given string as subsequence.Below is the implementation of above idea C++ Java Python3 C# PHP Javascript // C++ program to find largest word in Dictionary// by deleting some characters of given string#include <bits/stdc++.h>using namespace std; // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2bool isSubSequence(string str1, string str2){ int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m);} // Returns the longest string in dictionary which is a// subsequence of str.string findLongestString(vector<string> dict, string str){ string result = ""; int length = 0; // Traverse through all words of dictionary for (string word : dict) { // If current word is subsequence of str and is // largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest string return result;} // Driver program to test above functionint main(){ vector<string> dict = { "ale", "apple", "monkey", "plea" }; string str = "abpcplea"; cout << findLongestString(dict, str) << endl; return 0;} // Java program to find largest// word in Dictionary by deleting// some characters of given String import java.util.*; class GFG{ // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 static boolean isSubSequence(String str1, String str2) { int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence) // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) { if (str1.charAt(j) == str2.charAt(i)) { j++; } } // If all characters of str1 // were found in str2 return (j == m); } // Returns the longest String// in dictionary which is a// subsequence of str. static String findLongestString(Vector<String> dict, String str) { String result = ""; int length = 0; // Traverse through all words of dictionary for (String word : dict) { // If current word is subsequence of str // and is largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest String return result; } // Driver code public static void main(String[] args) { String[] arr = {"ale", "apple", "monkey", "plea"}; Vector dict = new Vector(Arrays.asList(arr)); String str = "abpcplea"; System.out.println(findLongestString(dict, str)); }} // This code is contributed by 29AjayKumar # Python3 program to find largest word in Dictionary# by deleting some characters of given string # Returns true if str1[] is a subsequence of str2[].# m is length of str1 and n is length of str2def isSubSequence(str1, str2): m = len(str1); n = len(str2); j = 0; # For index of str1 (or subsequence # Traverse str2 and str1, and compare current # character of str2 with first unmatched char # of str1, if matched then move ahead in str1 i = 0; while (i < n and j < m): if (str1[j] == str2[i]): j += 1; i += 1; # If all characters of str1 were found in str2 return (j == m); # Returns the longest string in dictionary which is a# subsequence of str.def findLongestString(dict1, str1): result = ""; length = 0; # Traverse through all words of dictionary for word in dict1: # If current word is subsequence of str and is largest # such word so far. if (length < len(word) and isSubSequence(word, str1)): result = word; length = len(word); # Return longest string return result; # Driver program to test above function dict1 = ["ale", "apple", "monkey", "plea"];str1 = "abpcplea" ;print(findLongestString(dict1, str1)); # This code is conribued by mits // C# program to find largest// word in Dictionary by deleting// some characters of given Stringusing System;using System.Collections.Generic; class GFG{ // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 static bool isSubSequence(String str1, String str2) { int m = str1.Length, n = str2.Length; int j = 0; // For index of str1 (or subsequence) // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) { if (str1[j] == str2[i]) { j++; } } // If all characters of str1 // were found in str2 return (j == m); } // Returns the longest String // in dictionary which is a // subsequence of str. static String findLongestString(List<String> dict, String str) { String result = ""; int length = 0; // Traverse through all words of dictionary foreach (String word in dict) { // If current word is subsequence of str // and is largest such word so far. if (length < word.Length && isSubSequence(word, str)) { result = word; length = word.Length; } } // Return longest String return result; } // Driver code public static void Main(String[] args) { String[] arr = {"ale", "apple", "monkey", "plea"}; List<String> dict = new List<String>(arr); String str = "abpcplea"; Console.WriteLine(findLongestString(dict, str)); }} // This code contributed by Rajput-Ji <?php// PHP program to find largest word in Dictionary// by deleting some characters of given string // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2function isSubSequence($str1, $str2){ $m = strlen($str1); $n = strlen($str2); $j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for ($i = 0; $i < $n && $j < $m; $i++) if ($str1[$j] == $str2[$i]) $j++; // If all characters of str1 were found in str2 return ($j == $m);} // Returns the longest string in dictionary which is a// subsequence of str.function findLongestString($dict, $str){ $result = ""; $length = 0; // Traverse through all words of dictionary foreach ($dict as $word) { // If current word is subsequence // of str and is largest // such word so far. if ($length < strlen($word) && isSubSequence($word, $str)) { $result = $word; $length = strlen($word); } } // Return longest string return $result;} // Driver code$dict = array("ale", "apple", "monkey", "plea");$str = "abpcplea" ;echo findLongestString($dict, $str); // This code is conribued by mits?> <script> // JavaScript program to find largest word in Dictionary// by deleting some characters of given string // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2function isSubSequence(str1, str2){ var m = str1.length, n = str2.length; var j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (var i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m);} // Returns the longest string in dictionary which is a// subsequence of str.function findLongestString(dict, str){ var result = ""; var length = 0; // Traverse through all words of dictionary dict.forEach(word => { // If current word is subsequence of str and is // largest such word so far. if (length < word.length && isSubSequence(word, str)) { result = word; length = word.length; } }); // Return longest string return result;} // Driver program to test above functionvar dict = ["ale", "apple", "monkey", "plea"];var str = "abpcplea";document.write( findLongestString(dict, str)); </script> Output: apple Time Complexity: O(N*(K+n)) Here N is the length of dictionary and n is the length of given string ‘str’ and K – maximum length of words in the dictionary.Auxiliary Space: O(1) An efficient solution is we Sort the dictionary word. We traverse all dictionary words and for every word, we check if it is subsequence of given string and at last we check this subsequence is largest of all such subsequence.. We finally return the longest word with given string as subsequence. C++ Python3 Javascript // C++ program to find largest word in Dictionary// by deleting some characters of given string#include <bits/stdc++.h>using namespace std; string res=""; void check(string d,string s) { int i=0; int j=0; while(i<d.size() && j<s.size()) { if(d[i]==s[j]) { i++; j++; } else j++; } if(i==d.size() && res.size()<d.size()) { res=d; } } string LongestWord(vector<string> d,string S) { //sort the dictionary word // for smallest lexicographical order sort(d.begin(),d.end()); for(string c:d) { check(c,S); } return res; }// Driver programint main(){ vector<string> dict = { "ale", "apple", "monkey", "plea" }; string str = "abpcplea"; cout << LongestWord(dict, str) << endl; return 0;} # Python3 program to find largest word in Dictionary# by deleting some characters of given string res="" def check(d,s): global res i = 0 j = 0 while(i < len(d) and j < len(s)): if(d[i] == s[j]): i += 1 j += 1 else: j += 1 if(i == len(d) and len(res) < len(d)): res = d def LongestWord(d, S): # sort the dictionary word # for smallest lexicographical order d.sort() for c in d : check(c,S) return res # Driver programdict = [ "ale", "apple", "monkey", "plea" ]str = "abpcplea"print(LongestWord(dict, str)) # This code is contributed by shinjanpatra <script> // JavaScript program to find largest word in Dictionary// by deleting some characters of given stringlet res="";function check(d, s){ let i = 0; let j = 0; while(i < d.length && j < s.length) { if(d[i] == s[j]) { i++; j++; } else j++; } if(i == d.length && res.length < d.length) { res = d; } }function LongestWord(d,S){ // sort the dictionary word // for smallest lexicographical order d.sort(); for(let c of d) { check(c, S); } return res;} // Driver programlet dict = [ "ale", "apple", "monkey", "plea" ];let str = "abpcplea";document.write(LongestWord(dict, str),"</br>"); // This code is contributed by shinjanpatra </script> YouTubeGeeksforGeeks500K subscribersFind largest word in dictionary by deleting some characters of given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=31iAzVf8UxU" 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 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar Rajput-Ji Mithun Kumar NikitaRana07 noob2000 pushkar_s shinjanpatra subsequence Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Caesar Cipher in Cryptography Check for Balanced Brackets in an expression (well-formedness) using Stack Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Hill Cipher Length of the longest substring without repeating characters
[ { "code": null, "e": 24825, "s": 24797, "text": "\n14 Mar, 2022" }, { "code": null, "e": 24982, "s": 24825, "text": "Giving a dictionary and a string ‘str’, find the longest string in dictionary which can be formed by deleting some characters of the given ‘str’. Examples: " }, { "code": null, "e": 25236, "s": 24982, "text": "Input : dict = {\"ale\", \"apple\", \"monkey\", \"plea\"} \n str = \"abpcplea\" \nOutput : apple \n\nInput : dict = {\"pintu\", \"geeksfor\", \"geeksgeeks\", \n \" forgeek\"} \n str = \"geeksforgeeks\"\nOutput : geeksgeeks" }, { "code": null, "e": 25265, "s": 25236, "text": "Asked In: Google Interview " }, { "code": null, "e": 25595, "s": 25265, "text": "This problem reduces to finding if a string is subsequence of another string or not. We traverse all dictionary words and for every word, we check if it is subsequence of given string and is largest of all such words. We finally return the longest word with given string as subsequence.Below is the implementation of above idea " }, { "code": null, "e": 25599, "s": 25595, "text": "C++" }, { "code": null, "e": 25604, "s": 25599, "text": "Java" }, { "code": null, "e": 25612, "s": 25604, "text": "Python3" }, { "code": null, "e": 25615, "s": 25612, "text": "C#" }, { "code": null, "e": 25619, "s": 25615, "text": "PHP" }, { "code": null, "e": 25630, "s": 25619, "text": "Javascript" }, { "code": "// C++ program to find largest word in Dictionary// by deleting some characters of given string#include <bits/stdc++.h>using namespace std; // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2bool isSubSequence(string str1, string str2){ int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m);} // Returns the longest string in dictionary which is a// subsequence of str.string findLongestString(vector<string> dict, string str){ string result = \"\"; int length = 0; // Traverse through all words of dictionary for (string word : dict) { // If current word is subsequence of str and is // largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest string return result;} // Driver program to test above functionint main(){ vector<string> dict = { \"ale\", \"apple\", \"monkey\", \"plea\" }; string str = \"abpcplea\"; cout << findLongestString(dict, str) << endl; return 0;}", "e": 27081, "s": 25630, "text": null }, { "code": "// Java program to find largest// word in Dictionary by deleting// some characters of given String import java.util.*; class GFG{ // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 static boolean isSubSequence(String str1, String str2) { int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence) // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) { if (str1.charAt(j) == str2.charAt(i)) { j++; } } // If all characters of str1 // were found in str2 return (j == m); } // Returns the longest String// in dictionary which is a// subsequence of str. static String findLongestString(Vector<String> dict, String str) { String result = \"\"; int length = 0; // Traverse through all words of dictionary for (String word : dict) { // If current word is subsequence of str // and is largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest String return result; } // Driver code public static void main(String[] args) { String[] arr = {\"ale\", \"apple\", \"monkey\", \"plea\"}; Vector dict = new Vector(Arrays.asList(arr)); String str = \"abpcplea\"; System.out.println(findLongestString(dict, str)); }} // This code is contributed by 29AjayKumar", "e": 28951, "s": 27081, "text": null }, { "code": "# Python3 program to find largest word in Dictionary# by deleting some characters of given string # Returns true if str1[] is a subsequence of str2[].# m is length of str1 and n is length of str2def isSubSequence(str1, str2): m = len(str1); n = len(str2); j = 0; # For index of str1 (or subsequence # Traverse str2 and str1, and compare current # character of str2 with first unmatched char # of str1, if matched then move ahead in str1 i = 0; while (i < n and j < m): if (str1[j] == str2[i]): j += 1; i += 1; # If all characters of str1 were found in str2 return (j == m); # Returns the longest string in dictionary which is a# subsequence of str.def findLongestString(dict1, str1): result = \"\"; length = 0; # Traverse through all words of dictionary for word in dict1: # If current word is subsequence of str and is largest # such word so far. if (length < len(word) and isSubSequence(word, str1)): result = word; length = len(word); # Return longest string return result; # Driver program to test above function dict1 = [\"ale\", \"apple\", \"monkey\", \"plea\"];str1 = \"abpcplea\" ;print(findLongestString(dict1, str1)); # This code is conribued by mits", "e": 30235, "s": 28951, "text": null }, { "code": "// C# program to find largest// word in Dictionary by deleting// some characters of given Stringusing System;using System.Collections.Generic; class GFG{ // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 static bool isSubSequence(String str1, String str2) { int m = str1.Length, n = str2.Length; int j = 0; // For index of str1 (or subsequence) // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) { if (str1[j] == str2[i]) { j++; } } // If all characters of str1 // were found in str2 return (j == m); } // Returns the longest String // in dictionary which is a // subsequence of str. static String findLongestString(List<String> dict, String str) { String result = \"\"; int length = 0; // Traverse through all words of dictionary foreach (String word in dict) { // If current word is subsequence of str // and is largest such word so far. if (length < word.Length && isSubSequence(word, str)) { result = word; length = word.Length; } } // Return longest String return result; } // Driver code public static void Main(String[] args) { String[] arr = {\"ale\", \"apple\", \"monkey\", \"plea\"}; List<String> dict = new List<String>(arr); String str = \"abpcplea\"; Console.WriteLine(findLongestString(dict, str)); }} // This code contributed by Rajput-Ji", "e": 32110, "s": 30235, "text": null }, { "code": "<?php// PHP program to find largest word in Dictionary// by deleting some characters of given string // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2function isSubSequence($str1, $str2){ $m = strlen($str1); $n = strlen($str2); $j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for ($i = 0; $i < $n && $j < $m; $i++) if ($str1[$j] == $str2[$i]) $j++; // If all characters of str1 were found in str2 return ($j == $m);} // Returns the longest string in dictionary which is a// subsequence of str.function findLongestString($dict, $str){ $result = \"\"; $length = 0; // Traverse through all words of dictionary foreach ($dict as $word) { // If current word is subsequence // of str and is largest // such word so far. if ($length < strlen($word) && isSubSequence($word, $str)) { $result = $word; $length = strlen($word); } } // Return longest string return $result;} // Driver code$dict = array(\"ale\", \"apple\", \"monkey\", \"plea\");$str = \"abpcplea\" ;echo findLongestString($dict, $str); // This code is conribued by mits?>", "e": 33476, "s": 32110, "text": null }, { "code": "<script> // JavaScript program to find largest word in Dictionary// by deleting some characters of given string // Returns true if str1[] is a subsequence of str2[].// m is length of str1 and n is length of str2function isSubSequence(str1, str2){ var m = str1.length, n = str2.length; var j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (var i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m);} // Returns the longest string in dictionary which is a// subsequence of str.function findLongestString(dict, str){ var result = \"\"; var length = 0; // Traverse through all words of dictionary dict.forEach(word => { // If current word is subsequence of str and is // largest such word so far. if (length < word.length && isSubSequence(word, str)) { result = word; length = word.length; } }); // Return longest string return result;} // Driver program to test above functionvar dict = [\"ale\", \"apple\", \"monkey\", \"plea\"];var str = \"abpcplea\";document.write( findLongestString(dict, str)); </script>", "e": 34820, "s": 33476, "text": null }, { "code": null, "e": 34829, "s": 34820, "text": "Output: " }, { "code": null, "e": 34835, "s": 34829, "text": "apple" }, { "code": null, "e": 35014, "s": 34835, "text": "Time Complexity: O(N*(K+n)) Here N is the length of dictionary and n is the length of given string ‘str’ and K – maximum length of words in the dictionary.Auxiliary Space: O(1) " }, { "code": null, "e": 35312, "s": 35014, "text": "An efficient solution is we Sort the dictionary word. We traverse all dictionary words and for every word, we check if it is subsequence of given string and at last we check this subsequence is largest of all such subsequence.. We finally return the longest word with given string as subsequence." }, { "code": null, "e": 35316, "s": 35312, "text": "C++" }, { "code": null, "e": 35324, "s": 35316, "text": "Python3" }, { "code": null, "e": 35335, "s": 35324, "text": "Javascript" }, { "code": "// C++ program to find largest word in Dictionary// by deleting some characters of given string#include <bits/stdc++.h>using namespace std; string res=\"\"; void check(string d,string s) { int i=0; int j=0; while(i<d.size() && j<s.size()) { if(d[i]==s[j]) { i++; j++; } else j++; } if(i==d.size() && res.size()<d.size()) { res=d; } } string LongestWord(vector<string> d,string S) { //sort the dictionary word // for smallest lexicographical order sort(d.begin(),d.end()); for(string c:d) { check(c,S); } return res; }// Driver programint main(){ vector<string> dict = { \"ale\", \"apple\", \"monkey\", \"plea\" }; string str = \"abpcplea\"; cout << LongestWord(dict, str) << endl; return 0;}", "e": 36246, "s": 35335, "text": null }, { "code": "# Python3 program to find largest word in Dictionary# by deleting some characters of given string res=\"\" def check(d,s): global res i = 0 j = 0 while(i < len(d) and j < len(s)): if(d[i] == s[j]): i += 1 j += 1 else: j += 1 if(i == len(d) and len(res) < len(d)): res = d def LongestWord(d, S): # sort the dictionary word # for smallest lexicographical order d.sort() for c in d : check(c,S) return res # Driver programdict = [ \"ale\", \"apple\", \"monkey\", \"plea\" ]str = \"abpcplea\"print(LongestWord(dict, str)) # This code is contributed by shinjanpatra", "e": 36907, "s": 36246, "text": null }, { "code": "<script> // JavaScript program to find largest word in Dictionary// by deleting some characters of given stringlet res=\"\";function check(d, s){ let i = 0; let j = 0; while(i < d.length && j < s.length) { if(d[i] == s[j]) { i++; j++; } else j++; } if(i == d.length && res.length < d.length) { res = d; } }function LongestWord(d,S){ // sort the dictionary word // for smallest lexicographical order d.sort(); for(let c of d) { check(c, S); } return res;} // Driver programlet dict = [ \"ale\", \"apple\", \"monkey\", \"plea\" ];let str = \"abpcplea\";document.write(LongestWord(dict, str),\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 37692, "s": 36907, "text": null }, { "code": null, "e": 38566, "s": 37692, "text": "YouTubeGeeksforGeeks500K subscribersFind largest word in dictionary by deleting some characters of given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:38•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=31iAzVf8UxU\" 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": 38988, "s": 38566, "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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39000, "s": 38988, "text": "29AjayKumar" }, { "code": null, "e": 39010, "s": 39000, "text": "Rajput-Ji" }, { "code": null, "e": 39023, "s": 39010, "text": "Mithun Kumar" }, { "code": null, "e": 39036, "s": 39023, "text": "NikitaRana07" }, { "code": null, "e": 39045, "s": 39036, "text": "noob2000" }, { "code": null, "e": 39055, "s": 39045, "text": "pushkar_s" }, { "code": null, "e": 39068, "s": 39055, "text": "shinjanpatra" }, { "code": null, "e": 39080, "s": 39068, "text": "subsequence" }, { "code": null, "e": 39088, "s": 39080, "text": "Strings" }, { "code": null, "e": 39096, "s": 39088, "text": "Strings" }, { "code": null, "e": 39194, "s": 39096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39203, "s": 39194, "text": "Comments" }, { "code": null, "e": 39216, "s": 39203, "text": "Old Comments" }, { "code": null, "e": 39273, "s": 39216, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 39309, "s": 39273, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 39356, "s": 39309, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 39392, "s": 39356, "text": "Convert string to char array in C++" }, { "code": null, "e": 39422, "s": 39392, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 39497, "s": 39422, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 39550, "s": 39497, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 39588, "s": 39550, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 39600, "s": 39588, "text": "Hill Cipher" } ]
LISP - Loop For Construct
The loop for construct allows you to implement a for-loop like iteration as most common in other languages. It allows you to set up variables for iteration set up variables for iteration specify expression(s) that will conditionally terminate the iteration specify expression(s) that will conditionally terminate the iteration specify expression(s) for performing some job on each iteration specify expression(s) for performing some job on each iteration specify expression(s), and expressions for doing some job before exiting the loop specify expression(s), and expressions for doing some job before exiting the loop The for loop for construct follows several syntax − (loop for loop-variable in <a list> do (action) ) (loop for loop-variable from value1 to value2 do (action) ) Create a new source code file named main.lisp and type the following code in it − (loop for x in '(tom dick harry) do (format t " ~s" x) ) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − TOM DICK HARRY Create a new source code file named main.lisp and type the following code in it − (loop for a from 10 to 20 do (print a) ) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − 10 11 12 13 14 15 16 17 18 19 20 Create a new source code file named main.lisp and type the following code in it − (loop for x from 1 to 20 if(evenp x) do (print x) ) When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is − 2 4 6 8 10 12 14 16 18 20 79 Lectures 7 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2168, "s": 2060, "text": "The loop for construct allows you to implement a for-loop like iteration as most common in other languages." }, { "code": null, "e": 2185, "s": 2168, "text": "It allows you to" }, { "code": null, "e": 2216, "s": 2185, "text": "set up variables for iteration" }, { "code": null, "e": 2247, "s": 2216, "text": "set up variables for iteration" }, { "code": null, "e": 2317, "s": 2247, "text": "specify expression(s) that will conditionally terminate the iteration" }, { "code": null, "e": 2387, "s": 2317, "text": "specify expression(s) that will conditionally terminate the iteration" }, { "code": null, "e": 2451, "s": 2387, "text": "specify expression(s) for performing some job on each iteration" }, { "code": null, "e": 2515, "s": 2451, "text": "specify expression(s) for performing some job on each iteration" }, { "code": null, "e": 2597, "s": 2515, "text": "specify expression(s), and expressions for doing some job before exiting the loop" }, { "code": null, "e": 2679, "s": 2597, "text": "specify expression(s), and expressions for doing some job before exiting the loop" }, { "code": null, "e": 2731, "s": 2679, "text": "The for loop for construct follows several syntax −" }, { "code": null, "e": 2849, "s": 2731, "text": "(loop for loop-variable in <a list>\n do (action)\n)\n\n(loop for loop-variable from value1 to value2\n do (action)\n)\n" }, { "code": null, "e": 2931, "s": 2849, "text": "Create a new source code file named main.lisp and type the following code in it −" }, { "code": null, "e": 2991, "s": 2931, "text": "(loop for x in '(tom dick harry)\n do (format t \" ~s\" x)\n)" }, { "code": null, "e": 3100, "s": 2991, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3116, "s": 3100, "text": "TOM DICK HARRY\n" }, { "code": null, "e": 3198, "s": 3116, "text": "Create a new source code file named main.lisp and type the following code in it −" }, { "code": null, "e": 3242, "s": 3198, "text": "(loop for a from 10 to 20\n do (print a)\n)" }, { "code": null, "e": 3351, "s": 3242, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3396, "s": 3351, "text": "10 \n11 \n12 \n13 \n14 \n15 \n16 \n17 \n18 \n19 \n20 \n" }, { "code": null, "e": 3478, "s": 3396, "text": "Create a new source code file named main.lisp and type the following code in it −" }, { "code": null, "e": 3536, "s": 3478, "text": "(loop for x from 1 to 20\n if(evenp x)\n do (print x)\n)" }, { "code": null, "e": 3645, "s": 3536, "text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −" }, { "code": null, "e": 3681, "s": 3645, "text": "2 \n4 \n6 \n8 \n10 \n12 \n14 \n16 \n18 \n20\n" }, { "code": null, "e": 3714, "s": 3681, "text": "\n 79 Lectures \n 7 hours \n" }, { "code": null, "e": 3729, "s": 3714, "text": " Arnold Higuit" }, { "code": null, "e": 3736, "s": 3729, "text": " Print" }, { "code": null, "e": 3747, "s": 3736, "text": " Add Notes" } ]
Python - String Matrix Concatenation - GeeksforGeeks
13 Jan, 2022 Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join()We can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just join the elements extracted and put them into a as a single string. # Python3 code to demonstrate# String Matrix Concatenation# Using list comprehension # initializing listtest_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]] # printing original listprint("The original list : " + str(test_list)) # using list comprehension# count of all the elements in listres = "".join([ele for sub in test_list for ele in sub]) # print resultprint("The Matrix Concatenation is : " + str(res)) The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']] The Matrix Concatenation is : geeksforgeeks is best I Love Gfg Method #2 : Using chain() + join()This particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional join function to join. # Python3 code to demonstrate# String Matrix Concatenation # Using chain() + join()from itertools import chain # initializing listtest_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]] # printing original listprint("The original list : " + str(test_list)) # using chain() + join()# String Matrix Concatenationres = "".join(list(chain(*test_list))) # print resultprint("The Matrix Concatenation is : " + str(res)) The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']] The Matrix Concatenation is : geeksforgeeks is best I Love Gfg simmytarika5 Python list-programs Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24716, "s": 24688, "text": "\n13 Jan, 2022" }, { "code": null, "e": 24935, "s": 24716, "text": "Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25211, "s": 24935, "text": "Method #1 : Using list comprehension + join()We can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just join the elements extracted and put them into a as a single string." }, { "code": "# Python3 code to demonstrate# String Matrix Concatenation# Using list comprehension # initializing listtest_list = [[\"geeksforgeeks\", \" is\", \" best\"], [\" I\", \" Love\"], [\" Gfg\"]] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension# count of all the elements in listres = \"\".join([ele for sub in test_list for ele in sub]) # print resultprint(\"The Matrix Concatenation is : \" + str(res))", "e": 25648, "s": 25211, "text": null }, { "code": null, "e": 25795, "s": 25648, "text": "The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]\nThe Matrix Concatenation is : geeksforgeeks is best I Love Gfg\n" }, { "code": null, "e": 25985, "s": 25797, "text": "Method #2 : Using chain() + join()This particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional join function to join." }, { "code": "# Python3 code to demonstrate# String Matrix Concatenation # Using chain() + join()from itertools import chain # initializing listtest_list = [[\"geeksforgeeks\", \" is\", \" best\"], [\" I\", \" Love\"], [\" Gfg\"]] # printing original listprint(\"The original list : \" + str(test_list)) # using chain() + join()# String Matrix Concatenationres = \"\".join(list(chain(*test_list))) # print resultprint(\"The Matrix Concatenation is : \" + str(res))", "e": 26422, "s": 25985, "text": null }, { "code": null, "e": 26569, "s": 26422, "text": "The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]\nThe Matrix Concatenation is : geeksforgeeks is best I Love Gfg\n" }, { "code": null, "e": 26582, "s": 26569, "text": "simmytarika5" }, { "code": null, "e": 26603, "s": 26582, "text": "Python list-programs" }, { "code": null, "e": 26625, "s": 26603, "text": "Python matrix-program" }, { "code": null, "e": 26632, "s": 26625, "text": "Python" }, { "code": null, "e": 26648, "s": 26632, "text": "Python Programs" }, { "code": null, "e": 26746, "s": 26648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26755, "s": 26746, "text": "Comments" }, { "code": null, "e": 26768, "s": 26755, "text": "Old Comments" }, { "code": null, "e": 26786, "s": 26768, "text": "Python Dictionary" }, { "code": null, "e": 26818, "s": 26786, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26853, "s": 26818, "text": "Read a file line by line in Python" }, { "code": null, "e": 26875, "s": 26853, "text": "Enumerate() in Python" }, { "code": null, "e": 26905, "s": 26875, "text": "Iterate over a list in Python" }, { "code": null, "e": 26948, "s": 26905, "text": "Python program to convert a list to string" }, { "code": null, "e": 26970, "s": 26948, "text": "Defaultdict in Python" }, { "code": null, "e": 27009, "s": 26970, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27055, "s": 27009, "text": "Python | Split string into list of characters" } ]
JasmineJS - afterEach()
Like beforeEach(), afterEach() works exactly the same way. It executes after the execution of the spec block. Let us modify the previous example using the following code. var currentVal = 0; afterEach(function() { currentVal = 5; }); describe("Different Methods of Expect Block",function() { it("first call ", function() { expect(currentVal).toEqual(0); }); it("second call ", function() { expect(currentVal).toEqual(5); }); }); In the above example, while running the first spec block the value of the currentVal is 0. Hence, it will pass the test case but after running the first it block, Jasmine compile ran the afterEach() block, which makes the value of the currentVal to 5. Hence it also satisfies the second case and yields a green screenshot as an output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2221, "s": 2050, "text": "Like beforeEach(), afterEach() works exactly the same way. It executes after the execution of the spec block. Let us modify the previous example using the following code." }, { "code": null, "e": 2537, "s": 2221, "text": "var currentVal = 0; \n\nafterEach(function() { \n currentVal = 5; \n}); \n\ndescribe(\"Different Methods of Expect Block\",function() { \n it(\"first call \", function() { \n expect(currentVal).toEqual(0); \n }); \n \n it(\"second call \", function() { \n expect(currentVal).toEqual(5); \n });\n});" }, { "code": null, "e": 2873, "s": 2537, "text": "In the above example, while running the first spec block the value of the currentVal is 0. Hence, it will pass the test case but after running the first it block, Jasmine compile ran the afterEach() block, which makes the value of the currentVal to 5. Hence it also satisfies the second case and yields a green screenshot as an output." }, { "code": null, "e": 2880, "s": 2873, "text": " Print" }, { "code": null, "e": 2891, "s": 2880, "text": " Add Notes" } ]
Scrapy - Environment
In this chapter, we will discuss how to install and set up Scrapy. Scrapy must be installed with Python. Scrapy can be installed by using pip. To install, run the following command − pip install Scrapy Note − Python 3 is not supported on Windows OS. Step 1 − Install Python 2.7 from Python Set environmental variables by adding the following paths to the PATH − C:\Python27\;C:\Python27\Scripts\; You can check the Python version using the following command − python --version Step 2 − Install OpenSSL. Add C:\OpenSSL-Win32\bin in your environmental variables. Note − OpenSSL comes preinstalled in all operating systems except Windows. Step 3 − Install Visual C++ 2008 redistributables. Step 4 − Install pywin32. Step 5 − Install pip for Python versions older than 2.7.9. You can check the pip version using the following command − pip --version Step 6 − To install scrapy, run the following command − pip install Scrapy If you have anaconda or miniconda installed on your machine, run the below command to install Scrapy using conda − conda install -c scrapinghub scrapy Scrapinghub company supports official conda packages for Linux, Windows, and OS X. Note − It is recommended to install Scrapy using the above command if you have issues installing via pip. The latest version of Python is pre-installed on Ubuntu OS. Use the Ubuntu packages aptgettable provided by Scrapinghub. To use the packages − Step 1 − You need to import the GPG key used to sign Scrapy packages into APT keyring − sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 627220E7 Step 2 − Next, use the following command to create /etc/apt/sources.list.d/scrapy.list file − echo 'deb http://archive.scrapy.org/ubuntu scrapy main' | sudo tee /etc/apt/sources.list.d/scrapy.list Step 3 − Update package list and install scrapy − sudo apt-get update && sudo apt-get install scrapy You can install Scrapy from AUR Scrapy package using the following command − yaourt -S scrapy Use the following command to install Xcode command line tools − xcode-select --install Instead of using system Python, install a new updated version that doesn't conflict with the rest of your system. Step 1 − Install homebrew. Step 2 − Set environmental PATH variable to specify that homebrew packages should be used before system packages − echo "export PATH = /usr/local/bin:/usr/local/sbin:$PATH" >> ~/.bashrc Step 3 − To make sure the changes are done, reload .bashrc using the following command − source ~/.bashrc Step 4 − Next, install Python using the following command − brew install python Step 5 − Install Scrapy using the following command − pip install Scrapy 27 Lectures 3.5 hours Attreya Bhatt Print Add Notes Bookmark this page
[ { "code": null, "e": 2342, "s": 2237, "text": "In this chapter, we will discuss how to install and set up Scrapy. Scrapy must be installed with Python." }, { "code": null, "e": 2420, "s": 2342, "text": "Scrapy can be installed by using pip. To install, run the following command −" }, { "code": null, "e": 2440, "s": 2420, "text": "pip install Scrapy\n" }, { "code": null, "e": 2488, "s": 2440, "text": "Note − Python 3 is not supported on Windows OS." }, { "code": null, "e": 2528, "s": 2488, "text": "Step 1 − Install Python 2.7 from Python" }, { "code": null, "e": 2600, "s": 2528, "text": "Set environmental variables by adding the following paths to the PATH −" }, { "code": null, "e": 2637, "s": 2600, "text": "C:\\Python27\\;C:\\Python27\\Scripts\\; \n" }, { "code": null, "e": 2700, "s": 2637, "text": "You can check the Python version using the following command −" }, { "code": null, "e": 2718, "s": 2700, "text": "python --version\n" }, { "code": null, "e": 2745, "s": 2718, "text": "Step 2 − Install OpenSSL." }, { "code": null, "e": 2803, "s": 2745, "text": "Add C:\\OpenSSL-Win32\\bin in your environmental variables." }, { "code": null, "e": 2878, "s": 2803, "text": "Note − OpenSSL comes preinstalled in all operating systems except Windows." }, { "code": null, "e": 2929, "s": 2878, "text": "Step 3 − Install Visual C++ 2008 redistributables." }, { "code": null, "e": 2955, "s": 2929, "text": "Step 4 − Install pywin32." }, { "code": null, "e": 3014, "s": 2955, "text": "Step 5 − Install pip for Python versions older than 2.7.9." }, { "code": null, "e": 3074, "s": 3014, "text": "You can check the pip version using the following command −" }, { "code": null, "e": 3089, "s": 3074, "text": "pip --version\n" }, { "code": null, "e": 3145, "s": 3089, "text": "Step 6 − To install scrapy, run the following command −" }, { "code": null, "e": 3165, "s": 3145, "text": "pip install Scrapy\n" }, { "code": null, "e": 3280, "s": 3165, "text": "If you have anaconda or miniconda installed on your machine, run the below command to install Scrapy using conda −" }, { "code": null, "e": 3318, "s": 3280, "text": "conda install -c scrapinghub scrapy \n" }, { "code": null, "e": 3401, "s": 3318, "text": "Scrapinghub company supports official conda packages for Linux, Windows, and OS X." }, { "code": null, "e": 3507, "s": 3401, "text": "Note − It is recommended to install Scrapy using the above command if you have issues installing via pip." }, { "code": null, "e": 3650, "s": 3507, "text": "The latest version of Python is pre-installed on Ubuntu OS. Use the Ubuntu packages aptgettable provided by Scrapinghub. To use the packages −" }, { "code": null, "e": 3738, "s": 3650, "text": "Step 1 − You need to import the GPG key used to sign Scrapy packages into APT keyring −" }, { "code": null, "e": 3814, "s": 3738, "text": "sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 627220E7\n" }, { "code": null, "e": 3908, "s": 3814, "text": "Step 2 − Next, use the following command to create /etc/apt/sources.list.d/scrapy.list file −" }, { "code": null, "e": 4013, "s": 3908, "text": "echo 'deb http://archive.scrapy.org/ubuntu scrapy main' | sudo tee \n/etc/apt/sources.list.d/scrapy.list\n" }, { "code": null, "e": 4063, "s": 4013, "text": "Step 3 − Update package list and install scrapy −" }, { "code": null, "e": 4115, "s": 4063, "text": "sudo apt-get update && sudo apt-get install scrapy\n" }, { "code": null, "e": 4192, "s": 4115, "text": "You can install Scrapy from AUR Scrapy package using the following command −" }, { "code": null, "e": 4210, "s": 4192, "text": "yaourt -S scrapy\n" }, { "code": null, "e": 4274, "s": 4210, "text": "Use the following command to install Xcode command line tools −" }, { "code": null, "e": 4299, "s": 4274, "text": "xcode-select --install \n" }, { "code": null, "e": 4413, "s": 4299, "text": "Instead of using system Python, install a new updated version that doesn't conflict with the rest of your system." }, { "code": null, "e": 4440, "s": 4413, "text": "Step 1 − Install homebrew." }, { "code": null, "e": 4555, "s": 4440, "text": "Step 2 − Set environmental PATH variable to specify that homebrew packages should be used before system packages −" }, { "code": null, "e": 4627, "s": 4555, "text": "echo \"export PATH = /usr/local/bin:/usr/local/sbin:$PATH\" >> ~/.bashrc\n" }, { "code": null, "e": 4716, "s": 4627, "text": "Step 3 − To make sure the changes are done, reload .bashrc using the following command −" }, { "code": null, "e": 4735, "s": 4716, "text": "source ~/.bashrc \n" }, { "code": null, "e": 4795, "s": 4735, "text": "Step 4 − Next, install Python using the following command −" }, { "code": null, "e": 4816, "s": 4795, "text": "brew install python\n" }, { "code": null, "e": 4870, "s": 4816, "text": "Step 5 − Install Scrapy using the following command −" }, { "code": null, "e": 4890, "s": 4870, "text": "pip install Scrapy\n" }, { "code": null, "e": 4925, "s": 4890, "text": "\n 27 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4940, "s": 4925, "text": " Attreya Bhatt" }, { "code": null, "e": 4947, "s": 4940, "text": " Print" }, { "code": null, "e": 4958, "s": 4947, "text": " Add Notes" } ]
Adaptive Huffman Coding And Decoding - GeeksforGeeks
24 Jun, 2021 Prerequisite: Huffman Coding, Huffman Decoding Adaptive Huffman Coding is also known as Dynamic Huffman Coding. The implementation is done using Vitter Algorithm. Encoding Adaptive Huffman coding for a string containing alphabets: Let m be the total number of alphabets. So m = 26. For Vitter Algorithm, find a parameters e & r such that m = 2e + r and 0 ≤ r ≤ 2e Therefore, for m = 26 we get e = 4 & r = 10 There are two type of code NYT Code & Fixed Code. NYT code = Traversing tree from the root node to that particular NYT node. For Fixed Code, it can be calculated from the following two conditions: If 0 ≤ k ≤ 2r Then the letter Sk is encoded as the binary representation of (k-1) in (e+1) bits. (where k is position of alphabet in sorted order)Else the letter Sk is encoded as the binary representation of (k-r-1) in e bits. If 0 ≤ k ≤ 2r Then the letter Sk is encoded as the binary representation of (k-1) in (e+1) bits. (where k is position of alphabet in sorted order) Else the letter Sk is encoded as the binary representation of (k-r-1) in e bits. Tree Updation Tree Updation in Vitter Algorithm follows Implicit Numbering. In Implicit numbering, Nodes are numbered in increasing order i.e., by level and from left to right The Nodes that have the same weight and the type together form a block Blocks are related to each other as by increasing order of their weights Internal Node is represented by Oval shape. Weight of internal nodes = Sum of child node weights External Node is represented by a square shape. Weight of external nodes = Initially 1 and if repeated then increased the weight by 1 Steps for Tree Updation: Initialize the tree with the NYT NodeFor a symbol is recognized for the first time, the initial NYT node is further divided into an NYT Node and new Node initialize to that symbol and weight = 1.Assign the sum of the weight of child nodes to the parent nodeIf a repeated symbol is encountered than weights are updated to that symbol. Initialize the tree with the NYT Node For a symbol is recognized for the first time, the initial NYT node is further divided into an NYT Node and new Node initialize to that symbol and weight = 1. Assign the sum of the weight of child nodes to the parent node If a repeated symbol is encountered than weights are updated to that symbol. Note: During Updation in Tree if the weight of the left subtree is greater than the right subtree, then nodes must be swapped. Example code = "aardvark" The final Code we get is: 00000 1 010001 0000011 0001011 0 10 110001010 a a r d v a r k Explanation: For string code = “aardvark”, e = 5, r = 10 As shown in the above image Tree is initialize with NYT Node with weight 0. For symbol ‘a’, k = 1. For symbol ‘a’, k = 1. NYT Code = "" (initially tree is empty) For Fixed Code: As k < 2r i.e, 1 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1) = 0 as 5-bit representation For Fixed Code: As k < 2r i.e, 1 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1) = 0 as 5-bit representation Fixed Code = "00000" Huffman Code for symbol for 'a' is "00000" For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “1” For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “1” Huffman Code for symbol for 'a' is "1" For symbol ‘r’, k = 18. For symbol ‘r’, k = 18. NYT Code = "0" (traversing up to NYT Node) For Fixed Code: As k > 2r i.e, 18 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-1 = 17) as 5-bit representation For Fixed Code: As k > 2r i.e, 18 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-1 = 17) as 5-bit representation Fixed Code = "10001" Huffman Code for symbol for 'r' is "010001" For symbol ‘d’, k = 4. For symbol ‘d’, k = 4. NYT Code = "000" (traversing up to NYT Node) For Fixed Code: As k < 2r i.e, 4 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 3) as 5-bit representation For Fixed Code: As k < 2r i.e, 4 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 3) as 5-bit representation Fixed Code = "00011" Huffman Code = "00000011" For symbol ‘v’, k = 22. For symbol ‘v’, k = 22. NYT Code = "000" (traversing up to NYT Node) For Fixed Code: As k > 2r i.e, 22 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-r-1 = 11) as 4-bit representation For Fixed Code: As k > 2r i.e, 22 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-r-1 = 11) as 4-bit representation Fixed Code = "1011" Huffman Code = "0001011" Swap the node of left subtree and right as the tree is violating propertyFor symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “0” Swap the node of left subtree and right as the tree is violating property For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “0” Huffman Code for symbol for 'a' is "0" For symbol ‘r’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “10” For symbol ‘r’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “10” Huffman Code for symbol for 'r' is "10" For symbol ‘k’, k = 11. For symbol ‘k’, k = 11. NYT Code = "1100" (traversing up to NYT Node) For Fixed Code: As k < 2r i.e, 11 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 10) as 5-bit representation For Fixed Code: As k < 2r i.e, 11 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 10) as 5-bit representation Fixed Code = "01010" Huffman Code for symbol for 'r' is "110001010" Decoding Steps for Decoding: Read Binary stringIf encountered leaf node is NYT Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1 Read Binary string If encountered leaf node is NYT Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1 Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1 If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1 If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1 If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1 Example: code = "00000101000100000110001011010110001010" We get final decoded code as 00000 1 0 10001 00 00011 000 1011 0 10 1100 01010 a a NYT r NYT d NYT v a r NYT k Explanation: Begin decoding by reading first e bits. So the first 4 bits are 0000, converting into decimal = 0. Now the value 0 < r , i.e, 0 < 10 satisfy condition (1). Now according to the condition (1), convert first e+1 = 5 bit into decimal and add 1 to it. 00000 = 0 0 + 1 = 1, which is value for alphabet a. Update the tree and add a node for the symbol ‘a’ in the tree Read the next bit in the given code and traverse the tree. We reach the external leaf node ‘a’. So the next decoded symbol is ‘a’. Read the next set of bits given code and traverse the tree. We have 0 as NYT Node. After reaching the NYT Node, read e bits which are 1000. Convert 1000 to decimal is 8. As 8 < r satisfy condition (1). Now Convert e+1 bits in decimal and add 1 to it. 10001 = 17 17 + 1 = 18, which is value for alphabet r. Update the tree and add a node for the symbol ‘r’ in the tree. Reading the next set of bits and traversing the Tree we reach NYT node at 00. Read e bits which are 0001. Convert 0001 to decimal is 1. As 1 < r satisfy condition (1). Now Convert e+1 bits in decimal and add 1 to it. 00011 = 3 3 + 1 = 4, which is value for alphabet d. Update the tree and add a node for the symbol ‘d’ in the tree. Reading the next set of bits and traversing the Tree we reach NYT node at 000. Read e bits which are 1011. Convert 1011 to decimal is 11. As 11 > r satisfy condition (2). Now Convert k+r+1 bits in decimal and decode the symbol. 10110 = 22, which is value for alphabet v. Update the tree and add a node for the symbol ‘v’ in the tree. Reading the next set of bits and traversing the Tree we get symbol ‘a’ at 0. Update the tree and add a node for the symbol ‘a’ in the tree. Reading the next set of bits and traversing the Tree we get symbol ‘r’ at 10. Update the tree and add a node for the symbol ‘a’ in the tree. Reading the next set of bits and traversing the Tree we reach NYT node at 1100. Read e bits which are 0101. Convert 0101 to decimal is 9. As 9 < r satisfy condition (1). Now Convert e+1 bits in decimal and and add 1 to it. 01000 = 8, 8 + 1 = 9. which is value for alphabet k. Update the tree and add a node for the symbol ‘v’ in the tree. gabaa406 Technical Scripter 2019 Algorithms Technical Scripter Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SCAN (Elevator) Disk Scheduling Algorithms Program for SSTF disk scheduling algorithm Quadratic Probing in Hashing Rail Fence Cipher - Encryption and Decryption K means Clustering - Introduction Difference between Algorithm, Pseudocode and Program Difference between Informed and Uninformed Search in AI K-Nearest Neighbours Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
[ { "code": null, "e": 24700, "s": 24672, "text": "\n24 Jun, 2021" }, { "code": null, "e": 24865, "s": 24700, "text": "Prerequisite: Huffman Coding, Huffman Decoding Adaptive Huffman Coding is also known as Dynamic Huffman Coding. The implementation is done using Vitter Algorithm. " }, { "code": null, "e": 24874, "s": 24865, "text": "Encoding" }, { "code": null, "e": 25042, "s": 24874, "text": "Adaptive Huffman coding for a string containing alphabets: Let m be the total number of alphabets. So m = 26. For Vitter Algorithm, find a parameters e & r such that " }, { "code": null, "e": 25112, "s": 25042, "text": "m = 2e + r and 0 ≤ r ≤ 2e\nTherefore, for m = 26 we get e = 4 & r = 10" }, { "code": null, "e": 25164, "s": 25112, "text": "There are two type of code NYT Code & Fixed Code. " }, { "code": null, "e": 25239, "s": 25164, "text": "NYT code = Traversing tree from the root node to that particular NYT node." }, { "code": null, "e": 25313, "s": 25239, "text": "For Fixed Code, it can be calculated from the following two conditions: " }, { "code": null, "e": 25540, "s": 25313, "text": "If 0 ≤ k ≤ 2r Then the letter Sk is encoded as the binary representation of (k-1) in (e+1) bits. (where k is position of alphabet in sorted order)Else the letter Sk is encoded as the binary representation of (k-r-1) in e bits." }, { "code": null, "e": 25687, "s": 25540, "text": "If 0 ≤ k ≤ 2r Then the letter Sk is encoded as the binary representation of (k-1) in (e+1) bits. (where k is position of alphabet in sorted order)" }, { "code": null, "e": 25768, "s": 25687, "text": "Else the letter Sk is encoded as the binary representation of (k-r-1) in e bits." }, { "code": null, "e": 25869, "s": 25768, "text": "Tree Updation Tree Updation in Vitter Algorithm follows Implicit Numbering. In Implicit numbering, " }, { "code": null, "e": 25946, "s": 25869, "text": "Nodes are numbered in increasing order i.e., by level and from left to right" }, { "code": null, "e": 26017, "s": 25946, "text": "The Nodes that have the same weight and the type together form a block" }, { "code": null, "e": 26090, "s": 26017, "text": "Blocks are related to each other as by increasing order of their weights" }, { "code": null, "e": 26187, "s": 26090, "text": "Internal Node is represented by Oval shape. Weight of internal nodes = Sum of child node weights" }, { "code": null, "e": 26321, "s": 26187, "text": "External Node is represented by a square shape. Weight of external nodes = Initially 1 and if repeated then increased the weight by 1" }, { "code": null, "e": 26348, "s": 26321, "text": "Steps for Tree Updation: " }, { "code": null, "e": 26682, "s": 26348, "text": "Initialize the tree with the NYT NodeFor a symbol is recognized for the first time, the initial NYT node is further divided into an NYT Node and new Node initialize to that symbol and weight = 1.Assign the sum of the weight of child nodes to the parent nodeIf a repeated symbol is encountered than weights are updated to that symbol." }, { "code": null, "e": 26720, "s": 26682, "text": "Initialize the tree with the NYT Node" }, { "code": null, "e": 26879, "s": 26720, "text": "For a symbol is recognized for the first time, the initial NYT node is further divided into an NYT Node and new Node initialize to that symbol and weight = 1." }, { "code": null, "e": 26942, "s": 26879, "text": "Assign the sum of the weight of child nodes to the parent node" }, { "code": null, "e": 27019, "s": 26942, "text": "If a repeated symbol is encountered than weights are updated to that symbol." }, { "code": null, "e": 27147, "s": 27019, "text": "Note: During Updation in Tree if the weight of the left subtree is greater than the right subtree, then nodes must be swapped. " }, { "code": null, "e": 27157, "s": 27147, "text": "Example " }, { "code": null, "e": 27290, "s": 27157, "text": "code = \"aardvark\"\nThe final Code we get is:\n00000 1 010001 0000011 0001011 0 10 110001010\n a a r d v a r k" }, { "code": null, "e": 27427, "s": 27292, "text": "Explanation: For string code = “aardvark”, e = 5, r = 10 As shown in the above image Tree is initialize with NYT Node with weight 0. " }, { "code": null, "e": 27452, "s": 27427, "text": "For symbol ‘a’, k = 1. " }, { "code": null, "e": 27477, "s": 27452, "text": "For symbol ‘a’, k = 1. " }, { "code": null, "e": 27517, "s": 27477, "text": "NYT Code = \"\" (initially tree is empty)" }, { "code": null, "e": 27658, "s": 27517, "text": "For Fixed Code: As k < 2r i.e, 1 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1) = 0 as 5-bit representation " }, { "code": null, "e": 27799, "s": 27658, "text": "For Fixed Code: As k < 2r i.e, 1 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1) = 0 as 5-bit representation " }, { "code": null, "e": 27820, "s": 27799, "text": "Fixed Code = \"00000\"" }, { "code": null, "e": 27867, "s": 27824, "text": "Huffman Code for symbol for 'a' is \"00000\"" }, { "code": null, "e": 27971, "s": 27867, "text": " For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “1” " }, { "code": null, "e": 28076, "s": 27973, "text": "For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “1” " }, { "code": null, "e": 28115, "s": 28076, "text": "Huffman Code for symbol for 'a' is \"1\"" }, { "code": null, "e": 28141, "s": 28115, "text": "For symbol ‘r’, k = 18. " }, { "code": null, "e": 28167, "s": 28141, "text": "For symbol ‘r’, k = 18. " }, { "code": null, "e": 28210, "s": 28167, "text": "NYT Code = \"0\" (traversing up to NYT Node)" }, { "code": null, "e": 28353, "s": 28210, "text": "For Fixed Code: As k > 2r i.e, 18 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-1 = 17) as 5-bit representation " }, { "code": null, "e": 28496, "s": 28353, "text": "For Fixed Code: As k > 2r i.e, 18 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-1 = 17) as 5-bit representation " }, { "code": null, "e": 28517, "s": 28496, "text": "Fixed Code = \"10001\"" }, { "code": null, "e": 28565, "s": 28521, "text": "Huffman Code for symbol for 'r' is \"010001\"" }, { "code": null, "e": 28590, "s": 28565, "text": "For symbol ‘d’, k = 4. " }, { "code": null, "e": 28615, "s": 28590, "text": "For symbol ‘d’, k = 4. " }, { "code": null, "e": 28660, "s": 28615, "text": "NYT Code = \"000\" (traversing up to NYT Node)" }, { "code": null, "e": 28801, "s": 28660, "text": "For Fixed Code: As k < 2r i.e, 4 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 3) as 5-bit representation " }, { "code": null, "e": 28942, "s": 28801, "text": "For Fixed Code: As k < 2r i.e, 4 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 3) as 5-bit representation " }, { "code": null, "e": 28963, "s": 28942, "text": "Fixed Code = \"00011\"" }, { "code": null, "e": 28993, "s": 28967, "text": "Huffman Code = \"00000011\"" }, { "code": null, "e": 29019, "s": 28993, "text": "For symbol ‘v’, k = 22. " }, { "code": null, "e": 29045, "s": 29019, "text": "For symbol ‘v’, k = 22. " }, { "code": null, "e": 29090, "s": 29045, "text": "NYT Code = \"000\" (traversing up to NYT Node)" }, { "code": null, "e": 29235, "s": 29090, "text": "For Fixed Code: As k > 2r i.e, 22 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-r-1 = 11) as 4-bit representation " }, { "code": null, "e": 29380, "s": 29235, "text": "For Fixed Code: As k > 2r i.e, 22 > 2*10, satisfy condition (2) So Fixed Code is Binary Representation of (k-r-1 = 11) as 4-bit representation " }, { "code": null, "e": 29400, "s": 29380, "text": "Fixed Code = \"1011\"" }, { "code": null, "e": 29429, "s": 29404, "text": "Huffman Code = \"0001011\"" }, { "code": null, "e": 29605, "s": 29429, "text": "Swap the node of left subtree and right as the tree is violating propertyFor symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “0” " }, { "code": null, "e": 29679, "s": 29605, "text": "Swap the node of left subtree and right as the tree is violating property" }, { "code": null, "e": 29782, "s": 29679, "text": "For symbol ‘a’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “0” " }, { "code": null, "e": 29821, "s": 29782, "text": "Huffman Code for symbol for 'a' is \"0\"" }, { "code": null, "e": 29925, "s": 29821, "text": "For symbol ‘r’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “10” " }, { "code": null, "e": 30029, "s": 29925, "text": "For symbol ‘r’ which already exists in the tree. Traversing Tree up to symbol ‘a’, we get code = “10” " }, { "code": null, "e": 30069, "s": 30029, "text": "Huffman Code for symbol for 'r' is \"10\"" }, { "code": null, "e": 30095, "s": 30069, "text": "For symbol ‘k’, k = 11. " }, { "code": null, "e": 30121, "s": 30095, "text": "For symbol ‘k’, k = 11. " }, { "code": null, "e": 30167, "s": 30121, "text": "NYT Code = \"1100\" (traversing up to NYT Node)" }, { "code": null, "e": 30310, "s": 30167, "text": "For Fixed Code: As k < 2r i.e, 11 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 10) as 5-bit representation " }, { "code": null, "e": 30453, "s": 30310, "text": "For Fixed Code: As k < 2r i.e, 11 < 2*10, satisfy condition (1) So Fixed Code is Binary Representation of (k-1 = 10) as 5-bit representation " }, { "code": null, "e": 30474, "s": 30453, "text": "Fixed Code = \"01010\"" }, { "code": null, "e": 30525, "s": 30478, "text": "Huffman Code for symbol for 'r' is \"110001010\"" }, { "code": null, "e": 30536, "s": 30527, "text": "Decoding" }, { "code": null, "e": 30557, "s": 30536, "text": "Steps for Decoding: " }, { "code": null, "e": 30825, "s": 30559, "text": "Read Binary stringIf encountered leaf node is NYT Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1" }, { "code": null, "e": 30844, "s": 30825, "text": "Read Binary string" }, { "code": null, "e": 31092, "s": 30844, "text": "If encountered leaf node is NYT Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1" }, { "code": null, "e": 31308, "s": 31092, "text": "Read next e bits If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1" }, { "code": null, "e": 31507, "s": 31308, "text": "If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1" }, { "code": null, "e": 31609, "s": 31507, "text": "If e bit value < r, Then to get required symbol convert (e+1) bits to decimal value of (e+1) bits + 1" }, { "code": null, "e": 31707, "s": 31609, "text": "If e bit value > r, Then to get required symbol convert e bits to decimal value of e bits + r + 1" }, { "code": null, "e": 31718, "s": 31707, "text": "Example: " }, { "code": null, "e": 31925, "s": 31718, "text": "code = \"00000101000100000110001011010110001010\"\nWe get final decoded code as\n 00000 1 0 10001 00 00011 000 1011 0 10 1100 01010\n a a NYT r NYT d NYT v a r NYT k" }, { "code": null, "e": 31940, "s": 31925, "text": "Explanation: " }, { "code": null, "e": 32190, "s": 31940, "text": "Begin decoding by reading first e bits. So the first 4 bits are 0000, converting into decimal = 0. Now the value 0 < r , i.e, 0 < 10 satisfy condition (1). Now according to the condition (1), convert first e+1 = 5 bit into decimal and add 1 to it. " }, { "code": null, "e": 32242, "s": 32190, "text": "00000 = 0\n0 + 1 = 1, which is value for alphabet a." }, { "code": null, "e": 32304, "s": 32242, "text": "Update the tree and add a node for the symbol ‘a’ in the tree" }, { "code": null, "e": 32435, "s": 32304, "text": "Read the next bit in the given code and traverse the tree. We reach the external leaf node ‘a’. So the next decoded symbol is ‘a’." }, { "code": null, "e": 32688, "s": 32435, "text": "Read the next set of bits given code and traverse the tree. We have 0 as NYT Node. After reaching the NYT Node, read e bits which are 1000. Convert 1000 to decimal is 8. As 8 < r satisfy condition (1). Now Convert e+1 bits in decimal and add 1 to it. " }, { "code": null, "e": 32743, "s": 32688, "text": "10001 = 17\n17 + 1 = 18, which is value for alphabet r." }, { "code": null, "e": 32806, "s": 32743, "text": "Update the tree and add a node for the symbol ‘r’ in the tree." }, { "code": null, "e": 33025, "s": 32806, "text": "Reading the next set of bits and traversing the Tree we reach NYT node at 00. Read e bits which are 0001. Convert 0001 to decimal is 1. As 1 < r satisfy condition (1). Now Convert e+1 bits in decimal and add 1 to it. " }, { "code": null, "e": 33077, "s": 33025, "text": "00011 = 3\n3 + 1 = 4, which is value for alphabet d." }, { "code": null, "e": 33140, "s": 33077, "text": "Update the tree and add a node for the symbol ‘d’ in the tree." }, { "code": null, "e": 33370, "s": 33140, "text": "Reading the next set of bits and traversing the Tree we reach NYT node at 000. Read e bits which are 1011. Convert 1011 to decimal is 11. As 11 > r satisfy condition (2). Now Convert k+r+1 bits in decimal and decode the symbol. " }, { "code": null, "e": 33413, "s": 33370, "text": "10110 = 22, which is value for alphabet v." }, { "code": null, "e": 33476, "s": 33413, "text": "Update the tree and add a node for the symbol ‘v’ in the tree." }, { "code": null, "e": 33616, "s": 33476, "text": "Reading the next set of bits and traversing the Tree we get symbol ‘a’ at 0. Update the tree and add a node for the symbol ‘a’ in the tree." }, { "code": null, "e": 33757, "s": 33616, "text": "Reading the next set of bits and traversing the Tree we get symbol ‘r’ at 10. Update the tree and add a node for the symbol ‘a’ in the tree." }, { "code": null, "e": 33982, "s": 33757, "text": "Reading the next set of bits and traversing the Tree we reach NYT node at 1100. Read e bits which are 0101. Convert 0101 to decimal is 9. As 9 < r satisfy condition (1). Now Convert e+1 bits in decimal and and add 1 to it. " }, { "code": null, "e": 34036, "s": 33982, "text": "01000 = 8, \n8 + 1 = 9. which is value for alphabet k." }, { "code": null, "e": 34099, "s": 34036, "text": "Update the tree and add a node for the symbol ‘v’ in the tree." }, { "code": null, "e": 34110, "s": 34101, "text": "gabaa406" }, { "code": null, "e": 34134, "s": 34110, "text": "Technical Scripter 2019" }, { "code": null, "e": 34145, "s": 34134, "text": "Algorithms" }, { "code": null, "e": 34164, "s": 34145, "text": "Technical Scripter" }, { "code": null, "e": 34175, "s": 34164, "text": "Algorithms" }, { "code": null, "e": 34273, "s": 34175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34298, "s": 34273, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 34341, "s": 34298, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 34384, "s": 34341, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 34413, "s": 34384, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 34459, "s": 34413, "text": "Rail Fence Cipher - Encryption and Decryption" }, { "code": null, "e": 34493, "s": 34459, "text": "K means Clustering - Introduction" }, { "code": null, "e": 34546, "s": 34493, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 34602, "s": 34546, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 34623, "s": 34602, "text": "K-Nearest Neighbours" } ]
Circular Queue Data Structure in C++
A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first. Queue cane be one linear data structure. But it may create some problem if we implement queue using array. Sometimes by using some consecutive insert and delete operation, the front and rear position will change. In that moment, it will look like the queue has no space to insert elements into it. Even if there are some free spaces, that will not be used due to some logical problems. To overcome this problem, we will use the circular queue data structure. A circular queue is a type of queue in which the last position is connected to the first position to make a circle. #include <iostream> using namespace std; int cqueue[5]; int front = -1, rear = -1, n=5; void insertCQ(int val) { if ((front == 0 && rear == n-1) || (front == rear+1)) { cout<<"Queue Overflow \n"; return; } if (front == -1) { front = 0; rear = 0; } else { if (rear == n - 1) rear = 0; else rear = rear + 1; } cqueue[rear] = val ; } void deleteCQ() { if (front == -1) { cout<<"Queue Underflow\n"; return ; } cout<<"Element deleted from queue is : "<<cqueue[front<<endl; if (front == rear) { front = -1; rear = -1; } else { if (front == n - 1) front = 0; else front = front + 1; } } void displayCQ() { int f = front, r = rear; if (front == -1) { cout<<"Queue is empty"<<endl; return; } cout<<"Queue elements are :\n"; if (f <= r) { while (f <= r){ cout<<cqueue[f]<<" "; f++; } } else { while (f <= n - 1) { cout<<cqueue[f]<<" "; f++; } f = 0; while (f <= r) { cout<<cqueue[f]<<" "; f++; } } cout<<endl; } int main() { int ch, val; cout<<"1)Insert\n"; cout<<"2)Delete\n"; cout<<"3)Display\n"; cout<<"4)Exit\n"; do { cout<<"Enter choice : "<<endl; cin>>ch; switch(ch) { case 1: cout<<"Input for insertion: "<<endl; cin>>val; insertCQ(val); break; case 2: deleteCQ(); break; case 3: displayCQ(); break; case 4: cout<<"Exit\n"; break; default: cout<<"Incorrect!\n"; } } while(ch != 4); return 0; } 1)Insert 2)Delete 3)Display 4)Exit Enter choice : 1 Input for insertion: 10 Enter choice : 1 Input for insertion: 20 Enter choice : 1 Input for insertion: 30 Enter choice : 1 Input for insertion: 40 Enter choice : 1 Input for insertion: 50 Enter choice : 3 Queue elements are : 10 20 30 40 50 Enter choice : 2 Element deleted from queue is : 10 Enter choice : 2 Element deleted from queue is : 20 Enter choice : 3 Queue elements are : 30 40 50 Enter choice : 4 Exit
[ { "code": null, "e": 1238, "s": 1062, "text": "A queue is an abstract data structure that contains a collection of elements. Queue implements the FIFO mechanism i.e the element that is inserted first is also deleted first." }, { "code": null, "e": 1697, "s": 1238, "text": "Queue cane be one linear data structure. But it may create some problem if we implement queue using array. Sometimes by using some consecutive insert and delete operation, the front and rear position will change. In that moment, it will look like the queue has no space to insert elements into it. Even if there are some free spaces, that will not be used due to some logical problems. To overcome this problem, we will use the circular queue data structure." }, { "code": null, "e": 1813, "s": 1697, "text": "A circular queue is a type of queue in which the last position is connected to the first position to make a circle." }, { "code": null, "e": 3693, "s": 1813, "text": "#include <iostream>\nusing namespace std;\nint cqueue[5];\nint front = -1, rear = -1, n=5;\nvoid insertCQ(int val) {\n if ((front == 0 && rear == n-1) || (front == rear+1)) {\n cout<<\"Queue Overflow \\n\";\n return;\n }\n if (front == -1) {\n front = 0;\n rear = 0;\n }\n else {\n if (rear == n - 1)\n rear = 0;\n else\n rear = rear + 1;\n }\n cqueue[rear] = val ;\n}\nvoid deleteCQ() {\n if (front == -1) {\n cout<<\"Queue Underflow\\n\";\n return ;\n }\n cout<<\"Element deleted from queue is : \"<<cqueue[front<<endl;\n if (front == rear) {\n front = -1;\n rear = -1;\n }\n else {\n if (front == n - 1)\n front = 0;\n else\n front = front + 1;\n }\n }\n void displayCQ() {\n int f = front, r = rear;\n if (front == -1) {\n cout<<\"Queue is empty\"<<endl;\n return;\n }\n cout<<\"Queue elements are :\\n\";\n if (f <= r) {\n while (f <= r){\n cout<<cqueue[f]<<\" \";\n f++;\n }\n }\n else {\n while (f <= n - 1) {\n cout<<cqueue[f]<<\" \";\n f++;\n }\n f = 0;\n while (f <= r) {\n cout<<cqueue[f]<<\" \";\n f++;\n }\n }\n cout<<endl;\n}\nint main() {\n int ch, val;\n cout<<\"1)Insert\\n\";\n cout<<\"2)Delete\\n\";\n cout<<\"3)Display\\n\";\n cout<<\"4)Exit\\n\";\n do {\n cout<<\"Enter choice : \"<<endl;\n cin>>ch;\n switch(ch) {\n case 1:\n cout<<\"Input for insertion: \"<<endl;\n cin>>val;\n insertCQ(val);\n break;\n case 2:\n deleteCQ();\n break;\n case 3:\n displayCQ();\n break;\n case 4:\n cout<<\"Exit\\n\";\n break;\n default: cout<<\"Incorrect!\\n\";\n }\n }\n while(ch != 4);\n return 0;\n}" }, { "code": null, "e": 4159, "s": 3693, "text": "1)Insert\n2)Delete\n3)Display\n4)Exit\nEnter choice :\n1\nInput for insertion:\n10\nEnter choice :\n1\nInput for insertion:\n20\nEnter choice :\n1\nInput for insertion:\n30\nEnter choice :\n1\nInput for insertion:\n40\nEnter choice :\n1\nInput for insertion:\n50\nEnter choice :\n3\nQueue elements are :\n10 20 30 40 50\nEnter choice :\n2\nElement deleted from queue is : 10\nEnter choice :\n2\nElement deleted from queue is : 20\nEnter choice :\n3\nQueue elements are :\n30 40 50\nEnter choice :\n4\nExit" } ]
Display all the values of an array in p tag on a web page with JavaScript
For this, you can use .data(anyArrayObject). Following is the code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://d3js.org/d3.v5.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> </head> <body> <script> const arrayValues = [1000000001,"John","Smith",100, 200, 3000] var originalData = d3.select("body").selectAll("p") .data(arrayValues) .enter() .append("p") .text(function(allValuesOfArray){ console.log(allValuesOfArray+" "); return allValuesOfArray; }) </script> </body> </html> To run the above program, just save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor. This will produce the following output −
[ { "code": null, "e": 1131, "s": 1062, "text": "For this, you can use .data(anyArrayObject). Following is the code −" }, { "code": null, "e": 1142, "s": 1131, "text": " Live Demo" }, { "code": null, "e": 2023, "s": 1142, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<script src=\"https://d3js.org/d3.v5.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css\">\n</head>\n<body>\n<script>\n const arrayValues = [1000000001,\"John\",\"Smith\",100, 200, 3000]\n var originalData = d3.select(\"body\").selectAll(\"p\")\n .data(arrayValues)\n .enter()\n .append(\"p\")\n .text(function(allValuesOfArray){\n console.log(allValuesOfArray+\" \");\n return allValuesOfArray;\n })\n</script>\n</body>\n</html>" }, { "code": null, "e": 2189, "s": 2023, "text": "To run the above program, just save the file name anyName.html(index.html) and right click on\nthe file and select the option open with live server in VS Code editor." }, { "code": null, "e": 2230, "s": 2189, "text": "This will produce the following output −" } ]
C library function - log10()
The C library function double log10(double x) returns the common logarithm (base-10 logarithm) of x. Following is the declaration for log10() function. double log10(double x) x − This is the floating point value. x − This is the floating point value. This function returns the common logarithm of x, for values of x greater than zero. The following example shows the usage of log10() function. #include <stdio.h> #include <math.h> int main () { double x, ret; x = 10000; /* finding value of log1010000 */ ret = log10(x); printf("log10(%lf) = %lf\n", x, ret); return(0); } Let us compile and run the above program that will produce the following result − log10(10000.000000) = 4.000000 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": 2108, "s": 2007, "text": "The C library function double log10(double x) returns the common logarithm (base-10 logarithm) of x." }, { "code": null, "e": 2159, "s": 2108, "text": "Following is the declaration for log10() function." }, { "code": null, "e": 2182, "s": 2159, "text": "double log10(double x)" }, { "code": null, "e": 2220, "s": 2182, "text": "x − This is the floating point value." }, { "code": null, "e": 2258, "s": 2220, "text": "x − This is the floating point value." }, { "code": null, "e": 2342, "s": 2258, "text": "This function returns the common logarithm of x, for values of x greater than zero." }, { "code": null, "e": 2401, "s": 2342, "text": "The following example shows the usage of log10() function." }, { "code": null, "e": 2605, "s": 2401, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n double x, ret;\n x = 10000;\n \n /* finding value of log1010000 */\n ret = log10(x);\n printf(\"log10(%lf) = %lf\\n\", x, ret);\n \n return(0);\n}" }, { "code": null, "e": 2687, "s": 2605, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2719, "s": 2687, "text": "log10(10000.000000) = 4.000000\n" }, { "code": null, "e": 2752, "s": 2719, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2767, "s": 2752, "text": " Nishant Malik" }, { "code": null, "e": 2802, "s": 2767, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2817, "s": 2802, "text": " Nishant Malik" }, { "code": null, "e": 2852, "s": 2817, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2866, "s": 2852, "text": " Asif Hussain" }, { "code": null, "e": 2899, "s": 2866, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2917, "s": 2899, "text": " Richa Maheshwari" }, { "code": null, "e": 2952, "s": 2917, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2971, "s": 2952, "text": " Vandana Annavaram" }, { "code": null, "e": 3004, "s": 2971, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3016, "s": 3004, "text": " Amit Diwan" }, { "code": null, "e": 3023, "s": 3016, "text": " Print" }, { "code": null, "e": 3034, "s": 3023, "text": " Add Notes" } ]
Swing Examples - Add Border to JPanel
Following example showcase how to add border to a JPanel in a Java Swing application. We are using the following APIs. BorderFactory.createLineBorder() − To create a line border. BorderFactory.createLineBorder() − To create a line border. JPanel.setBorder(border) − To set the desired border to the JPanel. JPanel.setBorder(border) − To set the desired border to the JPanel. import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.LayoutManager; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame){ //Create a border Border blackline = BorderFactory.createLineBorder(Color.black); JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JPanel panel1 = new JPanel(); String spaces = " "; panel1.add(new JLabel(spaces + "Border to JPanel" + spaces)); panel1.setBorder(blackline); panel.add(panel1); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 2039, "text": "Following example showcase how to add border to a JPanel in a Java Swing application." }, { "code": null, "e": 2158, "s": 2125, "text": "We are using the following APIs." }, { "code": null, "e": 2218, "s": 2158, "text": "BorderFactory.createLineBorder() − To create a line border." }, { "code": null, "e": 2278, "s": 2218, "text": "BorderFactory.createLineBorder() − To create a line border." }, { "code": null, "e": 2346, "s": 2278, "text": "JPanel.setBorder(border) − To set the desired border to the JPanel." }, { "code": null, "e": 2414, "s": 2346, "text": "JPanel.setBorder(border) − To set the desired border to the JPanel." }, { "code": null, "e": 3616, "s": 2414, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.border.Border;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(JFrame frame){\n //Create a border\n Border blackline = BorderFactory.createLineBorder(Color.black);\n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n JPanel panel1 = new JPanel();\n String spaces = \" \";\n panel1.add(new JLabel(spaces + \"Border to JPanel\" + spaces)); \n panel1.setBorder(blackline);\n panel.add(panel1);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}" }, { "code": null, "e": 3623, "s": 3616, "text": " Print" }, { "code": null, "e": 3634, "s": 3623, "text": " Add Notes" } ]
Count the number of ways to give ranks for N students such that same ranks are possible - GeeksforGeeks
07 May, 2021 Given a number N which represents the number of students, the task is to calculate all possible ways to rank them according to their CGPA/marks, considering that two or more students can have the same rank. Since the answer can be large, perform the modulo with 109 + 7. Examples: Input: N = 1 Output: 1 Explanation: There is only one way to rank a student, irrespective of his marks. Input: N = 2 Output: 2 Explanation: In the following two ways the ranks can be distributed among two students: The high scoring student can be awarded the first rank and the low scoring student the second rank or both of them can be awarded the same rank if they have equal scores. Approach: The idea for this problem is to use the Bell Numbers. A bell number is a number that counts the possible partitions of a set. Therefore, an N-th bell number is a number of non-empty subsets a set of size N can be partitioned into. For example, let’s consider the set {1, 2, 3} for N = 3. The bell number corresponding to N = 3 is 5. This signifies that the given set can be partitioned into following 5 non-empty subsets: {{1}, {2}, {3}} {{1, 2}, {3}} {{1, 3}, {2}} {{2, 3}, {1}} {{1, 2, 3}} Clearly, the above bell numbers signify all the possible ranks. However, they do not calculate the permutations of the subset. Therefore, by multiplying every subset with K!, where K denotes the size of the respective subset, we get all the possible arrangements. As the same subproblems can be repeated, we can store the values of each subproblem in a data structure to optimize the complexity. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to calculate the number// of ways to give ranks for N// students such that same ranks// are possible #include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Initializing a table in order to// store the bell trianglevector<vector<int> > dp; // Function to calculate the K-th// bell numberint f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblelong operation(int n){ // Resizing the dp table for the // given value of n dp.resize(n + 1, vector<int>(n + 1, -1)); // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for (int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codeint main(){ int n = 5; cout << operation(n) << endl; return 0;} // Java program to calculate the number// of ways to give ranks for N// students such that same ranks// are possibleimport java.util.*; class GFG{ static int mod = (int)(1e9 + 7); // Initializing a table in order to// store the bell trianglestatic int [][]dp; // Function to calculate the K-th// bell numberstatic int f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblestatic long operation(int n){ // Resizing the dp table for the // given value of n dp = new int[n + 1][n + 1]; for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for(int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codepublic static void main(String[] args){ int n = 5; System.out.print(operation(n) + "\n");}} // This code is contributed by amal kumar choubey # Python3 program to calculate the number# of ways to give ranks for N# students such that same ranks# are possiblemod = 1e9 + 7 # Initializing a table in order to# store the bell triangledp = [[-1 for x in range(6)] for y in range(6)] # Function to calculate the K-th# bell numberdef f(n, k): # If we have already calculated # the bell numbers until the # required N if (n < k): return 0 # Base case if (n == k): return 1 # First Bell Number if (k == 1): return 1 # If the value of the bell # triangle has already been # calculated if (dp[n][k] != -1): return dp[n][k] # Fill the defined dp table dp[n][k] = ((((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod)) return dp[n][k] # Function to return the number# of ways to give ranks for N# students such that same ranks# are possibledef operation(n): # Resizing the dp table for the # given value of n global dp # Variables to store the answer # and the factorial value ans = 0 fac = 1 # Iterating till N for k in range(1, n + 1): # Simultaneously calculate the k! fac *= k # Computing the K-th bell number # and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod return ans # Driver codeif __name__ == "__main__": n = 5 print(int(operation(n))) # This code is contributed by ukasp // C# program to calculate the number// of ways to give ranks for N// students such that same ranks// are possibleusing System; class GFG{ static int mod = (int)(1e9 + 7); // Initializing a table in order to// store the bell trianglestatic int [,]dp; // Function to calculate the K-th// bell numberstatic int f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n, k] != -1) return dp[n, k]; // Fill the defined dp table return dp[n, k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblestatic long operation(int n){ // Resizing the dp table for the // given value of n dp = new int[n + 1, n + 1]; for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i, j] = -1; } } // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for(int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codepublic static void Main(String[] args){ int n = 5; Console.Write(operation(n) + "\n");}} // This code is contributed by amal kumar choubey <script> // Javascript program to calculate the number// of ways to give ranks for N// students such that same ranks// are possible var mod = parseInt( 1e9 + 7); // Initializing a table in order to // store the bell triangle var dp; // Function to calculate the K-th // bell number function f(n , k) { // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod; } // Function to return the number // of ways to give ranks for N // students such that same ranks // are possible function operation(n) { // Resizing the dp table for the // given value of n dp = Array(n + 1).fill().map(() =>Array(n + 1).fill(0)); for (i = 0; i < n + 1; i++) { for (j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Variables to store the answer // and the factorial value var ans = 0, fac = 1; // Iterating till N for (k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans; } // Driver code var n = 5; document.write(operation(n) + "\n"); // This code contributed by umadevi9616 </script> 541 Amal Kumar Choubey ukasp umadevi9616 Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count All Palindrome Sub-Strings in a String | Set 1 Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent Min Cost Path | DP-6 Optimal Binary Search Tree | DP-24 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 24698, "s": 24670, "text": "\n07 May, 2021" }, { "code": null, "e": 24969, "s": 24698, "text": "Given a number N which represents the number of students, the task is to calculate all possible ways to rank them according to their CGPA/marks, considering that two or more students can have the same rank. Since the answer can be large, perform the modulo with 109 + 7." }, { "code": null, "e": 24981, "s": 24969, "text": "Examples: " }, { "code": null, "e": 25086, "s": 24981, "text": "Input: N = 1 Output: 1 Explanation: There is only one way to rank a student, irrespective of his marks. " }, { "code": null, "e": 25369, "s": 25086, "text": "Input: N = 2 Output: 2 Explanation: In the following two ways the ranks can be distributed among two students: The high scoring student can be awarded the first rank and the low scoring student the second rank or both of them can be awarded the same rank if they have equal scores. " }, { "code": null, "e": 25435, "s": 25369, "text": "Approach: The idea for this problem is to use the Bell Numbers. " }, { "code": null, "e": 25612, "s": 25435, "text": "A bell number is a number that counts the possible partitions of a set. Therefore, an N-th bell number is a number of non-empty subsets a set of size N can be partitioned into." }, { "code": null, "e": 25803, "s": 25612, "text": "For example, let’s consider the set {1, 2, 3} for N = 3. The bell number corresponding to N = 3 is 5. This signifies that the given set can be partitioned into following 5 non-empty subsets:" }, { "code": null, "e": 25873, "s": 25803, "text": "{{1}, {2}, {3}}\n{{1, 2}, {3}}\n{{1, 3}, {2}}\n{{2, 3}, {1}}\n{{1, 2, 3}}" }, { "code": null, "e": 26000, "s": 25873, "text": "Clearly, the above bell numbers signify all the possible ranks. However, they do not calculate the permutations of the subset." }, { "code": null, "e": 26137, "s": 26000, "text": "Therefore, by multiplying every subset with K!, where K denotes the size of the respective subset, we get all the possible arrangements." }, { "code": null, "e": 26269, "s": 26137, "text": "As the same subproblems can be repeated, we can store the values of each subproblem in a data structure to optimize the complexity." }, { "code": null, "e": 26321, "s": 26269, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26325, "s": 26321, "text": "C++" }, { "code": null, "e": 26330, "s": 26325, "text": "Java" }, { "code": null, "e": 26338, "s": 26330, "text": "Python3" }, { "code": null, "e": 26341, "s": 26338, "text": "C#" }, { "code": null, "e": 26352, "s": 26341, "text": "Javascript" }, { "code": "// C++ program to calculate the number// of ways to give ranks for N// students such that same ranks// are possible #include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Initializing a table in order to// store the bell trianglevector<vector<int> > dp; // Function to calculate the K-th// bell numberint f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblelong operation(int n){ // Resizing the dp table for the // given value of n dp.resize(n + 1, vector<int>(n + 1, -1)); // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for (int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codeint main(){ int n = 5; cout << operation(n) << endl; return 0;}", "e": 27899, "s": 26352, "text": null }, { "code": "// Java program to calculate the number// of ways to give ranks for N// students such that same ranks// are possibleimport java.util.*; class GFG{ static int mod = (int)(1e9 + 7); // Initializing a table in order to// store the bell trianglestatic int [][]dp; // Function to calculate the K-th// bell numberstatic int f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblestatic long operation(int n){ // Resizing the dp table for the // given value of n dp = new int[n + 1][n + 1]; for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for(int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codepublic static void main(String[] args){ int n = 5; System.out.print(operation(n) + \"\\n\");}} // This code is contributed by amal kumar choubey", "e": 29620, "s": 27899, "text": null }, { "code": "# Python3 program to calculate the number# of ways to give ranks for N# students such that same ranks# are possiblemod = 1e9 + 7 # Initializing a table in order to# store the bell triangledp = [[-1 for x in range(6)] for y in range(6)] # Function to calculate the K-th# bell numberdef f(n, k): # If we have already calculated # the bell numbers until the # required N if (n < k): return 0 # Base case if (n == k): return 1 # First Bell Number if (k == 1): return 1 # If the value of the bell # triangle has already been # calculated if (dp[n][k] != -1): return dp[n][k] # Fill the defined dp table dp[n][k] = ((((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod)) return dp[n][k] # Function to return the number# of ways to give ranks for N# students such that same ranks# are possibledef operation(n): # Resizing the dp table for the # given value of n global dp # Variables to store the answer # and the factorial value ans = 0 fac = 1 # Iterating till N for k in range(1, n + 1): # Simultaneously calculate the k! fac *= k # Computing the K-th bell number # and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod return ans # Driver codeif __name__ == \"__main__\": n = 5 print(int(operation(n))) # This code is contributed by ukasp", "e": 31067, "s": 29620, "text": null }, { "code": "// C# program to calculate the number// of ways to give ranks for N// students such that same ranks// are possibleusing System; class GFG{ static int mod = (int)(1e9 + 7); // Initializing a table in order to// store the bell trianglestatic int [,]dp; // Function to calculate the K-th// bell numberstatic int f(int n, int k){ // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n, k] != -1) return dp[n, k]; // Fill the defined dp table return dp[n, k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod;} // Function to return the number// of ways to give ranks for N// students such that same ranks// are possiblestatic long operation(int n){ // Resizing the dp table for the // given value of n dp = new int[n + 1, n + 1]; for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i, j] = -1; } } // Variables to store the answer // and the factorial value long ans = 0, fac = 1; // Iterating till N for(int k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans;} // Driver codepublic static void Main(String[] args){ int n = 5; Console.Write(operation(n) + \"\\n\");}} // This code is contributed by amal kumar choubey", "e": 32776, "s": 31067, "text": null }, { "code": "<script> // Javascript program to calculate the number// of ways to give ranks for N// students such that same ranks// are possible var mod = parseInt( 1e9 + 7); // Initializing a table in order to // store the bell triangle var dp; // Function to calculate the K-th // bell number function f(n , k) { // If we have already calculated // the bell numbers until the // required N if (n < k) return 0; // Base case if (n == k) return 1; // First Bell Number if (k == 1) return 1; // If the value of the bell // triangle has already been // calculated if (dp[n][k] != -1) return dp[n][k]; // Fill the defined dp table return dp[n][k] = ((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod; } // Function to return the number // of ways to give ranks for N // students such that same ranks // are possible function operation(n) { // Resizing the dp table for the // given value of n dp = Array(n + 1).fill().map(() =>Array(n + 1).fill(0)); for (i = 0; i < n + 1; i++) { for (j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Variables to store the answer // and the factorial value var ans = 0, fac = 1; // Iterating till N for (k = 1; k <= n; k++) { // Simultaneously calculate the k! fac *= k; // Computing the K-th bell number // and multiplying it with K! ans = (ans + (fac * f(n, k)) % mod) % mod; } return ans; } // Driver code var n = 5; document.write(operation(n) + \"\\n\"); // This code contributed by umadevi9616 </script>", "e": 34618, "s": 32776, "text": null }, { "code": null, "e": 34622, "s": 34618, "text": "541" }, { "code": null, "e": 34643, "s": 34624, "text": "Amal Kumar Choubey" }, { "code": null, "e": 34649, "s": 34643, "text": "ukasp" }, { "code": null, "e": 34661, "s": 34649, "text": "umadevi9616" }, { "code": null, "e": 34681, "s": 34661, "text": "Dynamic Programming" }, { "code": null, "e": 34694, "s": 34681, "text": "Mathematical" }, { "code": null, "e": 34714, "s": 34694, "text": "Dynamic Programming" }, { "code": null, "e": 34727, "s": 34714, "text": "Mathematical" }, { "code": null, "e": 34825, "s": 34727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34878, "s": 34825, "text": "Count All Palindrome Sub-Strings in a String | Set 1" }, { "code": null, "e": 34938, "s": 34878, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 34989, "s": 34938, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 35010, "s": 34989, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35045, "s": 35010, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 35105, "s": 35045, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35120, "s": 35105, "text": "C++ Data Types" }, { "code": null, "e": 35163, "s": 35120, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 35205, "s": 35163, "text": "Program to find GCD or HCF of two numbers" } ]
Mean Estimation: Median of Means. The Arithmetic Mean is boring... and... | by Jakob Poerschmann | Towards Data Science
If we break it down, machine learning comes back to making statistical inferences. Inference means making statements about an unknown distribution based on a sample generated by that same distribution. Consequently, mean estimation is one of the underlying problems of statistical inference and machine learning. We study samples, drawn from some unknown distribution aiming to understand where the original population is centered. Once that is uncovered, we can move on and learn more about the data generating process. The Empirical Mean applied to the sample is the most common and straightforward estimator for the population mean. It convinces through its ease of use. For most students, the Arithmetic Mean must be the first equation they see in their educational careers. So how can this estimator be wrong? Well, it depends. Let’s look at one simple example. We generate a population generated by a standard Gaussian distribution. We then draw a random sample of 100 data points from the same distribution and compute the Arithmetic Mean as an estimator of the population Mean. Unsurprisingly, our estimation is close to perfect. We denote a squared error of 0.0004. import numpy as npimport randomnp.random.seed(1813)population = np.random.normal(loc=0, size=1000, scale=1)sample = random.choices(population, k=100)print(np.mean(population))print(np.mean(sample))print((np.mean(population)-np.mean(sample))**2) So let us move on and always use the Arithmetic Mean, right? We tested and validated its performance. And that makes sense since everyone is using it, right? ... Of course not! This good performance is just due to the wonderfully clean distribution the data has been generated from. But the reality is far from Gaussian. Let’s look at a case that is just a little bit more complex. population = np.random.standard_t(df=1, size=1000)sample = random.choices(population, k=100)print(np.mean(population))print(np.mean(sample))print((np.mean(population)-np.mean(sample))**2 Things look very different now. With a Student-t distribution, we denote an error squared of 5.806. The thick tails of the sampled Student-t distribution may lead to a large number of extreme values occurring in the sample. This compromises estimation performance. So how do we solve this? The Median of Means (MoM) estimator is one approach to solve the problem described above. Given a data sample, the MoM estimator shuffles the data points and then splits them into k groups of m data points. It then computes the Arithmetic Mean of each group. Finally, we calculate the median over the resulting k Arithmetic Means. This technique diminishes the effect that outliers have on the final estimation by splitting the data and only considering the median of the resulting sub-estimations. Let’s see how this improved estimator performs on the previous example. We can reduce the squared error on the same example to 0.730. A significant improvement to the 5.806 we have seen with the Arithmetic Mean. However, every technique has its weaknesses. The MoM is dependent on the way we split the data initially. Imagine a case in which all the extremes in the data are sorted into one single sub-group by chance. While unlikely, as data scientists we never want to be dependent on pure chance to such a high degree. You can find the from-scratch implementation in my repo. As we know, expected values are every statistician’s friend. Thus let us treat the MoM as a random variable dependent on the specific permutation of the data sample. There is still one problem with this approach. To precisely calculate this estimator, we would need to compute the MoM for every possible sample permutation. That would be n! MoM to compute. Not sexy enough yet! To make it simple, we can estimate the actual permutation invariant MoM by something that comes close to it. For this, we can fix some number N, as the number of permutations we are going to sample randomly. Testing this estimator against our running example yields an error squared of 0.332. Success! We were able to improve our estimation even further. It’s time to move out of the kindergarten and become a little bolder in terms of experimentation. def _rob_median_of_means(seq, n): res = [_median_of_means(seq, 10) for _ in range(n)] return np.mean(res)print(_rob_median_of_means(population, 10))print(np.mean(population))print((np.mean(population)-_rob_median_of_means(population, 10))**2) You can find the from-scratch implementation in my repo. While we got a basic grasp, we need to understand the behavior of these estimators even better. Therefore let us observe their performance ni dependence on various sample sizes and data generating processes. The plots display the test performance of the introduced estimators. The performance is measured given a large variety of sample sizes and distribution shapes. The Arithmetic Mean is referred to as EM. The MoM and permutation invariant MoM are referred to as MoM and RMoM. Furthermore, green curves display the estimator performance on a standard gaussian and the red curve denote the performance on a Student-t data generating process. Find the from-scratch implementation of this experiment in my repo. The results yield some satisfying insights. As expected, the (R)MoM outperforms the Arithmetic Mean for thick-tailed distributions. It is not surprising to observe that the Arithmetic Mean is tough to beat for close to Gaussian distributions. However, we can confidently state that (R)MoM can keep up with Arithmetic Mean estimation performance. In summary, mean estimation is a challenge that we can solve very well in a laboratory environment. However, once the distributions are no longer normal the challenge might grow increasingly hard. Especially outliers might compromise the performance of the most common mean estimator significantly. The Median of Means represents one of many alternatives to this problem. While the MoM comes with its own flaws, it does improve estimation performance in most cases that are not normal. Also, the computational complexity is controllable over the number of data permutations that we want to include. Thus, why don’t you give it a try in your next model?
[ { "code": null, "e": 692, "s": 171, "text": "If we break it down, machine learning comes back to making statistical inferences. Inference means making statements about an unknown distribution based on a sample generated by that same distribution. Consequently, mean estimation is one of the underlying problems of statistical inference and machine learning. We study samples, drawn from some unknown distribution aiming to understand where the original population is centered. Once that is uncovered, we can move on and learn more about the data generating process." }, { "code": null, "e": 845, "s": 692, "text": "The Empirical Mean applied to the sample is the most common and straightforward estimator for the population mean. It convinces through its ease of use." }, { "code": null, "e": 1004, "s": 845, "text": "For most students, the Arithmetic Mean must be the first equation they see in their educational careers. So how can this estimator be wrong? Well, it depends." }, { "code": null, "e": 1346, "s": 1004, "text": "Let’s look at one simple example. We generate a population generated by a standard Gaussian distribution. We then draw a random sample of 100 data points from the same distribution and compute the Arithmetic Mean as an estimator of the population Mean. Unsurprisingly, our estimation is close to perfect. We denote a squared error of 0.0004." }, { "code": null, "e": 1591, "s": 1346, "text": "import numpy as npimport randomnp.random.seed(1813)population = np.random.normal(loc=0, size=1000, scale=1)sample = random.choices(population, k=100)print(np.mean(population))print(np.mean(sample))print((np.mean(population)-np.mean(sample))**2)" }, { "code": null, "e": 1973, "s": 1591, "text": "So let us move on and always use the Arithmetic Mean, right? We tested and validated its performance. And that makes sense since everyone is using it, right? ... Of course not! This good performance is just due to the wonderfully clean distribution the data has been generated from. But the reality is far from Gaussian. Let’s look at a case that is just a little bit more complex." }, { "code": null, "e": 2160, "s": 1973, "text": "population = np.random.standard_t(df=1, size=1000)sample = random.choices(population, k=100)print(np.mean(population))print(np.mean(sample))print((np.mean(population)-np.mean(sample))**2" }, { "code": null, "e": 2450, "s": 2160, "text": "Things look very different now. With a Student-t distribution, we denote an error squared of 5.806. The thick tails of the sampled Student-t distribution may lead to a large number of extreme values occurring in the sample. This compromises estimation performance. So how do we solve this?" }, { "code": null, "e": 2781, "s": 2450, "text": "The Median of Means (MoM) estimator is one approach to solve the problem described above. Given a data sample, the MoM estimator shuffles the data points and then splits them into k groups of m data points. It then computes the Arithmetic Mean of each group. Finally, we calculate the median over the resulting k Arithmetic Means." }, { "code": null, "e": 3021, "s": 2781, "text": "This technique diminishes the effect that outliers have on the final estimation by splitting the data and only considering the median of the resulting sub-estimations. Let’s see how this improved estimator performs on the previous example." }, { "code": null, "e": 3161, "s": 3021, "text": "We can reduce the squared error on the same example to 0.730. A significant improvement to the 5.806 we have seen with the Arithmetic Mean." }, { "code": null, "e": 3471, "s": 3161, "text": "However, every technique has its weaknesses. The MoM is dependent on the way we split the data initially. Imagine a case in which all the extremes in the data are sorted into one single sub-group by chance. While unlikely, as data scientists we never want to be dependent on pure chance to such a high degree." }, { "code": null, "e": 3528, "s": 3471, "text": "You can find the from-scratch implementation in my repo." }, { "code": null, "e": 3906, "s": 3528, "text": "As we know, expected values are every statistician’s friend. Thus let us treat the MoM as a random variable dependent on the specific permutation of the data sample. There is still one problem with this approach. To precisely calculate this estimator, we would need to compute the MoM for every possible sample permutation. That would be n! MoM to compute. Not sexy enough yet!" }, { "code": null, "e": 4114, "s": 3906, "text": "To make it simple, we can estimate the actual permutation invariant MoM by something that comes close to it. For this, we can fix some number N, as the number of permutations we are going to sample randomly." }, { "code": null, "e": 4359, "s": 4114, "text": "Testing this estimator against our running example yields an error squared of 0.332. Success! We were able to improve our estimation even further. It’s time to move out of the kindergarten and become a little bolder in terms of experimentation." }, { "code": null, "e": 4608, "s": 4359, "text": "def _rob_median_of_means(seq, n): res = [_median_of_means(seq, 10) for _ in range(n)] return np.mean(res)print(_rob_median_of_means(population, 10))print(np.mean(population))print((np.mean(population)-_rob_median_of_means(population, 10))**2)" }, { "code": null, "e": 4665, "s": 4608, "text": "You can find the from-scratch implementation in my repo." }, { "code": null, "e": 5310, "s": 4665, "text": "While we got a basic grasp, we need to understand the behavior of these estimators even better. Therefore let us observe their performance ni dependence on various sample sizes and data generating processes. The plots display the test performance of the introduced estimators. The performance is measured given a large variety of sample sizes and distribution shapes. The Arithmetic Mean is referred to as EM. The MoM and permutation invariant MoM are referred to as MoM and RMoM. Furthermore, green curves display the estimator performance on a standard gaussian and the red curve denote the performance on a Student-t data generating process." }, { "code": null, "e": 5378, "s": 5310, "text": "Find the from-scratch implementation of this experiment in my repo." }, { "code": null, "e": 5724, "s": 5378, "text": "The results yield some satisfying insights. As expected, the (R)MoM outperforms the Arithmetic Mean for thick-tailed distributions. It is not surprising to observe that the Arithmetic Mean is tough to beat for close to Gaussian distributions. However, we can confidently state that (R)MoM can keep up with Arithmetic Mean estimation performance." } ]
Matplotlib.axes.Axes.cla() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.cla() function in axes module of matplotlib library is used to clear the current axes. Syntax: Axes.cla(self) Parameters: This method does not accept any parameters. Returns:This method does not returns any values. Below examples illustrate the matplotlib.axes.Axes.cla() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(19)data = np.random.random((5, 10, 10)) fig, ax = plt.subplots() for i in range(len(data)): ax.cla() ax.imshow(data[i]) ax.set_title("Axes {}".format(i)) plt.pause(0.1) Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('matplotlib.axes.Axes.cla() Example\n\n Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.set_xlabel('x-axis')ax1.plot(t, s)ax1.grid(True)ax1.cla()ax1.set_title('Above example with cla()\ function', fontsize = 12, fontweight ='bold')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n19 Apr, 2020" }, { "code": null, "e": 24592, "s": 24292, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 24688, "s": 24592, "text": "The Axes.cla() function in axes module of matplotlib library is used to clear the current axes." }, { "code": null, "e": 24711, "s": 24688, "text": "Syntax: Axes.cla(self)" }, { "code": null, "e": 24767, "s": 24711, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 24816, "s": 24767, "text": "Returns:This method does not returns any values." }, { "code": null, "e": 24902, "s": 24816, "text": "Below examples illustrate the matplotlib.axes.Axes.cla() function in matplotlib.axes:" }, { "code": null, "e": 24913, "s": 24902, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt np.random.seed(19)data = np.random.random((5, 10, 10)) fig, ax = plt.subplots() for i in range(len(data)): ax.cla() ax.imshow(data[i]) ax.set_title(\"Axes {}\".format(i)) plt.pause(0.1)", "e": 25201, "s": 24913, "text": null }, { "code": null, "e": 25209, "s": 25201, "text": "Output:" }, { "code": null, "e": 25220, "s": 25209, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t) fig, [ax, ax1] = plt.subplots(2, 1) ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('matplotlib.axes.Axes.cla() Example\\n\\n Sample Example', fontsize = 12, fontweight ='bold') ax1.set_ylabel('y-axis')ax1.set_xlabel('x-axis')ax1.plot(t, s)ax1.grid(True)ax1.cla()ax1.set_title('Above example with cla()\\ function', fontsize = 12, fontweight ='bold')plt.show()", "e": 25756, "s": 25220, "text": null }, { "code": null, "e": 25764, "s": 25756, "text": "Output:" }, { "code": null, "e": 25782, "s": 25764, "text": "Python-matplotlib" }, { "code": null, "e": 25789, "s": 25782, "text": "Python" }, { "code": null, "e": 25887, "s": 25789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25919, "s": 25887, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25975, "s": 25919, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26017, "s": 25975, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26072, "s": 26017, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26114, "s": 26072, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26136, "s": 26114, "text": "Defaultdict in Python" }, { "code": null, "e": 26175, "s": 26136, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26206, "s": 26175, "text": "Python | os.path.join() method" }, { "code": null, "e": 26235, "s": 26206, "text": "Create a directory in Python" } ]
C library function - fgetpos()
The C library function int fgetpos(FILE *stream, fpos_t *pos) gets the current file position of the stream and writes it to pos. Following is the declaration for fgetpos() function. int fgetpos(FILE *stream, fpos_t *pos) stream − This is the pointer to a FILE object that identifies the stream. stream − This is the pointer to a FILE object that identifies the stream. pos − This is the pointer to a fpos_t object. pos − This is the pointer to a fpos_t object. This function returns zero on success, else non-zero value in case of an error. The following example shows the usage of fgetpos() function. #include <stdio.h> int main () { FILE *fp; fpos_t position; fp = fopen("file.txt","w+"); fgetpos(fp, &position); fputs("Hello, World!", fp); fsetpos(fp, &position); fputs("This is going to override previous content", fp); fclose(fp); return(0); } Let us compile and run the above program to create a file file.txt which will have the following content. First of all we get the initial position of the file using fgetpos() function and then we write Hello, World!in the file, but later we have used fsetpos() function to reset the write pointer at the beginning of the file and then over-write the file with the following content − This is going to override previous content Now let us see the content of the above file using the following program − #include <stdio.h> int main () { FILE *fp; int c; int n = 0; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); } Let us compile and run above program to produce the following result − This is going to override previous content 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": 2136, "s": 2007, "text": "The C library function int fgetpos(FILE *stream, fpos_t *pos) gets the current file position of the stream and writes it to pos." }, { "code": null, "e": 2189, "s": 2136, "text": "Following is the declaration for fgetpos() function." }, { "code": null, "e": 2228, "s": 2189, "text": "int fgetpos(FILE *stream, fpos_t *pos)" }, { "code": null, "e": 2302, "s": 2228, "text": "stream − This is the pointer to a FILE object that identifies the stream." }, { "code": null, "e": 2376, "s": 2302, "text": "stream − This is the pointer to a FILE object that identifies the stream." }, { "code": null, "e": 2422, "s": 2376, "text": "pos − This is the pointer to a fpos_t object." }, { "code": null, "e": 2468, "s": 2422, "text": "pos − This is the pointer to a fpos_t object." }, { "code": null, "e": 2548, "s": 2468, "text": "This function returns zero on success, else non-zero value in case of an error." }, { "code": null, "e": 2609, "s": 2548, "text": "The following example shows the usage of fgetpos() function." }, { "code": null, "e": 2892, "s": 2609, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n fpos_t position;\n\n fp = fopen(\"file.txt\",\"w+\");\n fgetpos(fp, &position);\n fputs(\"Hello, World!\", fp);\n \n fsetpos(fp, &position);\n fputs(\"This is going to override previous content\", fp);\n fclose(fp);\n \n return(0);\n}" }, { "code": null, "e": 3276, "s": 2892, "text": "Let us compile and run the above program to create a file file.txt which will have the following content. First of all we get the initial position of the file using fgetpos() function and then we write Hello, World!in the file, but later we have used fsetpos() function to reset the write pointer at the beginning of the file and then over-write the file with the following content −" }, { "code": null, "e": 3320, "s": 3276, "text": "This is going to override previous content\n" }, { "code": null, "e": 3395, "s": 3320, "text": "Now let us see the content of the above file using the following program −" }, { "code": null, "e": 3646, "s": 3395, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n int n = 0;\n\n fp = fopen(\"file.txt\",\"r\");\n \n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n\n fclose(fp);\n\n return(0);\n}" }, { "code": null, "e": 3717, "s": 3646, "text": "Let us compile and run above program to produce the following result −" }, { "code": null, "e": 3761, "s": 3717, "text": "This is going to override previous content\n" }, { "code": null, "e": 3794, "s": 3761, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3809, "s": 3794, "text": " Nishant Malik" }, { "code": null, "e": 3844, "s": 3809, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3859, "s": 3844, "text": " Nishant Malik" }, { "code": null, "e": 3894, "s": 3859, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3908, "s": 3894, "text": " Asif Hussain" }, { "code": null, "e": 3941, "s": 3908, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3959, "s": 3941, "text": " Richa Maheshwari" }, { "code": null, "e": 3994, "s": 3959, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4013, "s": 3994, "text": " Vandana Annavaram" }, { "code": null, "e": 4046, "s": 4013, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4058, "s": 4046, "text": " Amit Diwan" }, { "code": null, "e": 4065, "s": 4058, "text": " Print" }, { "code": null, "e": 4076, "s": 4065, "text": " Add Notes" } ]
SAP UI5 - Key Components
SAP UI5 has multiple components which are independent and reusable objects in UI5 application. These components can be developed by different people and can be used in different projects. An application can use the components from different locations and hence you can easily get the structure of an application. You can create different types of components under SAP UI5 development. Faceless components are used to get the data from the backend system and they don’t contain a user interface. Example− They are a part of class sap.ui.core.component UI components are used to add rendering functionality and represent a screen area or element on the user interface. Example − UI component can be a button with settings to perform some task. It is a part of class: sap.ui.core.UIComponent Note − sap.ui.core.component is the base class for faceless and UI components. To define the extensibility function, the components can inherit from the base class or from other components in UI development. The module name of a component is known as the package name, and .component where the package name is defined as the name of the parameter passed to the component constructor. SAP UI5 components can also be divided as per the system landscape − Client side component: This includes, Control libraries sap.m, sap.ui.common, etc. Core Javascript Test includes HTML and Javascript Control libraries sap.m, sap.ui.common, etc. Core Javascript Test includes HTML and Javascript Server side component Theming Generator Control and application development tools in Eclipse Resource handler Theming Generator Control and application development tools in Eclipse Resource handler Each component is represented in the form of a folder and contains the name of the components and the resources required to manage the component. Each component should contain the following files − Component.json file that contains metadata for design time and is used only for design time tools. Component.json file that contains metadata for design time and is used only for design time tools. Component.js is used to define properties, events, and components methods that are responsible for runtime metadata. Component.js is used to define properties, events, and components methods that are responsible for runtime metadata. To create a new component, you have to create new folder. Let us name this as button. Next is to create the component.js file Then, you have to extend UI component base class sap.ui.core.UIComponent.extend and enter the name of the component and package path. Later, to define a new component, you have to start with the require statement as follows − // defining a new UI Component jQuery.sap.require("sap.ui.core.UIComponent"); jQuery.sap.require("sap.ui.commons.Button"); jQuery.sap.declare("samples.components.button.Component"); // new Component sap.ui.core.UIComponent.extend("samples.components.button.Component", { metadata : { properties : { text: "string" } } }); samples.components.button.Component.prototype.createContent = function(){ this.oButton = new sap.ui.commons.Button("btn"); return this.oButton; }; /* * Overrides setText method of the component to set this text in the button */ samples.components.button.Component.prototype.setText = function(sText) { this.oButton.setText(sText); this.setProperty("text", sText); return this; }; The next step is to define the component.json in your folder as follows − { "name": "samples.components.button", "version": "0.1.0", "description": "Sample button component", "keywords": [ "button", "example" ], "dependencies": { } } To use a component, you have to wrap the component in a component container. You cannot directly use a UI component in a page using placeAt method. Another way is to pass the component to the componentContainer constructor. It includes adding the component to the container and using placeAt method to place the component on the page. var oComp = sap.ui.getCore().createComponent({ name: "samples.components.shell", id: "Comp1", settings: {appTitle: "Hello John"} }); var oCompCont = new sap.ui.core.ComponentContainer("CompCont1", { component: oComp }); oCompCont.placeAt("target1"); //using placeAt method A component container carries specific settings and also contains the lifecycle methods of a regular control. The following code segment shows how to pass the component to the componentContainer constructor. var oCompCont2 = new sap.ui.core.ComponentContainer("CompCont2", { name: " samples.components.shell", settings: {text: "Hello John 1"} }); oCompCont2.placeAt("target2"); 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": 2229, "s": 2041, "text": "SAP UI5 has multiple components which are independent and reusable objects in UI5 application. These components can be developed by different people and can be used in different projects." }, { "code": null, "e": 2426, "s": 2229, "text": "An application can use the components from different locations and hence you can easily get the structure of an application. You can create different types of components under SAP UI5 development." }, { "code": null, "e": 2536, "s": 2426, "text": "Faceless components are used to get the data from the backend system and they don’t contain a user interface." }, { "code": null, "e": 2592, "s": 2536, "text": "Example− They are a part of class sap.ui.core.component" }, { "code": null, "e": 2708, "s": 2592, "text": "UI components are used to add rendering functionality and represent a screen area or element on the user interface." }, { "code": null, "e": 2830, "s": 2708, "text": "Example − UI component can be a button with settings to perform some task. It is a part of class: sap.ui.core.UIComponent" }, { "code": null, "e": 3038, "s": 2830, "text": "Note − sap.ui.core.component is the base class for faceless and UI components. To define the extensibility function, the components can inherit from the base class or from other components in UI development." }, { "code": null, "e": 3214, "s": 3038, "text": "The module name of a component is known as the package name, and .component where the package name is defined as the name of the parameter passed to the component constructor." }, { "code": null, "e": 3283, "s": 3214, "text": "SAP UI5 components can also be divided as per the system landscape −" }, { "code": null, "e": 3418, "s": 3283, "text": "Client side component: This includes,\n\nControl libraries sap.m, sap.ui.common, etc.\nCore Javascript\nTest includes HTML and Javascript\n" }, { "code": null, "e": 3463, "s": 3418, "text": "Control libraries sap.m, sap.ui.common, etc." }, { "code": null, "e": 3479, "s": 3463, "text": "Core Javascript" }, { "code": null, "e": 3513, "s": 3479, "text": "Test includes HTML and Javascript" }, { "code": null, "e": 3625, "s": 3513, "text": "Server side component\n\nTheming Generator\nControl and application development tools in Eclipse\nResource handler\n" }, { "code": null, "e": 3643, "s": 3625, "text": "Theming Generator" }, { "code": null, "e": 3696, "s": 3643, "text": "Control and application development tools in Eclipse" }, { "code": null, "e": 3713, "s": 3696, "text": "Resource handler" }, { "code": null, "e": 3859, "s": 3713, "text": "Each component is represented in the form of a folder and contains the name of the components and the resources required to manage the component." }, { "code": null, "e": 3911, "s": 3859, "text": "Each component should contain the following files −" }, { "code": null, "e": 4010, "s": 3911, "text": "Component.json file that contains metadata for design time and is used only for design time tools." }, { "code": null, "e": 4109, "s": 4010, "text": "Component.json file that contains metadata for design time and is used only for design time tools." }, { "code": null, "e": 4226, "s": 4109, "text": "Component.js is used to define properties, events, and components methods that are responsible for runtime metadata." }, { "code": null, "e": 4343, "s": 4226, "text": "Component.js is used to define properties, events, and components methods that are responsible for runtime metadata." }, { "code": null, "e": 4429, "s": 4343, "text": "To create a new component, you have to create new folder. Let us name this as button." }, { "code": null, "e": 4469, "s": 4429, "text": "Next is to create the component.js file" }, { "code": null, "e": 4603, "s": 4469, "text": "Then, you have to extend UI component base class sap.ui.core.UIComponent.extend and enter the name of the component and package path." }, { "code": null, "e": 4695, "s": 4603, "text": "Later, to define a new component, you have to start with the require statement as follows −" }, { "code": null, "e": 5442, "s": 4695, "text": "// defining a new UI Component\njQuery.sap.require(\"sap.ui.core.UIComponent\");\njQuery.sap.require(\"sap.ui.commons.Button\");\njQuery.sap.declare(\"samples.components.button.Component\");\n\n// new Component\nsap.ui.core.UIComponent.extend(\"samples.components.button.Component\", {\n metadata : {\n properties : {\n text: \"string\"\n }\n }\n});\n\nsamples.components.button.Component.prototype.createContent = function(){\n this.oButton = new sap.ui.commons.Button(\"btn\");\n return this.oButton;\n};\n\n/*\n* Overrides setText method of the component to set this text in the button\n*/\nsamples.components.button.Component.prototype.setText = function(sText) {\n this.oButton.setText(sText);\n this.setProperty(\"text\", sText);\n return this;\n};" }, { "code": null, "e": 5516, "s": 5442, "text": "The next step is to define the component.json in your folder as follows −" }, { "code": null, "e": 5709, "s": 5516, "text": "{\n \"name\": \"samples.components.button\",\n \"version\": \"0.1.0\",\n \"description\": \"Sample button component\",\n \"keywords\": [\n \"button\",\n \"example\"\n ],\n \"dependencies\": {\n }\n}" }, { "code": null, "e": 5933, "s": 5709, "text": "To use a component, you have to wrap the component in a component container. You cannot directly use a UI component in a page using placeAt method. Another way is to pass the component to the componentContainer constructor." }, { "code": null, "e": 6044, "s": 5933, "text": "It includes adding the component to the container and using placeAt method to place the component on the page." }, { "code": null, "e": 6331, "s": 6044, "text": "var oComp = sap.ui.getCore().createComponent({\n name: \"samples.components.shell\",\n id: \"Comp1\",\n settings: {appTitle: \"Hello John\"}\n});\n\nvar oCompCont = new sap.ui.core.ComponentContainer(\"CompCont1\", {\n component: oComp\n});\n\noCompCont.placeAt(\"target1\");\n//using placeAt method" }, { "code": null, "e": 6539, "s": 6331, "text": "A component container carries specific settings and also contains the lifecycle methods of a regular control. The following code segment shows how to pass the component to the componentContainer constructor." }, { "code": null, "e": 6716, "s": 6539, "text": "var oCompCont2 = new sap.ui.core.ComponentContainer(\"CompCont2\", {\n name: \" samples.components.shell\",\n settings: {text: \"Hello John 1\"}\n});\noCompCont2.placeAt(\"target2\");\n" }, { "code": null, "e": 6749, "s": 6716, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6763, "s": 6749, "text": " Sanjo Thomas" }, { "code": null, "e": 6796, "s": 6763, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6808, "s": 6796, "text": " Neha Gupta" }, { "code": null, "e": 6843, "s": 6808, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6858, "s": 6843, "text": " Sumit Agarwal" }, { "code": null, "e": 6891, "s": 6858, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6906, "s": 6891, "text": " Sumit Agarwal" }, { "code": null, "e": 6941, "s": 6906, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6953, "s": 6941, "text": " Neha Malik" }, { "code": null, "e": 6988, "s": 6953, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7000, "s": 6988, "text": " Neha Malik" }, { "code": null, "e": 7007, "s": 7000, "text": " Print" }, { "code": null, "e": 7018, "s": 7007, "text": " Add Notes" } ]
What is the keyword used in instantiating a class in Java?
An object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Following is an example of creating an object − Live Demo public class Puppy { public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args) { // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ); } } Passed Name is :tommy
[ { "code": null, "e": 1153, "s": 1062, "text": "An object is created from a class. In Java, the new keyword is used to create new objects." }, { "code": null, "e": 1214, "s": 1153, "text": "There are three steps when creating an object from a class −" }, { "code": null, "e": 1293, "s": 1214, "text": "Declaration − A variable declaration with a variable name with an object type." }, { "code": null, "e": 1372, "s": 1293, "text": "Declaration − A variable declaration with a variable name with an object type." }, { "code": null, "e": 1436, "s": 1372, "text": "Instantiation − The 'new' keyword is used to create the object." }, { "code": null, "e": 1500, "s": 1436, "text": "Instantiation − The 'new' keyword is used to create the object." }, { "code": null, "e": 1613, "s": 1500, "text": "Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 1726, "s": 1613, "text": "Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object." }, { "code": null, "e": 1774, "s": 1726, "text": "Following is an example of creating an object −" }, { "code": null, "e": 1785, "s": 1774, "text": " Live Demo" }, { "code": null, "e": 2106, "s": 1785, "text": "public class Puppy {\n public Puppy(String name) {\n // This constructor has one parameter, name.\n System.out.println(\"Passed Name is :\" + name );\n }\n \n public static void main(String []args) {\n // Following statement would create an object myPuppy\n Puppy myPuppy = new Puppy( \"tommy\" );\n }\n}" }, { "code": null, "e": 2129, "s": 2106, "text": "Passed Name is :tommy\n" } ]
NumPy Array Shape
The shape of an array is the number of elements in each dimension. NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements. Print the shape of a 2-D array: The example above returns (2, 4), which means that the array has 2 dimensions, where the first dimension has 2 elements and the second has 4. Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4 and verify that last dimension has value 4: Integers at every index tells about the number of elements the corresponding dimension has. In the example above at index-4 we have value 4, so we can say that 5th ( 4 + 1 th) dimension has 4 elements. Use the correct NumPy syntax to check the shape of an array. arr = np.array([1, 2, 3, 4, 5]) print(arr.) Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 67, "s": 0, "text": "The shape of an array is the number of elements in each dimension." }, { "code": null, "e": 193, "s": 67, "text": "NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements." }, { "code": null, "e": 225, "s": 193, "text": "Print the shape of a 2-D array:" }, { "code": null, "e": 368, "s": 225, "text": "The example above returns (2, 4), which means that the array has 2 dimensions, \nwhere the first dimension has 2 elements and the second has 4." }, { "code": null, "e": 493, "s": 368, "text": "Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4 and verify that last dimension has value 4:" }, { "code": null, "e": 585, "s": 493, "text": "Integers at every index tells about the number of elements the corresponding dimension has." }, { "code": null, "e": 695, "s": 585, "text": "In the example above at index-4 we have value 4, so we can say that 5th ( 4 + 1 th) dimension has 4 elements." }, { "code": null, "e": 756, "s": 695, "text": "Use the correct NumPy syntax to check the shape of an array." }, { "code": null, "e": 802, "s": 756, "text": "arr = np.array([1, 2, 3, 4, 5])\n\nprint(arr.)\n" }, { "code": null, "e": 821, "s": 802, "text": "Start the Exercise" }, { "code": null, "e": 854, "s": 821, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 896, "s": 854, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1003, "s": 896, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1022, "s": 1003, "text": "[email protected]" } ]
Transmitting data over WiFi using MQTT
MQTT (Message Queuing Telemetry Transport) has gained a lot of prominence in the context of IoT devices. It is a protocol that runs generally over TCP/IP. Instead of the server−client model that we saw for HTTP, MQTT uses the broker−client model. Wikipedia defines MQTT brokers and clients as − An MQTT broker is a server that receives all messages from the clients and then routes the messages to the appropriate destination clients. An MQTT client is any device (from a micro controller up to a full−fledged server) that runs an MQTT library and connects to an MQTT broker over a network. Think of the broker as a service like Medium. The topics would be the Medium publications, and the clients would be the Medium users. A user (client) can post to a publication, and another user (client) who has subscribed to that publication (topic) would be told that a new post is available for reading. By now, you would have understood a major difference between HTTP and MQTT. In HTTP, your messages are directly sent to the intended server and you even get an acknowledgment in the form of status codes. In MQTT, you just send messages to the broker in the hope that your intended server(s) will take it from there. Several features of MQTT turn out to be a boon if you are resource−constrained. They are listed below − With MQTT, header overheads are very short and throughput is high. This helps save time and also battery. With MQTT, header overheads are very short and throughput is high. This helps save time and also battery. MQTT sends information as a byte array instead of the text format. This makes the message lightweight. MQTT sends information as a byte array instead of the text format. This makes the message lightweight. Because MQTT isn't dependent on the response from the server, the client is independent and can go to sleep (conserve battery) as soon as it has transmitted the message. Because MQTT isn't dependent on the response from the server, the client is independent and can go to sleep (conserve battery) as soon as it has transmitted the message. These are just some of the points which have resulted in the popularity of MQTT. You can get a more detailed comparison between MQTT and HTTP here. In general, testing MQTT requires you to sign up for a free/ paid account with a broker. AWS IoT and Azure IoT are very popular platforms providing MQTT broker services, but they come with a lengthy signup and configuration process. Luckily, there is a free broker service from HiveMQ which can be used for testing MQTT without any signup or configuration. It is ideal for those of you who are new to MQTT and just want to get your hands dirty, and also lets you focus more on the firmware of ESP32. Therefore, that is the broker we will be using for this chapter. Of course, because it is a free service, there will be limitations. You can't share sensitive information, because all your messages are public, anyone can subscribe to your topics. For testing purposes, of course, these limitations won't matter. The code can be found on GitHub We will be using the PubSubClient library. You can install it from Tools −> Manage Libraries. Once the library is installed, we include WiFi and PubSubClient libraries. #include <WiFi.h> #include <PubSubClient.h> Next, we will define some constants. Remember to replace the WiFi credentials. The mqttServer and mqttPort are the once mandated by http://www.mqtt−dashboard.com/.The mqtt_client_name, mqtt_pub_topic and mqtt_sub_topic can be any strings of your choice. Just make sure that you do change their values. If multiple users copy the same code from this tutorial, you will receive a lot of messages from unknown clients when testing. We also define the WiFiClient and mqttClient object. The MQTTClient object requires the network client as an argument. If you are using Ethernet, you would provide the Ethernet client as an argument. Since we are using WiFi, we have provided the WiFi client as an argument. const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; //The broker and port are provided by http://www.mqtt−dashboard.com/ char *mqttServer = "broker.hivemq.com"; int mqttPort = 1883; //Replace these 3 with the strings of your choice const char* mqtt_client_name = "ESPYS2111"; const char* mqtt_pub_topic = "/ys/testpub"; //The topic to which our client will publish const char* mqtt_sub_topic = "/ys/testsub"; //The topic to which our client will subscribe WiFiClient client; PubSubClient mqttClient(client); Next, we define the callback function. A callback function is an interrupt function. Every time a new message is received from a subscribed topic, this function will be triggered. It has three arguments− the topic from which the message was received, the message as a byte array, and the length of the message. You can do whatever you want to do with that message (store it in SPIFFS, send it to another topic, and so on). Here, we are just printing the topic and the message. void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message received from: "); Serial.println(topic); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); Serial.println(); } In the setup, we connect to the WiFi like in every other sketch. The last two lines concern MQTT. We set the server and port for MQTT and also the callback function. void setup() { // put your setup code here, to run once: Serial.begin(115200); WiFi.mode(WIFI_STA); //The WiFi is in station mode WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("WiFi connected to: "); Serial.println(ssid); Serial.println("IP address: "); Serial.println(WiFi.localIP()); delay(2000); mqttClient.setServer(mqttServer, mqttPort); mqttClient.setCallback(callback); } Within the loop, we do the following: If the client is not connected to the broker, we connect it using our client name. If the client is not connected to the broker, we connect it using our client name. Once connected, we also subscribe our client to the mqtt_sub_topic. Once connected, we also subscribe our client to the mqtt_sub_topic. We then publish a message to mqtt_pub_topic We then publish a message to mqtt_pub_topic We then run the mqttClient.loop(). This loop() function should be called regularly. It maintains the connection of the client with the broker and also helps the client process incoming messages. If you don't have this mqttClient.loop() line, you will be able to publish to mqtt_pub_topic, but won't get messages from mqtt_sub_topic, because the incoming messages are processed only when this line is called. We then run the mqttClient.loop(). This loop() function should be called regularly. It maintains the connection of the client with the broker and also helps the client process incoming messages. If you don't have this mqttClient.loop() line, you will be able to publish to mqtt_pub_topic, but won't get messages from mqtt_sub_topic, because the incoming messages are processed only when this line is called. Finally, we wait for 5 seconds, before starting this cycle again. Finally, we wait for 5 seconds, before starting this cycle again. void loop() { // put your main code here, to run repeatedly: if (!mqttClient.connected()){ while (!mqttClient.connected()){ if(mqttClient.connect(mqtt_client_name)){ Serial.println("MQTT Connected!"); mqttClient.subscribe(mqtt_sub_topic); } else{ Serial.print("."); } } } mqttClient.publish(mqtt_pub_topic, "TestMsg"); Serial.println("Message published"); mqttClient.loop(); delay(5000); } In order to test the above code, you need to go to www.hivemq.com Follow these steps once you are on that webpage − Click Connect Click Connect Click on Add New Topic Subscription and enter the name of the topic to which your ESP32 will publish (/ys/testpub in this case) Click on Add New Topic Subscription and enter the name of the topic to which your ESP32 will publish (/ys/testpub in this case) Once you flash your ESP32, you will start receiving messages on that topic every 5 seconds. Once you flash your ESP32, you will start receiving messages on that topic every 5 seconds. Next, to test reception of message on ESP32, enter the name of the topic your ESP32 is subscribed to (ys/testsub in this case), then type a message in the message box and click publish. You should see the message on the Serial Monitor. Congratulations!! You've tested both publish and subscribe using MQTT on ESP32. MQTT - Wikipedia MQTT - Wikipedia ESP-MQTT ESP-MQTT 54 Lectures 4.5 hours Frahaan Hussain 20 Lectures 5 hours Azaz Patel 20 Lectures 4 hours Azaz Patel 0 Lectures 0 mins Eduonix Learning Solutions 169 Lectures 12.5 hours Kalob Taulien 29 Lectures 2 hours Zenva Print Add Notes Bookmark this page
[ { "code": null, "e": 2478, "s": 2183, "text": "MQTT (Message Queuing Telemetry Transport) has gained a lot of prominence in the context of IoT devices. It is a protocol that runs generally over TCP/IP. Instead of the server−client model that we saw for HTTP, MQTT uses the broker−client model. Wikipedia defines MQTT brokers and clients as −" }, { "code": null, "e": 2775, "s": 2478, "text": "An MQTT broker is a server that receives all messages from the clients and then routes the messages to the appropriate destination clients. An MQTT client is any device (from a micro controller up to a full−fledged server) that runs an MQTT library and connects to an MQTT broker over a network." }, { "code": null, "e": 3501, "s": 2775, "text": "Think of the broker as a service like Medium. The topics would be the Medium publications, and the clients would be the Medium users. A user (client) can post to a publication, and another user (client) who has subscribed to that publication (topic) would be told that a new post is available for reading. By now, you would have understood a major difference between HTTP and MQTT. In HTTP, your messages are directly sent to the intended server and you even get an acknowledgment in the form of status codes. In MQTT, you just send messages to the broker in the hope that your intended server(s) will take it from there. Several features of MQTT turn out to be a boon if you are resource−constrained. They are listed below −" }, { "code": null, "e": 3607, "s": 3501, "text": "With MQTT, header overheads are very short and throughput is high. This helps save time and also battery." }, { "code": null, "e": 3713, "s": 3607, "text": "With MQTT, header overheads are very short and throughput is high. This helps save time and also battery." }, { "code": null, "e": 3816, "s": 3713, "text": "MQTT sends information as a byte array instead of the text format. This makes the message lightweight." }, { "code": null, "e": 3919, "s": 3816, "text": "MQTT sends information as a byte array instead of the text format. This makes the message lightweight." }, { "code": null, "e": 4089, "s": 3919, "text": "Because MQTT isn't dependent on the response from the server, the client is independent and can go to sleep (conserve battery) as soon as it has transmitted the message." }, { "code": null, "e": 4259, "s": 4089, "text": "Because MQTT isn't dependent on the response from the server, the client is independent and can go to sleep (conserve battery) as soon as it has transmitted the message." }, { "code": null, "e": 4407, "s": 4259, "text": "These are just some of the points which have resulted in the popularity of MQTT. You can get a more detailed comparison between MQTT and HTTP here." }, { "code": null, "e": 5219, "s": 4407, "text": "In general, testing MQTT requires you to sign up for a free/ paid account with a broker. AWS IoT and Azure IoT are very popular platforms providing MQTT broker services, but they come with a lengthy signup and configuration process. Luckily, there is a free broker service from HiveMQ which can be used for testing MQTT without any signup or configuration. It is ideal for those of you who are new to MQTT and just want to get your hands dirty, and also lets you focus more on the firmware of ESP32. Therefore, that is the broker we will be using for this chapter. Of course, because it is a free service, there will be limitations. You can't share sensitive information, because all your messages are public, anyone can subscribe to your topics. For testing purposes, of course, these limitations won't matter." }, { "code": null, "e": 5251, "s": 5219, "text": "The code can be found on GitHub" }, { "code": null, "e": 5345, "s": 5251, "text": "We will be using the PubSubClient library. You can install it from Tools −> Manage Libraries." }, { "code": null, "e": 5420, "s": 5345, "text": "Once the library is installed, we include WiFi and PubSubClient libraries." }, { "code": null, "e": 5464, "s": 5420, "text": "#include <WiFi.h>\n#include <PubSubClient.h>" }, { "code": null, "e": 5893, "s": 5464, "text": "Next, we will define some constants. Remember to replace the WiFi credentials. The mqttServer and mqttPort are the once mandated by http://www.mqtt−dashboard.com/.The mqtt_client_name, mqtt_pub_topic and mqtt_sub_topic can be any strings of your choice. Just make sure that you do change their values. If multiple users copy the same code from this tutorial, you will receive a lot of messages from unknown clients when testing." }, { "code": null, "e": 6167, "s": 5893, "text": "We also define the WiFiClient and mqttClient object. The MQTTClient object requires the network client as an argument. If you are using Ethernet, you would provide the Ethernet client as an argument. Since we are using WiFi, we have provided the WiFi client as an argument." }, { "code": null, "e": 6699, "s": 6167, "text": "const char* ssid = \"YOUR_SSID\";\nconst char* password = \"YOUR_PASSWORD\";\n\n//The broker and port are provided by http://www.mqtt−dashboard.com/\nchar *mqttServer = \"broker.hivemq.com\";\nint mqttPort = 1883;\n\n//Replace these 3 with the strings of your choice\nconst char* mqtt_client_name = \"ESPYS2111\";\nconst char* mqtt_pub_topic = \"/ys/testpub\"; //The topic to which our client will publish\nconst char* mqtt_sub_topic = \"/ys/testsub\"; //The topic to which our client will subscribe\n\nWiFiClient client;\nPubSubClient mqttClient(client);\n" }, { "code": null, "e": 7177, "s": 6699, "text": "Next, we define the callback function. A callback function is an interrupt function. Every time a new message is received from a subscribed topic, this function will be triggered. It has three arguments− the topic from which the message was received, the message as a byte array, and the length of the message. You can do whatever you want to do with that message (store it in\nSPIFFS, send it to another topic, and so on). Here, we are just printing the topic and the message." }, { "code": null, "e": 7435, "s": 7177, "text": "void callback(char* topic, byte* payload, unsigned int length) {\n Serial.print(\"Message received from: \"); Serial.println(topic);\n for (int i = 0; i < length; i++) {\n Serial.print((char)payload[i]);\n }\n Serial.println();\n Serial.println();\n}\n" }, { "code": null, "e": 7601, "s": 7435, "text": "In the setup, we connect to the WiFi like in every other sketch. The last two lines concern MQTT. We set the server and port for MQTT and also the callback function." }, { "code": null, "e": 8135, "s": 7601, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(115200);\n WiFi.mode(WIFI_STA); //The WiFi is in station mode\n WiFi.begin(ssid, password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n Serial.println(\"\"); Serial.print(\"WiFi connected to: \"); Serial.println(ssid); Serial.println(\"IP address: \"); Serial.println(WiFi.localIP());\n delay(2000);\n mqttClient.setServer(mqttServer, mqttPort);\n mqttClient.setCallback(callback);\n}" }, { "code": null, "e": 8173, "s": 8135, "text": "Within the loop, we do the following:" }, { "code": null, "e": 8256, "s": 8173, "text": "If the client is not connected to the broker, we connect it using our client name." }, { "code": null, "e": 8339, "s": 8256, "text": "If the client is not connected to the broker, we connect it using our client name." }, { "code": null, "e": 8407, "s": 8339, "text": "Once connected, we also subscribe our client to the mqtt_sub_topic." }, { "code": null, "e": 8475, "s": 8407, "text": "Once connected, we also subscribe our client to the mqtt_sub_topic." }, { "code": null, "e": 8519, "s": 8475, "text": "We then publish a message to mqtt_pub_topic" }, { "code": null, "e": 8563, "s": 8519, "text": "We then publish a message to mqtt_pub_topic" }, { "code": null, "e": 8971, "s": 8563, "text": "We then run the mqttClient.loop(). This loop() function should be called regularly. It maintains the connection of the client with the broker and also helps the client process incoming messages. If you don't have this mqttClient.loop() line, you will be able to publish to mqtt_pub_topic, but won't get messages from mqtt_sub_topic, because the incoming messages are processed only when this line is called." }, { "code": null, "e": 9379, "s": 8971, "text": "We then run the mqttClient.loop(). This loop() function should be called regularly. It maintains the connection of the client with the broker and also helps the client process incoming messages. If you don't have this mqttClient.loop() line, you will be able to publish to mqtt_pub_topic, but won't get messages from mqtt_sub_topic, because the incoming messages are processed only when this line is called." }, { "code": null, "e": 9445, "s": 9379, "text": "Finally, we wait for 5 seconds, before starting this cycle again." }, { "code": null, "e": 9511, "s": 9445, "text": "Finally, we wait for 5 seconds, before starting this cycle again." }, { "code": null, "e": 10006, "s": 9511, "text": "void loop() {\n // put your main code here, to run repeatedly:\n if (!mqttClient.connected()){\n while (!mqttClient.connected()){\n if(mqttClient.connect(mqtt_client_name)){\n Serial.println(\"MQTT Connected!\");\n mqttClient.subscribe(mqtt_sub_topic);\n }\n else{\n Serial.print(\".\");\n }\n }\n }\n mqttClient.publish(mqtt_pub_topic, \"TestMsg\");\n Serial.println(\"Message published\");\n mqttClient.loop();\n delay(5000);\n}" }, { "code": null, "e": 10072, "s": 10006, "text": "In order to test the above code, you need to go to www.hivemq.com" }, { "code": null, "e": 10122, "s": 10072, "text": "Follow these steps once you are on that webpage −" }, { "code": null, "e": 10136, "s": 10122, "text": "Click Connect" }, { "code": null, "e": 10150, "s": 10136, "text": "Click Connect" }, { "code": null, "e": 10278, "s": 10150, "text": "Click on Add New Topic Subscription and enter the name of the topic to which your ESP32 will publish (/ys/testpub in this case)" }, { "code": null, "e": 10406, "s": 10278, "text": "Click on Add New Topic Subscription and enter the name of the topic to which your ESP32 will publish (/ys/testpub in this case)" }, { "code": null, "e": 10498, "s": 10406, "text": "Once you flash your ESP32, you will start receiving messages on that topic every 5 seconds." }, { "code": null, "e": 10590, "s": 10498, "text": "Once you flash your ESP32, you will start receiving messages on that topic every 5 seconds." }, { "code": null, "e": 10826, "s": 10590, "text": "Next, to test reception of message on ESP32, enter the name of the topic your ESP32 is subscribed to (ys/testsub in this case), then type a message in the message box and click publish.\nYou should see the message on the Serial Monitor." }, { "code": null, "e": 10906, "s": 10826, "text": "Congratulations!! You've tested both publish and subscribe using MQTT on ESP32." }, { "code": null, "e": 10923, "s": 10906, "text": "MQTT - Wikipedia" }, { "code": null, "e": 10940, "s": 10923, "text": "MQTT - Wikipedia" }, { "code": null, "e": 10949, "s": 10940, "text": "ESP-MQTT" }, { "code": null, "e": 10958, "s": 10949, "text": "ESP-MQTT" }, { "code": null, "e": 10993, "s": 10958, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11010, "s": 10993, "text": " Frahaan Hussain" }, { "code": null, "e": 11043, "s": 11010, "text": "\n 20 Lectures \n 5 hours \n" }, { "code": null, "e": 11055, "s": 11043, "text": " Azaz Patel" }, { "code": null, "e": 11088, "s": 11055, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 11100, "s": 11088, "text": " Azaz Patel" }, { "code": null, "e": 11130, "s": 11100, "text": "\n 0 Lectures \n 0 mins\n" }, { "code": null, "e": 11158, "s": 11130, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11195, "s": 11158, "text": "\n 169 Lectures \n 12.5 hours \n" }, { "code": null, "e": 11210, "s": 11195, "text": " Kalob Taulien" }, { "code": null, "e": 11243, "s": 11210, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 11250, "s": 11243, "text": " Zenva" }, { "code": null, "e": 11257, "s": 11250, "text": " Print" }, { "code": null, "e": 11268, "s": 11257, "text": " Add Notes" } ]
A Generative Approach to Classification | by Rahul Agarwal | Towards Data Science
I always get confused whenever someone talks about generative vs. discriminative classification models. I end up reading it again and again, yet somehow it eludes me. So I thought of writing a post on it to improve my understanding. This post is about understanding Generative Models and how they differ from Discriminative models. In the end, we will create a simple generative model ourselves. Problem Statement: Having some input data, X we want to classify the data into labels y. A generative model learns the joint probability distribution p(x,y) while a discriminative model learns the conditional probability distribution p(y|x) So really, what is the difference? They both look pretty much the same. Suppose we have a small sample of data: (x,y) : [(0,1), (1,0), (1,0), (1, 1)] Then p(x,y) is While p(y|x) is As you can see, they model different probabilities. The discriminative distribution p(y|x) could be used straightforward to classify an example x into a class y. An example of a discriminative classification model is Logistic regression, where we try to model P(y|X). Generative algorithms model p(x,y). An example is the Naive Bayes model in which we try to model P(X,y) and then use the Bayes equation to predict. Fit each class separately with a probability distribution. To classify a new point, find out which distribution is it most probable to come from. Don’t worry if you don’t understand yet. You will surely get it by the end of this post. Let us work with the iris dataset. For our simple example, we will work with a single x variable SepalLength and our target variable Species. Let us see the distribution of sepal length with Species. I am using plotly_express for this. import plotly_express as pxpx.histogram(iris, x = 'SepalLengthCm',color = 'Species',nbins=20) To create generative models, we need to find out two sets of values: To get individual class probability is fairly trivial- For example, the number of instances in our dataset, which is setosa divided by the total number of cases in the dataset. 0.3333333333333333 0.3333333333333333 0.3333333333333333 The iris dataset is pretty much balanced. Here we fit a probability distribution over our X. We assume here that the X data is distributed normally. And hence we can find the sample means and variance for these three distributions(As we have three classes) In the above graph, I have fitted three normal distributions for each of the species just using sample means and variances for each of the three species. So, how do we predict using this? Let us say we get a new example with SepalLength = 7 cm. Since we see that the maximum probability comes for Virginica, we predict virginica for x=7, and based on the graph too; it looks pretty much the right choice. You can get the values using the code too. Setosa 3.062104211904799e-08Versicolor 0.029478757465669376Virginica 0.16881724812694823 This is all well and good. But when do we ever work with a single variable? Let us extend our example for two variables. This time let us use PetalLength too. px.scatter(iris, 'SepalLengthCm', 'PetalLengthCm',color = 'Species') So how do we proceed in this case? The first time we had fit a Normal Distribution over our single x, this time we will fit Bivariate Normal. Here is how it looks: Now the rest of the calculations remains the same. Just the normal gets replaced by Bivariate normal in the above equations. And as you can see, we get a pretty better separation amongst the classes by using the bivariate normal. As an extension to this case for multiple variables(more than 2), we can use the multivariate normal distribution. Generative models are good at generating data. But at the same time, creating such models that capture the underlying distribution of data is extremely hard. Generative modeling involves a lot of assumptions, and thus, these models don’t perform as well as discriminative models in the classification setting. In the above example also we assumed that the distribution is normal, which might not be correct and hence may induce a bias. But understanding how they work is helpful all the same. One class of such models is called generative adversarial networks which are pretty useful for generating new images and are pretty interesting too. Here is the kernel with all the code along with the visualizations. If you want to learn more about generative models and Machine Learning, I would recommend this Machine Learning Fundamentals course from the University of San Diego. The above post is by and large inspired from content from this course in the MicroMasters from SanDiego, which I am currently working on to structure my Data Science learning. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
[ { "code": null, "e": 276, "s": 172, "text": "I always get confused whenever someone talks about generative vs. discriminative classification models." }, { "code": null, "e": 339, "s": 276, "text": "I end up reading it again and again, yet somehow it eludes me." }, { "code": null, "e": 405, "s": 339, "text": "So I thought of writing a post on it to improve my understanding." }, { "code": null, "e": 504, "s": 405, "text": "This post is about understanding Generative Models and how they differ from Discriminative models." }, { "code": null, "e": 568, "s": 504, "text": "In the end, we will create a simple generative model ourselves." }, { "code": null, "e": 657, "s": 568, "text": "Problem Statement: Having some input data, X we want to classify the data into labels y." }, { "code": null, "e": 809, "s": 657, "text": "A generative model learns the joint probability distribution p(x,y) while a discriminative model learns the conditional probability distribution p(y|x)" }, { "code": null, "e": 881, "s": 809, "text": "So really, what is the difference? They both look pretty much the same." }, { "code": null, "e": 921, "s": 881, "text": "Suppose we have a small sample of data:" }, { "code": null, "e": 959, "s": 921, "text": "(x,y) : [(0,1), (1,0), (1,0), (1, 1)]" }, { "code": null, "e": 974, "s": 959, "text": "Then p(x,y) is" }, { "code": null, "e": 990, "s": 974, "text": "While p(y|x) is" }, { "code": null, "e": 1042, "s": 990, "text": "As you can see, they model different probabilities." }, { "code": null, "e": 1258, "s": 1042, "text": "The discriminative distribution p(y|x) could be used straightforward to classify an example x into a class y. An example of a discriminative classification model is Logistic regression, where we try to model P(y|X)." }, { "code": null, "e": 1406, "s": 1258, "text": "Generative algorithms model p(x,y). An example is the Naive Bayes model in which we try to model P(X,y) and then use the Bayes equation to predict." }, { "code": null, "e": 1465, "s": 1406, "text": "Fit each class separately with a probability distribution." }, { "code": null, "e": 1552, "s": 1465, "text": "To classify a new point, find out which distribution is it most probable to come from." }, { "code": null, "e": 1641, "s": 1552, "text": "Don’t worry if you don’t understand yet. You will surely get it by the end of this post." }, { "code": null, "e": 1676, "s": 1641, "text": "Let us work with the iris dataset." }, { "code": null, "e": 1783, "s": 1676, "text": "For our simple example, we will work with a single x variable SepalLength and our target variable Species." }, { "code": null, "e": 1877, "s": 1783, "text": "Let us see the distribution of sepal length with Species. I am using plotly_express for this." }, { "code": null, "e": 1971, "s": 1877, "text": "import plotly_express as pxpx.histogram(iris, x = 'SepalLengthCm',color = 'Species',nbins=20)" }, { "code": null, "e": 2040, "s": 1971, "text": "To create generative models, we need to find out two sets of values:" }, { "code": null, "e": 2217, "s": 2040, "text": "To get individual class probability is fairly trivial- For example, the number of instances in our dataset, which is setosa divided by the total number of cases in the dataset." }, { "code": null, "e": 2274, "s": 2217, "text": "0.3333333333333333 0.3333333333333333 0.3333333333333333" }, { "code": null, "e": 2316, "s": 2274, "text": "The iris dataset is pretty much balanced." }, { "code": null, "e": 2531, "s": 2316, "text": "Here we fit a probability distribution over our X. We assume here that the X data is distributed normally. And hence we can find the sample means and variance for these three distributions(As we have three classes)" }, { "code": null, "e": 2685, "s": 2531, "text": "In the above graph, I have fitted three normal distributions for each of the species just using sample means and variances for each of the three species." }, { "code": null, "e": 2719, "s": 2685, "text": "So, how do we predict using this?" }, { "code": null, "e": 2776, "s": 2719, "text": "Let us say we get a new example with SepalLength = 7 cm." }, { "code": null, "e": 2936, "s": 2776, "text": "Since we see that the maximum probability comes for Virginica, we predict virginica for x=7, and based on the graph too; it looks pretty much the right choice." }, { "code": null, "e": 2979, "s": 2936, "text": "You can get the values using the code too." }, { "code": null, "e": 3068, "s": 2979, "text": "Setosa 3.062104211904799e-08Versicolor 0.029478757465669376Virginica 0.16881724812694823" }, { "code": null, "e": 3144, "s": 3068, "text": "This is all well and good. But when do we ever work with a single variable?" }, { "code": null, "e": 3227, "s": 3144, "text": "Let us extend our example for two variables. This time let us use PetalLength too." }, { "code": null, "e": 3296, "s": 3227, "text": "px.scatter(iris, 'SepalLengthCm', 'PetalLengthCm',color = 'Species')" }, { "code": null, "e": 3331, "s": 3296, "text": "So how do we proceed in this case?" }, { "code": null, "e": 3438, "s": 3331, "text": "The first time we had fit a Normal Distribution over our single x, this time we will fit Bivariate Normal." }, { "code": null, "e": 3460, "s": 3438, "text": "Here is how it looks:" }, { "code": null, "e": 3511, "s": 3460, "text": "Now the rest of the calculations remains the same." }, { "code": null, "e": 3690, "s": 3511, "text": "Just the normal gets replaced by Bivariate normal in the above equations. And as you can see, we get a pretty better separation amongst the classes by using the bivariate normal." }, { "code": null, "e": 3805, "s": 3690, "text": "As an extension to this case for multiple variables(more than 2), we can use the multivariate normal distribution." }, { "code": null, "e": 3963, "s": 3805, "text": "Generative models are good at generating data. But at the same time, creating such models that capture the underlying distribution of data is extremely hard." }, { "code": null, "e": 4241, "s": 3963, "text": "Generative modeling involves a lot of assumptions, and thus, these models don’t perform as well as discriminative models in the classification setting. In the above example also we assumed that the distribution is normal, which might not be correct and hence may induce a bias." }, { "code": null, "e": 4447, "s": 4241, "text": "But understanding how they work is helpful all the same. One class of such models is called generative adversarial networks which are pretty useful for generating new images and are pretty interesting too." }, { "code": null, "e": 4515, "s": 4447, "text": "Here is the kernel with all the code along with the visualizations." }, { "code": null, "e": 4857, "s": 4515, "text": "If you want to learn more about generative models and Machine Learning, I would recommend this Machine Learning Fundamentals course from the University of San Diego. The above post is by and large inspired from content from this course in the MicroMasters from SanDiego, which I am currently working on to structure my Data Science learning." } ]
MySQL - CURDATE() Function
The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values. The MYSQL CURDATE() is used to get the current days date. The resultant value is a string or a numerical value based on the context and, the date returned will be in the 'YYYY-MM-DD' or YYYYMMDD format. Following is the syntax of the above function – CURDATE(); Following example demonstrates the usage of the CURDATE() function – mysql> SELECT CURDATE(); +------------+ | CURDATE() | +------------+ | 2021-07-11 | +------------+ 1 row in set (0.00 sec) Following is an example of this function in numerical context – mysql> SELECT CURDATE() +0; +--------------+ | CURDATE() +0 | +--------------+ | 20210711 | +--------------+ 1 row in set (0.00 sec) You can add days to the current date as shown below – mysql> SELECT CURDATE()+12; +--------------+ | CURDATE()+12 | +--------------+ | 20210723 | +--------------+ 1 row in set (0.00 sec) We can also subtract the desired number of days from the current date using this function – mysql> SELECT CURDATE()-22213; +-----------------+ | CURDATE()-22213 | +-----------------+ | 20188498 | +-----------------+ 1 row in set (0.00 sec) Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below – mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements − mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); mysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following query calculates the age of the players in days — mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, DATEDIFF(CURDATE(),Date_Of_Birth) as Age_In_Days FROM MyPlayers; +------------+------------+---------------+-------------+-------------+ | First_Name | Last_Name | Date_Of_Birth | Country | Age_In_Days | +------------+------------+---------------+-------------+-------------+ | Shikhar | Dhawan | 1981-12-05 | India | 14463 | | Jonathan | Trott | 1981-04-22 | SouthAfrica | 14690 | | Kumara | Sangakkara | 1977-10-27 | Srilanka | 15963 | | Virat | Kohli | 1988-11-05 | India | 11936 | | Rohit | Sharma | 1987-04-30 | India | 12491 | | Ravindra | Jadeja | 1988-12-06 | India | 11905 | | James | Anderson | 1982-06-30 | England | 14256 | +------------+------------+---------------+-------------+-------------+ 7 rows in set (0.11 sec) Let us create another table with name Sales in MySQL database using CREATE statement as follows mysql> CREATE TABLE sales( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DispatchTime time, Price INT, Location VARCHAR(255) ); Query OK, 0 rows affected (2.22 sec) Now, we will insert 5 records in Sales table using INSERT statements − insert into sales values (1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into sales values (2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into sales values (3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into sales values (4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into sales values (5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following is another example of this function — mysql> SELECT ProductName, CustomerName, DispatchDate, Price, DATEDIFF(CURDATE(), DispatchDate) as difference_in_days FROM sales; +-------------+--------------+--------------+-------+--------------------+ | ProductName | CustomerName | DispatchDate | Price | difference_in_days | +-------------+--------------+--------------+-------+--------------------+ | Key-Board | Raja | 2019-09-01 | 7000 | 679 | | Earphones | Roja | 2019-05-01 | 2000 | 802 | | Mouse | Puja | 2019-03-01 | 3000 | 863 | | Mobile | Vanaja | 2019-03-01 | 9000 | 863 | | Headset | Jalaja | 2019-04-06 | 6000 | 827 | +-------------+--------------+--------------+-------+--------------------+ 5 rows in set (0.00 sec) Suppose we have created a table named Subscribers with 5 records in it using the following queries – mysql> CREATE TABLE Subscribers( SubscriberName VARCHAR(255), PackageName VARCHAR(255), SubscriptionDate date ); insert into Subscribers values('Raja', 'Premium', Date('2020-10-21')); insert into Subscribers values('Roja', 'Basic', Date('2020-11-26')); insert into Subscribers values('Puja', 'Moderate', Date('2021-03-07')); insert into Subscribers values('Vanaja', 'Basic', Date('2021-02-21')); insert into Subscribers values('Jalaja', 'Premium', Date('2021-01-30')); Following query calculates and displays the remaining number of days for the subscription to complete — mysql> SELECT SubscriberName, PackageName, SubscriptionDate, DATEDIFF(CURDATE(), SubscriptionDate) as Remaining_Days FROM Subscribers; +----------------+-------------+------------------+----------------+ | SubscriberName | PackageName | SubscriptionDate | Remaining_Days | +----------------+-------------+------------------+----------------+ | Raja | Premium | 2020-10-21 | 263 | | Roja | Basic | 2020-11-26 | 227 | | Puja | Moderate | 2021-03-07 | 126 | | Vanaja | Basic | 2021-02-21 | 140 | | Jalaja | Premium | 2021-01-30 | 162 | +----------------+-------------+------------------+----------------+ 5 rows in set (0.11 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2664, "s": 2333, "text": "The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values." }, { "code": null, "e": 2867, "s": 2664, "text": "The MYSQL CURDATE() is used to get the current days date. The resultant value is a string or a numerical value based on the context and, the date returned will be in the 'YYYY-MM-DD' or YYYYMMDD format." }, { "code": null, "e": 2915, "s": 2867, "text": "Following is the syntax of the above function –" }, { "code": null, "e": 2927, "s": 2915, "text": "CURDATE();\n" }, { "code": null, "e": 2996, "s": 2927, "text": "Following example demonstrates the usage of the CURDATE() function –" }, { "code": null, "e": 3120, "s": 2996, "text": "mysql> SELECT CURDATE();\n+------------+\n| CURDATE() |\n+------------+\n| 2021-07-11 |\n+------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3184, "s": 3120, "text": "Following is an example of this function in numerical context –" }, { "code": null, "e": 3321, "s": 3184, "text": "mysql> SELECT CURDATE() +0;\n+--------------+\n| CURDATE() +0 |\n+--------------+\n| 20210711 |\n+--------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3375, "s": 3321, "text": "You can add days to the current date as shown below –" }, { "code": null, "e": 3512, "s": 3375, "text": "mysql> SELECT CURDATE()+12;\n+--------------+\n| CURDATE()+12 |\n+--------------+\n| 20210723 |\n+--------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3604, "s": 3512, "text": "We can also subtract the desired number of days from the current date using this function –" }, { "code": null, "e": 3759, "s": 3604, "text": "mysql> SELECT CURDATE()-22213;\n+-----------------+\n| CURDATE()-22213 |\n+-----------------+\n| 20188498 |\n+-----------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3859, "s": 3759, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below –" }, { "code": null, "e": 4045, "s": 3859, "text": "mysql> CREATE TABLE MyPlayers(\n\tID INT,\n\tFirst_Name VARCHAR(255),\n\tLast_Name VARCHAR(255),\n\tDate_Of_Birth date,\n\tPlace_Of_Birth VARCHAR(255),\n\tCountry VARCHAR(255),\n\tPRIMARY KEY (ID)\n);" }, { "code": null, "e": 4120, "s": 4045, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 4831, "s": 4120, "text": "mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\nmysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\nmysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\nmysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\nmysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 4891, "s": 4831, "text": "Following query calculates the age of the players in days —" }, { "code": null, "e": 5834, "s": 4891, "text": "mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, DATEDIFF(CURDATE(),Date_Of_Birth) as Age_In_Days FROM MyPlayers;\n+------------+------------+---------------+-------------+-------------+\n| First_Name | Last_Name | Date_Of_Birth | Country | Age_In_Days |\n+------------+------------+---------------+-------------+-------------+\n| Shikhar | Dhawan | 1981-12-05 | India | 14463 |\n| Jonathan | Trott | 1981-04-22 | SouthAfrica | 14690 |\n| Kumara | Sangakkara | 1977-10-27 | Srilanka | 15963 |\n| Virat | Kohli | 1988-11-05 | India | 11936 |\n| Rohit | Sharma | 1987-04-30 | India | 12491 |\n| Ravindra | Jadeja | 1988-12-06 | India | 11905 |\n| James | Anderson | 1982-06-30 | England | 14256 |\n+------------+------------+---------------+-------------+-------------+\n7 rows in set (0.11 sec)" }, { "code": null, "e": 5930, "s": 5834, "text": "Let us create another table with name Sales in MySQL database using CREATE statement as follows" }, { "code": null, "e": 6136, "s": 5930, "text": "mysql> CREATE TABLE sales(\n\tID INT,\n\tProductName VARCHAR(255),\n\tCustomerName VARCHAR(255),\n\tDispatchDate date,\n\tDispatchTime time,\n\tPrice INT,\n\tLocation VARCHAR(255)\n);\nQuery OK, 0 rows affected (2.22 sec)" }, { "code": null, "e": 6207, "s": 6136, "text": "Now, we will insert 5 records in Sales table using INSERT statements −" }, { "code": null, "e": 6740, "s": 6207, "text": "insert into sales values (1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into sales values (2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into sales values (3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into sales values (4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into sales values (5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 6788, "s": 6740, "text": "Following is another example of this function —" }, { "code": null, "e": 7618, "s": 6788, "text": "mysql> SELECT ProductName, CustomerName, DispatchDate, Price, DATEDIFF(CURDATE(), DispatchDate) as difference_in_days FROM sales;\n+-------------+--------------+--------------+-------+--------------------+\n| ProductName | CustomerName | DispatchDate | Price | difference_in_days |\n+-------------+--------------+--------------+-------+--------------------+\n| Key-Board | Raja | 2019-09-01 | 7000 | 679 |\n| Earphones | Roja | 2019-05-01 | 2000 | 802 |\n| Mouse | Puja | 2019-03-01 | 3000 | 863 |\n| Mobile | Vanaja | 2019-03-01 | 9000 | 863 |\n| Headset | Jalaja | 2019-04-06 | 6000 | 827 |\n+-------------+--------------+--------------+-------+--------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 7719, "s": 7618, "text": "Suppose we have created a table named Subscribers with 5 records in it using the following queries –" }, { "code": null, "e": 8191, "s": 7719, "text": "mysql> CREATE TABLE Subscribers(\n\tSubscriberName VARCHAR(255),\n\tPackageName VARCHAR(255),\n\tSubscriptionDate date\n);\ninsert into Subscribers values('Raja', 'Premium', Date('2020-10-21'));\ninsert into Subscribers values('Roja', 'Basic', Date('2020-11-26'));\ninsert into Subscribers values('Puja', 'Moderate', Date('2021-03-07'));\ninsert into Subscribers values('Vanaja', 'Basic', Date('2021-02-21'));\ninsert into Subscribers values('Jalaja', 'Premium', Date('2021-01-30'));" }, { "code": null, "e": 8295, "s": 8191, "text": "Following query calculates and displays the remaining number of days for the subscription to complete —" }, { "code": null, "e": 9076, "s": 8295, "text": "mysql> SELECT SubscriberName, PackageName, SubscriptionDate, DATEDIFF(CURDATE(), SubscriptionDate) as Remaining_Days FROM Subscribers;\n+----------------+-------------+------------------+----------------+\n| SubscriberName | PackageName | SubscriptionDate | Remaining_Days |\n+----------------+-------------+------------------+----------------+\n| Raja | Premium | 2020-10-21 | 263 |\n| Roja | Basic | 2020-11-26 | 227 |\n| Puja | Moderate | 2021-03-07 | 126 |\n| Vanaja | Basic | 2021-02-21 | 140 |\n| Jalaja | Premium | 2021-01-30 | 162 |\n+----------------+-------------+------------------+----------------+\n5 rows in set (0.11 sec)" }, { "code": null, "e": 9109, "s": 9076, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 9137, "s": 9109, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9172, "s": 9137, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9189, "s": 9172, "text": " Frahaan Hussain" }, { "code": null, "e": 9223, "s": 9189, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9258, "s": 9223, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 9292, "s": 9258, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 9320, "s": 9292, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 9353, "s": 9320, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 9373, "s": 9353, "text": " Harshit Srivastava" }, { "code": null, "e": 9406, "s": 9373, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 9424, "s": 9406, "text": " Trevoir Williams" }, { "code": null, "e": 9431, "s": 9424, "text": " Print" }, { "code": null, "e": 9442, "s": 9431, "text": " Add Notes" } ]
VueJS - Mixins
Mixins are basically to be used with components. They share reusable code among components. When a component uses mixin, all options of mixin become a part of the component options. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"></div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { }, methods : { }, }); var myMixin = { created: function () { this.startmixin() }, methods: { startmixin: function () { alert("Welcome to mixin example"); } } }; var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component(); </script> </body> </html> When a mixin and a component contain overlapping options, they are merged as shown in the following example. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"></div> <script type = "text/javascript"> var mixin = { created: function () { console.log('mixin called') } } new Vue({ mixins: [mixin], created: function () { console.log('component called') } }); </script> </body> </html> Now the mixin and the vue instance has the same method created. This is the output we see in the console. As seen, the option of the vue and the mixin will be merged. If we happen to have the same function name in methods, then the main vue instance will take priority. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"></div> <script type = "text/javascript"> var mixin = { methods: { hellworld: function () { console.log('In HelloWorld'); }, samemethod: function () { console.log('Mixin:Same Method'); } } }; var vm = new Vue({ mixins: [mixin], methods: { start: function () { console.log('start method'); }, samemethod: function () { console.log('Main: same method'); } } }); vm.hellworld(); vm.start(); vm.samemethod(); </script> </body> </html> We will see mixin has a method property in which helloworld and samemethod functions are defined. Similarly, vue instance has a methods property in which again two methods are defined start and samemethod. Each of the following methods are called. vm.hellworld(); // In HelloWorld vm.start(); // start method vm.samemethod(); // Main: same method As seen above, we have called helloworld, start, and samemethod function. samemethod is also present in mixin, however, priority will be given to the main instance, as seen in the following console. Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 1936, "text": "Mixins are basically to be used with components. They share reusable code among components. When a component uses mixin, all options of mixin become a part of the component options." }, { "code": null, "e": 2909, "s": 2118, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\"></div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n },\n methods : {\n },\n });\n var myMixin = {\n created: function () {\n this.startmixin()\n },\n methods: {\n startmixin: function () {\n alert(\"Welcome to mixin example\");\n }\n }\n };\n var Component = Vue.extend({\n mixins: [myMixin]\n })\n var component = new Component();\n </script>\n </body>\n</html>" }, { "code": null, "e": 3018, "s": 2909, "text": "When a mixin and a component contain overlapping options, they are merged as shown in the following example." }, { "code": null, "e": 3554, "s": 3018, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\"></div>\n <script type = \"text/javascript\">\n var mixin = {\n created: function () {\n console.log('mixin called')\n }\n }\n new Vue({\n mixins: [mixin],\n created: function () {\n console.log('component called')\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 3721, "s": 3554, "text": "Now the mixin and the vue instance has the same method created. This is the output we see in the console. As seen, the option of the vue and the mixin will be merged." }, { "code": null, "e": 3824, "s": 3721, "text": "If we happen to have the same function name in methods, then the main vue instance will take priority." }, { "code": null, "e": 4755, "s": 3824, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\"></div>\n <script type = \"text/javascript\">\n var mixin = {\n methods: {\n hellworld: function () {\n console.log('In HelloWorld');\n },\n samemethod: function () {\n console.log('Mixin:Same Method');\n }\n }\n };\n var vm = new Vue({\n mixins: [mixin],\n methods: {\n start: function () {\n console.log('start method');\n },\n samemethod: function () {\n console.log('Main: same method');\n }\n }\n });\n vm.hellworld();\n vm.start();\n vm.samemethod();\n </script>\n </body>\n</html>" }, { "code": null, "e": 4961, "s": 4755, "text": "We will see mixin has a method property in which helloworld and samemethod functions are defined. Similarly, vue instance has a methods property in which again two methods are defined start and samemethod." }, { "code": null, "e": 5003, "s": 4961, "text": "Each of the following methods are called." }, { "code": null, "e": 5102, "s": 5003, "text": "vm.hellworld(); // In HelloWorld\nvm.start(); // start method\nvm.samemethod(); // Main: same method" }, { "code": null, "e": 5301, "s": 5102, "text": "As seen above, we have called helloworld, start, and samemethod function. samemethod is also present in mixin, however, priority will be given to the main instance, as seen in the following console." }, { "code": null, "e": 5308, "s": 5301, "text": " Print" }, { "code": null, "e": 5319, "s": 5308, "text": " Add Notes" } ]
DCGANs (Deep Convolutional Generative Adversarial Networks) | by Connor Shorten | Towards Data Science
One of the most interesting parts of Generative Adversarial Networks is the design of the Generator network. The Generator network is able to take random noise and map it into images such that the discriminator cannot tell which images came from the dataset and which images came from the generator. This is a very interesting application of neural networks. Typically neural nets map input into a binary output, (1 or 0), maybe a regression output, (some real-valued number), or even multiple categorical outputs, (such as MNIST or CIFAR-10/100). In this article, we will see how a neural net maps from random noise to an image matrix and how using Convolutional Layers in the generator network produces better results. We will review the paper presenting DCGANs at ICLR, a generator network architecture that generated bedrooms, and we will review some Python/Keras code from the GANs-in-Action repository. This is the DCGAN generator presented in the LSUN scene modeling paper. This network takes in a 100x1 noise vector, denoted z, and maps it into the G(Z) output which is 64x64x3. This architecture is especially interesting the way the first layer expands the random noise. The network goes from 100x1 to 1024x4x4! This layer is denoted ‘project and reshape’. We see that following this layer, classical convolutional layers are applied which reshape the network with the (N+P — F)/S + 1 equation classically taught with convolutional layers. In the diagram above we can see that the N parameter, (Height/Width), goes from 4 to 8 to 16 to 32, it doesn’t appear that there is any padding, the kernel filter parameter F is 5x5, and the stride is 2. You may find this equation to be useful for designing your own convolutional layers for customized output sizes. We see the network goes from 100x1 → 1024x4x4 → 512x8x8 → 256x16x16 → 128x32x32 → 64x64x3 Above is the output from the network presented in the paper, citing that this came after 5 epochs of training. Pretty impressive stuff. Now, let’s look at some python code: This code is taken from the gans-in-action repository created by Jakub Langr and Vladimir Bok, from what I have found this is the best starter code for implementing GANs in Keras. I don’t think this book has been released yet, but I imagine it will be very good. github.com The code below is how I got my first GAN network running, (does not implement DCGANs): def generator(img_shape, z_dim): model = Sequential() # Hidden layer model.add(Dense(128, input_dim = z_dim)) # Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Output layer with tanh activation model.add(Dense(28*28*1, activation='tanh')) model.add(Reshape(img_shape) z = Input(shape=(z_dim,)) img = model(z) return Model(z, img) The architecture below isn’t too complicated and actually does produce pretty decent results on the MNIST dataset example. This model takes in the noise vector and maps it to a densely connected layer which maps to an output layer which is a flat 784x1 vector which is reshaped into the 28x28 MNIST digit matrix. Now let’s contrast this with the DCGAN code provided in the gans-in-action repository: def generator(img_shape, z_dim): model = Sequential() # Reshape input into 7x7x256 tensor via a fully connected layer model.add(Dense(256*7*7, input_dim = z_dim)) model.add(Reshape((7,7,256)) # Transposed convolution layer, from 7x7x256 into 14x14x128 tensor model.add(Conv2DTranspose( 128, kernel_size = 3, strides = 2, padding='same')) #Batch normalization model.add(BatchNormalization()) #Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Transposed convolution layer, from 14x14x128 to 14x14x64 tensor model.add(Conv2DTranspose( 64, kernel_size=3, strides=1, padding='same')) # Batch normalization model.add(BatchNormalization()) # Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Transposed convolution layer, from 14x14x64 to 28x28x1 tensor model.add(Conv2DTranspose( 1, kernel_size = 3, strides = 2, padding='same')) # Tanh activation model.add(Activation('tanh')) z = Input(shape=(z_dim,)) img = model(z) return Model(z, img) We see the architecture above is very similar to the DCGAN presented in the ICLR, LSUN scene generator paper. The input is projected from 100x1 noise into a 7x7x256 tensor, which is then convolved over until you reach the 28x28x1 MNIST digit output. Again, we see this same project and reshape, followed by convolutional layers into the output from the diagram in the starter code. I hope this article helped you get started building your own DCGANs. I think it at least provides a good explanation of how the high-level architecture should work. The remaining challenge lies in finding the right parameters for the convolutional layers, as well as the project and reshape layer. I really found the combination of this open source code repository and the ICLR paper to help me understand this concept. I am very excited about building GANs and seeing what they can do, please leave a comment with any additional resources that you think are really helpful. Please follow if you would like to stay notified on further research using these DCGANs for Data Augmentation. Connor Shorten is a Computer Science student at Florida Atlantic University. Research interests in computer vision, deep learning, and software engineering.
[ { "code": null, "e": 472, "s": 172, "text": "One of the most interesting parts of Generative Adversarial Networks is the design of the Generator network. The Generator network is able to take random noise and map it into images such that the discriminator cannot tell which images came from the dataset and which images came from the generator." }, { "code": null, "e": 720, "s": 472, "text": "This is a very interesting application of neural networks. Typically neural nets map input into a binary output, (1 or 0), maybe a regression output, (some real-valued number), or even multiple categorical outputs, (such as MNIST or CIFAR-10/100)." }, { "code": null, "e": 893, "s": 720, "text": "In this article, we will see how a neural net maps from random noise to an image matrix and how using Convolutional Layers in the generator network produces better results." }, { "code": null, "e": 1081, "s": 893, "text": "We will review the paper presenting DCGANs at ICLR, a generator network architecture that generated bedrooms, and we will review some Python/Keras code from the GANs-in-Action repository." }, { "code": null, "e": 1259, "s": 1081, "text": "This is the DCGAN generator presented in the LSUN scene modeling paper. This network takes in a 100x1 noise vector, denoted z, and maps it into the G(Z) output which is 64x64x3." }, { "code": null, "e": 1439, "s": 1259, "text": "This architecture is especially interesting the way the first layer expands the random noise. The network goes from 100x1 to 1024x4x4! This layer is denoted ‘project and reshape’." }, { "code": null, "e": 1939, "s": 1439, "text": "We see that following this layer, classical convolutional layers are applied which reshape the network with the (N+P — F)/S + 1 equation classically taught with convolutional layers. In the diagram above we can see that the N parameter, (Height/Width), goes from 4 to 8 to 16 to 32, it doesn’t appear that there is any padding, the kernel filter parameter F is 5x5, and the stride is 2. You may find this equation to be useful for designing your own convolutional layers for customized output sizes." }, { "code": null, "e": 1968, "s": 1939, "text": "We see the network goes from" }, { "code": null, "e": 2029, "s": 1968, "text": "100x1 → 1024x4x4 → 512x8x8 → 256x16x16 → 128x32x32 → 64x64x3" }, { "code": null, "e": 2165, "s": 2029, "text": "Above is the output from the network presented in the paper, citing that this came after 5 epochs of training. Pretty impressive stuff." }, { "code": null, "e": 2202, "s": 2165, "text": "Now, let’s look at some python code:" }, { "code": null, "e": 2465, "s": 2202, "text": "This code is taken from the gans-in-action repository created by Jakub Langr and Vladimir Bok, from what I have found this is the best starter code for implementing GANs in Keras. I don’t think this book has been released yet, but I imagine it will be very good." }, { "code": null, "e": 2476, "s": 2465, "text": "github.com" }, { "code": null, "e": 2563, "s": 2476, "text": "The code below is how I got my first GAN network running, (does not implement DCGANs):" }, { "code": null, "e": 2902, "s": 2563, "text": "def generator(img_shape, z_dim): model = Sequential() # Hidden layer model.add(Dense(128, input_dim = z_dim)) # Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Output layer with tanh activation model.add(Dense(28*28*1, activation='tanh')) model.add(Reshape(img_shape) z = Input(shape=(z_dim,)) img = model(z) return Model(z, img)" }, { "code": null, "e": 3215, "s": 2902, "text": "The architecture below isn’t too complicated and actually does produce pretty decent results on the MNIST dataset example. This model takes in the noise vector and maps it to a densely connected layer which maps to an output layer which is a flat 784x1 vector which is reshaped into the 28x28 MNIST digit matrix." }, { "code": null, "e": 3302, "s": 3215, "text": "Now let’s contrast this with the DCGAN code provided in the gans-in-action repository:" }, { "code": null, "e": 4294, "s": 3302, "text": "def generator(img_shape, z_dim): model = Sequential() # Reshape input into 7x7x256 tensor via a fully connected layer model.add(Dense(256*7*7, input_dim = z_dim)) model.add(Reshape((7,7,256)) # Transposed convolution layer, from 7x7x256 into 14x14x128 tensor model.add(Conv2DTranspose( 128, kernel_size = 3, strides = 2, padding='same')) #Batch normalization model.add(BatchNormalization()) #Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Transposed convolution layer, from 14x14x128 to 14x14x64 tensor model.add(Conv2DTranspose( 64, kernel_size=3, strides=1, padding='same')) # Batch normalization model.add(BatchNormalization()) # Leaky ReLU model.add(LeakyReLU(alpha=0.01)) # Transposed convolution layer, from 14x14x64 to 28x28x1 tensor model.add(Conv2DTranspose( 1, kernel_size = 3, strides = 2, padding='same')) # Tanh activation model.add(Activation('tanh')) z = Input(shape=(z_dim,)) img = model(z) return Model(z, img)" }, { "code": null, "e": 4544, "s": 4294, "text": "We see the architecture above is very similar to the DCGAN presented in the ICLR, LSUN scene generator paper. The input is projected from 100x1 noise into a 7x7x256 tensor, which is then convolved over until you reach the 28x28x1 MNIST digit output." }, { "code": null, "e": 4676, "s": 4544, "text": "Again, we see this same project and reshape, followed by convolutional layers into the output from the diagram in the starter code." }, { "code": null, "e": 4974, "s": 4676, "text": "I hope this article helped you get started building your own DCGANs. I think it at least provides a good explanation of how the high-level architecture should work. The remaining challenge lies in finding the right parameters for the convolutional layers, as well as the project and reshape layer." }, { "code": null, "e": 5362, "s": 4974, "text": "I really found the combination of this open source code repository and the ICLR paper to help me understand this concept. I am very excited about building GANs and seeing what they can do, please leave a comment with any additional resources that you think are really helpful. Please follow if you would like to stay notified on further research using these DCGANs for Data Augmentation." } ]
Handshakes That Don't Cross in C++
Suppose we have an even number of people n that stand around a circle and each person shakes hands with someone else, so that there will be n / 2 handshakes total. We have to find the number of ways these handshakes could occur such that none of the handshakes cross. The answers may be very large so return the answer mod 10^9 + 7. So, if the input is like n = 2, then the output will be 1 To solve this, we will follow these steps − m := 10^9 + 7 m := 10^9 + 7 Define an array dp of size (n+1) Define an array dp of size (n+1) dp[0] := 1 dp[0] := 1 for initialize i := 0, when i <= n, update i := i + 2, do −for initialize j := 0, when j <= i-2, update j := j + 2, do −dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)dp[i] := dp[i] mod m for initialize i := 0, when i <= n, update i := i + 2, do − for initialize j := 0, when j <= i-2, update j := j + 2, do −dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)dp[i] := dp[i] mod m for initialize j := 0, when j <= i-2, update j := j + 2, do − dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m) dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m) dp[i] := dp[i] mod m dp[i] := dp[i] mod m return dp[n] mod m return dp[n] mod m Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; const int m = 1e9+7; typedef long long int lli; class Solution { public: int numberOfWays(int n) { vector <lli> dp(n+1); dp[0] = 1; for(int i = 0; i <= n; i+=2 ){ for(int j =0 ; j <= i-2; j+=2){ dp[i] += (dp[j]%m * dp[i-2-j]%m)%m; dp[i]%=m; } } return dp[n]%m; } }; main(){ Solution ob; cout << (ob.numberOfWays(2)); } 2 1
[ { "code": null, "e": 1395, "s": 1062, "text": "Suppose we have an even number of people n that stand around a circle and each person shakes hands with someone else, so that there will be n / 2 handshakes total. We have to find the number of ways these handshakes could occur such that none of the handshakes cross. The answers may be very large so return the answer mod 10^9 + 7." }, { "code": null, "e": 1453, "s": 1395, "text": "So, if the input is like n = 2, then the output will be 1" }, { "code": null, "e": 1497, "s": 1453, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1511, "s": 1497, "text": "m := 10^9 + 7" }, { "code": null, "e": 1525, "s": 1511, "text": "m := 10^9 + 7" }, { "code": null, "e": 1558, "s": 1525, "text": "Define an array dp of size (n+1)" }, { "code": null, "e": 1591, "s": 1558, "text": "Define an array dp of size (n+1)" }, { "code": null, "e": 1602, "s": 1591, "text": "dp[0] := 1" }, { "code": null, "e": 1613, "s": 1602, "text": "dp[0] := 1" }, { "code": null, "e": 1806, "s": 1613, "text": "for initialize i := 0, when i <= n, update i := i + 2, do −for initialize j := 0, when j <= i-2, update j := j + 2, do −dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)dp[i] := dp[i] mod m" }, { "code": null, "e": 1866, "s": 1806, "text": "for initialize i := 0, when i <= n, update i := i + 2, do −" }, { "code": null, "e": 2000, "s": 1866, "text": "for initialize j := 0, when j <= i-2, update j := j + 2, do −dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)dp[i] := dp[i] mod m" }, { "code": null, "e": 2062, "s": 2000, "text": "for initialize j := 0, when j <= i-2, update j := j + 2, do −" }, { "code": null, "e": 2115, "s": 2062, "text": "dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)" }, { "code": null, "e": 2168, "s": 2115, "text": "dp[i] := dp[i] + (dp[j] mod m * dp[i - 2 - j] mod m)" }, { "code": null, "e": 2189, "s": 2168, "text": "dp[i] := dp[i] mod m" }, { "code": null, "e": 2210, "s": 2189, "text": "dp[i] := dp[i] mod m" }, { "code": null, "e": 2229, "s": 2210, "text": "return dp[n] mod m" }, { "code": null, "e": 2248, "s": 2229, "text": "return dp[n] mod m" }, { "code": null, "e": 2318, "s": 2248, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2329, "s": 2318, "text": " Live Demo" }, { "code": null, "e": 2781, "s": 2329, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int m = 1e9+7;\ntypedef long long int lli;\nclass Solution {\n public:\n int numberOfWays(int n) {\n vector <lli> dp(n+1);\n dp[0] = 1;\n for(int i = 0; i <= n; i+=2 ){\n for(int j =0 ; j <= i-2; j+=2){\n dp[i] += (dp[j]%m * dp[i-2-j]%m)%m;\n dp[i]%=m;\n }\n }\n return dp[n]%m;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.numberOfWays(2));\n}" }, { "code": null, "e": 2783, "s": 2781, "text": "2" }, { "code": null, "e": 2785, "s": 2783, "text": "1" } ]
Longest Decreasing Subsequence - GeeksforGeeks
11 May, 2021 Given an array of N integers, find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly decreasing order. Examples: Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85] Output: 3 Explanation: The longest decreasing subsequence is {63, 55, 46} Input: arr[] = {50, 3, 10, 7, 40, 80} Output: 3 Explanation: The longest decreasing subsequence is {50, 10, 7} The problem can be solved using Dynamic ProgrammingOptimal Substructure: Let arr[0...n-1] be the input array and lds[i] be the length of the LDS ending at index i such that arr[i] is the last element of the LDS. Then, lds[i] can be recursively written as: lds[i] = 1 + max(lds[j]) where i > j > 0 and arr[j] > arr[i] or lds[i] = 1, if no such j exists. To find the LDS for a given array, we need to return max(lds[i]) where n > i > 0. C++ Java Python 3 C# PHP Javascript // CPP program to find the length of the// longest decreasing subsequence#include <bits/stdc++.h>using namespace std; // Function that returns the length// of the longest decreasing subsequenceint lds(int arr[], int n){ int lds[n]; int i, j, max = 0; // Initialize LDS with 1 for all index // The minimum LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every index // in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length of the LDS return max;}// Driver Codeint main(){ int arr[] = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length of LDS is " << lds(arr, n); return 0;} // Java program to find the// length of the longest// decreasing subsequenceimport java.io.*; class GFG{ // Function that returns the// length of the longest// decreasing subsequencestatic int lds(int arr[], int n){ int lds[] = new int[n]; int i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max;}// Driver Codepublic static void main (String[] args){ int arr[] = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = arr.length; System.out.print("Length of LDS is " + lds(arr, n));}} // This code is contributed by anuj_67. # Python 3 program to find the length of# the longest decreasing subsequence # Function that returns the length# of the longest decreasing subsequencedef lds(arr, n): lds = [0] * n max = 0 # Initialize LDS with 1 for all index # The minimum LDS starting with any # element is always 1 for i in range(n): lds[i] = 1 # Compute LDS from every index # in bottom up manner for i in range(1, n): for j in range(i): if (arr[i] < arr[j] and lds[i] < lds[j] + 1): lds[i] = lds[j] + 1 # Select the maximum # of all the LDS values for i in range(n): if (max < lds[i]): max = lds[i] # returns the length of the LDS return max # Driver Codeif __name__ == "__main__": arr = [ 15, 27, 14, 38, 63, 55, 46, 65, 85 ] n = len(arr) print("Length of LDS is", lds(arr, n)) # This code is contributed by ita_c // C# program to find the// length of the longest// decreasing subsequenceusing System; class GFG{ // Function that returns the// length of the longest// decreasing subsequencestatic int lds(int []arr, int n){ int []lds = new int[n]; int i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max;}// Driver Codepublic static void Main (){ int []arr = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = arr.Length; Console.Write("Length of LDS is " + lds(arr, n));}} // This code is contributed by anuj_67. <?php// PHP program to find the// length of the longest// decreasing subsequence // Function that returns the// length of the longest// decreasing subsequencefunction lds($arr, $n){ $lds = array(); $i; $j; $max = 0; // Initialize LDS with 1 // for all index The minimum // LDS starting with any // element is always 1 for ($i = 0; $i < $n; $i++) $lds[$i] = 1; // Compute LDS from every // index in bottom up manner for ($i = 1; $i < $n; $i++) for ($j = 0; $j < $i; $j++) if ($arr[$i] < $arr[$j] and $lds[$i] < $lds[$j] + 1) { $lds[$i] = $lds[$j] + 1; } // Select the maximum // of all the LDS values for ($i = 0; $i < $n; $i++) if ($max < $lds[$i]) $max = $lds[$i]; // returns the length // of the LDS return $max;} // Driver Code$arr = array(15, 27, 14, 38, 63, 55, 46, 65, 85);$n = count($arr);echo "Length of LDS is " , lds($arr, $n); // This code is contributed by anuj_67.?> <script>// Javascript program to find the// length of the longest// decreasing subsequence // Function that returns the// length of the longest// decreasing subsequence function lds(arr,n) { let lds = new Array(n); let i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max; } // Driver Code let arr=[15, 27, 14, 38, 63, 55, 46, 65, 85 ]; let n = arr.length; document.write("Length of LDS is " + lds(arr, n)); // This code is contributed by rag2127</script> Length of LDS is 3 Time Complexity: O(n2) Auxiliary Space: O(n)Related Article: https://www.geeksforgeeks.org/longest-increasing-subsequence/ vt_m ukasp rag2127 Algorithms-Dynamic Programming Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Edit Distance | DP-5
[ { "code": null, "e": 24991, "s": 24963, "text": "\n11 May, 2021" }, { "code": null, "e": 25168, "s": 24991, "text": "Given an array of N integers, find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in strictly decreasing order. " }, { "code": null, "e": 25180, "s": 25168, "text": "Examples: " }, { "code": null, "e": 25418, "s": 25180, "text": "Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85] Output: 3 Explanation: The longest decreasing subsequence is {63, 55, 46} Input: arr[] = {50, 3, 10, 7, 40, 80} Output: 3 Explanation: The longest decreasing subsequence is {50, 10, 7} " }, { "code": null, "e": 25675, "s": 25418, "text": "The problem can be solved using Dynamic ProgrammingOptimal Substructure: Let arr[0...n-1] be the input array and lds[i] be the length of the LDS ending at index i such that arr[i] is the last element of the LDS. Then, lds[i] can be recursively written as: " }, { "code": null, "e": 25772, "s": 25675, "text": "lds[i] = 1 + max(lds[j]) where i > j > 0 and arr[j] > arr[i] or lds[i] = 1, if no such j exists." }, { "code": null, "e": 25856, "s": 25772, "text": "To find the LDS for a given array, we need to return max(lds[i]) where n > i > 0. " }, { "code": null, "e": 25860, "s": 25856, "text": "C++" }, { "code": null, "e": 25865, "s": 25860, "text": "Java" }, { "code": null, "e": 25874, "s": 25865, "text": "Python 3" }, { "code": null, "e": 25877, "s": 25874, "text": "C#" }, { "code": null, "e": 25881, "s": 25877, "text": "PHP" }, { "code": null, "e": 25892, "s": 25881, "text": "Javascript" }, { "code": "// CPP program to find the length of the// longest decreasing subsequence#include <bits/stdc++.h>using namespace std; // Function that returns the length// of the longest decreasing subsequenceint lds(int arr[], int n){ int lds[n]; int i, j, max = 0; // Initialize LDS with 1 for all index // The minimum LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every index // in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length of the LDS return max;}// Driver Codeint main(){ int arr[] = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Length of LDS is \" << lds(arr, n); return 0;}", "e": 26881, "s": 25892, "text": null }, { "code": "// Java program to find the// length of the longest// decreasing subsequenceimport java.io.*; class GFG{ // Function that returns the// length of the longest// decreasing subsequencestatic int lds(int arr[], int n){ int lds[] = new int[n]; int i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max;}// Driver Codepublic static void main (String[] args){ int arr[] = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = arr.length; System.out.print(\"Length of LDS is \" + lds(arr, n));}} // This code is contributed by anuj_67.", "e": 28008, "s": 26881, "text": null }, { "code": "# Python 3 program to find the length of# the longest decreasing subsequence # Function that returns the length# of the longest decreasing subsequencedef lds(arr, n): lds = [0] * n max = 0 # Initialize LDS with 1 for all index # The minimum LDS starting with any # element is always 1 for i in range(n): lds[i] = 1 # Compute LDS from every index # in bottom up manner for i in range(1, n): for j in range(i): if (arr[i] < arr[j] and lds[i] < lds[j] + 1): lds[i] = lds[j] + 1 # Select the maximum # of all the LDS values for i in range(n): if (max < lds[i]): max = lds[i] # returns the length of the LDS return max # Driver Codeif __name__ == \"__main__\": arr = [ 15, 27, 14, 38, 63, 55, 46, 65, 85 ] n = len(arr) print(\"Length of LDS is\", lds(arr, n)) # This code is contributed by ita_c", "e": 28940, "s": 28008, "text": null }, { "code": "// C# program to find the// length of the longest// decreasing subsequenceusing System; class GFG{ // Function that returns the// length of the longest// decreasing subsequencestatic int lds(int []arr, int n){ int []lds = new int[n]; int i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max;}// Driver Codepublic static void Main (){ int []arr = { 15, 27, 14, 38, 63, 55, 46, 65, 85 }; int n = arr.Length; Console.Write(\"Length of LDS is \" + lds(arr, n));}} // This code is contributed by anuj_67.", "e": 30039, "s": 28940, "text": null }, { "code": "<?php// PHP program to find the// length of the longest// decreasing subsequence // Function that returns the// length of the longest// decreasing subsequencefunction lds($arr, $n){ $lds = array(); $i; $j; $max = 0; // Initialize LDS with 1 // for all index The minimum // LDS starting with any // element is always 1 for ($i = 0; $i < $n; $i++) $lds[$i] = 1; // Compute LDS from every // index in bottom up manner for ($i = 1; $i < $n; $i++) for ($j = 0; $j < $i; $j++) if ($arr[$i] < $arr[$j] and $lds[$i] < $lds[$j] + 1) { $lds[$i] = $lds[$j] + 1; } // Select the maximum // of all the LDS values for ($i = 0; $i < $n; $i++) if ($max < $lds[$i]) $max = $lds[$i]; // returns the length // of the LDS return $max;} // Driver Code$arr = array(15, 27, 14, 38, 63, 55, 46, 65, 85);$n = count($arr);echo \"Length of LDS is \" , lds($arr, $n); // This code is contributed by anuj_67.?>", "e": 31102, "s": 30039, "text": null }, { "code": "<script>// Javascript program to find the// length of the longest// decreasing subsequence // Function that returns the// length of the longest// decreasing subsequence function lds(arr,n) { let lds = new Array(n); let i, j, max = 0; // Initialize LDS with 1 // for all index. The minimum // LDS starting with any // element is always 1 for (i = 0; i < n; i++) lds[i] = 1; // Compute LDS from every // index in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] < arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1; // Select the maximum // of all the LDS values for (i = 0; i < n; i++) if (max < lds[i]) max = lds[i]; // returns the length // of the LDS return max; } // Driver Code let arr=[15, 27, 14, 38, 63, 55, 46, 65, 85 ]; let n = arr.length; document.write(\"Length of LDS is \" + lds(arr, n)); // This code is contributed by rag2127</script>", "e": 32220, "s": 31102, "text": null }, { "code": null, "e": 32239, "s": 32220, "text": "Length of LDS is 3" }, { "code": null, "e": 32365, "s": 32241, "text": "Time Complexity: O(n2) Auxiliary Space: O(n)Related Article: https://www.geeksforgeeks.org/longest-increasing-subsequence/ " }, { "code": null, "e": 32370, "s": 32365, "text": "vt_m" }, { "code": null, "e": 32376, "s": 32370, "text": "ukasp" }, { "code": null, "e": 32384, "s": 32376, "text": "rag2127" }, { "code": null, "e": 32415, "s": 32384, "text": "Algorithms-Dynamic Programming" }, { "code": null, "e": 32435, "s": 32415, "text": "Dynamic Programming" }, { "code": null, "e": 32455, "s": 32435, "text": "Dynamic Programming" }, { "code": null, "e": 32553, "s": 32455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32562, "s": 32553, "text": "Comments" }, { "code": null, "e": 32575, "s": 32562, "text": "Old Comments" }, { "code": null, "e": 32606, "s": 32575, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32639, "s": 32606, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32666, "s": 32639, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 32685, "s": 32666, "text": "Coin Change | DP-7" }, { "code": null, "e": 32720, "s": 32685, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 32758, "s": 32720, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32826, "s": 32758, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 32848, "s": 32826, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32911, "s": 32848, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
Practice Questions for Recursion | Set 1
21 Jun, 2022 Explain the functionality of the following functions. Question 1 C++ C Java Python3 C# Javascript int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);} int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);} static int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);} def fun1(x, y) : if (x == 0) : return y else : return fun1(x - 1, x + y) # This code is contributed by divyesh072019 static int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);} // This code is contributed by divyesh072019 <script> function fun1(x, y){ if (x == 0) return y else return fun1(x - 1, x + y)} // This code is contributed by gottumukkalabobby </script> Answer: The function fun() calculates and returns ((1 + 2 ... + x-1 + x) +y), which is x(x+1)/2 + y. For example, if x is 5 and y is 2, then fun should return 15 + 2 = 17. Question 2 C++ C Java Python3 C# Javascript // minimum index finder int minIndex(int arr[], int s, int e){ int sml = INT32_MAX; int mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); // swap the element at start_index and min_index swap(arr[start_index], arr[min_index]); fun2(arr, start_index + 1, end_index);} // This code is contributed by nishant_0073 // minimum index finder int minIndex(int arr[], int s, int e){ int sml = INT32_MAX; int mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);} // minimum index finderstatic int minIndex(int arr[], int s, int e){ int sml = Integer.MAX_VALUE; int mindex = ; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} static void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);} // This code is contributed by nishant_0073 # Minimum index finderdef minIndex(arr, s, e): sml = sys.maxsize mindex = 0 for i in range(s, e): if (sml > arr[i]): sml = arr[i] mindex = i return mindex def fun2(arr, start_index, end_index): if (start_index >= end_index): return # minIndex() returns index of minimum value in # array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index) arr[start_index], arr[min_index] = arr[min_index], arr[start_index] fun2(arr, start_index + 1, end_index) # This code is contributed by rag2127 // minimum index finderstatic int minIndex(int[] arr, int s, int e){ int sml = Int32.MaxValue; int mindex; for(int i = s; i < e; i++) { if(sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex; }static void fun2(int[] arr, int start_index, int end_index) { if(start_index >= end_index) { return; } int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);} // This code is contributed by avanitrachhadiya2155 <script>//Javascript Implementation// minimum index finder function minIndex(arr, s, e){ var sml = Number.MAX_SAFE_INTEGER; var mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} function fun2(arr, start_index, end_index){ if (start_index >= end_index) return; var min_index; var temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); // swap the element at start_index and min_index temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);}// This code is contributed by shubhamsingh10</script> Answer: The function fun2() is a recursive implementation of Selection Sort. Time complexity: O(n) Auxiliary Space: O(1) Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above. NikSta nishant0073 divyesh072019 divyeshrabadiya07 rag2127 avanitrachhadiya2155 gottumukkalabobby SHUBHAMSINGH10 geekygirl2001 Misc Recursion Misc Recursion Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write Regular Expressions? OOPs | Object Oriented Design Association Rule Software Engineering | Prototyping Model std::unique in C++ Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Backtracking | Introduction Print all subsequences of a string
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 107, "s": 52, "text": "Explain the functionality of the following functions. " }, { "code": null, "e": 119, "s": 107, "text": "Question 1 " }, { "code": null, "e": 123, "s": 119, "text": "C++" }, { "code": null, "e": 125, "s": 123, "text": "C" }, { "code": null, "e": 130, "s": 125, "text": "Java" }, { "code": null, "e": 138, "s": 130, "text": "Python3" }, { "code": null, "e": 141, "s": 138, "text": "C#" }, { "code": null, "e": 152, "s": 141, "text": "Javascript" }, { "code": "int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);}", "e": 251, "s": 152, "text": null }, { "code": "int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);}", "e": 350, "s": 251, "text": null }, { "code": "static int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);}", "e": 456, "s": 350, "text": null }, { "code": "def fun1(x, y) : if (x == 0) : return y else : return fun1(x - 1, x + y) # This code is contributed by divyesh072019", "e": 594, "s": 456, "text": null }, { "code": "static int fun1(int x, int y){ if (x == 0) return y; else return fun1(x - 1, x + y);} // This code is contributed by divyesh072019", "e": 745, "s": 594, "text": null }, { "code": "<script> function fun1(x, y){ if (x == 0) return y else return fun1(x - 1, x + y)} // This code is contributed by gottumukkalabobby </script>", "e": 908, "s": 745, "text": null }, { "code": null, "e": 1080, "s": 908, "text": "Answer: The function fun() calculates and returns ((1 + 2 ... + x-1 + x) +y), which is x(x+1)/2 + y. For example, if x is 5 and y is 2, then fun should return 15 + 2 = 17." }, { "code": null, "e": 1092, "s": 1080, "text": "Question 2 " }, { "code": null, "e": 1096, "s": 1092, "text": "C++" }, { "code": null, "e": 1098, "s": 1096, "text": "C" }, { "code": null, "e": 1103, "s": 1098, "text": "Java" }, { "code": null, "e": 1111, "s": 1103, "text": "Python3" }, { "code": null, "e": 1114, "s": 1111, "text": "C#" }, { "code": null, "e": 1125, "s": 1114, "text": "Javascript" }, { "code": "// minimum index finder int minIndex(int arr[], int s, int e){ int sml = INT32_MAX; int mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); // swap the element at start_index and min_index swap(arr[start_index], arr[min_index]); fun2(arr, start_index + 1, end_index);} // This code is contributed by nishant_0073", "e": 1832, "s": 1125, "text": null }, { "code": "// minimum index finder int minIndex(int arr[], int s, int e){ int sml = INT32_MAX; int mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);}", "e": 2492, "s": 1832, "text": null }, { "code": "// minimum index finderstatic int minIndex(int arr[], int s, int e){ int sml = Integer.MAX_VALUE; int mindex = ; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} static void fun2(int arr[], int start_index, int end_index){ if (start_index >= end_index) return; int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);} // This code is contributed by nishant_0073", "e": 3222, "s": 2492, "text": null }, { "code": "# Minimum index finderdef minIndex(arr, s, e): sml = sys.maxsize mindex = 0 for i in range(s, e): if (sml > arr[i]): sml = arr[i] mindex = i return mindex def fun2(arr, start_index, end_index): if (start_index >= end_index): return # minIndex() returns index of minimum value in # array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index) arr[start_index], arr[min_index] = arr[min_index], arr[start_index] fun2(arr, start_index + 1, end_index) # This code is contributed by rag2127", "e": 3835, "s": 3222, "text": null }, { "code": "// minimum index finderstatic int minIndex(int[] arr, int s, int e){ int sml = Int32.MaxValue; int mindex; for(int i = s; i < e; i++) { if(sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex; }static void fun2(int[] arr, int start_index, int end_index) { if(start_index >= end_index) { return; } int min_index; int temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);} // This code is contributed by avanitrachhadiya2155", "e": 4590, "s": 3835, "text": null }, { "code": "<script>//Javascript Implementation// minimum index finder function minIndex(arr, s, e){ var sml = Number.MAX_SAFE_INTEGER; var mindex; for (int i = s; i < e; i++) { if (sml > arr[i]) { sml = arr[i]; mindex = i; } } return mindex;} function fun2(arr, start_index, end_index){ if (start_index >= end_index) return; var min_index; var temp; // minIndex() returns index of minimum value in // array arr[start_index...end_index] min_index = minIndex(arr, start_index, end_index); // swap the element at start_index and min_index temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; fun2(arr, start_index + 1, end_index);}// This code is contributed by shubhamsingh10</script>", "e": 5391, "s": 4590, "text": null }, { "code": null, "e": 5468, "s": 5391, "text": "Answer: The function fun2() is a recursive implementation of Selection Sort." }, { "code": null, "e": 5490, "s": 5468, "text": "Time complexity: O(n)" }, { "code": null, "e": 5512, "s": 5490, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5655, "s": 5512, "text": "Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 5662, "s": 5655, "text": "NikSta" }, { "code": null, "e": 5674, "s": 5662, "text": "nishant0073" }, { "code": null, "e": 5688, "s": 5674, "text": "divyesh072019" }, { "code": null, "e": 5706, "s": 5688, "text": "divyeshrabadiya07" }, { "code": null, "e": 5714, "s": 5706, "text": "rag2127" }, { "code": null, "e": 5735, "s": 5714, "text": "avanitrachhadiya2155" }, { "code": null, "e": 5753, "s": 5735, "text": "gottumukkalabobby" }, { "code": null, "e": 5768, "s": 5753, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 5782, "s": 5768, "text": "geekygirl2001" }, { "code": null, "e": 5787, "s": 5782, "text": "Misc" }, { "code": null, "e": 5797, "s": 5787, "text": "Recursion" }, { "code": null, "e": 5802, "s": 5797, "text": "Misc" }, { "code": null, "e": 5812, "s": 5802, "text": "Recursion" }, { "code": null, "e": 5817, "s": 5812, "text": "Misc" }, { "code": null, "e": 5915, "s": 5817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5949, "s": 5915, "text": "How to write Regular Expressions?" }, { "code": null, "e": 5979, "s": 5949, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 5996, "s": 5979, "text": "Association Rule" }, { "code": null, "e": 6037, "s": 5996, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 6056, "s": 6037, "text": "std::unique in C++" }, { "code": null, "e": 6116, "s": 6056, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6201, "s": 6116, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 6228, "s": 6201, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 6256, "s": 6228, "text": "Backtracking | Introduction" } ]
How to normalize images in PyTorch ?
06 Jun, 2022 Image transformation is a process to change the original values of image pixels to a set of new values. One type of transformation that we do on images is to transform an image into a PyTorch tensor. When an image is transformed into a PyTorch tensor, the pixel values are scaled between 0.0 and 1.0. In PyTorch, this transformation can be done using torchvision.transforms.ToTensor(). It converts the PIL image with a pixel range of [0, 255] to a PyTorch FloatTensor of shape (C, H, W) with a range [0.0, 1.0]. The normalization of images is a very good practice when we work with deep neural networks. Normalizing the images means transforming the images into such values that the mean and standard deviation of the image become 0.0 and 1.0 respectively. To do this first the channel mean is subtracted from each input channel and then the result is divided by the channel standard deviation. output[channel] = (input[channel] - mean[channel]) / std[channel] Normalization helps get data within a range and reduces the skewness which helps learn faster and better. Normalization can also tackle the diminishing and exploding gradients problems. Normalization in PyTorch is done using torchvision.transforms.Normalize(). This normalizes the tensor image with mean and standard deviation. Syntax: torchvision.transforms.Normalize() Parameter: mean: Sequence of means for each channel. std: Sequence of standard deviations for each channel. inplace: Bool to make this operation in-place. Returns: Normalized Tensor image. We will perform the following steps while normalizing images in PyTorch: Load and visualize image and plot pixel values. Transform image to Tensors using torchvision.transforms.ToTensor() Calculate mean and standard deviation (std) Normalize the image using torchvision.transforms.Normalize(). Visualize normalized image. Calculate mean and std after normalize and verify them. Example: Loading Image Input image: Load the above input image using PIL. We are using the above Koala.jpg image in our program. And plot the pixel values of the image. Python3 # python code to load and visualize# an image # import necessary librariesfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np # load the imageimg_path = 'Koala.jpg'img = Image.open(img_path) # convert PIL image to numpy arrayimg_np = np.array(img) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel("pixel values")plt.ylabel("relative frequency")plt.title("distribution of pixels") Output: We find that pixel values of RGB image range from 0 to 255. Convert the PIL image to a PyTorch tensor using ToTensor() and plot the pixel values of this tensor image. We define our transform function to convert the PIL image to a PyTorch tensor image. Python3 # Python code for converting PIL Image to# PyTorch Tensor image and plot pixel values # import necessary librariesimport torchvision.transforms as transformsimport matplotlib.pyplot as plt # define custom transform functiontransform = transforms.Compose([ transforms.ToTensor()]) # transform the pIL image to tensor# imageimg_tr = transform(img) # Convert tensor image to numpy arrayimg_np = np.array(img_tr) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel("pixel values")plt.ylabel("relative frequency")plt.title("distribution of pixels") Output: We find that pixel values of tensor image range from 0.0 to 1.0. We notice that the pixel distributions of RBG and tensor image look the same but differ in the pixel values range. We calculate the mean and std of the image. Python3 # Python code to calculate mean and std# of image # get tensor imageimg_tr = transform(img) # calculate mean and stdmean, std = img_tr.mean([1,2]), img_tr.std([1,2]) # print mean and stdprint("mean and std before normalize:")print("Mean of the image:", mean)print("Std of the image:", std) Output: Here we calculated the mean and std of the image for all three channels Red, Green, and Blue. These values are before normalization. We will use these values to normalize the image. We will compare these values with those after normalization. To normalize the image, here we use the above calculated mean and std of the image. We can also use the mean and std of the ImageNet dataset if the image is similar to ImageNet images. The mean and std of ImageNet are: mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]. If the image is not similar to ImageNet, like medical images, then it is always advised to calculate the mean and std of the dataset and use them to normalize the images. Python3 # python code to normalize the image from torchvision import transforms # define custom transform# here we are using our calculated# mean & stdtransform_norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean, std)]) # get normalized imageimg_normalized = transform_norm(img) # convert normalized image to numpy# arrayimg_np = np.array(img_normalized) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel("pixel values")plt.ylabel("relative frequency")plt.title("distribution of pixels") Output: We have normalized the image with our calculated mean and std. The above output shows the distribution of the pixel values of the normalized image. We can notice the difference between pixel distributions of tensor image (before normalize) and of normalized image. Now visualize the normalized image. Python3 # Python Code to visualize normalized image # get normalized imageimg_normalized = transform_norm(img) # convert this image to numpy arrayimg_normalized = np.array(img_normalized) # transpose from shape of (3,,) to shape of (,,3)img_normalized = img_normalized.transpose(1, 2, 0) # display the normalized imageplt.imshow(img_normalized)plt.xticks([])plt.yticks([]) Output: There are clear differences, we can notice, between the input image and normalized image. We calculate the mean and std again for normalized images/ dataset. Now after normalization, the mean should be 0.0, and std be 1.0. Python3 # Python code to calculate mean and std# of normalized image # get normalized imageimg_nor = transform_norm(img) # cailculate mean and stdmean, std = img_nor.mean([1,2]), img_nor.std([1,2]) # print mean and stdprint("Mean and Std of normalized image:")print("Mean of the image:", mean)print("Std of the image:", std) Output: Here we find that after normalization the values of mean and std are 0.0 and 1.0 respectively. This verifies that after normalize the image mean and standard deviation becomes 0 and 1 respectively. varshagumber28 Picked Python-PyTorch 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 Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jun, 2022" }, { "code": null, "e": 566, "s": 53, "text": "Image transformation is a process to change the original values of image pixels to a set of new values. One type of transformation that we do on images is to transform an image into a PyTorch tensor. When an image is transformed into a PyTorch tensor, the pixel values are scaled between 0.0 and 1.0. In PyTorch, this transformation can be done using torchvision.transforms.ToTensor(). It converts the PIL image with a pixel range of [0, 255] to a PyTorch FloatTensor of shape (C, H, W) with a range [0.0, 1.0]. " }, { "code": null, "e": 950, "s": 566, "text": "The normalization of images is a very good practice when we work with deep neural networks. Normalizing the images means transforming the images into such values that the mean and standard deviation of the image become 0.0 and 1.0 respectively. To do this first the channel mean is subtracted from each input channel and then the result is divided by the channel standard deviation. " }, { "code": null, "e": 1016, "s": 950, "text": "output[channel] = (input[channel] - mean[channel]) / std[channel]" }, { "code": null, "e": 1202, "s": 1016, "text": "Normalization helps get data within a range and reduces the skewness which helps learn faster and better. Normalization can also tackle the diminishing and exploding gradients problems." }, { "code": null, "e": 1345, "s": 1202, "text": "Normalization in PyTorch is done using torchvision.transforms.Normalize(). This normalizes the tensor image with mean and standard deviation. " }, { "code": null, "e": 1388, "s": 1345, "text": "Syntax: torchvision.transforms.Normalize()" }, { "code": null, "e": 1399, "s": 1388, "text": "Parameter:" }, { "code": null, "e": 1441, "s": 1399, "text": "mean: Sequence of means for each channel." }, { "code": null, "e": 1496, "s": 1441, "text": "std: Sequence of standard deviations for each channel." }, { "code": null, "e": 1543, "s": 1496, "text": "inplace: Bool to make this operation in-place." }, { "code": null, "e": 1577, "s": 1543, "text": "Returns: Normalized Tensor image." }, { "code": null, "e": 1650, "s": 1577, "text": "We will perform the following steps while normalizing images in PyTorch:" }, { "code": null, "e": 1698, "s": 1650, "text": "Load and visualize image and plot pixel values." }, { "code": null, "e": 1765, "s": 1698, "text": "Transform image to Tensors using torchvision.transforms.ToTensor()" }, { "code": null, "e": 1809, "s": 1765, "text": "Calculate mean and standard deviation (std)" }, { "code": null, "e": 1871, "s": 1809, "text": "Normalize the image using torchvision.transforms.Normalize()." }, { "code": null, "e": 1899, "s": 1871, "text": "Visualize normalized image." }, { "code": null, "e": 1955, "s": 1899, "text": "Calculate mean and std after normalize and verify them." }, { "code": null, "e": 1978, "s": 1955, "text": "Example: Loading Image" }, { "code": null, "e": 1991, "s": 1978, "text": "Input image:" }, { "code": null, "e": 2124, "s": 1991, "text": "Load the above input image using PIL. We are using the above Koala.jpg image in our program. And plot the pixel values of the image." }, { "code": null, "e": 2132, "s": 2124, "text": "Python3" }, { "code": "# python code to load and visualize# an image # import necessary librariesfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np # load the imageimg_path = 'Koala.jpg'img = Image.open(img_path) # convert PIL image to numpy arrayimg_np = np.array(img) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel(\"pixel values\")plt.ylabel(\"relative frequency\")plt.title(\"distribution of pixels\")", "e": 2563, "s": 2132, "text": null }, { "code": null, "e": 2571, "s": 2563, "text": "Output:" }, { "code": null, "e": 2631, "s": 2571, "text": "We find that pixel values of RGB image range from 0 to 255." }, { "code": null, "e": 2823, "s": 2631, "text": "Convert the PIL image to a PyTorch tensor using ToTensor() and plot the pixel values of this tensor image. We define our transform function to convert the PIL image to a PyTorch tensor image." }, { "code": null, "e": 2831, "s": 2823, "text": "Python3" }, { "code": "# Python code for converting PIL Image to# PyTorch Tensor image and plot pixel values # import necessary librariesimport torchvision.transforms as transformsimport matplotlib.pyplot as plt # define custom transform functiontransform = transforms.Compose([ transforms.ToTensor()]) # transform the pIL image to tensor# imageimg_tr = transform(img) # Convert tensor image to numpy arrayimg_np = np.array(img_tr) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel(\"pixel values\")plt.ylabel(\"relative frequency\")plt.title(\"distribution of pixels\")", "e": 3407, "s": 2831, "text": null }, { "code": null, "e": 3415, "s": 3407, "text": "Output:" }, { "code": null, "e": 3595, "s": 3415, "text": "We find that pixel values of tensor image range from 0.0 to 1.0. We notice that the pixel distributions of RBG and tensor image look the same but differ in the pixel values range." }, { "code": null, "e": 3640, "s": 3595, "text": "We calculate the mean and std of the image. " }, { "code": null, "e": 3648, "s": 3640, "text": "Python3" }, { "code": "# Python code to calculate mean and std# of image # get tensor imageimg_tr = transform(img) # calculate mean and stdmean, std = img_tr.mean([1,2]), img_tr.std([1,2]) # print mean and stdprint(\"mean and std before normalize:\")print(\"Mean of the image:\", mean)print(\"Std of the image:\", std)", "e": 3938, "s": 3648, "text": null }, { "code": null, "e": 3946, "s": 3938, "text": "Output:" }, { "code": null, "e": 4190, "s": 3946, "text": "Here we calculated the mean and std of the image for all three channels Red, Green, and Blue. These values are before normalization. We will use these values to normalize the image. We will compare these values with those after normalization." }, { "code": null, "e": 4642, "s": 4190, "text": "To normalize the image, here we use the above calculated mean and std of the image. We can also use the mean and std of the ImageNet dataset if the image is similar to ImageNet images. The mean and std of ImageNet are: mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]. If the image is not similar to ImageNet, like medical images, then it is always advised to calculate the mean and std of the dataset and use them to normalize the images." }, { "code": null, "e": 4650, "s": 4642, "text": "Python3" }, { "code": "# python code to normalize the image from torchvision import transforms # define custom transform# here we are using our calculated# mean & stdtransform_norm = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean, std)]) # get normalized imageimg_normalized = transform_norm(img) # convert normalized image to numpy# arrayimg_np = np.array(img_normalized) # plot the pixel valuesplt.hist(img_np.ravel(), bins=50, density=True)plt.xlabel(\"pixel values\")plt.ylabel(\"relative frequency\")plt.title(\"distribution of pixels\")", "e": 5194, "s": 4650, "text": null }, { "code": null, "e": 5202, "s": 5194, "text": "Output:" }, { "code": null, "e": 5471, "s": 5204, "text": "We have normalized the image with our calculated mean and std. The above output shows the distribution of the pixel values of the normalized image. We can notice the difference between pixel distributions of tensor image (before normalize) and of normalized image. " }, { "code": null, "e": 5507, "s": 5471, "text": "Now visualize the normalized image." }, { "code": null, "e": 5515, "s": 5507, "text": "Python3" }, { "code": "# Python Code to visualize normalized image # get normalized imageimg_normalized = transform_norm(img) # convert this image to numpy arrayimg_normalized = np.array(img_normalized) # transpose from shape of (3,,) to shape of (,,3)img_normalized = img_normalized.transpose(1, 2, 0) # display the normalized imageplt.imshow(img_normalized)plt.xticks([])plt.yticks([])", "e": 5880, "s": 5515, "text": null }, { "code": null, "e": 5888, "s": 5880, "text": "Output:" }, { "code": null, "e": 5978, "s": 5888, "text": "There are clear differences, we can notice, between the input image and normalized image." }, { "code": null, "e": 6111, "s": 5978, "text": "We calculate the mean and std again for normalized images/ dataset. Now after normalization, the mean should be 0.0, and std be 1.0." }, { "code": null, "e": 6119, "s": 6111, "text": "Python3" }, { "code": "# Python code to calculate mean and std# of normalized image # get normalized imageimg_nor = transform_norm(img) # cailculate mean and stdmean, std = img_nor.mean([1,2]), img_nor.std([1,2]) # print mean and stdprint(\"Mean and Std of normalized image:\")print(\"Mean of the image:\", mean)print(\"Std of the image:\", std)", "e": 6436, "s": 6119, "text": null }, { "code": null, "e": 6444, "s": 6436, "text": "Output:" }, { "code": null, "e": 6642, "s": 6444, "text": "Here we find that after normalization the values of mean and std are 0.0 and 1.0 respectively. This verifies that after normalize the image mean and standard deviation becomes 0 and 1 respectively." }, { "code": null, "e": 6657, "s": 6642, "text": "varshagumber28" }, { "code": null, "e": 6664, "s": 6657, "text": "Picked" }, { "code": null, "e": 6679, "s": 6664, "text": "Python-PyTorch" }, { "code": null, "e": 6686, "s": 6679, "text": "Python" }, { "code": null, "e": 6784, "s": 6686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6816, "s": 6784, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6843, "s": 6816, "text": "Python Classes and Objects" }, { "code": null, "e": 6864, "s": 6843, "text": "Python OOPs Concepts" }, { "code": null, "e": 6887, "s": 6864, "text": "Introduction To PYTHON" }, { "code": null, "e": 6918, "s": 6887, "text": "Python | os.path.join() method" }, { "code": null, "e": 6974, "s": 6918, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7016, "s": 6974, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7058, "s": 7016, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7097, "s": 7058, "text": "Python | Get unique values from a list" } ]
How to Create a Basic Widget of an Android App?
29 Apr, 2021 Widgets are the micro-version of the application that consists of some functionality of the application that is displayed only on the Home Screens or the Lock Screen. For example, we see Weather, Time, Google Search Bars on the Home Screen, and FaceLock, FingerprintLock on the Lock Screen, which are some of the Widgets available on the device. Widgets come along with the Application when you install it or download it from the Web. Generally, phones come with a manufacturing configuration but such elements can be adjusted by a user later in time. In this article, we demonstrate how one can implement a basic widget for an Android App. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We are implementing it for both Java and Kotlin languages. Step 2: Add the App Widget to the Project Right-Click on the app, move the cursor to new, find the “Widget” option at the end, select it. Specify the required properties for the widget such as min. width and height, config file and preferred language, etc, and proceed. Files are automatically generated. Step 3: Install and Run the Code Install and Run the code on Android Virtual Device (AVD) or a personal device. Open the widget section of the phone, lookup for a widget with the Application name, select it, bring it to the home screen. Try changing the dimensions and we are done! Output: Run On Emulator During this selecting and deploying process, a few extra files are generated and minor changes are made to existing files as well. No programming is required for generating a basic widget and is only required if an application is to be embedded inside the widget, as discussed in the later parts of the article. Let us now explain the newly generated files the changes make to the existing ones, one by one. 1. NewAppWidget.kt Where it’s generated? Kotlin Java import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.widget.RemoteViews // Implementation of App Widget functionality. class NewAppWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } // Enter relevant functionality for // when the first widget is created override fun onEnabled(context: Context) { } // Enter relevant functionality for // when the last widget is disabled override fun onDisabled(context: Context) { } } internal fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val widgetText = context.getString(R.string.appwidget_text) // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.new_app_widget) views.setTextViewText(R.id.appwidget_text, widgetText) // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views) } import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.widget.RemoteViews; // Implementation of App Widget functionality.class NewAppWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple // widgets active, so update // all of them for (int appWidgetId : appWidgetIds) {updateAppWidget(context, appWidgetManager, appWidgetId); } } // Enter relevant functionality for // when the first widget is created @Override public void onEnabled(Context context) { super.onEnabled(context); } // Enter relevant functionality for // when the last widget is disabled @Override public void onDisabled(Context context) { super.onDisabled(context); } private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { String widgetText = context.getString(R.string.appwidget_text); // Construct the RemoteViews object RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget); views.setTextViewText(R.id.appwidget_text, widgetText); // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views); }} 2. new_app_widget.xml Where it’s generated? XML <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#09C" android:padding="@dimen/widget_margin"> <TextView android:id="@+id/appwidget_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_margin="8dp" android:background="#09C" android:contentDescription="@string/appwidget_text" android:text="@string/appwidget_text" android:textColor="#ffffff" android:textSize="24sp" android:textStyle="bold|italic" /> </RelativeLayout> 3. dimens.xml Where it’s generated? XML <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Refer to App Widget Documentation for margin information http://developer.android.com/guide/topics/appwidgets/index.html#CreatingLayout --> <dimen name="widget_margin">8dp</dimen> </resources> 4. new_app_widget_info.xml Where it’s generated? XML <?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialKeyguardLayout="@layout/new_app_widget" android:initialLayout="@layout/new_app_widget" android:minWidth="40dp" android:minHeight="40dp" android:previewImage="@drawable/example_appwidget_preview" android:resizeMode="horizontal|vertical" android:updatePeriodMillis="86400000" android:widgetCategory="home_screen"> </appwidget-provider> 5. Changes made to AndroidManifest.xml file XML <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.geeksforgeeks.widget_basic"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-- Receiver Element is Added to link the widget files to the Application --> <receiver android:name=".NewAppWidget"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/new_app_widget_info" /> </receiver> <!-- ----------------------------Until Here------------------------------------> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Yes, Programming is still a requirement for creating widgets. Changes are made inside the NewAppWidget.kt which is a Kotlin class and its counterpart new_app_widget.xml file that displays the widget. Functionalities can be declared inside the update app widget function for the application operations and new_app_widget.xml for adding multiple elements to the widget’s display. Since both the files are linked internally, altering one of them brings changes to another. There are no restrictions on the number of widgets that an app can have, however, it is advised to have a minimum number of widgets as possible as widgets are dynamically changing elements. There are update callbacks (refer to new_app_widget_info.xml file ), updatePeriodMillis is a parameter referring to which the application keeps updating the widget, meaning, the application thread to update the widget keeps running in the background, acquiring some part of the limited RAM. raghav14 android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Apr, 2021" }, { "code": null, "e": 694, "s": 53, "text": "Widgets are the micro-version of the application that consists of some functionality of the application that is displayed only on the Home Screens or the Lock Screen. For example, we see Weather, Time, Google Search Bars on the Home Screen, and FaceLock, FingerprintLock on the Lock Screen, which are some of the Widgets available on the device. Widgets come along with the Application when you install it or download it from the Web. Generally, phones come with a manufacturing configuration but such elements can be adjusted by a user later in time. In this article, we demonstrate how one can implement a basic widget for an Android App." }, { "code": null, "e": 723, "s": 694, "text": "Step 1: Create a New Project" }, { "code": null, "e": 893, "s": 723, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We are implementing it for both Java and Kotlin languages." }, { "code": null, "e": 935, "s": 893, "text": "Step 2: Add the App Widget to the Project" }, { "code": null, "e": 1031, "s": 935, "text": "Right-Click on the app, move the cursor to new, find the “Widget” option at the end, select it." }, { "code": null, "e": 1198, "s": 1031, "text": "Specify the required properties for the widget such as min. width and height, config file and preferred language, etc, and proceed. Files are automatically generated." }, { "code": null, "e": 1231, "s": 1198, "text": "Step 3: Install and Run the Code" }, { "code": null, "e": 1310, "s": 1231, "text": "Install and Run the code on Android Virtual Device (AVD) or a personal device." }, { "code": null, "e": 1435, "s": 1310, "text": "Open the widget section of the phone, lookup for a widget with the Application name, select it, bring it to the home screen." }, { "code": null, "e": 1480, "s": 1435, "text": "Try changing the dimensions and we are done!" }, { "code": null, "e": 1504, "s": 1480, "text": "Output: Run On Emulator" }, { "code": null, "e": 1912, "s": 1504, "text": "During this selecting and deploying process, a few extra files are generated and minor changes are made to existing files as well. No programming is required for generating a basic widget and is only required if an application is to be embedded inside the widget, as discussed in the later parts of the article. Let us now explain the newly generated files the changes make to the existing ones, one by one." }, { "code": null, "e": 1931, "s": 1912, "text": "1. NewAppWidget.kt" }, { "code": null, "e": 1953, "s": 1931, "text": "Where it’s generated?" }, { "code": null, "e": 1960, "s": 1953, "text": "Kotlin" }, { "code": null, "e": 1965, "s": 1960, "text": "Java" }, { "code": "import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.widget.RemoteViews // Implementation of App Widget functionality. class NewAppWidget : AppWidgetProvider() { override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } // Enter relevant functionality for // when the first widget is created override fun onEnabled(context: Context) { } // Enter relevant functionality for // when the last widget is disabled override fun onDisabled(context: Context) { } } internal fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val widgetText = context.getString(R.string.appwidget_text) // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.new_app_widget) views.setTextViewText(R.id.appwidget_text, widgetText) // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views) }", "e": 3312, "s": 1965, "text": null }, { "code": "import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.widget.RemoteViews; // Implementation of App Widget functionality.class NewAppWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple // widgets active, so update // all of them for (int appWidgetId : appWidgetIds) {updateAppWidget(context, appWidgetManager, appWidgetId); } } // Enter relevant functionality for // when the first widget is created @Override public void onEnabled(Context context) { super.onEnabled(context); } // Enter relevant functionality for // when the last widget is disabled @Override public void onDisabled(Context context) { super.onDisabled(context); } private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { String widgetText = context.getString(R.string.appwidget_text); // Construct the RemoteViews object RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget); views.setTextViewText(R.id.appwidget_text, widgetText); // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views); }}", "e": 4753, "s": 3312, "text": null }, { "code": null, "e": 4775, "s": 4753, "text": "2. new_app_widget.xml" }, { "code": null, "e": 4797, "s": 4775, "text": "Where it’s generated?" }, { "code": null, "e": 4801, "s": 4797, "text": "XML" }, { "code": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#09C\" android:padding=\"@dimen/widget_margin\"> <TextView android:id=\"@+id/appwidget_text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_centerVertical=\"true\" android:layout_margin=\"8dp\" android:background=\"#09C\" android:contentDescription=\"@string/appwidget_text\" android:text=\"@string/appwidget_text\" android:textColor=\"#ffffff\" android:textSize=\"24sp\" android:textStyle=\"bold|italic\" /> </RelativeLayout>", "e": 5563, "s": 4801, "text": null }, { "code": null, "e": 5577, "s": 5563, "text": "3. dimens.xml" }, { "code": null, "e": 5599, "s": 5577, "text": "Where it’s generated?" }, { "code": null, "e": 5603, "s": 5599, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <resources> <!-- Refer to App Widget Documentation for margin information http://developer.android.com/guide/topics/appwidgets/index.html#CreatingLayout --> <dimen name=\"widget_margin\">8dp</dimen> </resources>", "e": 5875, "s": 5603, "text": null }, { "code": null, "e": 5902, "s": 5875, "text": "4. new_app_widget_info.xml" }, { "code": null, "e": 5924, "s": 5902, "text": "Where it’s generated?" }, { "code": null, "e": 5928, "s": 5924, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <appwidget-provider xmlns:android=\"http://schemas.android.com/apk/res/android\" android:initialKeyguardLayout=\"@layout/new_app_widget\" android:initialLayout=\"@layout/new_app_widget\" android:minWidth=\"40dp\" android:minHeight=\"40dp\" android:previewImage=\"@drawable/example_appwidget_preview\" android:resizeMode=\"horizontal|vertical\" android:updatePeriodMillis=\"86400000\" android:widgetCategory=\"home_screen\"> </appwidget-provider>", "e": 6422, "s": 5928, "text": null }, { "code": null, "e": 6466, "s": 6422, "text": "5. Changes made to AndroidManifest.xml file" }, { "code": null, "e": 6470, "s": 6466, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"org.geeksforgeeks.widget_basic\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <!-- Receiver Element is Added to link the widget files to the Application --> <receiver android:name=\".NewAppWidget\"> <intent-filter> <action android:name=\"android.appwidget.action.APPWIDGET_UPDATE\" /> </intent-filter> <meta-data android:name=\"android.appwidget.provider\" android:resource=\"@xml/new_app_widget_info\" /> </receiver> <!-- ----------------------------Until Here------------------------------------> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 7742, "s": 6470, "text": null }, { "code": null, "e": 8213, "s": 7742, "text": "Yes, Programming is still a requirement for creating widgets. Changes are made inside the NewAppWidget.kt which is a Kotlin class and its counterpart new_app_widget.xml file that displays the widget. Functionalities can be declared inside the update app widget function for the application operations and new_app_widget.xml for adding multiple elements to the widget’s display. Since both the files are linked internally, altering one of them brings changes to another. " }, { "code": null, "e": 8694, "s": 8213, "text": "There are no restrictions on the number of widgets that an app can have, however, it is advised to have a minimum number of widgets as possible as widgets are dynamically changing elements. There are update callbacks (refer to new_app_widget_info.xml file ), updatePeriodMillis is a parameter referring to which the application keeps updating the widget, meaning, the application thread to update the widget keeps running in the background, acquiring some part of the limited RAM." }, { "code": null, "e": 8703, "s": 8694, "text": "raghav14" }, { "code": null, "e": 8711, "s": 8703, "text": "android" }, { "code": null, "e": 8719, "s": 8711, "text": "Android" }, { "code": null, "e": 8726, "s": 8719, "text": "Kotlin" }, { "code": null, "e": 8734, "s": 8726, "text": "Android" } ]
HTML | InputElement.setSelectionRange() method
31 Jul, 2019 The InputElement.setSelectionRange() method is used to set the start and end positions of the current index value to select text in an input or textarea element. Syntax: element.setSelectionRange( Start, End, Direction ); Parameters: This function accepts three parameters as mentioned above and described below: Start: This parameter holds the index of the first selected character. The index value greater than the length of the element pointing to the end value. End: This parameter holds the index of the character after the last selected character. The index value greater than the length of the element pointing to the end value. Direction: This parameter holds the direction to perform selection operation. The possible value of direction are: forward, backward and None. Example: <!DOCTYPE html> <html> <head> <title> HTML | InputElement.setSelectionRange() method </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> HTML InputElement.setSelectionRange() method </h2> <input type="text" id="geeks" size="50" value="Welcome to GeeksforGeeks"> <button onclick="myGeeks()"> Select text content </button> <script> function myGeeks() { const input = document.getElementById('geeks'); input.focus(); input.setSelectionRange(11, 24); } </script> </body> </html> Output:Before Clicking the Button:After Clicking the Button: Supported Browsers: The browser supported by HTML InputElement.setSelectionRange() method are listed below: Google Chrome 1.0 Internet Explorer 9.0 Firefox 1.0 Safari Opera 8.0 HTML-Methods HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2019" }, { "code": null, "e": 190, "s": 28, "text": "The InputElement.setSelectionRange() method is used to set the start and end positions of the current index value to select text in an input or textarea element." }, { "code": null, "e": 198, "s": 190, "text": "Syntax:" }, { "code": null, "e": 250, "s": 198, "text": "element.setSelectionRange( Start, End, Direction );" }, { "code": null, "e": 341, "s": 250, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 494, "s": 341, "text": "Start: This parameter holds the index of the first selected character. The index value greater than the length of the element pointing to the end value." }, { "code": null, "e": 664, "s": 494, "text": "End: This parameter holds the index of the character after the last selected character. The index value greater than the length of the element pointing to the end value." }, { "code": null, "e": 807, "s": 664, "text": "Direction: This parameter holds the direction to perform selection operation. The possible value of direction are: forward, backward and None." }, { "code": null, "e": 816, "s": 807, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML | InputElement.setSelectionRange() method </title> </head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> HTML InputElement.setSelectionRange() method </h2> <input type=\"text\" id=\"geeks\" size=\"50\" value=\"Welcome to GeeksforGeeks\"> <button onclick=\"myGeeks()\"> Select text content </button> <script> function myGeeks() { const input = document.getElementById('geeks'); input.focus(); input.setSelectionRange(11, 24); } </script> </body> </html>", "e": 1520, "s": 816, "text": null }, { "code": null, "e": 1581, "s": 1520, "text": "Output:Before Clicking the Button:After Clicking the Button:" }, { "code": null, "e": 1689, "s": 1581, "text": "Supported Browsers: The browser supported by HTML InputElement.setSelectionRange() method are listed below:" }, { "code": null, "e": 1707, "s": 1689, "text": "Google Chrome 1.0" }, { "code": null, "e": 1729, "s": 1707, "text": "Internet Explorer 9.0" }, { "code": null, "e": 1741, "s": 1729, "text": "Firefox 1.0" }, { "code": null, "e": 1748, "s": 1741, "text": "Safari" }, { "code": null, "e": 1758, "s": 1748, "text": "Opera 8.0" }, { "code": null, "e": 1771, "s": 1758, "text": "HTML-Methods" }, { "code": null, "e": 1776, "s": 1771, "text": "HTML" }, { "code": null, "e": 1793, "s": 1776, "text": "Web Technologies" }, { "code": null, "e": 1798, "s": 1793, "text": "HTML" } ]
Bank Of America Interview Experience | On-Campus 2021
16 Oct, 2021 Bank of America visited our campus on 9th September for various profiles testing, analysis, and development. The whole interview process was done virtually. It consists of 3 rounds. Online AssessmentHR RoundTechnical Round and Managerial Round Online Assessment HR Round Technical Round and Managerial Round Round 1: Online assessment Time: 90 minutes The test was active on 9th and 10th September and we had to complete it in 48 hours, so it was like we could attempt it at any time in these 48 hours given time and was conducted on the company’s platform. There were 5 questions (3 video questions + 2 coding questions). The camera and microphone were open for 3 video questions and the only camera was on for 2 coding questions. The first video question was to “Introduce yourself”, the second was “Why should you be a good match for this profile” and the third question was “Explaining the approach of your second coding question” like u need to explain in detail what logic you applied to solve the second coding question. Coding Questions: Given n test cases each of which has numbers in form of strings, output all numbers from 1 to that number which is not divisible by 5 or 7. Example: i/p – 24 o/p - 1 2 3 4 6 8 9 11 12 13 16 17 18 19 22 23 24 Given a string s consisting of lower and uppercase letters where each letter has a value from 1 to 26 and we need to calculate the beauty value of this string which is the sum of all alphabets in it. Note: The string is not case sensitive meaning F is exactly beautiful as f is. Output the maximum possible beauty of this string. Example: i/p – AbBCcc o/p – 152 Tips: You need to observe which alphabet will have what value..... like it’s not necessary for A or a to have a value as 1 and Z or z to have a value as 26. So think. Solution for 2nd question: First Count the frequency of all elements in the string then the one with the largest frequency is given number 26, then another one with less frequency as 25, and so on. So, for the above example: AbBCcc – here frequency of c is maximum so c has number 26, the frequency of A max so its value is 25 and for b it’s 24 so answer = 3*26 + 2*25 + 1*24 = 152 I was able to solve both the coding questions easily and also the video questions with confidence. About 80-90 students were shortlisted for further rounds. Round 2: HR Round Time: 10 min All further face-to-face interview rounds were conducted on Web-Ex. This was a very small round and was majorly around resume and HR-type questions. When I entered the meet, the first question was to Introduce myself. After this the discussion went on my projects, the technologies I used and how did I overcome all the challenges during making my project. Round 3: Technical + Managerial round Time: 1 hour This round again started with my introduction followed up with a good discussion. The interviewer was very friendly and started asking me questions on each and everything mentioned in my resume right from questions from all languages to all projects, a good discussion on projects made, to everything related to my hobby. What are lists, dictionary Differences b/w list, dictionary, and tuple The above two were asked as I mentioned Python in my resume. Difference between x++ and x=x+1 Are multiple inheritances allowed in Java How comfortable are u in coding? What is OS, DBMS, different types of joins, 1 SQL query (fairly easy – given a table with employees and their respective salaries o/p the second highest salary) Basic commands like CREATE, SELECT, GROUP BY, etc were also asked What is networking, OSI Model, LAN, and WAN since I mentioned NETWORKING in my resume and he was a networking person Implement stack using queue and vice versa only verbal implementation Questions on the project were asked and since my project was related to HTML and Css so questions from that domain were asked I mention traveling as my hobby so he asked: Where did you travel last and what enthusiast you about that place and all like he wanted to hear why is traveling my hobby Some Hr type questions were: What are your strengths and weaknesses? Which profile would you prefer? Where do you see yourself in 5 years and what are your goals? If given a choice between the client, you, and the company who would you choose first and why? So overall it was a kind of healthy conversation. The results were declared in a week and I was one of the selected people!!! Tips: Must be aware and prepare for each and every word in your resume so be confident on whatever you have mentioned in your resume. Should have high knowledge of all core subjects (i.e) OOPS, DBMS, and OS and Networking Should have at least solved more number medium questions in Competitive coding. (Standard questions are compulsory) Know about the company before applying (Very Important). All The Best!! Bank of America Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Interview Experience League 2022 Amazon Interview Experience for SDE-1 Nagarro Interview Experience | On-Campus 2021 Tiger Analytics Interview Experience for Data Analyst (On-Campus) Nagarro Interview Experience Nagarro Interview Experience Tejas Networks Interview Experience for R&D Engineer Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 137, "s": 28, "text": "Bank of America visited our campus on 9th September for various profiles testing, analysis, and development." }, { "code": null, "e": 210, "s": 137, "text": "The whole interview process was done virtually. It consists of 3 rounds." }, { "code": null, "e": 272, "s": 210, "text": "Online AssessmentHR RoundTechnical Round and Managerial Round" }, { "code": null, "e": 290, "s": 272, "text": "Online Assessment" }, { "code": null, "e": 299, "s": 290, "text": "HR Round" }, { "code": null, "e": 336, "s": 299, "text": "Technical Round and Managerial Round" }, { "code": null, "e": 363, "s": 336, "text": "Round 1: Online assessment" }, { "code": null, "e": 380, "s": 363, "text": "Time: 90 minutes" }, { "code": null, "e": 587, "s": 380, "text": "The test was active on 9th and 10th September and we had to complete it in 48 hours, so it was like we could attempt it at any time in these 48 hours given time and was conducted on the company’s platform." }, { "code": null, "e": 652, "s": 587, "text": "There were 5 questions (3 video questions + 2 coding questions)." }, { "code": null, "e": 761, "s": 652, "text": "The camera and microphone were open for 3 video questions and the only camera was on for 2 coding questions." }, { "code": null, "e": 1057, "s": 761, "text": "The first video question was to “Introduce yourself”, the second was “Why should you be a good match for this profile” and the third question was “Explaining the approach of your second coding question” like u need to explain in detail what logic you applied to solve the second coding question." }, { "code": null, "e": 1075, "s": 1057, "text": "Coding Questions:" }, { "code": null, "e": 1215, "s": 1075, "text": "Given n test cases each of which has numbers in form of strings, output all numbers from 1 to that number which is not divisible by 5 or 7." }, { "code": null, "e": 1283, "s": 1215, "text": "Example: i/p – 24\no/p - 1 2 3 4 6 8 9 11 12 13 16 17 18 19 22 23 24" }, { "code": null, "e": 1483, "s": 1283, "text": "Given a string s consisting of lower and uppercase letters where each letter has a value from 1 to 26 and we need to calculate the beauty value of this string which is the sum of all alphabets in it." }, { "code": null, "e": 1613, "s": 1483, "text": "Note: The string is not case sensitive meaning F is exactly beautiful as f is. Output the maximum possible beauty of this string." }, { "code": null, "e": 1645, "s": 1613, "text": "Example: i/p – AbBCcc\no/p – 152" }, { "code": null, "e": 1652, "s": 1645, "text": "Tips: " }, { "code": null, "e": 1814, "s": 1652, "text": " You need to observe which alphabet will have what value..... like it’s not necessary for A or a to have a value as 1 and Z or z to have a value as 26. So think." }, { "code": null, "e": 2012, "s": 1814, "text": "Solution for 2nd question: First Count the frequency of all elements in the string then the one with the largest frequency is given number 26, then another one with less frequency as 25, and so on." }, { "code": null, "e": 2197, "s": 2012, "text": "So, for the above example: AbBCcc – here frequency of c is maximum so c has number 26, the frequency of A max so its value is 25 and for b it’s 24 so answer = 3*26 + 2*25 + 1*24 = 152" }, { "code": null, "e": 2296, "s": 2197, "text": "I was able to solve both the coding questions easily and also the video questions with confidence." }, { "code": null, "e": 2354, "s": 2296, "text": "About 80-90 students were shortlisted for further rounds." }, { "code": null, "e": 2372, "s": 2354, "text": "Round 2: HR Round" }, { "code": null, "e": 2385, "s": 2372, "text": "Time: 10 min" }, { "code": null, "e": 2453, "s": 2385, "text": "All further face-to-face interview rounds were conducted on Web-Ex." }, { "code": null, "e": 2534, "s": 2453, "text": "This was a very small round and was majorly around resume and HR-type questions." }, { "code": null, "e": 2603, "s": 2534, "text": "When I entered the meet, the first question was to Introduce myself." }, { "code": null, "e": 2742, "s": 2603, "text": "After this the discussion went on my projects, the technologies I used and how did I overcome all the challenges during making my project." }, { "code": null, "e": 2780, "s": 2742, "text": "Round 3: Technical + Managerial round" }, { "code": null, "e": 2793, "s": 2780, "text": "Time: 1 hour" }, { "code": null, "e": 3116, "s": 2793, "text": "This round again started with my introduction followed up with a good discussion. The interviewer was very friendly and started asking me questions on each and everything mentioned in my resume right from questions from all languages to all projects, a good discussion on projects made, to everything related to my hobby." }, { "code": null, "e": 3143, "s": 3116, "text": "What are lists, dictionary" }, { "code": null, "e": 3187, "s": 3143, "text": "Differences b/w list, dictionary, and tuple" }, { "code": null, "e": 3248, "s": 3187, "text": "The above two were asked as I mentioned Python in my resume." }, { "code": null, "e": 3281, "s": 3248, "text": "Difference between x++ and x=x+1" }, { "code": null, "e": 3323, "s": 3281, "text": "Are multiple inheritances allowed in Java" }, { "code": null, "e": 3356, "s": 3323, "text": "How comfortable are u in coding?" }, { "code": null, "e": 3517, "s": 3356, "text": "What is OS, DBMS, different types of joins, 1 SQL query (fairly easy – given a table with employees and their respective salaries o/p the second highest salary)" }, { "code": null, "e": 3583, "s": 3517, "text": "Basic commands like CREATE, SELECT, GROUP BY, etc were also asked" }, { "code": null, "e": 3701, "s": 3583, "text": "What is networking, OSI Model, LAN, and WAN since I mentioned NETWORKING in my resume and he was a networking person" }, { "code": null, "e": 3771, "s": 3701, "text": "Implement stack using queue and vice versa only verbal implementation" }, { "code": null, "e": 3897, "s": 3771, "text": "Questions on the project were asked and since my project was related to HTML and Css so questions from that domain were asked" }, { "code": null, "e": 3942, "s": 3897, "text": "I mention traveling as my hobby so he asked:" }, { "code": null, "e": 4066, "s": 3942, "text": "Where did you travel last and what enthusiast you about that place and all like he wanted to hear why is traveling my hobby" }, { "code": null, "e": 4095, "s": 4066, "text": "Some Hr type questions were:" }, { "code": null, "e": 4135, "s": 4095, "text": "What are your strengths and weaknesses?" }, { "code": null, "e": 4167, "s": 4135, "text": "Which profile would you prefer?" }, { "code": null, "e": 4229, "s": 4167, "text": "Where do you see yourself in 5 years and what are your goals?" }, { "code": null, "e": 4324, "s": 4229, "text": "If given a choice between the client, you, and the company who would you choose first and why?" }, { "code": null, "e": 4450, "s": 4324, "text": "So overall it was a kind of healthy conversation. The results were declared in a week and I was one of the selected people!!!" }, { "code": null, "e": 4456, "s": 4450, "text": "Tips:" }, { "code": null, "e": 4584, "s": 4456, "text": "Must be aware and prepare for each and every word in your resume so be confident on whatever you have mentioned in your resume." }, { "code": null, "e": 4672, "s": 4584, "text": "Should have high knowledge of all core subjects (i.e) OOPS, DBMS, and OS and Networking" }, { "code": null, "e": 4788, "s": 4672, "text": "Should have at least solved more number medium questions in Competitive coding. (Standard questions are compulsory)" }, { "code": null, "e": 4845, "s": 4788, "text": "Know about the company before applying (Very Important)." }, { "code": null, "e": 4860, "s": 4845, "text": "All The Best!!" }, { "code": null, "e": 4876, "s": 4860, "text": "Bank of America" }, { "code": null, "e": 4886, "s": 4876, "text": "Marketing" }, { "code": null, "e": 4896, "s": 4886, "text": "On-Campus" }, { "code": null, "e": 4918, "s": 4896, "text": "Interview Experiences" }, { "code": null, "e": 5016, "s": 4918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5054, "s": 5016, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 5110, "s": 5054, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 5143, "s": 5110, "text": "Interview Experience League 2022" }, { "code": null, "e": 5181, "s": 5143, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 5227, "s": 5181, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 5293, "s": 5227, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" }, { "code": null, "e": 5322, "s": 5293, "text": "Nagarro Interview Experience" }, { "code": null, "e": 5351, "s": 5322, "text": "Nagarro Interview Experience" }, { "code": null, "e": 5404, "s": 5351, "text": "Tejas Networks Interview Experience for R&D Engineer" } ]
Removing punctuations from a given string
12 Jul, 2022 Given a string, remove the punctuation from the string if the given character is a punctuation character, as classified by the current C locale. The default C locale classifies these characters as punctuation: ! " # $ % & ' ( ) * + , - . / : ; ? @ [ \ ] ^ _ ` { | } ~ Examples: 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. Input : %welcome' to @geeksforgeek<s Output : welcome to geeksforgeeks Input : Hello!!!, he said ---and went. Output : Hello he said and went Approach: First check the input string if it consists of punctuations then we have to make it punctuation free. In order to do this, we will traverse over the string, and if punctuations are found we will remove them. Let’s say the input string is ‘$Student@‘ then we have to remove $ and @, furthermore we have to print the plain string ‘Student‘ which is free from any punctuations. Algorithm: Initialize the input stringCheck if the character present in the string is punctuation or not.If a character is a punctuation, then erase that character and decrement the index.Print the output string, which will be free of any punctuation. Initialize the input string Check if the character present in the string is punctuation or not. If a character is a punctuation, then erase that character and decrement the index. Print the output string, which will be free of any punctuation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to remove punctuation from a given string #include <iostream>using namespace std; int main(){ // input string std::string str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks"; for (int i = 0, len = str.size(); i < len; i++) { // check whether parsing character is punctuation or not if (ispunct(str[i])) { str.erase(i--, 1); len = str.size(); } } // print string without punctuation std::cout << str; return 0;} // Java program to remove punctuation from a given string public class Test{ public static void main(String[] args) { // input string String str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks"; // similar to Matcher.replaceAll str = str.replaceAll("\\p{Punct}",""); System.out.println(str); } }// This code is contributed by Gaurav Miglani # Python program to remove punctuation from a given string# Function to remove punctuationdef Punctuation(string): # punctuation marks punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # traverse the given string and if any punctuation # marks occur replace it with null for x in string.lower(): if x in punctuations: string = string.replace(x, "") # Print string without punctuation print(string) # Driver programstring = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks"Punctuation(string) // C# program to remove punctuation// from a given stringusing System;using System.Text.RegularExpressions; class GFG{public static void Main(){ // input string String str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks"; // similar to Matcher.replaceAll str = Regex.Replace(str,@"[^\w\d\s]",""); Console.Write(str);}} // This code is contributed// by 29AjayKumar <script> // JavaScript program to remove punctuation from a given string { // input string var str = "Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks"; // similar to Matcher.replaceAll str = str.replace(/[^a-zA-Z ]/g, ""); document.write(str); } // This code is contributed by shivanisingh </script> Welcome to GeeksforGeeks Time Complexity: O(n2) Auxiliary Space: O(1) This article is contributed by Aarti_Rathi and Pramod 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. 29AjayKumar shivanisinghss2110 amartyaghoshgfg _shinchancode lucidcoder121 hardikkoriintern School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jul, 2022" }, { "code": null, "e": 263, "s": 52, "text": "Given a string, remove the punctuation from the string if the given character is a punctuation character, as classified by the current C locale. The default C locale classifies these characters as punctuation: " }, { "code": null, "e": 322, "s": 263, "text": "! \" # $ % & ' ( ) * + , - . / : ; ? @ [ \\ ] ^ _ ` { | } ~ " }, { "code": null, "e": 333, "s": 322, "text": "Examples: " }, { "code": null, "e": 342, "s": 333, "text": "Chapters" }, { "code": null, "e": 369, "s": 342, "text": "descriptions off, selected" }, { "code": null, "e": 419, "s": 369, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 442, "s": 419, "text": "captions off, selected" }, { "code": null, "e": 450, "s": 442, "text": "English" }, { "code": null, "e": 474, "s": 450, "text": "This is a modal window." }, { "code": null, "e": 543, "s": 474, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 565, "s": 543, "text": "End of dialog window." }, { "code": null, "e": 708, "s": 565, "text": "Input : %welcome' to @geeksforgeek<s\nOutput : welcome to geeksforgeeks\n\nInput : Hello!!!, he said ---and went.\nOutput : Hello he said and went" }, { "code": null, "e": 1093, "s": 708, "text": "Approach: First check the input string if it consists of punctuations then we have to make it punctuation free. In order to do this, we will traverse over the string, and if punctuations are found we will remove them. Let’s say the input string is ‘$Student@‘ then we have to remove $ and @, furthermore we have to print the plain string ‘Student‘ which is free from any punctuations." }, { "code": null, "e": 1104, "s": 1093, "text": "Algorithm:" }, { "code": null, "e": 1345, "s": 1104, "text": "Initialize the input stringCheck if the character present in the string is punctuation or not.If a character is a punctuation, then erase that character and decrement the index.Print the output string, which will be free of any punctuation." }, { "code": null, "e": 1373, "s": 1345, "text": "Initialize the input string" }, { "code": null, "e": 1441, "s": 1373, "text": "Check if the character present in the string is punctuation or not." }, { "code": null, "e": 1525, "s": 1441, "text": "If a character is a punctuation, then erase that character and decrement the index." }, { "code": null, "e": 1589, "s": 1525, "text": "Print the output string, which will be free of any punctuation." }, { "code": null, "e": 1640, "s": 1589, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1644, "s": 1640, "text": "C++" }, { "code": null, "e": 1649, "s": 1644, "text": "Java" }, { "code": null, "e": 1657, "s": 1649, "text": "Python3" }, { "code": null, "e": 1660, "s": 1657, "text": "C#" }, { "code": null, "e": 1671, "s": 1660, "text": "Javascript" }, { "code": "// CPP program to remove punctuation from a given string #include <iostream>using namespace std; int main(){ // input string std::string str = \"Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks\"; for (int i = 0, len = str.size(); i < len; i++) { // check whether parsing character is punctuation or not if (ispunct(str[i])) { str.erase(i--, 1); len = str.size(); } } // print string without punctuation std::cout << str; return 0;}", "e": 2176, "s": 1671, "text": null }, { "code": "// Java program to remove punctuation from a given string public class Test{ public static void main(String[] args) { // input string String str = \"Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks\"; // similar to Matcher.replaceAll str = str.replaceAll(\"\\\\p{Punct}\",\"\"); System.out.println(str); } }// This code is contributed by Gaurav Miglani", "e": 2581, "s": 2176, "text": null }, { "code": "# Python program to remove punctuation from a given string# Function to remove punctuationdef Punctuation(string): # punctuation marks punctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~''' # traverse the given string and if any punctuation # marks occur replace it with null for x in string.lower(): if x in punctuations: string = string.replace(x, \"\") # Print string without punctuation print(string) # Driver programstring = \"Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks\"Punctuation(string)", "e": 3110, "s": 2581, "text": null }, { "code": "// C# program to remove punctuation// from a given stringusing System;using System.Text.RegularExpressions; class GFG{public static void Main(){ // input string String str = \"Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks\"; // similar to Matcher.replaceAll str = Regex.Replace(str,@\"[^\\w\\d\\s]\",\"\"); Console.Write(str);}} // This code is contributed// by 29AjayKumar", "e": 3513, "s": 3110, "text": null }, { "code": "<script> // JavaScript program to remove punctuation from a given string { // input string var str = \"Welcome???@@##$ to#$% Geeks%$^for$%^&Geeks\"; // similar to Matcher.replaceAll str = str.replace(/[^a-zA-Z ]/g, \"\"); document.write(str); } // This code is contributed by shivanisingh </script>", "e": 3871, "s": 3513, "text": null }, { "code": null, "e": 3896, "s": 3871, "text": "Welcome to GeeksforGeeks" }, { "code": null, "e": 3941, "s": 3896, "text": "Time Complexity: O(n2) Auxiliary Space: O(1)" }, { "code": null, "e": 4254, "s": 3941, "text": "This article is contributed by Aarti_Rathi and Pramod 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. " }, { "code": null, "e": 4266, "s": 4254, "text": "29AjayKumar" }, { "code": null, "e": 4285, "s": 4266, "text": "shivanisinghss2110" }, { "code": null, "e": 4301, "s": 4285, "text": "amartyaghoshgfg" }, { "code": null, "e": 4315, "s": 4301, "text": "_shinchancode" }, { "code": null, "e": 4329, "s": 4315, "text": "lucidcoder121" }, { "code": null, "e": 4346, "s": 4329, "text": "hardikkoriintern" }, { "code": null, "e": 4365, "s": 4346, "text": "School Programming" }, { "code": null, "e": 4373, "s": 4365, "text": "Strings" }, { "code": null, "e": 4381, "s": 4373, "text": "Strings" } ]
Subarray whose sum is closest to K
14 Jun, 2022 Given an array of positive and negative integers and an integer K. The task is to find the subarray which has its sum closest to k. In case of multiple answers, print anyone. Note: Closest here means abs(sum-k) should be minimal. Examples: Input: a[] = { -5, 12, -3, 4, -15, 6, 1 }, K = 2 Output: 1 The subarray {-3, 4} or {1} has sum = 1 which is the closest to K. Input: a[] = { 2, 2, -1, 5, -3, -2 }, K = 7 Output: 6 Here the output can be 6 or 8 The subarray {2, 2, -1, 5} gives sum as 8 which has abs(8-7) = 1 which is same as that of the subarray {2, -1, 5} which has abs(6-7) = 1. A naive approach is to check for all possible subarray sum using prefix sum. The complexity in that case will be O(N2). An efficient solution will be to use C++ STL set and binary search to solve the following problem. Follow the below algorithm to solve the above problem. Initially insert the first element in the set container. Initialize the answer sum as first element and difference as abs(A0-k). Iterate for all array elements from 1 to N and keep adding the elements to prefix sum at each step to the set container. At every iteration, since the prefix sum is already there, we just need to subtract the sum of some elements from beginning to get the sum of any subarray. The greedy way will be to subtract the sum of the subarray which takes the sum closest to K. Using binary search (lower_bound() function can be used) find the sum of subarray from beginning which is closest to (prefix-k) as the subtraction of that number from prefix sum will give the subarray sum which is closest to K till that iteration. Also check for the index before which lower_bound() returns, since the sum can either be greater or lesser than K. If the lower_bound returns no such element, then the current prefix sum is compared and updated if it was lesser than the previous computed sum. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to find the// sum of subarray whose sum is// closest to K#include <bits/stdc++.h>using namespace std; // Function to find the sum of subarray// whose sum is closest to Kint closestSubarraySumToK(int a[], int n, int k){ // Declare a set set<int> s; // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.insert(a[0]); // Initially let this difference // be the minimum int mini = abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound auto it = s.lower_bound(presum - k); // if it is the first element // in the set if (it == s.begin()) { // get the prefix sum till start // of the subarray int diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } if(abs(presum - k) < mini){ // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it != s.end()) { // get the prefix sum till start // of the subarray int diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (abs(presum - k) < mini) { // update the minimal difference mini = abs(presum - k); // update the sum sum = presum; } } // insert the current prefix sum s.insert(presum); } return sum;} // Driver Codeint main(){ int a[] = { -5, 12, -3, 4, -15, 6, 1 }; int n = sizeof(a) / sizeof(a[0]); int k = 2; cout << closestSubarraySumToK(a, n, k); return 0;} // Java program to find the// sum of subarray whose sum is// closest to Kimport java.util.*; class GFG{ // Function to find the sum of subarray // whose sum is closest to K static int closestSubarraySumToK(int a[], int n, int k) { // Declare a set TreeSet<Integer> s = new TreeSet<>(); // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.add(a[0]); // Initially let this difference // be the minimum int mini = Math.abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound Integer it = s.lower(presum - k); // if it is the first element // in the set if (it == s.first()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s.last()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.abs(presum - k) < mini) { // update the minimal difference mini = Math.abs(presum - k); // update the sum sum = presum+1; } } // insert the current prefix sum s.add(presum); } return sum; } // Driver Code public static void main(String[] args) { int a[] = { -5, 12, -3, 4, -15, 6, 1 }; int n = a.length; int k = 2; System.out.print(closestSubarraySumToK(a, n, k)); }} // This code contributed by Rajput-Ji # Python3 program to find the# sum of subarray whose sum is# closest to Kimport bisect # Function to find the sum of subarray# whose sum is closest to Kdef closestSubarraySumToK(a , n , k): # Declare a set s = [] # initially consider the # first subarray as the first # element in the array presum = a[0] # insert s.append(a[0]) # Initially let this difference # be the minimum mini = abs(a[0] - k) # let this be the sum # of the subarray # to be searched initially sum = presum # iterate for all the array elements for i in range(1, n): # calculate the prefix sum presum += a[i] # find the closest subarray # sum to by using lower_bound it = bisect.bisect_left(s,presum - k) if(it == -1): continue #if it is the first element # in the set if (it == 0): #get the prefix sum till start #of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff if (abs(presum - k) < mini): #update the minimal difference mini = abs((presum - diff) - k) #update the sum sum = presum - diff # if the difference is # present in between elif (it != len(s)): # get the prefix sum till start # of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff # also check for the one before that # since the sum can be greater than # or less than K also it -= 1 # get the prefix sum till start # of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff; # if there exists no such prefix sum # then the current prefix sum is # checked and updated else : # if the subarray sum is closest to K # than the previous one if (abs(presum - k) < mini): # update the minimal difference mini = abs(presum - k) # update the sum sum = presum + 1; # insert the current prefix sum bisect.insort(s, presum) return sum # Driver Codea = [ -5, 12, -3, 4, -15, 6, 1 ]n = len(a)k = 2 print(closestSubarraySumToK(a, n, k)) #This code is contributed by phasing17 // C# program to find the// sum of subarray whose sum is// closest to Kusing System;using System.Linq;using System.Collections.Generic; public class GFG { // Function to find the sum of subarray // whose sum is closest to K static int closestSubarraySumToK(int []a, int n, int k) { // Declare a set SortedSet<int> s = new SortedSet<int>(); // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.Add(a[0]); // Initially let this difference // be the minimum int mini = Math.Abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound int it = lower_bound(s,presum - k); // if it is the first element // in the set if (it == s.First()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s.Last()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.Abs(presum - k) < mini) { // update the minimal difference mini = Math.Abs(presum - k); // update the sum sum = presum + 1; } } // insert the current prefix sum s.Add(presum); } return sum-1; } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; return temp[temp.IndexOf(val) + 1]; } // Driver Code public static void Main(String[] args) { int []a = { -5, 12, -3, 4, -15, 6, 1 }; int n = a.Length; int k = 2; Console.Write(closestSubarraySumToK(a, n, k)); }} // This code is contributed by Rajput-Ji <script>// javascript program to find the// sum of subarray whose sum is// closest to K // Function to find the sum of subarray // whose sum is closest to K function closestSubarraySumToK(a , n , k) { // Declare a set var s = []; // initially consider the // first subarray as the first // element in the array var presum = a[0]; // insert s.push(a[0]); // Initially let this difference // be the minimum var mini = Math.abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially var sum = presum; // iterate for all the array elements for (var i = 1; i < n; i++) { s.sort(); // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound var it = lower_bound(s,presum - k); if(it == -1) continue; // if it is the first element // in the set if (it == s[0]) { // get the prefix sum till start // of the subarray var diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s[s.length-1]) { // get the prefix sum till start // of the subarray var diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.abs(presum - k) < mini) { // update the minimal difference mini = Math.abs(presum - k); // update the sum sum = presum + 1; } } // insert the current prefix sum s.push(presum); } return sum; } function lower_bound(s, val) { let temp = [...s]; temp.sort((a, b) => a - b); return temp[temp.indexOf(val) + 1]; } // Driver Code var a = [ -5, 12, -3, 4, -15, 6, 1 ]; var n = a.length; var k = 2; document.write(closestSubarraySumToK(a, n, k)); // This code is contributed by Rajput-Ji</script> 1 Time Complexity: O(N log N), where N represents the size of the given array.Auxiliary Space: O(N), where N represents the size of the given array. anikaseth98 Rajput-Ji songsgaana08 phasing17 samim2000 Binary Search cpp-set subarray subarray-sum Arrays Binary Search Tree Arrays Binary Search Tree Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 228, "s": 52, "text": "Given an array of positive and negative integers and an integer K. The task is to find the subarray which has its sum closest to k. In case of multiple answers, print anyone. " }, { "code": null, "e": 284, "s": 228, "text": "Note: Closest here means abs(sum-k) should be minimal. " }, { "code": null, "e": 295, "s": 284, "text": "Examples: " }, { "code": null, "e": 421, "s": 295, "text": "Input: a[] = { -5, 12, -3, 4, -15, 6, 1 }, K = 2 Output: 1 The subarray {-3, 4} or {1} has sum = 1 which is the closest to K." }, { "code": null, "e": 644, "s": 421, "text": "Input: a[] = { 2, 2, -1, 5, -3, -2 }, K = 7 Output: 6 Here the output can be 6 or 8 The subarray {2, 2, -1, 5} gives sum as 8 which has abs(8-7) = 1 which is same as that of the subarray {2, -1, 5} which has abs(6-7) = 1. " }, { "code": null, "e": 764, "s": 644, "text": "A naive approach is to check for all possible subarray sum using prefix sum. The complexity in that case will be O(N2)." }, { "code": null, "e": 919, "s": 764, "text": "An efficient solution will be to use C++ STL set and binary search to solve the following problem. Follow the below algorithm to solve the above problem. " }, { "code": null, "e": 976, "s": 919, "text": "Initially insert the first element in the set container." }, { "code": null, "e": 1048, "s": 976, "text": "Initialize the answer sum as first element and difference as abs(A0-k)." }, { "code": null, "e": 1169, "s": 1048, "text": "Iterate for all array elements from 1 to N and keep adding the elements to prefix sum at each step to the set container." }, { "code": null, "e": 1418, "s": 1169, "text": "At every iteration, since the prefix sum is already there, we just need to subtract the sum of some elements from beginning to get the sum of any subarray. The greedy way will be to subtract the sum of the subarray which takes the sum closest to K." }, { "code": null, "e": 1666, "s": 1418, "text": "Using binary search (lower_bound() function can be used) find the sum of subarray from beginning which is closest to (prefix-k) as the subtraction of that number from prefix sum will give the subarray sum which is closest to K till that iteration." }, { "code": null, "e": 1781, "s": 1666, "text": "Also check for the index before which lower_bound() returns, since the sum can either be greater or lesser than K." }, { "code": null, "e": 1926, "s": 1781, "text": "If the lower_bound returns no such element, then the current prefix sum is compared and updated if it was lesser than the previous computed sum." }, { "code": null, "e": 1978, "s": 1926, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1982, "s": 1978, "text": "C++" }, { "code": null, "e": 1987, "s": 1982, "text": "Java" }, { "code": null, "e": 1995, "s": 1987, "text": "Python3" }, { "code": null, "e": 1998, "s": 1995, "text": "C#" }, { "code": null, "e": 2009, "s": 1998, "text": "Javascript" }, { "code": "// C++ program to find the// sum of subarray whose sum is// closest to K#include <bits/stdc++.h>using namespace std; // Function to find the sum of subarray// whose sum is closest to Kint closestSubarraySumToK(int a[], int n, int k){ // Declare a set set<int> s; // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.insert(a[0]); // Initially let this difference // be the minimum int mini = abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound auto it = s.lower_bound(presum - k); // if it is the first element // in the set if (it == s.begin()) { // get the prefix sum till start // of the subarray int diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } if(abs(presum - k) < mini){ // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it != s.end()) { // get the prefix sum till start // of the subarray int diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = *it; // if the subarray sum is closest to K // than the previous one if (abs((presum - diff) - k) < mini) { // update the minimal difference mini = abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (abs(presum - k) < mini) { // update the minimal difference mini = abs(presum - k); // update the sum sum = presum; } } // insert the current prefix sum s.insert(presum); } return sum;} // Driver Codeint main(){ int a[] = { -5, 12, -3, 4, -15, 6, 1 }; int n = sizeof(a) / sizeof(a[0]); int k = 2; cout << closestSubarraySumToK(a, n, k); return 0;}", "e": 5406, "s": 2009, "text": null }, { "code": "// Java program to find the// sum of subarray whose sum is// closest to Kimport java.util.*; class GFG{ // Function to find the sum of subarray // whose sum is closest to K static int closestSubarraySumToK(int a[], int n, int k) { // Declare a set TreeSet<Integer> s = new TreeSet<>(); // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.add(a[0]); // Initially let this difference // be the minimum int mini = Math.abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound Integer it = s.lower(presum - k); // if it is the first element // in the set if (it == s.first()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s.last()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.abs(presum - k) < mini) { // update the minimal difference mini = Math.abs(presum - k); // update the sum sum = presum+1; } } // insert the current prefix sum s.add(presum); } return sum; } // Driver Code public static void main(String[] args) { int a[] = { -5, 12, -3, 4, -15, 6, 1 }; int n = a.length; int k = 2; System.out.print(closestSubarraySumToK(a, n, k)); }} // This code contributed by Rajput-Ji", "e": 8434, "s": 5406, "text": null }, { "code": "# Python3 program to find the# sum of subarray whose sum is# closest to Kimport bisect # Function to find the sum of subarray# whose sum is closest to Kdef closestSubarraySumToK(a , n , k): # Declare a set s = [] # initially consider the # first subarray as the first # element in the array presum = a[0] # insert s.append(a[0]) # Initially let this difference # be the minimum mini = abs(a[0] - k) # let this be the sum # of the subarray # to be searched initially sum = presum # iterate for all the array elements for i in range(1, n): # calculate the prefix sum presum += a[i] # find the closest subarray # sum to by using lower_bound it = bisect.bisect_left(s,presum - k) if(it == -1): continue #if it is the first element # in the set if (it == 0): #get the prefix sum till start #of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff if (abs(presum - k) < mini): #update the minimal difference mini = abs((presum - diff) - k) #update the sum sum = presum - diff # if the difference is # present in between elif (it != len(s)): # get the prefix sum till start # of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff # also check for the one before that # since the sum can be greater than # or less than K also it -= 1 # get the prefix sum till start # of the subarray diff = s[it] # if the subarray sum is closest to K # than the previous one if (abs((presum - diff) - k) < mini): # update the minimal difference mini = abs((presum - diff) - k) # update the sum sum = presum - diff; # if there exists no such prefix sum # then the current prefix sum is # checked and updated else : # if the subarray sum is closest to K # than the previous one if (abs(presum - k) < mini): # update the minimal difference mini = abs(presum - k) # update the sum sum = presum + 1; # insert the current prefix sum bisect.insort(s, presum) return sum # Driver Codea = [ -5, 12, -3, 4, -15, 6, 1 ]n = len(a)k = 2 print(closestSubarraySumToK(a, n, k)) #This code is contributed by phasing17", "e": 11696, "s": 8434, "text": null }, { "code": "// C# program to find the// sum of subarray whose sum is// closest to Kusing System;using System.Linq;using System.Collections.Generic; public class GFG { // Function to find the sum of subarray // whose sum is closest to K static int closestSubarraySumToK(int []a, int n, int k) { // Declare a set SortedSet<int> s = new SortedSet<int>(); // initially consider the // first subarray as the first // element in the array int presum = a[0]; // insert s.Add(a[0]); // Initially let this difference // be the minimum int mini = Math.Abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially int sum = presum; // iterate for all the array elements for (int i = 1; i < n; i++) { // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound int it = lower_bound(s,presum - k); // if it is the first element // in the set if (it == s.First()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s.Last()) { // get the prefix sum till start // of the subarray int diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.Abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.Abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.Abs(presum - k) < mini) { // update the minimal difference mini = Math.Abs(presum - k); // update the sum sum = presum + 1; } } // insert the current prefix sum s.Add(presum); } return sum-1; } public static int lower_bound(SortedSet<int> s, int val) { List<int> temp = new List<int>(); temp.AddRange(s); temp.Sort(); temp.Reverse(); if (temp.IndexOf(val) + 1 == temp.Count) return -1; return temp[temp.IndexOf(val) + 1]; } // Driver Code public static void Main(String[] args) { int []a = { -5, 12, -3, 4, -15, 6, 1 }; int n = a.Length; int k = 2; Console.Write(closestSubarraySumToK(a, n, k)); }} // This code is contributed by Rajput-Ji", "e": 15039, "s": 11696, "text": null }, { "code": "<script>// javascript program to find the// sum of subarray whose sum is// closest to K // Function to find the sum of subarray // whose sum is closest to K function closestSubarraySumToK(a , n , k) { // Declare a set var s = []; // initially consider the // first subarray as the first // element in the array var presum = a[0]; // insert s.push(a[0]); // Initially let this difference // be the minimum var mini = Math.abs(a[0] - k); // let this be the sum // of the subarray // to be searched initially var sum = presum; // iterate for all the array elements for (var i = 1; i < n; i++) { s.sort(); // calculate the prefix sum presum += a[i]; // find the closest subarray // sum to by using lower_bound var it = lower_bound(s,presum - k); if(it == -1) continue; // if it is the first element // in the set if (it == s[0]) { // get the prefix sum till start // of the subarray var diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if the difference is // present in between else if (it == s[s.length-1]) { // get the prefix sum till start // of the subarray var diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } // also check for the one before that // since the sum can be greater than // or less than K also it--; // get the prefix sum till start // of the subarray diff = it; // if the subarray sum is closest to K // than the previous one if (Math.abs((presum - diff) - k) < mini) { // update the minimal difference mini = Math.abs((presum - diff) - k); // update the sum sum = presum - diff; } } // if there exists no such prefix sum // then the current prefix sum is // checked and updated else { // if the subarray sum is closest to K // than the previous one if (Math.abs(presum - k) < mini) { // update the minimal difference mini = Math.abs(presum - k); // update the sum sum = presum + 1; } } // insert the current prefix sum s.push(presum); } return sum; } function lower_bound(s, val) { let temp = [...s]; temp.sort((a, b) => a - b); return temp[temp.indexOf(val) + 1]; } // Driver Code var a = [ -5, 12, -3, 4, -15, 6, 1 ]; var n = a.length; var k = 2; document.write(closestSubarraySumToK(a, n, k)); // This code is contributed by Rajput-Ji</script>", "e": 18836, "s": 15039, "text": null }, { "code": null, "e": 18838, "s": 18836, "text": "1" }, { "code": null, "e": 18985, "s": 18838, "text": "Time Complexity: O(N log N), where N represents the size of the given array.Auxiliary Space: O(N), where N represents the size of the given array." }, { "code": null, "e": 18997, "s": 18985, "text": "anikaseth98" }, { "code": null, "e": 19007, "s": 18997, "text": "Rajput-Ji" }, { "code": null, "e": 19020, "s": 19007, "text": "songsgaana08" }, { "code": null, "e": 19030, "s": 19020, "text": "phasing17" }, { "code": null, "e": 19040, "s": 19030, "text": "samim2000" }, { "code": null, "e": 19054, "s": 19040, "text": "Binary Search" }, { "code": null, "e": 19062, "s": 19054, "text": "cpp-set" }, { "code": null, "e": 19071, "s": 19062, "text": "subarray" }, { "code": null, "e": 19084, "s": 19071, "text": "subarray-sum" }, { "code": null, "e": 19091, "s": 19084, "text": "Arrays" }, { "code": null, "e": 19110, "s": 19091, "text": "Binary Search Tree" }, { "code": null, "e": 19117, "s": 19110, "text": "Arrays" }, { "code": null, "e": 19136, "s": 19117, "text": "Binary Search Tree" }, { "code": null, "e": 19150, "s": 19136, "text": "Binary Search" } ]
Node.js fs-extra ensureDirSync() function
06 Oct, 2021 The ensureDirSync() function is the synchronous version of ensureDir() function. The function makes sure that the directory exists, if the directory structure does not exist it will be created by the function. mkdirsSync() and mkdirpSync() can also be used in place of ensureDirSync() and the result will be same. Syntax: ensureDirSync(dir,options) // OR mkdirsSync(dir,options) // OR mkdirpSync(dir,options) Parameters: dir: It is a string that contains the directory path. options: It is an object or an integer that is used to specify the optional parameters.Integer: If it is an integer it will be mode.Object: If it is an object it will be {mode: integer}. Integer: If it is an integer it will be mode.Object: If it is an object it will be {mode: integer}. Integer: If it is an integer it will be mode. Object: If it is an object it will be {mode: integer}. Return value: It does not return anything. Follow the steps to implement the function: The module can be installed by using the following command.npm install fs-extraAfter the installation of the module you can check the version of the installed module by using this command.npm ls fs-extraCreate a file with the name index.js and require the fs-extra module in the file using the following command.const fs = require('fs-extra');To run the file write the following command in the terminal.node index.js The module can be installed by using the following command.npm install fs-extra npm install fs-extra After the installation of the module you can check the version of the installed module by using this command.npm ls fs-extra npm ls fs-extra Create a file with the name index.js and require the fs-extra module in the file using the following command.const fs = require('fs-extra'); const fs = require('fs-extra'); To run the file write the following command in the terminal.node index.js node index.js Project Structure: The project structure will look like this. Example 1: index.js // Requiring moduleconst fs = require("fs-extra"); // Function to check// if directory exists// or notconst dirExists = (dir) => { if (fs.existsSync(dir)) { return "Directory exists"; } else { return "Directory do not exist"; }}; // This directory// already exists so// function will not// do anythingconst dir = "dir"; // Checking before// calling functionconst before = dirExists(dir);console.log(`Before function call ${before}`); // Function callfs.ensureDirSync(dir); // Checking after// calling functionconst after = dirExists(dir);console.log(`After function call ${after}`); Output: Example 2: index.js // Requiring moduleconst fs = require("fs-extra"); // Function to check// if directory exists// or notconst dirExists = (dir) => { if (fs.existsSync(dir)) { return "Directory exists"; } else { return "Directory do not exist"; }}; // This directory// do not exists so// function will create// the directoryconst dir = "direc/dir"; const mode = 0o2775; // Checking before// calling functionconst before = dirExists(dir);console.log(`Before function call ${before}`); // Function callfs.ensureDirSync(dir, mode); // Checking after// calling functionconst after = dirExists(dir);console.log(`After function call ${after}`); Output: Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureDir-sync.md NodeJS-fs-extra NodeJS-function Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 342, "s": 28, "text": "The ensureDirSync() function is the synchronous version of ensureDir() function. The function makes sure that the directory exists, if the directory structure does not exist it will be created by the function. mkdirsSync() and mkdirpSync() can also be used in place of ensureDirSync() and the result will be same." }, { "code": null, "e": 350, "s": 342, "text": "Syntax:" }, { "code": null, "e": 437, "s": 350, "text": "ensureDirSync(dir,options)\n// OR\nmkdirsSync(dir,options)\n// OR\nmkdirpSync(dir,options)" }, { "code": null, "e": 449, "s": 437, "text": "Parameters:" }, { "code": null, "e": 503, "s": 449, "text": "dir: It is a string that contains the directory path." }, { "code": null, "e": 690, "s": 503, "text": "options: It is an object or an integer that is used to specify the optional parameters.Integer: If it is an integer it will be mode.Object: If it is an object it will be {mode: integer}." }, { "code": null, "e": 790, "s": 690, "text": "Integer: If it is an integer it will be mode.Object: If it is an object it will be {mode: integer}." }, { "code": null, "e": 836, "s": 790, "text": "Integer: If it is an integer it will be mode." }, { "code": null, "e": 891, "s": 836, "text": "Object: If it is an object it will be {mode: integer}." }, { "code": null, "e": 934, "s": 891, "text": "Return value: It does not return anything." }, { "code": null, "e": 978, "s": 934, "text": "Follow the steps to implement the function:" }, { "code": null, "e": 1395, "s": 978, "text": "The module can be installed by using the following command.npm install fs-extraAfter the installation of the module you can check the version of the installed module by using this command.npm ls fs-extraCreate a file with the name index.js and require the fs-extra module in the file using the following command.const fs = require('fs-extra');To run the file write the following command in the terminal.node index.js" }, { "code": null, "e": 1475, "s": 1395, "text": "The module can be installed by using the following command.npm install fs-extra" }, { "code": null, "e": 1496, "s": 1475, "text": "npm install fs-extra" }, { "code": null, "e": 1621, "s": 1496, "text": "After the installation of the module you can check the version of the installed module by using this command.npm ls fs-extra" }, { "code": null, "e": 1637, "s": 1621, "text": "npm ls fs-extra" }, { "code": null, "e": 1778, "s": 1637, "text": "Create a file with the name index.js and require the fs-extra module in the file using the following command.const fs = require('fs-extra');" }, { "code": null, "e": 1810, "s": 1778, "text": "const fs = require('fs-extra');" }, { "code": null, "e": 1884, "s": 1810, "text": "To run the file write the following command in the terminal.node index.js" }, { "code": null, "e": 1898, "s": 1884, "text": "node index.js" }, { "code": null, "e": 1960, "s": 1898, "text": "Project Structure: The project structure will look like this." }, { "code": null, "e": 1971, "s": 1960, "text": "Example 1:" }, { "code": null, "e": 1980, "s": 1971, "text": "index.js" }, { "code": "// Requiring moduleconst fs = require(\"fs-extra\"); // Function to check// if directory exists// or notconst dirExists = (dir) => { if (fs.existsSync(dir)) { return \"Directory exists\"; } else { return \"Directory do not exist\"; }}; // This directory// already exists so// function will not// do anythingconst dir = \"dir\"; // Checking before// calling functionconst before = dirExists(dir);console.log(`Before function call ${before}`); // Function callfs.ensureDirSync(dir); // Checking after// calling functionconst after = dirExists(dir);console.log(`After function call ${after}`);", "e": 2579, "s": 1980, "text": null }, { "code": null, "e": 2587, "s": 2579, "text": "Output:" }, { "code": null, "e": 2598, "s": 2587, "text": "Example 2:" }, { "code": null, "e": 2607, "s": 2598, "text": "index.js" }, { "code": "// Requiring moduleconst fs = require(\"fs-extra\"); // Function to check// if directory exists// or notconst dirExists = (dir) => { if (fs.existsSync(dir)) { return \"Directory exists\"; } else { return \"Directory do not exist\"; }}; // This directory// do not exists so// function will create// the directoryconst dir = \"direc/dir\"; const mode = 0o2775; // Checking before// calling functionconst before = dirExists(dir);console.log(`Before function call ${before}`); // Function callfs.ensureDirSync(dir, mode); // Checking after// calling functionconst after = dirExists(dir);console.log(`After function call ${after}`);", "e": 3245, "s": 2607, "text": null }, { "code": null, "e": 3253, "s": 3245, "text": "Output:" }, { "code": null, "e": 3343, "s": 3253, "text": "Reference: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureDir-sync.md" }, { "code": null, "e": 3359, "s": 3343, "text": "NodeJS-fs-extra" }, { "code": null, "e": 3375, "s": 3359, "text": "NodeJS-function" }, { "code": null, "e": 3383, "s": 3375, "text": "Node.js" }, { "code": null, "e": 3400, "s": 3383, "text": "Web Technologies" } ]
Python | Remove random element from list
27 Sep, 2019 Sometimes, while working with Python lists, we can have a problem or part of it, in which we desire to convert a list after deletion of some random element. This can have it’s application in gaming domain or personal projects. Let’s discuss certain way in which this task can be done. Method : Using randrange() + pop()In this, we just combine the functionality of above functions into one and achieve this task. The random element is chosen by randrange() and then is accessed and removed from the list using pop() # Python3 code to demonstrate working of# Remove random element from list# Using randrange() + pop()import random # initializing list test_list = [6, 4, 8, 9, 10] # printing list print("The original list : " + str(test_list)) # Remove random element from list# Using randrange() + pop()test_list.pop(random.randrange(len(test_list))) # Printing resultprint("List after removal of random number : " + str(test_list)) The original list : [6, 4, 8, 9, 10] List after removal of random number : [6, 4, 8, 10] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2019" }, { "code": null, "e": 313, "s": 28, "text": "Sometimes, while working with Python lists, we can have a problem or part of it, in which we desire to convert a list after deletion of some random element. This can have it’s application in gaming domain or personal projects. Let’s discuss certain way in which this task can be done." }, { "code": null, "e": 544, "s": 313, "text": "Method : Using randrange() + pop()In this, we just combine the functionality of above functions into one and achieve this task. The random element is chosen by randrange() and then is accessed and removed from the list using pop()" }, { "code": "# Python3 code to demonstrate working of# Remove random element from list# Using randrange() + pop()import random # initializing list test_list = [6, 4, 8, 9, 10] # printing list print(\"The original list : \" + str(test_list)) # Remove random element from list# Using randrange() + pop()test_list.pop(random.randrange(len(test_list))) # Printing resultprint(\"List after removal of random number : \" + str(test_list))", "e": 964, "s": 544, "text": null }, { "code": null, "e": 1056, "s": 964, "text": " \nThe original list : [6, 4, 8, 9, 10]\nList after removal of random number : [6, 4, 8, 10]\n" }, { "code": null, "e": 1077, "s": 1056, "text": "Python list-programs" }, { "code": null, "e": 1084, "s": 1077, "text": "Python" }, { "code": null, "e": 1100, "s": 1084, "text": "Python Programs" } ]
Program to calculate Percentile of Students
21 Apr, 2021 Given an array containing marks of students, the task is to calculate the percentile of the students. The percentile is calculated according to the following rule: The percentile of a student is the % of the number of students having marks less than him/her. Examples: Input: arr[] = { 12, 60, 80, 71, 30 }Output: { 0, 50, 100, 75, 25 }Explanation: Percentile of Student 1 = 0/4*100 = 0 (out of other 4 students no one has marks less than this student) Percentile of Student 2 = 2/4*100 = 50 (out of other 4 students, 2 have marks less than this student) Percentile of Student 3 = 4/4*100 = 100 (out of other 4 students, all 4 have marks less than this student) Percentile of Student 4 = 3/4*100 = 75 (out of other 4 students, 3 have marks less than this student) Percentile of Student 5 = 1/4*100 = 25 (out of other 4 students only 1 has marks less than this student) Approach: So basically, the percentile is a number where a certain percentage of scores fall below that number. For example: If in an examination a student’s percentile is 75 then it means that the student has scored more than 75% of students who took the test. Now, in order to calculate percentile we have the following formula:PERCENTILE = (NUMBER OF STUDENTS WHO SCORED BELOW OR EQUAL TO THE DESIRED STUDENT/ TOTAL NUMBER OF STUDENTS – 1) * 100 Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program to calculate Percentile of Students #include <bits/stdc++.h>using namespace std; // Function to calculate the percentilevoid percentile(int arr[], int n){ int i, j, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); cout << "\nPercentile of Student " << i + 1 << " = " << percent; }} // Driver Codeint main(){ int StudentMarks[] = { 12, 60, 80, 71, 30 }; int n = sizeof(StudentMarks) / sizeof(StudentMarks[0]); percentile(StudentMarks, n); return 0;} // Java program to calculate Percentile of Studentsclass GFG{ // Function to calculate the percentile static void percentile(int arr[], int n) { int i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); System.out.print("\nPercentile of Student " + (i + 1) + " = " + percent); } } // Driver Code public static void main(String[] args) { int[] StudentMarks = { 12, 60, 80, 71, 30 }; int n = StudentMarks.length; percentile(StudentMarks, n); }} // This code is contributed by Rajput-Ji # Python3 program to calculate Percentile of Students # Function to calculate the percentiledef percentile(arr, n): i, j = 0, 0 count, percent = 0, 0 # Start of the loop that calculates percentile while i < n: count = 0 j = 0 while j < n: # Comparing the marks of student i # with all other students if (arr[i] > arr[j]): count += 1 j += 1 percent = (count * 100) // (n - 1) print("Percentile of Student ", i + 1," = ", percent) i += 1 # Driver Code StudentMarks = [12, 60, 80, 71, 30]n = len(StudentMarks)percentile(StudentMarks, n) # This code is contributed by mohit kumar 29 // C# program to calculate Percentile of Studentsusing System; class GFG{ // Function to calculate the percentile static void percentile(int []arr, int n) { int i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); Console.Write("\nPercentile of Student " + (i + 1) + " = " + percent); } } // Driver Code public static void Main() { int[] StudentMarks = {12, 60, 80, 71, 30}; int n = StudentMarks.Length; percentile(StudentMarks, n); }} // This code is contributed by AnkitRai01 <script> // Javascript program to calculate// Percentile of Students // Function to calculate the percentilefunction percentile(arr, n){ var i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (var j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); document.write("\nPercentile of Student " + (i + 1) + " = " + percent + "<br>"); }} // Driver Codevar StudentMarks = [ 12, 60, 80, 71, 30 ];var n = StudentMarks.length; percentile(StudentMarks, n); // This code is contributed by Khushboogoyal499 </script> Percentile of Student 1 = 0 Percentile of Student 2 = 50 Percentile of Student 3 = 100 Percentile of Student 4 = 75 Percentile of Student 5 = 25 mohit kumar 29 Rajput-Ji ankthon khushboogoyal499 Arrays School Programming Arrays 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": 194, "s": 28, "text": "Given an array containing marks of students, the task is to calculate the percentile of the students. The percentile is calculated according to the following rule: " }, { "code": null, "e": 289, "s": 194, "text": "The percentile of a student is the % of the number of students having marks less than him/her." }, { "code": null, "e": 301, "s": 289, "text": "Examples: " }, { "code": null, "e": 903, "s": 301, "text": "Input: arr[] = { 12, 60, 80, 71, 30 }Output: { 0, 50, 100, 75, 25 }Explanation: Percentile of Student 1 = 0/4*100 = 0 (out of other 4 students no one has marks less than this student) Percentile of Student 2 = 2/4*100 = 50 (out of other 4 students, 2 have marks less than this student) Percentile of Student 3 = 4/4*100 = 100 (out of other 4 students, all 4 have marks less than this student) Percentile of Student 4 = 3/4*100 = 75 (out of other 4 students, 3 have marks less than this student) Percentile of Student 5 = 1/4*100 = 25 (out of other 4 students only 1 has marks less than this student) " }, { "code": null, "e": 917, "s": 905, "text": "Approach: " }, { "code": null, "e": 1021, "s": 917, "text": "So basically, the percentile is a number where a certain percentage of scores fall below that number. " }, { "code": null, "e": 1173, "s": 1021, "text": "For example: If in an examination a student’s percentile is 75 then it means that the student has scored more than 75% of students who took the test. " }, { "code": null, "e": 1362, "s": 1173, "text": "Now, in order to calculate percentile we have the following formula:PERCENTILE = (NUMBER OF STUDENTS WHO SCORED BELOW OR EQUAL TO THE DESIRED STUDENT/ TOTAL NUMBER OF STUDENTS – 1) * 100 " }, { "code": null, "e": 1414, "s": 1362, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1418, "s": 1414, "text": "C++" }, { "code": null, "e": 1423, "s": 1418, "text": "Java" }, { "code": null, "e": 1430, "s": 1423, "text": "Python" }, { "code": null, "e": 1433, "s": 1430, "text": "C#" }, { "code": null, "e": 1444, "s": 1433, "text": "Javascript" }, { "code": "// C++ program to calculate Percentile of Students #include <bits/stdc++.h>using namespace std; // Function to calculate the percentilevoid percentile(int arr[], int n){ int i, j, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); cout << \"\\nPercentile of Student \" << i + 1 << \" = \" << percent; }} // Driver Codeint main(){ int StudentMarks[] = { 12, 60, 80, 71, 30 }; int n = sizeof(StudentMarks) / sizeof(StudentMarks[0]); percentile(StudentMarks, n); return 0;}", "e": 2259, "s": 1444, "text": null }, { "code": "// Java program to calculate Percentile of Studentsclass GFG{ // Function to calculate the percentile static void percentile(int arr[], int n) { int i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); System.out.print(\"\\nPercentile of Student \" + (i + 1) + \" = \" + percent); } } // Driver Code public static void main(String[] args) { int[] StudentMarks = { 12, 60, 80, 71, 30 }; int n = StudentMarks.length; percentile(StudentMarks, n); }} // This code is contributed by Rajput-Ji", "e": 3214, "s": 2259, "text": null }, { "code": "# Python3 program to calculate Percentile of Students # Function to calculate the percentiledef percentile(arr, n): i, j = 0, 0 count, percent = 0, 0 # Start of the loop that calculates percentile while i < n: count = 0 j = 0 while j < n: # Comparing the marks of student i # with all other students if (arr[i] > arr[j]): count += 1 j += 1 percent = (count * 100) // (n - 1) print(\"Percentile of Student \", i + 1,\" = \", percent) i += 1 # Driver Code StudentMarks = [12, 60, 80, 71, 30]n = len(StudentMarks)percentile(StudentMarks, n) # This code is contributed by mohit kumar 29", "e": 3910, "s": 3214, "text": null }, { "code": "// C# program to calculate Percentile of Studentsusing System; class GFG{ // Function to calculate the percentile static void percentile(int []arr, int n) { int i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (int j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); Console.Write(\"\\nPercentile of Student \" + (i + 1) + \" = \" + percent); } } // Driver Code public static void Main() { int[] StudentMarks = {12, 60, 80, 71, 30}; int n = StudentMarks.Length; percentile(StudentMarks, n); }} // This code is contributed by AnkitRai01", "e": 4859, "s": 3910, "text": null }, { "code": "<script> // Javascript program to calculate// Percentile of Students // Function to calculate the percentilefunction percentile(arr, n){ var i, count, percent; // Start of the loop that calculates percentile for (i = 0; i < n; i++) { count = 0; for (var j = 0; j < n; j++) { // Comparing the marks of student i // with all other students if (arr[i] > arr[j]) { count++; } } percent = (count * 100) / (n - 1); document.write(\"\\nPercentile of Student \" + (i + 1) + \" = \" + percent + \"<br>\"); }} // Driver Codevar StudentMarks = [ 12, 60, 80, 71, 30 ];var n = StudentMarks.length; percentile(StudentMarks, n); // This code is contributed by Khushboogoyal499 </script>", "e": 5666, "s": 4859, "text": null }, { "code": null, "e": 5811, "s": 5666, "text": "Percentile of Student 1 = 0\nPercentile of Student 2 = 50\nPercentile of Student 3 = 100\nPercentile of Student 4 = 75\nPercentile of Student 5 = 25" }, { "code": null, "e": 5828, "s": 5813, "text": "mohit kumar 29" }, { "code": null, "e": 5838, "s": 5828, "text": "Rajput-Ji" }, { "code": null, "e": 5846, "s": 5838, "text": "ankthon" }, { "code": null, "e": 5863, "s": 5846, "text": "khushboogoyal499" }, { "code": null, "e": 5870, "s": 5863, "text": "Arrays" }, { "code": null, "e": 5889, "s": 5870, "text": "School Programming" }, { "code": null, "e": 5896, "s": 5889, "text": "Arrays" } ]
jQuery change() with Example
The change() method in jQuery is used to trigger the change event. It occurs when the value of an element has been changed. The syntax is as follows − $(selector).change() Let us now see an example to implement the jQuery change() method − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".demo").change(function() { $(this).css("background-color", "red"); }); }); </script> </head> <body> <h2>Login</h2> Enter Username: <input type="text" class="demo"><br> Enter Password: <input type="password"> </body> </html> This will produce the following output − Write some text in the first input and press enter −
[ { "code": null, "e": 1311, "s": 1187, "text": "The change() method in jQuery is used to trigger the change event. It occurs when the value of an element has been changed." }, { "code": null, "e": 1338, "s": 1311, "text": "The syntax is as follows −" }, { "code": null, "e": 1359, "s": 1338, "text": "$(selector).change()" }, { "code": null, "e": 1427, "s": 1359, "text": "Let us now see an example to implement the jQuery change() method −" }, { "code": null, "e": 1438, "s": 1427, "text": " Live Demo" }, { "code": null, "e": 1852, "s": 1438, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function() {\n $(\".demo\").change(function() {\n $(this).css(\"background-color\", \"red\");\n });\n });\n</script>\n</head>\n<body>\n<h2>Login</h2>\nEnter Username:\n<input type=\"text\" class=\"demo\"><br>\nEnter Password:\n<input type=\"password\">\n</body>\n</html>" }, { "code": null, "e": 1893, "s": 1852, "text": "This will produce the following output −" }, { "code": null, "e": 1946, "s": 1893, "text": "Write some text in the first input and press enter −" } ]
Maximal Rectangle in C++
Suppose we have a 2D binary matrix where 0s and 1 values are present. We have to find the largest rectangle containing only 1s and return its area. To solve this, we will follow these steps− Define a function called getAns, this will take array a Define a function called getAns, this will take array a create stack st, i := 0, ans := 0 create stack st, i := 0, ans := 0 while i < size of a, thenif stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1otherwise −height := a[top of stack], delete from stackwidth := i when stack is empty, otherwise i – top of st – 1area := height * widthans := max of ans and area while i < size of a, then if stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1 if stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1 otherwise −height := a[top of stack], delete from stackwidth := i when stack is empty, otherwise i – top of st – 1area := height * widthans := max of ans and area otherwise − height := a[top of stack], delete from stack height := a[top of stack], delete from stack width := i when stack is empty, otherwise i – top of st – 1 width := i when stack is empty, otherwise i – top of st – 1 area := height * width area := height * width ans := max of ans and area ans := max of ans and area while st is not emptyheight := a[top of st], delete from stackwidth := size of a when st is empty, otherwise size of a – top of st – 1area := height * widthans := max of ans and area while st is not empty height := a[top of st], delete from stack height := a[top of st], delete from stack width := size of a when st is empty, otherwise size of a – top of st – 1 width := size of a when st is empty, otherwise size of a – top of st – 1 area := height * width area := height * width ans := max of ans and area ans := max of ans and area return ans return ans From the main method do the following − From the main method do the following − ans := 0, n := size of x ans := 0, n := size of x if n zero, then return 0 if n zero, then return 0 m := size of x[0] m := size of x[0] create one array height of size m create one array height of size m for i in range 0 to n – 1for j in range 0 to m – 1if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0ans := max of ans and getAns(height) for i in range 0 to n – 1 for j in range 0 to m – 1if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0 for j in range 0 to m – 1 if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0 if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0 ans := max of ans and getAns(height) ans := max of ans and getAns(height) return ans return ans Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int getAns(vector <int> a){ stack <int> st; int i = 0; int ans = 0; while(i<a.size()){ if(st.empty()||a[i]>=a[st.top()]){ st.push(i); i++; } else{ int height = a[st.top()]; st.pop(); int width = st.empty()?i:i-st.top()-1; int area = height * width; ans = max(ans,area); } } while(!st.empty()){ int height = a[st.top()]; st.pop(); int width = st.empty()?a.size():a.size() - st.top()-1; int area = height * width; ans = max(ans,area); } return ans; } int maximalRectangle(vector<vector<char>>& x) { int ans = 0; int n = x.size(); if(!n)return 0; int m = x[0].size(); vector <int> height(m);; for(int i =0;i<n;i++){ for(int j =0;j<m;j++){ if(x[i][j] == '1')height[j]++; else height[j] = 0; } ans = max(ans, getAns(height)); } return ans; } }; main(){ vector<vector<char>> v = { {'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'} }; Solution ob; cout << (ob.maximalRectangle(v)); } {{'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'} } 6
[ { "code": null, "e": 1335, "s": 1187, "text": "Suppose we have a 2D binary matrix where 0s and 1 values are present. We have to find the largest rectangle containing only 1s and return its area." }, { "code": null, "e": 1378, "s": 1335, "text": "To solve this, we will follow these steps−" }, { "code": null, "e": 1434, "s": 1378, "text": "Define a function called getAns, this will take array a" }, { "code": null, "e": 1490, "s": 1434, "text": "Define a function called getAns, this will take array a" }, { "code": null, "e": 1524, "s": 1490, "text": "create stack st, i := 0, ans := 0" }, { "code": null, "e": 1558, "s": 1524, "text": "create stack st, i := 0, ans := 0" }, { "code": null, "e": 1827, "s": 1558, "text": "while i < size of a, thenif stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1otherwise −height := a[top of stack], delete from stackwidth := i when stack is empty, otherwise i – top of st – 1area := height * widthans := max of ans and area" }, { "code": null, "e": 1853, "s": 1827, "text": "while i < size of a, then" }, { "code": null, "e": 1935, "s": 1853, "text": "if stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1" }, { "code": null, "e": 2017, "s": 1935, "text": "if stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1" }, { "code": null, "e": 2180, "s": 2017, "text": "otherwise −height := a[top of stack], delete from stackwidth := i when stack is empty, otherwise i – top of st – 1area := height * widthans := max of ans and area" }, { "code": null, "e": 2192, "s": 2180, "text": "otherwise −" }, { "code": null, "e": 2237, "s": 2192, "text": "height := a[top of stack], delete from stack" }, { "code": null, "e": 2282, "s": 2237, "text": "height := a[top of stack], delete from stack" }, { "code": null, "e": 2342, "s": 2282, "text": "width := i when stack is empty, otherwise i – top of st – 1" }, { "code": null, "e": 2402, "s": 2342, "text": "width := i when stack is empty, otherwise i – top of st – 1" }, { "code": null, "e": 2425, "s": 2402, "text": "area := height * width" }, { "code": null, "e": 2448, "s": 2425, "text": "area := height * width" }, { "code": null, "e": 2475, "s": 2448, "text": "ans := max of ans and area" }, { "code": null, "e": 2502, "s": 2475, "text": "ans := max of ans and area" }, { "code": null, "e": 2685, "s": 2502, "text": "while st is not emptyheight := a[top of st], delete from stackwidth := size of a when st is empty, otherwise size of a – top of st – 1area := height * widthans := max of ans and area" }, { "code": null, "e": 2707, "s": 2685, "text": "while st is not empty" }, { "code": null, "e": 2749, "s": 2707, "text": "height := a[top of st], delete from stack" }, { "code": null, "e": 2791, "s": 2749, "text": "height := a[top of st], delete from stack" }, { "code": null, "e": 2864, "s": 2791, "text": "width := size of a when st is empty, otherwise size of a – top of st – 1" }, { "code": null, "e": 2937, "s": 2864, "text": "width := size of a when st is empty, otherwise size of a – top of st – 1" }, { "code": null, "e": 2960, "s": 2937, "text": "area := height * width" }, { "code": null, "e": 2983, "s": 2960, "text": "area := height * width" }, { "code": null, "e": 3010, "s": 2983, "text": "ans := max of ans and area" }, { "code": null, "e": 3037, "s": 3010, "text": "ans := max of ans and area" }, { "code": null, "e": 3048, "s": 3037, "text": "return ans" }, { "code": null, "e": 3059, "s": 3048, "text": "return ans" }, { "code": null, "e": 3099, "s": 3059, "text": "From the main method do the following −" }, { "code": null, "e": 3139, "s": 3099, "text": "From the main method do the following −" }, { "code": null, "e": 3164, "s": 3139, "text": "ans := 0, n := size of x" }, { "code": null, "e": 3189, "s": 3164, "text": "ans := 0, n := size of x" }, { "code": null, "e": 3214, "s": 3189, "text": "if n zero, then return 0" }, { "code": null, "e": 3239, "s": 3214, "text": "if n zero, then return 0" }, { "code": null, "e": 3257, "s": 3239, "text": "m := size of x[0]" }, { "code": null, "e": 3275, "s": 3257, "text": "m := size of x[0]" }, { "code": null, "e": 3309, "s": 3275, "text": "create one array height of size m" }, { "code": null, "e": 3343, "s": 3309, "text": "create one array height of size m" }, { "code": null, "e": 3500, "s": 3343, "text": "for i in range 0 to n – 1for j in range 0 to m – 1if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0ans := max of ans and getAns(height)" }, { "code": null, "e": 3526, "s": 3500, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 3622, "s": 3526, "text": "for j in range 0 to m – 1if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0" }, { "code": null, "e": 3648, "s": 3622, "text": "for j in range 0 to m – 1" }, { "code": null, "e": 3719, "s": 3648, "text": "if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0" }, { "code": null, "e": 3790, "s": 3719, "text": "if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0" }, { "code": null, "e": 3827, "s": 3790, "text": "ans := max of ans and getAns(height)" }, { "code": null, "e": 3864, "s": 3827, "text": "ans := max of ans and getAns(height)" }, { "code": null, "e": 3875, "s": 3864, "text": "return ans" }, { "code": null, "e": 3886, "s": 3875, "text": "return ans" }, { "code": null, "e": 3958, "s": 3886, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 3969, "s": 3958, "text": " Live Demo" }, { "code": null, "e": 5309, "s": 3969, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int getAns(vector <int> a){\n stack <int> st;\n int i = 0;\n int ans = 0;\n while(i<a.size()){\n if(st.empty()||a[i]>=a[st.top()]){\n st.push(i);\n i++;\n } else{\n int height = a[st.top()];\n st.pop();\n int width = st.empty()?i:i-st.top()-1;\n int area = height * width;\n ans = max(ans,area);\n }\n }\n while(!st.empty()){\n int height = a[st.top()];\n st.pop();\n int width = st.empty()?a.size():a.size() - st.top()-1;\n int area = height * width;\n ans = max(ans,area);\n }\n return ans;\n }\n int maximalRectangle(vector<vector<char>>& x) {\n int ans = 0;\n int n = x.size();\n if(!n)return 0;\n int m = x[0].size();\n vector <int> height(m);;\n for(int i =0;i<n;i++){\n for(int j =0;j<m;j++){\n if(x[i][j] == '1')height[j]++;\n else height[j] = 0;\n }\n ans = max(ans, getAns(height));\n }\n return ans;\n }\n};\nmain(){\n vector<vector<char>> v = {\n {'1','0','1','0','0'},\n {'1','0','1','1','1'},\n {'1','1','1','1','1'},\n {'1','0','0','1','0'}\n };\n Solution ob;\n cout << (ob.maximalRectangle(v));\n}" }, { "code": null, "e": 5403, "s": 5309, "text": "{{'1','0','1','0','0'},\n{'1','0','1','1','1'},\n{'1','1','1','1','1'},\n{'1','0','0','1','0'}\n}" }, { "code": null, "e": 5405, "s": 5403, "text": "6" } ]
Divide array into two parts with equal sum according to the given constraints
06 May, 2019 Given an array arr[] of N integers, the task is to select an integer x (which may or may not be present in the array) and remove all of its occurrences from the array and divide the remaining array into two non-empty sub-sets such that: The elements of the first set are strictly smaller than x.The elements of the second set are strictly greater than x.The sum of the elements of both the sets is equal.If such an integer exists then print Yes otherwise print No.Examples:Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets.Input: arr[] = {2, 1}Output: NoRecommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal.Below is the implementation of the above approach:C++JavaPython3C#PHPC++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << "Yes"; else cout << "No";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;}Java// Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println("Yes"); else System.out.println("No"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab KunduPython3# Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print("Yes"); else : print("No"); # Driver code if __name__ == "__main__" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by RyugaC#// C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine("Yes"); else Console.WriteLine("No"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech.PHP<?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo "Yes"; else echo "No";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?>Output:Yes My Personal Notes arrow_drop_upSave The elements of the first set are strictly smaller than x. The elements of the second set are strictly greater than x. The sum of the elements of both the sets is equal. If such an integer exists then print Yes otherwise print No.Examples:Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets.Input: arr[] = {2, 1}Output: NoRecommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal.Below is the implementation of the above approach:C++JavaPython3C#PHPC++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << "Yes"; else cout << "No";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;}Java// Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println("Yes"); else System.out.println("No"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab KunduPython3# Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print("Yes"); else : print("No"); # Driver code if __name__ == "__main__" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by RyugaC#// C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine("Yes"); else Console.WriteLine("No"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech.PHP<?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo "Yes"; else echo "No";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?>Output:Yes My Personal Notes arrow_drop_upSave Examples: Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets. Input: arr[] = {2, 1}Output: No Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal. Below is the implementation of the above approach: C++ Java Python3 C# PHP // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << "Yes"; else cout << "No";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;} // Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println("Yes"); else System.out.println("No"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print("Yes"); else : print("No"); # Driver code if __name__ == "__main__" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by Ryuga // C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine("Yes"); else Console.WriteLine("No"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech. <?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo "Yes"; else echo "No";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?> Yes ankthon andrew1234 Code_Mech ihritik Binary Search Algorithms Searching Sorting Searching Sorting Binary Search Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 54, "s": 26, "text": "\n06 May, 2019" }, { "code": null, "e": 291, "s": 54, "text": "Given an array arr[] of N integers, the task is to select an integer x (which may or may not be present in the array) and remove all of its occurrences from the array and divide the remaining array into two non-empty sub-sets such that:" }, { "code": null, "e": 11194, "s": 291, "text": "The elements of the first set are strictly smaller than x.The elements of the second set are strictly greater than x.The sum of the elements of both the sets is equal.If such an integer exists then print Yes otherwise print No.Examples:Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets.Input: arr[] = {2, 1}Output: NoRecommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal.Below is the implementation of the above approach:C++JavaPython3C#PHPC++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << \"Yes\"; else cout << \"No\";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;}Java// Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab KunduPython3# Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print(\"Yes\"); else : print(\"No\"); # Driver code if __name__ == \"__main__\" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by RyugaC#// C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech.PHP<?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo \"Yes\"; else echo \"No\";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?>Output:Yes\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 11253, "s": 11194, "text": "The elements of the first set are strictly smaller than x." }, { "code": null, "e": 11313, "s": 11253, "text": "The elements of the second set are strictly greater than x." }, { "code": null, "e": 11364, "s": 11313, "text": "The sum of the elements of both the sets is equal." }, { "code": null, "e": 22100, "s": 11364, "text": "If such an integer exists then print Yes otherwise print No.Examples:Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets.Input: arr[] = {2, 1}Output: NoRecommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal.Below is the implementation of the above approach:C++JavaPython3C#PHPC++// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << \"Yes\"; else cout << \"No\";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;}Java// Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab KunduPython3# Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print(\"Yes\"); else : print(\"No\"); # Driver code if __name__ == \"__main__\" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by RyugaC#// C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech.PHP<?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo \"Yes\"; else echo \"No\";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?>Output:Yes\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 22110, "s": 22100, "text": "Examples:" }, { "code": null, "e": 22283, "s": 22110, "text": "Input: arr[] = {1, 2, 2, 5}Output: YesChoose x = 3, after removing all of its occurrences the array becomes arr[] = {1, 2, 2, 5}{1, 2, 2} and {5} are the required sub-sets." }, { "code": null, "e": 22315, "s": 22283, "text": "Input: arr[] = {2, 1}Output: No" }, { "code": null, "e": 22675, "s": 22315, "text": "Approach: The idea is to first sort the array and for all the numbers lying between 1 to maximum number present in the array, apply binary search and check if on removing all its occurrences from the array, sum of elements present on its left side (which are smaller than it) and sum of elements present on the right side (which are greater than it) is equal." }, { "code": null, "e": 22726, "s": 22675, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 22730, "s": 22726, "text": "C++" }, { "code": null, "e": 22735, "s": 22730, "text": "Java" }, { "code": null, "e": 22743, "s": 22735, "text": "Python3" }, { "code": null, "e": 22746, "s": 22743, "text": "C#" }, { "code": null, "e": 22750, "s": 22746, "text": "PHP" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that checks if the given// conditions are satisfiedvoid IfExists(int arr[], int n){ // To store the prefix sum // of the array elements int sum[n]; // Sort the array sort(arr, arr + n); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) cout << \"Yes\"; else cout << \"No\";} // Driver codeint main(){ int arr[] = { 1, 2, 2, 5 }; int n = sizeof(arr) / sizeof(int); IfExists(arr, n); return 0;}", "e": 24643, "s": 22750, "text": null }, { "code": "// Java implementation of the approach import java.util.*; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int arr[], int n) { // To store the prefix sum // of the array elements int sum[] = new int[n]; // Sort the array Arrays.sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number boolean flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) System.out.println(\"Yes\"); else System.out.println(\"No\"); } // Driver code public static void main(String args[]){ int arr[] = { 1, 2, 2, 5 }; int n = arr.length; IfExists(arr, n); }} // This code is contributed by Arnab Kundu", "e": 26733, "s": 24643, "text": null }, { "code": "# Python3 implementation of the approach # Function that checks if the given # conditions are satisfied def IfExists(arr, n) : # To store the prefix sum # of the array elements sum = [0] * n; # Sort the array arr.sort(); sum[0] = arr[0]; # Compute the prefix sum array for i in range(1, n) : sum[i] = sum[i - 1] + arr[i]; # Maximum element in the array max = arr[n - 1]; # Variable to check if there # exists any number flag = False; for i in range(1, max + 1) : # Stores the index of the largest # number present in the array # smaller than i findex = 0; # Stores the index of the smallest # number present in the array # greater than i lindex = 0; l = 0; r = n - 1; # Find index of smallest number # greater than i while (l <= r) : m = (l + r) // 2; if (arr[m] < i) : findex = m; l = m + 1; else : r = m - 1; l = 1; r = n; flag = False; # Find index of smallest number # greater than i while (l <= r) : m = (r + l) // 2; if (arr[m] > i) : lindex = m; r = m - 1; else : l = m + 1; # If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) : flag = True; break; # If no such number exists # print no if (flag) : print(\"Yes\"); else : print(\"No\"); # Driver code if __name__ == \"__main__\" : arr = [ 1, 2, 2, 5 ]; n = len(arr) ; IfExists(arr, n); # This code is contributed by Ryuga", "e": 28621, "s": 26733, "text": null }, { "code": "// C# implementation of the approach using System; class GFG{ // Function that checks if the given // conditions are satisfied static void IfExists(int[] arr, int n) { // To store the prefix sum // of the array elements int[] sum = new int[n]; // Sort the array Array.Sort(arr); sum[0] = arr[0]; // Compute the prefix sum array for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // Maximum element in the array int max = arr[n - 1]; // Variable to check if there exists any number bool flag = false; for (int i = 1; i <= max; i++) { // Stores the index of the largest // number present in the array // smaller than i int findex = 0; // Stores the index of the smallest // number present in the array // greater than i int lindex = 0; int l = 0; int r = n - 1; // Find index of smallest number // greater than i while (l <= r) { int m = (l + r) / 2; if (arr[m] < i) { findex = m; l = m + 1; } else r = m - 1; } l = 1; r = n; flag = false; // Find index of smallest number // greater than i while (l <= r) { int m = (r + l) / 2; if (arr[m] > i) { lindex = m; r = m - 1; } else l = m + 1; } // If there exists a number if (sum[findex] == sum[n - 1] - sum[lindex - 1]) { flag = true; break; } } // If no such number exists // print no if (flag) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } // Driver code public static void Main(){ int[] arr = { 1, 2, 2, 5 }; int n = arr.Length; IfExists(arr, n); }} // This code is contributed by Code_Mech.", "e": 30687, "s": 28621, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that checks if the given// conditions are satisfiedfunction IfExists($arr, $n){ // To store the prefix $sum // of the array elements $sum = array_fill(0, $n, 0); // Sort the array sort($arr); $sum[0] = $arr[0]; // Compute the prefix sum array for ($i = 1; $i < $n; $i++) $sum[$i] = $sum[$i - 1] + $arr[$i]; // Maximum element in the array $max = $arr[$n - 1]; // Variable to check if there exists any number $flag = false; for ($i = 1; $i <= $max; $i++) { // Stores the index of the largest // number present in the array // smaller than i $findex = 0; // Stores the index of the smallest // number present in the array // greater than i $lindex = 0; $l = 0; $r = $n - 1; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($l + $r) / 2; if ($arr[$m] < $i) { $findex = $m; $l = $m + 1; } else $r = $m - 1; } $l = 1; $r = $n; $flag = false; // Find index of smallest number // greater than i while ($l <= $r) { $m = ($r + $l) / 2; if ($arr[$m] > $i) { $lindex = $m; $r = $m - 1; } else $l = $m + 1; } // If there exists a number if ($sum[$findex] == $sum[$n - 1] - $sum[$lindex - 1]) { $flag = true; break; } } // If no such number exists // print no if ($flag == true) echo \"Yes\"; else echo \"No\";} // Driver code$arr = array(1, 2, 2, 5 );$n = sizeof($arr);IfExists($arr, $n); // This code is contributed by ihritik?>", "e": 32638, "s": 30687, "text": null }, { "code": null, "e": 32643, "s": 32638, "text": "Yes\n" }, { "code": null, "e": 32651, "s": 32643, "text": "ankthon" }, { "code": null, "e": 32662, "s": 32651, "text": "andrew1234" }, { "code": null, "e": 32672, "s": 32662, "text": "Code_Mech" }, { "code": null, "e": 32680, "s": 32672, "text": "ihritik" }, { "code": null, "e": 32694, "s": 32680, "text": "Binary Search" }, { "code": null, "e": 32705, "s": 32694, "text": "Algorithms" }, { "code": null, "e": 32715, "s": 32705, "text": "Searching" }, { "code": null, "e": 32723, "s": 32715, "text": "Sorting" }, { "code": null, "e": 32733, "s": 32723, "text": "Searching" }, { "code": null, "e": 32741, "s": 32733, "text": "Sorting" }, { "code": null, "e": 32755, "s": 32741, "text": "Binary Search" }, { "code": null, "e": 32766, "s": 32755, "text": "Algorithms" }, { "code": null, "e": 32864, "s": 32766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32902, "s": 32864, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 32970, "s": 32902, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 32997, "s": 32970, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33040, "s": 32997, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 33107, "s": 33040, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33121, "s": 33107, "text": "Binary Search" }, { "code": null, "e": 33189, "s": 33121, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33203, "s": 33189, "text": "Linear Search" }, { "code": null, "e": 33259, "s": 33203, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Risk Management for Information Security | Set-1
18 Jan, 2022 Prerequisite – Threat Modelling A risk is nothing but intersection of assets, threats and vulnerability. A+T+V = R NIST SP 800-30 Risk Management Guide for Information Technology Practitioners defines risk as a function of the likelihood of a given threat-source exercising a particular potential vulnerability, and the resulting impact of that adverse event on the organization. So the main components of Risk Assessment are: Threats Vulnerability Impact (i.e. potential loss) Likelihood of occurrence (i.e. the probability that an event – threat successful exploit of a vulnerability – will occur) Threats is anything that can exploit a vulnerability accidentally or intentionally and destroy or damage an asset. Asset can be anything people, property or information. Asset is what we are trying to protect and a threat is what we are trying to protect against. Vulnerability means gap or weakness in our protection efforts. Threat Source is a method to exploit a vulnerability or a situation either intentionally or unintentionally. For example a Malicious Software to which a virus or worm attaches to spread itself in the system and to others computer via email containing either virus as a attachment or as a link. If this email is shared by sender without knowing the malicious purpose of attachment or link then, this will be unintentional threat source otherwise it will be an intentional threat source. The complete process of handling Risk can be divided into following stages: Context EstablishmentRisk Assessment Risk IdentificationRisk EstimationRisk EvaluationRisk Management/ Mitigation Risk AssumptionRisk AvoidanceRisk LimitationRisk PlanningResearch and AcknowledgementRisk TransferenceRisk CommunicationRisk Monitoring and ReviewIT Evaluation and Assessment Context Establishment Risk Assessment Risk IdentificationRisk EstimationRisk Evaluation Risk Identification Risk Estimation Risk Evaluation Risk Management/ Mitigation Risk AssumptionRisk AvoidanceRisk LimitationRisk PlanningResearch and AcknowledgementRisk Transference Risk Assumption Risk Avoidance Risk Limitation Risk Planning Research and Acknowledgement Risk Transference Risk Communication Risk Monitoring and Review IT Evaluation and Assessment 1. Context Establishment – In this step information about the organization and basic criteria, purpose, scope and boundaries of risk management activities are obtained. In addition to this data, it is important to gather details about the organization in charge of risk management activities. Organization’s mission, values, structure, strategy, locations and cultural environment are studied to have a deep understanding of it’s scope and boundaries. The constraints (budgetary, cultural, political, technical) of the organization are to be collected and documented as guide for next steps. The main role inside organization in charge of risk management activities can be seen as: Senior ManagementChief information officer (CIO)System and Information ownersthe business and functional managersthe Information System Security Officer (ISSO) or Chief information security officer (CISO)IT Security PractitionersSecurity Awareness Trainers Senior Management Chief information officer (CIO) System and Information owners the business and functional managers the Information System Security Officer (ISSO) or Chief information security officer (CISO) IT Security Practitioners Security Awareness Trainers Risk Management for Information Security | Set-2 clintra rkbhola5 Information-Security Computer Networks GBlog Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C GSM in Wireless Communication DSA Sheet by Love Babbar Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge Practice for cracking any coding interview
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2022" }, { "code": null, "e": 61, "s": 28, "text": "Prerequisite – Threat Modelling " }, { "code": null, "e": 136, "s": 61, "text": "A risk is nothing but intersection of assets, threats and vulnerability. " }, { "code": null, "e": 146, "s": 136, "text": "A+T+V = R" }, { "code": null, "e": 412, "s": 146, "text": "NIST SP 800-30 Risk Management Guide for Information Technology Practitioners defines risk as a function of the likelihood of a given threat-source exercising a particular potential vulnerability, and the resulting impact of that adverse event on the organization. " }, { "code": null, "e": 461, "s": 412, "text": "So the main components of Risk Assessment are: " }, { "code": null, "e": 469, "s": 461, "text": "Threats" }, { "code": null, "e": 483, "s": 469, "text": "Vulnerability" }, { "code": null, "e": 512, "s": 483, "text": "Impact (i.e. potential loss)" }, { "code": null, "e": 634, "s": 512, "text": "Likelihood of occurrence (i.e. the probability that an event – threat successful exploit of a vulnerability – will occur)" }, { "code": null, "e": 962, "s": 634, "text": "Threats is anything that can exploit a vulnerability accidentally or intentionally and destroy or damage an asset. Asset can be anything people, property or information. Asset is what we are trying to protect and a threat is what we are trying to protect against. Vulnerability means gap or weakness in our protection efforts. " }, { "code": null, "e": 1449, "s": 962, "text": "Threat Source is a method to exploit a vulnerability or a situation either intentionally or unintentionally. For example a Malicious Software to which a virus or worm attaches to spread itself in the system and to others computer via email containing either virus as a attachment or as a link. If this email is shared by sender without knowing the malicious purpose of attachment or link then, this will be unintentional threat source otherwise it will be an intentional threat source. " }, { "code": null, "e": 1527, "s": 1449, "text": "The complete process of handling Risk can be divided into following stages: " }, { "code": null, "e": 1816, "s": 1527, "text": "Context EstablishmentRisk Assessment Risk IdentificationRisk EstimationRisk EvaluationRisk Management/ Mitigation Risk AssumptionRisk AvoidanceRisk LimitationRisk PlanningResearch and AcknowledgementRisk TransferenceRisk CommunicationRisk Monitoring and ReviewIT Evaluation and Assessment" }, { "code": null, "e": 1838, "s": 1816, "text": "Context Establishment" }, { "code": null, "e": 1904, "s": 1838, "text": "Risk Assessment Risk IdentificationRisk EstimationRisk Evaluation" }, { "code": null, "e": 1924, "s": 1904, "text": "Risk Identification" }, { "code": null, "e": 1940, "s": 1924, "text": "Risk Estimation" }, { "code": null, "e": 1956, "s": 1940, "text": "Risk Evaluation" }, { "code": null, "e": 2087, "s": 1956, "text": "Risk Management/ Mitigation Risk AssumptionRisk AvoidanceRisk LimitationRisk PlanningResearch and AcknowledgementRisk Transference" }, { "code": null, "e": 2103, "s": 2087, "text": "Risk Assumption" }, { "code": null, "e": 2118, "s": 2103, "text": "Risk Avoidance" }, { "code": null, "e": 2134, "s": 2118, "text": "Risk Limitation" }, { "code": null, "e": 2148, "s": 2134, "text": "Risk Planning" }, { "code": null, "e": 2177, "s": 2148, "text": "Research and Acknowledgement" }, { "code": null, "e": 2195, "s": 2177, "text": "Risk Transference" }, { "code": null, "e": 2214, "s": 2195, "text": "Risk Communication" }, { "code": null, "e": 2241, "s": 2214, "text": "Risk Monitoring and Review" }, { "code": null, "e": 2270, "s": 2241, "text": "IT Evaluation and Assessment" }, { "code": null, "e": 2564, "s": 2270, "text": "1. Context Establishment – In this step information about the organization and basic criteria, purpose, scope and boundaries of risk management activities are obtained. In addition to this data, it is important to gather details about the organization in charge of risk management activities. " }, { "code": null, "e": 2864, "s": 2564, "text": "Organization’s mission, values, structure, strategy, locations and cultural environment are studied to have a deep understanding of it’s scope and boundaries. The constraints (budgetary, cultural, political, technical) of the organization are to be collected and documented as guide for next steps. " }, { "code": null, "e": 2956, "s": 2864, "text": "The main role inside organization in charge of risk management activities can be seen as: " }, { "code": null, "e": 3213, "s": 2956, "text": "Senior ManagementChief information officer (CIO)System and Information ownersthe business and functional managersthe Information System Security Officer (ISSO) or Chief information security officer (CISO)IT Security PractitionersSecurity Awareness Trainers" }, { "code": null, "e": 3231, "s": 3213, "text": "Senior Management" }, { "code": null, "e": 3263, "s": 3231, "text": "Chief information officer (CIO)" }, { "code": null, "e": 3293, "s": 3263, "text": "System and Information owners" }, { "code": null, "e": 3330, "s": 3293, "text": "the business and functional managers" }, { "code": null, "e": 3422, "s": 3330, "text": "the Information System Security Officer (ISSO) or Chief information security officer (CISO)" }, { "code": null, "e": 3448, "s": 3422, "text": "IT Security Practitioners" }, { "code": null, "e": 3476, "s": 3448, "text": "Security Awareness Trainers" }, { "code": null, "e": 3526, "s": 3476, "text": "Risk Management for Information Security | Set-2 " }, { "code": null, "e": 3534, "s": 3526, "text": "clintra" }, { "code": null, "e": 3543, "s": 3534, "text": "rkbhola5" }, { "code": null, "e": 3564, "s": 3543, "text": "Information-Security" }, { "code": null, "e": 3582, "s": 3564, "text": "Computer Networks" }, { "code": null, "e": 3588, "s": 3582, "text": "GBlog" }, { "code": null, "e": 3606, "s": 3588, "text": "Computer Networks" }, { "code": null, "e": 3704, "s": 3606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3736, "s": 3704, "text": "Differences between TCP and UDP" }, { "code": null, "e": 3762, "s": 3736, "text": "Types of Network Topology" }, { "code": null, "e": 3792, "s": 3762, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 3830, "s": 3792, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3860, "s": 3830, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3885, "s": 3860, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 3959, "s": 3885, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 4014, "s": 3959, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 4051, "s": 4014, "text": "Geek Streak - 24 Days POTD Challenge" } ]
Matplotlib.ticker.MultipleLocator Class in Python
21 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a base within the view interval. Syntax: class matplotlib.ticker.MultipleLocator(base=1.0) Methods of the class: set_params(self, base): It is used for setting the parameters within the locator. tick_values(self, vmin, vmax): For a given vmin and vmax it returns the values of the located ticks. view_limits(self, dmin, dmax): It is used for setting the view limits to the nearest multiples of base that contain the data. Example 1: import matplotlib.pyplot as pltimport matplotlib.ticker as ticker x = [0, 5, 9, 10, 15]y = [0, 1, 2, 3, 4] tick_spacing = 1 fig, ax = plt.subplots(1, 1)ax.plot(x, y)ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) plt.show() Output: Example 2: import matplotlib.pyplot as pltimport matplotlib.ticker plt.plot([-1.5, 0, 1.5], [1, 3, 2])ax = plt.gca() func = lambda x, pos: str(x).rstrip('0').rstrip('.') ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.25))ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func)) plt.show() Output: Python-matplotlib Python Write From Home 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, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 374, "s": 240, "text": "The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a base within the view interval." }, { "code": null, "e": 432, "s": 374, "text": "Syntax: class matplotlib.ticker.MultipleLocator(base=1.0)" }, { "code": null, "e": 454, "s": 432, "text": "Methods of the class:" }, { "code": null, "e": 536, "s": 454, "text": "set_params(self, base): It is used for setting the parameters within the locator." }, { "code": null, "e": 637, "s": 536, "text": "tick_values(self, vmin, vmax): For a given vmin and vmax it returns the values of the located ticks." }, { "code": null, "e": 763, "s": 637, "text": "view_limits(self, dmin, dmax): It is used for setting the view limits to the nearest multiples of base that contain the data." }, { "code": null, "e": 774, "s": 763, "text": "Example 1:" }, { "code": "import matplotlib.pyplot as pltimport matplotlib.ticker as ticker x = [0, 5, 9, 10, 15]y = [0, 1, 2, 3, 4] tick_spacing = 1 fig, ax = plt.subplots(1, 1)ax.plot(x, y)ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) plt.show()", "e": 1021, "s": 774, "text": null }, { "code": null, "e": 1029, "s": 1021, "text": "Output:" }, { "code": null, "e": 1040, "s": 1029, "text": "Example 2:" }, { "code": "import matplotlib.pyplot as pltimport matplotlib.ticker plt.plot([-1.5, 0, 1.5], [1, 3, 2])ax = plt.gca() func = lambda x, pos: str(x).rstrip('0').rstrip('.') ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.25))ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func)) plt.show()", "e": 1351, "s": 1040, "text": null }, { "code": null, "e": 1359, "s": 1351, "text": "Output:" }, { "code": null, "e": 1377, "s": 1359, "text": "Python-matplotlib" }, { "code": null, "e": 1384, "s": 1377, "text": "Python" }, { "code": null, "e": 1400, "s": 1384, "text": "Write From Home" } ]
How to check file size in Python?
17 Dec, 2020 Prerequisites: os pathlib Given a file, the task here is to generate a Python Script to print its size. This article explains 2 methods to do so. Import module Get file size Name: Data.csv Size: 226 bytes Method1: Using pathlib Path().stat().st_size() function of pathlib module gets the size of any type of the file and the output of this function will be the size of the file in bytes. Syntax: Path('filename').stat().st_size() Example: Python3 from pathlib import Path sz = Path('Data.csv').stat().st_size print(sz) Output: Method 2: With Os module os.path.getsize() function only works with os Library, with the help of importing this library we can use this to get the size of any type of file and the output of this function will be the size of the file in bytes. Syntax: getsize(filename) Example: Python3 import os sz = os.path.getsize("Data.csv") print(sz) Output: We got the result as 226 bytes Picked Python file-handling-programs python-file-handling 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": 54, "s": 26, "text": "\n17 Dec, 2020" }, { "code": null, "e": 69, "s": 54, "text": "Prerequisites:" }, { "code": null, "e": 73, "s": 69, "text": "os " }, { "code": null, "e": 81, "s": 73, "text": "pathlib" }, { "code": null, "e": 201, "s": 81, "text": "Given a file, the task here is to generate a Python Script to print its size. This article explains 2 methods to do so." }, { "code": null, "e": 215, "s": 201, "text": "Import module" }, { "code": null, "e": 229, "s": 215, "text": "Get file size" }, { "code": null, "e": 244, "s": 229, "text": "Name: Data.csv" }, { "code": null, "e": 260, "s": 244, "text": "Size: 226 bytes" }, { "code": null, "e": 283, "s": 260, "text": "Method1: Using pathlib" }, { "code": null, "e": 443, "s": 283, "text": "Path().stat().st_size() function of pathlib module gets the size of any type of the file and the output of this function will be the size of the file in bytes." }, { "code": null, "e": 451, "s": 443, "text": "Syntax:" }, { "code": null, "e": 485, "s": 451, "text": "Path('filename').stat().st_size()" }, { "code": null, "e": 494, "s": 485, "text": "Example:" }, { "code": null, "e": 502, "s": 494, "text": "Python3" }, { "code": "from pathlib import Path sz = Path('Data.csv').stat().st_size print(sz)", "e": 576, "s": 502, "text": null }, { "code": null, "e": 584, "s": 576, "text": "Output:" }, { "code": null, "e": 609, "s": 584, "text": "Method 2: With Os module" }, { "code": null, "e": 827, "s": 609, "text": "os.path.getsize() function only works with os Library, with the help of importing this library we can use this to get the size of any type of file and the output of this function will be the size of the file in bytes." }, { "code": null, "e": 835, "s": 827, "text": "Syntax:" }, { "code": null, "e": 853, "s": 835, "text": "getsize(filename)" }, { "code": null, "e": 862, "s": 853, "text": "Example:" }, { "code": null, "e": 870, "s": 862, "text": "Python3" }, { "code": "import os sz = os.path.getsize(\"Data.csv\") print(sz)", "e": 925, "s": 870, "text": null }, { "code": null, "e": 933, "s": 925, "text": "Output:" }, { "code": null, "e": 964, "s": 933, "text": "We got the result as 226 bytes" }, { "code": null, "e": 971, "s": 964, "text": "Picked" }, { "code": null, "e": 1001, "s": 971, "text": "Python file-handling-programs" }, { "code": null, "e": 1022, "s": 1001, "text": "python-file-handling" }, { "code": null, "e": 1029, "s": 1022, "text": "Python" }, { "code": null, "e": 1127, "s": 1029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1172, "s": 1127, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1222, "s": 1172, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1238, "s": 1222, "text": "Deque in Python" }, { "code": null, "e": 1254, "s": 1238, "text": "Queue in Python" }, { "code": null, "e": 1276, "s": 1254, "text": "Defaultdict in Python" }, { "code": null, "e": 1318, "s": 1276, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1345, "s": 1318, "text": "Python Classes and Objects" }, { "code": null, "e": 1368, "s": 1345, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 1387, "s": 1368, "text": "reduce() in Python" } ]
Different Ways to Convert the Boolean Type in String in Golang
10 May, 2020 In order to convert Boolean Type to String type in Golang , you can use the strconv and fmt package function. 1. strconv.FormatBool() Method: The FormatBool is used to Boolean Type to String. It returns “true” or “false” according to the value of b. Syntax: func FormatBool(b bool) string Example : Convert an Boolean Type into String using strconv.FormatBool() function. Go // Go program to illustrate // How to convert the// Boolean Type into Stringpackage main import ( "fmt" "strconv") //Main Function func main() { i := true s := strconv.FormatBool(i) fmt.Printf("Type : %T \nValue : %v\n", s, s) } Output: Type : string Value : true 2. fmt.Sprintf() Method: The Sprintf is used to represents the string by formatting according to a format specifier. Syntax: func Sprintf(format string, a ...interface{}) string Example : Convert an Boolean Type into String using fmt.Sprintf() function. Go // Go program to illustrate // How to convert the// Boolean Type into Stringpackage main import ( "fmt") //Main Function func main() { i := true s := fmt.Sprintf("%v", i) fmt.Printf("Type : %T \nValue : %v\n\n", s, s) i1 := false s1 := fmt.Sprintf("%v", i1) fmt.Printf("Type : %T \nValue : %v\n", s1, s1)} Output: Type : string Value : true Type : string Value : false Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 138, "s": 28, "text": "In order to convert Boolean Type to String type in Golang , you can use the strconv and fmt package function." }, { "code": null, "e": 278, "s": 138, "text": "1. strconv.FormatBool() Method: The FormatBool is used to Boolean Type to String. It returns “true” or “false” according to the value of b." }, { "code": null, "e": 286, "s": 278, "text": "Syntax:" }, { "code": null, "e": 318, "s": 286, "text": "func FormatBool(b bool) string\n" }, { "code": null, "e": 401, "s": 318, "text": "Example : Convert an Boolean Type into String using strconv.FormatBool() function." }, { "code": null, "e": 404, "s": 401, "text": "Go" }, { "code": "// Go program to illustrate // How to convert the// Boolean Type into Stringpackage main import ( \"fmt\" \"strconv\") //Main Function func main() { i := true s := strconv.FormatBool(i) fmt.Printf(\"Type : %T \\nValue : %v\\n\", s, s) }", "e": 654, "s": 404, "text": null }, { "code": null, "e": 662, "s": 654, "text": "Output:" }, { "code": null, "e": 691, "s": 662, "text": "Type : string \nValue : true\n" }, { "code": null, "e": 808, "s": 691, "text": "2. fmt.Sprintf() Method: The Sprintf is used to represents the string by formatting according to a format specifier." }, { "code": null, "e": 816, "s": 808, "text": "Syntax:" }, { "code": null, "e": 870, "s": 816, "text": "func Sprintf(format string, a ...interface{}) string\n" }, { "code": null, "e": 946, "s": 870, "text": "Example : Convert an Boolean Type into String using fmt.Sprintf() function." }, { "code": null, "e": 949, "s": 946, "text": "Go" }, { "code": "// Go program to illustrate // How to convert the// Boolean Type into Stringpackage main import ( \"fmt\") //Main Function func main() { i := true s := fmt.Sprintf(\"%v\", i) fmt.Printf(\"Type : %T \\nValue : %v\\n\\n\", s, s) i1 := false s1 := fmt.Sprintf(\"%v\", i1) fmt.Printf(\"Type : %T \\nValue : %v\\n\", s1, s1)}", "e": 1287, "s": 949, "text": null }, { "code": null, "e": 1295, "s": 1287, "text": "Output:" }, { "code": null, "e": 1354, "s": 1295, "text": "Type : string \nValue : true\n\nType : string \nValue : false\n" }, { "code": null, "e": 1366, "s": 1354, "text": "Go Language" } ]
Java Program to Illustrate a Method Without Parameters and Return Type
17 Nov, 2020 Functions are a way to break a program into different modules which are executed one by one. To use a function in Java we need to: Declare the function i.e. declare a prototype of the function. Define the function Call the function It is important that we declare the function before calling it and the definition can be kept at any portion of the program. Declaring, Defining and Calling a function Now we will be creating a function with no return type and no parameters. While declaring a function we need to specify the return type of the functions and the number and types of parameters it is going to accept. For the return type, we have options such as int, float, char etc. But sometimes we don’t have to return anything in such scenario we have to use the void return type. And since we are not going to pass any parameter too, so we have to specify it while declaring by keeping the parenthesis empty. Example: Java // Java Program to Illustrate a Method with No Parameters// and Return Type public class Main { // Declaration and Definition of the function public static void greet() { System.out.println( "Hey Geeks! Welcome to NoWhere."); /* Optional program will work same without this return statement */ return; } public static void main(String args[]) { // Calling of the function without any parameters greet(); }} Hey Geeks! Welcome to NoWhere. In the above program, we declare and define the function at the same place which can be done and is also considered good if we want to use the function in the same program it is declared. Also, you can notice that the parameters during declaration and call are empty because we are not passing any parameters. Even we are not storing any data from the function because the function isn’t returning anything. Note: A return statement can be used at the end of the function but it’s completely optional if you remove the return statement then to the program will run in the same manner as it does with the return statement. Functions Picked Java Java Programs Java Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Nov, 2020" }, { "code": null, "e": 160, "s": 28, "text": "Functions are a way to break a program into different modules which are executed one by one. To use a function in Java we need to: " }, { "code": null, "e": 223, "s": 160, "text": "Declare the function i.e. declare a prototype of the function." }, { "code": null, "e": 243, "s": 223, "text": "Define the function" }, { "code": null, "e": 261, "s": 243, "text": "Call the function" }, { "code": null, "e": 386, "s": 261, "text": "It is important that we declare the function before calling it and the definition can be kept at any portion of the program." }, { "code": null, "e": 429, "s": 386, "text": "Declaring, Defining and Calling a function" }, { "code": null, "e": 942, "s": 429, "text": "Now we will be creating a function with no return type and no parameters. While declaring a function we need to specify the return type of the functions and the number and types of parameters it is going to accept. For the return type, we have options such as int, float, char etc. But sometimes we don’t have to return anything in such scenario we have to use the void return type. And since we are not going to pass any parameter too, so we have to specify it while declaring by keeping the parenthesis empty. " }, { "code": null, "e": 951, "s": 942, "text": "Example:" }, { "code": null, "e": 956, "s": 951, "text": "Java" }, { "code": "// Java Program to Illustrate a Method with No Parameters// and Return Type public class Main { // Declaration and Definition of the function public static void greet() { System.out.println( \"Hey Geeks! Welcome to NoWhere.\"); /* Optional program will work same without this return statement */ return; } public static void main(String args[]) { // Calling of the function without any parameters greet(); }}", "e": 1454, "s": 956, "text": null }, { "code": null, "e": 1486, "s": 1454, "text": "Hey Geeks! Welcome to NoWhere.\n" }, { "code": null, "e": 1894, "s": 1486, "text": "In the above program, we declare and define the function at the same place which can be done and is also considered good if we want to use the function in the same program it is declared. Also, you can notice that the parameters during declaration and call are empty because we are not passing any parameters. Even we are not storing any data from the function because the function isn’t returning anything." }, { "code": null, "e": 2108, "s": 1894, "text": "Note: A return statement can be used at the end of the function but it’s completely optional if you remove the return statement then to the program will run in the same manner as it does with the return statement." }, { "code": null, "e": 2118, "s": 2108, "text": "Functions" }, { "code": null, "e": 2125, "s": 2118, "text": "Picked" }, { "code": null, "e": 2130, "s": 2125, "text": "Java" }, { "code": null, "e": 2144, "s": 2130, "text": "Java Programs" }, { "code": null, "e": 2149, "s": 2144, "text": "Java" }, { "code": null, "e": 2159, "s": 2149, "text": "Functions" } ]
Data Structures and Algorithms | Set 22
11 Nov, 2021 Following questions have been asked in GATE CS 2005 exam. 1) A program P reads in 500 integers in the range [0..100] representing the scores of 500 students. It then prints the frequency of each score above 50. What would be the best way for P to store the frequencies?(a) An array of 50 numbers(b) An array of 100 numbers(c) An array of 500 numbers(d) A dynamically allocated array of 550 numbers Answer (a)An array of size 50 looks the best option to store number of students for each score. We need to store frequencies of scores above 50. We can ignore scores below 50 and to index the scores above 50, we can subtract 50 from the score value/ 2) An undirected graph G has n nodes. Its adjacency matrix is given by an n × n square matrix whose (i) diagonal elements are 0‘s and (ii) non-diagonal elements are 1‘s. which one of the following is TRUE?(a) Graph G has no minimum spanning tree (MST)(b) Graph G has a unique MST of cost n-1(c) Graph G has multiple distinct MSTs, each of cost n-1(d) Graph G has multiple spanning trees of different costs Answer (c)If all non diagonal elements are 1, then every vertex is connected to every other vertex in the graph with an edge of weight 1. Such a graph has multiple distinct MSTs with cost n-1. See the below example. The connected graph:Below are three Minimum Spanning trees each of cost 2.0.Minimum Spanning Tree 1 Minimum Spanning Tree 2 Minimum Spanning Tree 3 3) The time complexity of computing the transitive closure of a binary relation on a set of n elements is known to be:a) O(n)b) O(nLogn)c) O(n^(3/2))d) O(n^3) Answer (d)In mathematics, the transitive closure of a binary relation R on a set X is the smallest transitive relation on X that contains R. If the original relation is transitive, the transitive closure will be that same relation; otherwise, the transitive closure will be a different relation. In computer science the concept of transitive closure can be thought of as constructing a data structure that makes it possible to answer reachability questions. That is, can one get from node a to node other node b in one or more hops? A binary relation tells you only that node a is connected to node b, and that node b is connected to node c, etc. After the transitive closure is constructed in an O(1) operation one may determine that node c is reachable from node a. Warshall’s algorithm can be used to construct the Transitive closure of directed graphs (). In Warshall’s original formulation of the algorithm, the graph is unweighted and represented by a Boolean adjacency matrix. Then the addition operation is replaced by logical conjunction (AND) and the minimum operation by logical disjunction (OR). References:http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithmhttp://en.wikipedia.org/wiki/Transitive_closure 4. A Priority-Queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of the heap is given below:10, 8, 5, 3, 2Two new elements ”1‘ and ”7‘ are inserted in the heap in that order. The level-order traversal of the heap after the insertion of the elements is:(a) 10, 8, 7, 5, 3, 2, 1(b) 10, 8, 7, 2, 3, 1, 5(c) 10, 8, 7, 1, 2, 3, 5(d) 10, 8, 7, 3, 2, 1, 5 Answer (D) Original Max-Heap is: 10 / \ 8 5 / \ 3 2 After Insertion of 1. 10 / \ 8 5 / \ / 3 2 1 After Insertion of 7. 10 / \ 8 7 / \ / \ 3 2 1 5 Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2005 GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC) Differences between TCP and UDP Introduction of Operating System - Set 1 Semaphores in Process Synchronization Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Data Structures and Algorithms | Set 11 Computer Networks | Set 1 Database Management Systems | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2021" }, { "code": null, "e": 112, "s": 54, "text": "Following questions have been asked in GATE CS 2005 exam." }, { "code": null, "e": 452, "s": 112, "text": "1) A program P reads in 500 integers in the range [0..100] representing the scores of 500 students. It then prints the frequency of each score above 50. What would be the best way for P to store the frequencies?(a) An array of 50 numbers(b) An array of 100 numbers(c) An array of 500 numbers(d) A dynamically allocated array of 550 numbers" }, { "code": null, "e": 702, "s": 452, "text": "Answer (a)An array of size 50 looks the best option to store number of students for each score. We need to store frequencies of scores above 50. We can ignore scores below 50 and to index the scores above 50, we can subtract 50 from the score value/" }, { "code": null, "e": 1108, "s": 702, "text": "2) An undirected graph G has n nodes. Its adjacency matrix is given by an n × n square matrix whose (i) diagonal elements are 0‘s and (ii) non-diagonal elements are 1‘s. which one of the following is TRUE?(a) Graph G has no minimum spanning tree (MST)(b) Graph G has a unique MST of cost n-1(c) Graph G has multiple distinct MSTs, each of cost n-1(d) Graph G has multiple spanning trees of different costs" }, { "code": null, "e": 1324, "s": 1108, "text": "Answer (c)If all non diagonal elements are 1, then every vertex is connected to every other vertex in the graph with an edge of weight 1. Such a graph has multiple distinct MSTs with cost n-1. See the below example." }, { "code": null, "e": 1424, "s": 1324, "text": "The connected graph:Below are three Minimum Spanning trees each of cost 2.0.Minimum Spanning Tree 1" }, { "code": null, "e": 1448, "s": 1424, "text": "Minimum Spanning Tree 2" }, { "code": null, "e": 1472, "s": 1448, "text": "Minimum Spanning Tree 3" }, { "code": null, "e": 1631, "s": 1472, "text": "3) The time complexity of computing the transitive closure of a binary relation on a set of n elements is known to be:a) O(n)b) O(nLogn)c) O(n^(3/2))d) O(n^3)" }, { "code": null, "e": 1927, "s": 1631, "text": "Answer (d)In mathematics, the transitive closure of a binary relation R on a set X is the smallest transitive relation on X that contains R. If the original relation is transitive, the transitive closure will be that same relation; otherwise, the transitive closure will be a different relation." }, { "code": null, "e": 2399, "s": 1927, "text": "In computer science the concept of transitive closure can be thought of as constructing a data structure that makes it possible to answer reachability questions. That is, can one get from node a to node other node b in one or more hops? A binary relation tells you only that node a is connected to node b, and that node b is connected to node c, etc. After the transitive closure is constructed in an O(1) operation one may determine that node c is reachable from node a." }, { "code": null, "e": 2739, "s": 2399, "text": "Warshall’s algorithm can be used to construct the Transitive closure of directed graphs (). In Warshall’s original formulation of the algorithm, the graph is unweighted and represented by a Boolean adjacency matrix. Then the addition operation is replaced by logical conjunction (AND) and the minimum operation by logical disjunction (OR)." }, { "code": null, "e": 2859, "s": 2739, "text": "References:http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithmhttp://en.wikipedia.org/wiki/Transitive_closure" }, { "code": null, "e": 3249, "s": 2859, "text": "4. A Priority-Queue is implemented as a Max-Heap. Initially, it has 5 elements. The level-order traversal of the heap is given below:10, 8, 5, 3, 2Two new elements ”1‘ and ”7‘ are inserted in the heap in that order. The level-order traversal of the heap after the insertion of the elements is:(a) 10, 8, 7, 5, 3, 2, 1(b) 10, 8, 7, 2, 3, 1, 5(c) 10, 8, 7, 1, 2, 3, 5(d) 10, 8, 7, 3, 2, 1, 5" }, { "code": null, "e": 3260, "s": 3249, "text": "Answer (D)" }, { "code": null, "e": 3282, "s": 3260, "text": "Original Max-Heap is:" }, { "code": null, "e": 3338, "s": 3282, "text": " 10\n / \\\n 8 5\n / \\\n 3 2\n" }, { "code": null, "e": 3360, "s": 3338, "text": "After Insertion of 1." }, { "code": null, "e": 3429, "s": 3360, "text": " 10\n / \\\n 8 5\n / \\ /\n 3 2 1 \n" }, { "code": null, "e": 3451, "s": 3429, "text": "After Insertion of 7." }, { "code": null, "e": 3523, "s": 3451, "text": " 10\n / \\\n 8 7\n / \\ / \\ \n 3 2 1 5\n" }, { "code": null, "e": 3637, "s": 3523, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 3786, "s": 3637, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 3799, "s": 3786, "text": "GATE-CS-2005" }, { "code": null, "e": 3817, "s": 3799, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 3825, "s": 3817, "text": "GATE CS" }, { "code": null, "e": 3829, "s": 3825, "text": "MCQ" }, { "code": null, "e": 3927, "s": 3829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3976, "s": 3927, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 4010, "s": 3976, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 4042, "s": 4010, "text": "Differences between TCP and UDP" }, { "code": null, "e": 4083, "s": 4042, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 4121, "s": 4083, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 4147, "s": 4121, "text": "Operating Systems | Set 1" }, { "code": null, "e": 4194, "s": 4147, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 4234, "s": 4194, "text": "Data Structures and Algorithms | Set 11" }, { "code": null, "e": 4260, "s": 4234, "text": "Computer Networks | Set 1" } ]
How to create an Affix or sticky Navbar ?
01 Oct, 2021 To create an affix or sticky navbar, you need to use HTML, CSS, and JavaScript. HTML will make the structure of the body, CSS will make it looks good. This kind of sticky navbar looks attractive on website. By using JavaScript, you can easily make the navigation bar sticky when the user scrolls down.Creating Structure: In this section, we will create a basic website structure for the sticky navbar when the user scrolls down the page it will display the effect. HTML code to make the structure: html <!DOCTYPE html><html> <head> <title>How To Create a Affix Navbar</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Google fonts --> <link href="https://fonts.googleapis.com/css?family=Special+Elite&display=swap" rel="stylesheet"></head> <body> <div class="header"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png"> </div> <div id="navlist"> <b>GeeksforGeeks</b> <a href="javascript:void(0)">Contact us</a> <a href="javascript:void(0)">Careers</a> <a href="javascript:void(0)">Our Product</a> <a href="javascript:void(0)">About us</a> <a href="javascript:void(0)">Home</a> </div> <div class="scrollable" style="padding:15px 15px 4500px;"> <b>BLACK FRIDAY</b> <p> Want to get huge discounts on GeeksforGeeks Courses? This Black Friday, we are bringing the shopping festival to you!!! GeeksforGeeks is celebrating Black Friday on 29th November 2019 by providing you huge discounts on all its courses for the entire day! This will be a great opportunity for you to learn and enhance your skills. And that’s not all we are offering! </p> <p> There will also be Flash Sales that will go live for a particular duration of time where you can expect heavy discounts over a few courses in addition to the existing discounts. These Flash Sales will go live for 4 times during the entire day with different courses in each flash sale. Want to know more about Black Friday? Read on to find out! </p> <p> Black Friday is the Friday immediately after Thanksgiving in the United States, which is on 29th November this time. This Black Friday Sale is intended to provide you with the best courses along with great deals where the investment of your time and money will surely pay off. So Grab this opportunity, Grab the deals and celebrate this Black Friday in the most amazing way possible!!! </p> <center> <h3>Black Friday Sale Highlights</h3> </center> <p> This Black Friday, GeeksforGeeks is here with some Red Hot new deals on online and offline courses. Unbelievable offers will also be back in Flash Sales but you need to be quick to get them. Here’s everything you need to know about the Black Friday sale by GeeksforGeeks: </p> <h4>All Day Super Sale On All Courses:</h4> <p> There will be a Super Sale on all the available courses for the whole day of Black Friday. So you can buy your favorite courses at premium prices and learn a lot! </p> <h4>4 Flash Sales On Selected Courses:</h4> <p> There will be In Between Flash Sales on different courses for 1 hour each on Black Friday. These sales will reduce the prices of already discounted courses even further. Stay tuned to find out the times for different courses on the Flash Sale! There are Limited seats so the discount will be available on First Come First Serve basis. </p> <h4>Social Media Contest:</h4> <p> There will also be a Social Media Contest about “Guessing the Price of a Course” on the Black Friday Sale. Try your Luck!! Hefty discounts will be live on the following courses for the complete day. Grab them and pave the way to your dream product-based company! <hr> <i> All the details you will get by clicking this <a href="https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/"> link</a> </i> </div></body> </html> Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar and make the scroll down effect on the navbar using JavaScript. CSS code to look good the structure: css <style> body { margin: 0; } .header { text-align: center; width: 100%; } #navlist { overflow: hidden; background-color: #0074D9; } /* navlist designing */ #navlist a { float: right; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* navlist link hover effect */ #navlist a:hover { background-color: #ddd; color: black; } #navlist b{ margin-top: 4px; padding: 8px 12px; color:lime; float: left; font-size: 22px; } /* scroll portion design */ .scrollable b { font-family: 'Special Elite', cursive; font-size: 28px; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; }</style> JavaScript code for sticky navigation bar: javascript <script> window.onscroll = function() {myFunction()}; var navlist = document.getElementById("navlist"); var sticky = navlist.offsetTop; /* Function to stick the nav bar */ function myFunction() { if (window.pageYOffset >= sticky) { navlist.classList.add("sticky") } else { navlist.classList.remove("sticky"); } }</script> Combining the HTML, CSS, and JavaScript code: This example combinations the above sections to make a sticky navbar website. html <!DOCTYPE html><html> <head> <title>How To Create a Affix Navbar</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Google fonts --> <link href="https://fonts.googleapis.com/css?family=Special+Elite&display=swap" rel="stylesheet"> <style> body { margin: 0; } .header { text-align: center; width: 100%; } #navlist { overflow: hidden; background-color: #0074D9; } /* navlist designing */ #navlist a { float: right; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* navlist link hover effect */ #navlist a:hover { background-color: #ddd; color: black; } #navlist b{ margin-top: 4px; padding: 8px 12px; color:lime; float: left; font-size: 22px; } /* scroll portion design */ .scrollable b { font-family: 'Special Elite', cursive; font-size: 28px; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; } </style></head> <body> <div class="header"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png"> </div> <div id="navlist"> <b>GeeksforGeeks</b> <a href="javascript:void(0)">Contact us</a> <a href="javascript:void(0)">Careers</a> <a href="javascript:void(0)">Our Product</a> <a href="javascript:void(0)">About us</a> <a href="javascript:void(0)">Home</a> </div> <div class="scrollable" style="padding:15px 15px 4500px;"> <b>BLACK FRIDAY</b> <p> Want to get huge discounts on GeeksforGeeks Courses? This Black Friday, we are bringing the shopping festival to you!!! GeeksforGeeks is celebrating Black Friday on 29th November 2019 by providing you huge discounts on all its courses for the entire day! This will be a great opportunity for you to learn and enhance your skills. And that’s not all we are offering! </p> <p> There will also be Flash Sales that will go live for a particular duration of time where you can expect heavy discounts over a few courses in addition to the existing discounts. These Flash Sales will go live for 4 times during the entire day with different courses in each flash sale. Want to know more about Black Friday? Read on to find out! </p> <p> Black Friday is the Friday immediately after Thanksgiving in the United States, which is on 29th November this time. This Black Friday Sale is intended to provide you with the best courses along with great deals where the investment of your time and money will surely pay off. So Grab this opportunity, Grab the deals and celebrate this Black Friday in the most amazing way possible!!! </p> <center> <h3>Black Friday Sale Highlights</h3> </center> <p> This Black Friday, GeeksforGeeks is here with some Red Hot new deals on online and offline courses. Unbelievable offers will also be back in Flash Sales but you need to be quick to get them. Here’s everything you need to know about the Black Friday sale by GeeksforGeeks: </p> <h4>All Day Super Sale On All Courses:</h4> <p> There will be a Super Sale on all the available courses for the whole day of Black Friday. So you can buy your favorite courses at premium prices and learn a lot! </p> <h4>4 Flash Sales On Selected Courses:</h4> <p> There will be In Between Flash Sales on different courses for 1 hour each on Black Friday. These sales will reduce the prices of already discounted courses even further. Stay tuned to find out the times for different courses on the Flash Sale! There are Limited seats so the discount will be available on First Come First Serve basis. </p> <h4>Social Media Contest:</h4> <p> There will also be a Social Media Contest about “Guessing the Price of a Course” on the Black Friday Sale. Try your Luck!! Hefty discounts will be live on the following courses for the complete day. Grab them and pave the way to your dream product-based company! <hr> <i> All the details you will get by clicking this <a href="https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/"> link</a> </i> </div> <script> window.onscroll = function() {myFunction()}; var navlist = document.getElementById("navlist"); var sticky = navlist.offsetTop; /* Function to stick the nav bar */ function myFunction() { if (window.pageYOffset >= sticky) { navlist.classList.add("sticky") } else { navlist.classList.remove("sticky"); } } </script></body> </html> Output: sweetyty CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2021" }, { "code": null, "e": 495, "s": 28, "text": "To create an affix or sticky navbar, you need to use HTML, CSS, and JavaScript. HTML will make the structure of the body, CSS will make it looks good. This kind of sticky navbar looks attractive on website. By using JavaScript, you can easily make the navigation bar sticky when the user scrolls down.Creating Structure: In this section, we will create a basic website structure for the sticky navbar when the user scrolls down the page it will display the effect. " }, { "code": null, "e": 530, "s": 495, "text": "HTML code to make the structure: " }, { "code": null, "e": 535, "s": 530, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>How To Create a Affix Navbar</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Google fonts --> <link href=\"https://fonts.googleapis.com/css?family=Special+Elite&display=swap\" rel=\"stylesheet\"></head> <body> <div class=\"header\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png\"> </div> <div id=\"navlist\"> <b>GeeksforGeeks</b> <a href=\"javascript:void(0)\">Contact us</a> <a href=\"javascript:void(0)\">Careers</a> <a href=\"javascript:void(0)\">Our Product</a> <a href=\"javascript:void(0)\">About us</a> <a href=\"javascript:void(0)\">Home</a> </div> <div class=\"scrollable\" style=\"padding:15px 15px 4500px;\"> <b>BLACK FRIDAY</b> <p> Want to get huge discounts on GeeksforGeeks Courses? This Black Friday, we are bringing the shopping festival to you!!! GeeksforGeeks is celebrating Black Friday on 29th November 2019 by providing you huge discounts on all its courses for the entire day! This will be a great opportunity for you to learn and enhance your skills. And that’s not all we are offering! </p> <p> There will also be Flash Sales that will go live for a particular duration of time where you can expect heavy discounts over a few courses in addition to the existing discounts. These Flash Sales will go live for 4 times during the entire day with different courses in each flash sale. Want to know more about Black Friday? Read on to find out! </p> <p> Black Friday is the Friday immediately after Thanksgiving in the United States, which is on 29th November this time. This Black Friday Sale is intended to provide you with the best courses along with great deals where the investment of your time and money will surely pay off. So Grab this opportunity, Grab the deals and celebrate this Black Friday in the most amazing way possible!!! </p> <center> <h3>Black Friday Sale Highlights</h3> </center> <p> This Black Friday, GeeksforGeeks is here with some Red Hot new deals on online and offline courses. Unbelievable offers will also be back in Flash Sales but you need to be quick to get them. Here’s everything you need to know about the Black Friday sale by GeeksforGeeks: </p> <h4>All Day Super Sale On All Courses:</h4> <p> There will be a Super Sale on all the available courses for the whole day of Black Friday. So you can buy your favorite courses at premium prices and learn a lot! </p> <h4>4 Flash Sales On Selected Courses:</h4> <p> There will be In Between Flash Sales on different courses for 1 hour each on Black Friday. These sales will reduce the prices of already discounted courses even further. Stay tuned to find out the times for different courses on the Flash Sale! There are Limited seats so the discount will be available on First Come First Serve basis. </p> <h4>Social Media Contest:</h4> <p> There will also be a Social Media Contest about “Guessing the Price of a Course” on the Black Friday Sale. Try your Luck!! Hefty discounts will be live on the following courses for the complete day. Grab them and pave the way to your dream product-based company! <hr> <i> All the details you will get by clicking this <a href=\"https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/\"> link</a> </i> </div></body> </html>", "e": 4774, "s": 535, "text": null }, { "code": null, "e": 5007, "s": 4774, "text": "Designing Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the navigation bar and make the scroll down effect on the navbar using JavaScript. " }, { "code": null, "e": 5046, "s": 5007, "text": "CSS code to look good the structure: " }, { "code": null, "e": 5050, "s": 5046, "text": "css" }, { "code": "<style> body { margin: 0; } .header { text-align: center; width: 100%; } #navlist { overflow: hidden; background-color: #0074D9; } /* navlist designing */ #navlist a { float: right; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* navlist link hover effect */ #navlist a:hover { background-color: #ddd; color: black; } #navlist b{ margin-top: 4px; padding: 8px 12px; color:lime; float: left; font-size: 22px; } /* scroll portion design */ .scrollable b { font-family: 'Special Elite', cursive; font-size: 28px; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; }</style>", "e": 6030, "s": 5050, "text": null }, { "code": null, "e": 6075, "s": 6030, "text": "JavaScript code for sticky navigation bar: " }, { "code": null, "e": 6086, "s": 6075, "text": "javascript" }, { "code": "<script> window.onscroll = function() {myFunction()}; var navlist = document.getElementById(\"navlist\"); var sticky = navlist.offsetTop; /* Function to stick the nav bar */ function myFunction() { if (window.pageYOffset >= sticky) { navlist.classList.add(\"sticky\") } else { navlist.classList.remove(\"sticky\"); } }</script>", "e": 6480, "s": 6086, "text": null }, { "code": null, "e": 6604, "s": 6480, "text": "Combining the HTML, CSS, and JavaScript code: This example combinations the above sections to make a sticky navbar website." }, { "code": null, "e": 6609, "s": 6604, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>How To Create a Affix Navbar</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Google fonts --> <link href=\"https://fonts.googleapis.com/css?family=Special+Elite&display=swap\" rel=\"stylesheet\"> <style> body { margin: 0; } .header { text-align: center; width: 100%; } #navlist { overflow: hidden; background-color: #0074D9; } /* navlist designing */ #navlist a { float: right; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* navlist link hover effect */ #navlist a:hover { background-color: #ddd; color: black; } #navlist b{ margin-top: 4px; padding: 8px 12px; color:lime; float: left; font-size: 22px; } /* scroll portion design */ .scrollable b { font-family: 'Special Elite', cursive; font-size: 28px; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; } </style></head> <body> <div class=\"header\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191128123949/cover1.png\"> </div> <div id=\"navlist\"> <b>GeeksforGeeks</b> <a href=\"javascript:void(0)\">Contact us</a> <a href=\"javascript:void(0)\">Careers</a> <a href=\"javascript:void(0)\">Our Product</a> <a href=\"javascript:void(0)\">About us</a> <a href=\"javascript:void(0)\">Home</a> </div> <div class=\"scrollable\" style=\"padding:15px 15px 4500px;\"> <b>BLACK FRIDAY</b> <p> Want to get huge discounts on GeeksforGeeks Courses? This Black Friday, we are bringing the shopping festival to you!!! GeeksforGeeks is celebrating Black Friday on 29th November 2019 by providing you huge discounts on all its courses for the entire day! This will be a great opportunity for you to learn and enhance your skills. And that’s not all we are offering! </p> <p> There will also be Flash Sales that will go live for a particular duration of time where you can expect heavy discounts over a few courses in addition to the existing discounts. These Flash Sales will go live for 4 times during the entire day with different courses in each flash sale. Want to know more about Black Friday? Read on to find out! </p> <p> Black Friday is the Friday immediately after Thanksgiving in the United States, which is on 29th November this time. This Black Friday Sale is intended to provide you with the best courses along with great deals where the investment of your time and money will surely pay off. So Grab this opportunity, Grab the deals and celebrate this Black Friday in the most amazing way possible!!! </p> <center> <h3>Black Friday Sale Highlights</h3> </center> <p> This Black Friday, GeeksforGeeks is here with some Red Hot new deals on online and offline courses. Unbelievable offers will also be back in Flash Sales but you need to be quick to get them. Here’s everything you need to know about the Black Friday sale by GeeksforGeeks: </p> <h4>All Day Super Sale On All Courses:</h4> <p> There will be a Super Sale on all the available courses for the whole day of Black Friday. So you can buy your favorite courses at premium prices and learn a lot! </p> <h4>4 Flash Sales On Selected Courses:</h4> <p> There will be In Between Flash Sales on different courses for 1 hour each on Black Friday. These sales will reduce the prices of already discounted courses even further. Stay tuned to find out the times for different courses on the Flash Sale! There are Limited seats so the discount will be available on First Come First Serve basis. </p> <h4>Social Media Contest:</h4> <p> There will also be a Social Media Contest about “Guessing the Price of a Course” on the Black Friday Sale. Try your Luck!! Hefty discounts will be live on the following courses for the complete day. Grab them and pave the way to your dream product-based company! <hr> <i> All the details you will get by clicking this <a href=\"https://www.geeksforgeeks.org/black-friday-sale-programmers-have-carts-geeksforgeeks-has-deals/\"> link</a> </i> </div> <script> window.onscroll = function() {myFunction()}; var navlist = document.getElementById(\"navlist\"); var sticky = navlist.offsetTop; /* Function to stick the nav bar */ function myFunction() { if (window.pageYOffset >= sticky) { navlist.classList.add(\"sticky\") } else { navlist.classList.remove(\"sticky\"); } } </script></body> </html>", "e": 12494, "s": 6609, "text": null }, { "code": null, "e": 12504, "s": 12494, "text": "Output: " }, { "code": null, "e": 12515, "s": 12506, "text": "sweetyty" }, { "code": null, "e": 12524, "s": 12515, "text": "CSS-Misc" }, { "code": null, "e": 12534, "s": 12524, "text": "HTML-Misc" }, { "code": null, "e": 12550, "s": 12534, "text": "JavaScript-Misc" }, { "code": null, "e": 12554, "s": 12550, "text": "CSS" }, { "code": null, "e": 12559, "s": 12554, "text": "HTML" }, { "code": null, "e": 12570, "s": 12559, "text": "JavaScript" }, { "code": null, "e": 12587, "s": 12570, "text": "Web Technologies" }, { "code": null, "e": 12614, "s": 12587, "text": "Web technologies Questions" }, { "code": null, "e": 12619, "s": 12614, "text": "HTML" } ]
PHP | substr() function
09 Mar, 2018 The substr() is a built-in function in PHP that is used to extract a part of string. Syntax: substr(string_name, start_position, string_length_to_cut) Parameters:The substr() function allows 3 parameters or arguments out of which two are mandatory and one is optional. string_name: In this parameter, we pass the original string or the string that needs to cut or modified. This is a mandatory parameterstart_position: This refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter.string_length_to_cut: This parameter is optional and of integer type. This refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of string. string_name: In this parameter, we pass the original string or the string that needs to cut or modified. This is a mandatory parameter start_position: This refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter. string_length_to_cut: This parameter is optional and of integer type. This refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of string. Return Type:Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure. Below is a program to illustrate working of substr() in PHP: <?php // PHP program to illustrate substr()function Substring($str){ $len = strlen($str); echo substr($str, 8), "\n"; echo substr($str, 5, $len), "\n"; echo substr($str, -5, 10), "\n"; echo substr($str,-8, -5), "\n";} // Driver Code$str="GeeksforGeeks";Substring($str); ?> Output: Geeks forGeeks Geeks for Functions PHP-function PHP-string PHP Web Technologies Functions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? Download file from URL using PHP 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": 54, "s": 26, "text": "\n09 Mar, 2018" }, { "code": null, "e": 139, "s": 54, "text": "The substr() is a built-in function in PHP that is used to extract a part of string." }, { "code": null, "e": 147, "s": 139, "text": "Syntax:" }, { "code": null, "e": 205, "s": 147, "text": "substr(string_name, start_position, string_length_to_cut)" }, { "code": null, "e": 323, "s": 205, "text": "Parameters:The substr() function allows 3 parameters or arguments out of which two are mandatory and one is optional." }, { "code": null, "e": 1359, "s": 323, "text": "string_name: In this parameter, we pass the original string or the string that needs to cut or modified. This is a mandatory parameterstart_position: This refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter.string_length_to_cut: This parameter is optional and of integer type. This refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of string." }, { "code": null, "e": 1494, "s": 1359, "text": "string_name: In this parameter, we pass the original string or the string that needs to cut or modified. This is a mandatory parameter" }, { "code": null, "e": 1868, "s": 1494, "text": "start_position: This refers to the position of the original string from where the part needs to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of the position in the string from the beginning. If the integer is negative then it refers to the start of the position from the end of the string. This is also a mandatory parameter." }, { "code": null, "e": 2397, "s": 1868, "text": "string_length_to_cut: This parameter is optional and of integer type. This refers to the length of the part of the string that needs to be cut from the original string. If the integer is positive, it refers to start from start_position and extract length from the beginning. If the integer is negative then it refers to start from start_position and extract length from the end of the string. If this parameter is not passed, then the substr() function will return the string starting from start_position till the end of string." }, { "code": null, "e": 2511, "s": 2397, "text": "Return Type:Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure." }, { "code": null, "e": 2572, "s": 2511, "text": "Below is a program to illustrate working of substr() in PHP:" }, { "code": "<?php // PHP program to illustrate substr()function Substring($str){ $len = strlen($str); echo substr($str, 8), \"\\n\"; echo substr($str, 5, $len), \"\\n\"; echo substr($str, -5, 10), \"\\n\"; echo substr($str,-8, -5), \"\\n\";} // Driver Code$str=\"GeeksforGeeks\";Substring($str); ?>", "e": 2863, "s": 2572, "text": null }, { "code": null, "e": 2871, "s": 2863, "text": "Output:" }, { "code": null, "e": 2897, "s": 2871, "text": "Geeks\nforGeeks\nGeeks\nfor\n" }, { "code": null, "e": 2907, "s": 2897, "text": "Functions" }, { "code": null, "e": 2920, "s": 2907, "text": "PHP-function" }, { "code": null, "e": 2931, "s": 2920, "text": "PHP-string" }, { "code": null, "e": 2935, "s": 2931, "text": "PHP" }, { "code": null, "e": 2952, "s": 2935, "text": "Web Technologies" }, { "code": null, "e": 2962, "s": 2952, "text": "Functions" }, { "code": null, "e": 2966, "s": 2962, "text": "PHP" }, { "code": null, "e": 3064, "s": 2966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3104, "s": 3064, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3149, "s": 3104, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3176, "s": 3149, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3212, "s": 3176, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 3245, "s": 3212, "text": "Download file from URL using PHP" }, { "code": null, "e": 3278, "s": 3245, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3340, "s": 3278, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3401, "s": 3340, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3451, "s": 3401, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Online XML Formatter
Editable XML Code 123456789101112131415<?xml version="1.0"?><Company><Employee><FirstName>Tanmay</FirstName><LastName>Patil</LastName><ContactNo>1234567890</ContactNo><Email>[email protected]</Email><Address><City>Bangalore</City><State>Karnataka</State><Zip>560212</Zip></Address></Employee></Company>X Privacy Policy Cookies Policy Terms of Use
[ { "code": null, "e": 18, "s": 0, "text": "Editable XML Code" }, { "code": null, "e": 306, "s": 18, "text": "123456789101112131415<?xml version=\"1.0\"?><Company><Employee><FirstName>Tanmay</FirstName><LastName>Patil</LastName><ContactNo>1234567890</ContactNo><Email>[email protected]</Email><Address><City>Bangalore</City><State>Karnataka</State><Zip>560212</Zip></Address></Employee></Company>X" }, { "code": null, "e": 321, "s": 306, "text": "Privacy Policy" }, { "code": null, "e": 336, "s": 321, "text": "Cookies Policy" } ]
What happens when we type a URL - GeeksforGeeks
05 Jun, 2020 URL stands for Uniform Resource Locator. URL is the address of the website which you can find in the address bar of your web browser. It is a reference to a resource on the internet, be it images, hypertext pages, audio/video files, etc. Example : https://practice.geeksforgeeks.org/ What is DNS :DNS is short for Domain Name System. Like a phonebook, DNS maintains and maps the name of the website, i.e. URL, and particular IP address it links to. Every URL on the internet has a unique IP address which is of the computer which hosts the server of the website requested. Steps for what happens when we enter a URL : Browser checks cache for DNS entry to find the corresponding IP address of website.It looks for following cache. If not found in one, then continues checking to the next until found.Browser CacheOperating Systems CacheRouter CacheISP CacheIf not found in cache, ISP’s (Internet Service Provider) DNS server initiates a DNS query to find IP address of server that hosts the domain name.The requests are sent using small data packets that contain information content of request and IP address it is destined for.Browser initiates a TCP (Transfer Control Protocol) connection with the server using synchronize(SYN) and acknowledge(ACK) messages.Browser sends an HTTP request to the web server. GET or POST request.Server on the host computer handles that request and sends back a response. It assembles a response in some format like JSON, XML and HTML.Server sends out an HTTP response along with the status of response.Browser displays HTML contentFinally, Done. Browser checks cache for DNS entry to find the corresponding IP address of website.It looks for following cache. If not found in one, then continues checking to the next until found.Browser CacheOperating Systems CacheRouter CacheISP Cache Browser Cache Operating Systems Cache Router Cache ISP Cache If not found in cache, ISP’s (Internet Service Provider) DNS server initiates a DNS query to find IP address of server that hosts the domain name.The requests are sent using small data packets that contain information content of request and IP address it is destined for. Browser initiates a TCP (Transfer Control Protocol) connection with the server using synchronize(SYN) and acknowledge(ACK) messages. Browser sends an HTTP request to the web server. GET or POST request. Server on the host computer handles that request and sends back a response. It assembles a response in some format like JSON, XML and HTML. Server sends out an HTTP response along with the status of response. Browser displays HTML content Finally, Done. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Congestion Control in Computer Networks Routing Information Protocol (RIP) Architecture of Internet of Things (IoT) Wireless Sensor Network (WSN)
[ { "code": null, "e": 25779, "s": 25751, "text": "\n05 Jun, 2020" }, { "code": null, "e": 26017, "s": 25779, "text": "URL stands for Uniform Resource Locator. URL is the address of the website which you can find in the address bar of your web browser. It is a reference to a resource on the internet, be it images, hypertext pages, audio/video files, etc." }, { "code": null, "e": 26027, "s": 26017, "text": "Example :" }, { "code": null, "e": 26064, "s": 26027, "text": "https://practice.geeksforgeeks.org/ " }, { "code": null, "e": 26353, "s": 26064, "text": "What is DNS :DNS is short for Domain Name System. Like a phonebook, DNS maintains and maps the name of the website, i.e. URL, and particular IP address it links to. Every URL on the internet has a unique IP address which is of the computer which hosts the server of the website requested." }, { "code": null, "e": 26398, "s": 26353, "text": "Steps for what happens when we enter a URL :" }, { "code": null, "e": 27360, "s": 26398, "text": "Browser checks cache for DNS entry to find the corresponding IP address of website.It looks for following cache. If not found in one, then continues checking to the next until found.Browser CacheOperating Systems CacheRouter CacheISP CacheIf not found in cache, ISP’s (Internet Service Provider) DNS server initiates a DNS query to find IP address of server that hosts the domain name.The requests are sent using small data packets that contain information content of request and IP address it is destined for.Browser initiates a TCP (Transfer Control Protocol) connection with the server using synchronize(SYN) and acknowledge(ACK) messages.Browser sends an HTTP request to the web server. GET or POST request.Server on the host computer handles that request and sends back a response. It assembles a response in some format like JSON, XML and HTML.Server sends out an HTTP response along with the status of response.Browser displays HTML contentFinally, Done." }, { "code": null, "e": 27600, "s": 27360, "text": "Browser checks cache for DNS entry to find the corresponding IP address of website.It looks for following cache. If not found in one, then continues checking to the next until found.Browser CacheOperating Systems CacheRouter CacheISP Cache" }, { "code": null, "e": 27614, "s": 27600, "text": "Browser Cache" }, { "code": null, "e": 27638, "s": 27614, "text": "Operating Systems Cache" }, { "code": null, "e": 27651, "s": 27638, "text": "Router Cache" }, { "code": null, "e": 27661, "s": 27651, "text": "ISP Cache" }, { "code": null, "e": 27933, "s": 27661, "text": "If not found in cache, ISP’s (Internet Service Provider) DNS server initiates a DNS query to find IP address of server that hosts the domain name.The requests are sent using small data packets that contain information content of request and IP address it is destined for." }, { "code": null, "e": 28066, "s": 27933, "text": "Browser initiates a TCP (Transfer Control Protocol) connection with the server using synchronize(SYN) and acknowledge(ACK) messages." }, { "code": null, "e": 28136, "s": 28066, "text": "Browser sends an HTTP request to the web server. GET or POST request." }, { "code": null, "e": 28276, "s": 28136, "text": "Server on the host computer handles that request and sends back a response. It assembles a response in some format like JSON, XML and HTML." }, { "code": null, "e": 28345, "s": 28276, "text": "Server sends out an HTTP response along with the status of response." }, { "code": null, "e": 28375, "s": 28345, "text": "Browser displays HTML content" }, { "code": null, "e": 28390, "s": 28375, "text": "Finally, Done." }, { "code": null, "e": 28408, "s": 28390, "text": "Computer Networks" }, { "code": null, "e": 28426, "s": 28408, "text": "Computer Networks" }, { "code": null, "e": 28524, "s": 28426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28559, "s": 28524, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 28592, "s": 28559, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 28630, "s": 28592, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 28656, "s": 28630, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 28683, "s": 28656, "text": "Cryptography and its Types" }, { "code": null, "e": 28729, "s": 28683, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 28769, "s": 28729, "text": "Congestion Control in Computer Networks" }, { "code": null, "e": 28804, "s": 28769, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 28845, "s": 28804, "text": "Architecture of Internet of Things (IoT)" } ]
Complete Guide to Install C++17 on Windows - GeeksforGeeks
05 Oct, 2021 In the Competitive Programming field C++ is one of the most used language, because of it’s huge STL(standard template library) functions, and day by day its getting updated. So here is the complete guide to install the latest version of C++(C++ 17) and also setup guide for Sublime Text and CodeBlocks. To install C++17 compiler follow this link to download GCC 9.2 compiler. After download is completed, extract the file and save the extracted MinGw folder in C drive as shown in below images: If you are installing GCC compiler first time in your computer follow the steps below: Copy the bin folder path from MinGw file saved in C driveGo to Control Panel -> System -> Advanced System Setting -> Environment Variable -> Edit path from System variable -> new -> paste the path and save every thing. Copy the bin folder path from MinGw file saved in C drive Go to Control Panel -> System -> Advanced System Setting -> Environment Variable -> Edit path from System variable -> new -> paste the path and save every thing. If there is previously installed any GCC compiler then follow the same process to setup new GCC compiler path or just replace the previously existing MinGw folder with this new MinGw folder in C drive. Now, check the version of GCC installed on your computer to verify that is it successfully installed by running the below command in CMD: gcc --version It must be 9.2 if it is installed successfully. In Sublime Text editor while running a C++ code it gives warning for some newly added functions of C++17 STL and due to default build setting of C++ program would not run if it has any warning. To overcome this problem we will add our custom build code for C++ program as: { "cmd" : [ "g++.exe", "-std=c++17", "${file_name}", "-o", "${file_base_name}.exe", "&&", "start", "cmd", "/k", "${file_base_name}.exe" ], "file_regex" : "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "shell" : true, "working_dir" : "$file_path", "selector" : "source.cpp", } Copy the above code and create new build system (Tool -> build system -> new build system). Name it anything you want and save it with sublime-build extension. Now Go to tool -> build system and select the build file that you saved earlier, and we are done. Now, to run your code press Ctrl + B. 1. Go to global Compiler setting -> select compiler as GNU GCC compiler 2. Mark c++17 in compiler setting as: 3. Switch to Toolchain executables tab -> select MinGw folder from C drive in Compiler’s Installation directory and also update all the program files from C-> MinGw -> bin folder. Below is the illustration of the same: Go to Tools -> Compiler Options -> ‘+’ button (Add a compiler set by folder) Select the MinGW folder from C drive -> Click Ok to save the settings. Change the version/type of compiler anytime back to the previous one or this new one, using this drop-down menu: menonkartikeya sweetyty how-to-install C++ Competitive Programming Installation Guide Linux-Unix CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 25367, "s": 25339, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25670, "s": 25367, "text": "In the Competitive Programming field C++ is one of the most used language, because of it’s huge STL(standard template library) functions, and day by day its getting updated. So here is the complete guide to install the latest version of C++(C++ 17) and also setup guide for Sublime Text and CodeBlocks." }, { "code": null, "e": 25862, "s": 25670, "text": "To install C++17 compiler follow this link to download GCC 9.2 compiler. After download is completed, extract the file and save the extracted MinGw folder in C drive as shown in below images:" }, { "code": null, "e": 25951, "s": 25862, "text": "If you are installing GCC compiler first time in your computer follow the steps below: " }, { "code": null, "e": 26171, "s": 25951, "text": "Copy the bin folder path from MinGw file saved in C driveGo to Control Panel -> System -> Advanced System Setting -> Environment Variable -> Edit path from System variable -> new -> paste the path and save every thing. " }, { "code": null, "e": 26229, "s": 26171, "text": "Copy the bin folder path from MinGw file saved in C drive" }, { "code": null, "e": 26392, "s": 26229, "text": "Go to Control Panel -> System -> Advanced System Setting -> Environment Variable -> Edit path from System variable -> new -> paste the path and save every thing. " }, { "code": null, "e": 26733, "s": 26392, "text": "If there is previously installed any GCC compiler then follow the same process to setup new GCC compiler path or just replace the previously existing MinGw folder with this new MinGw folder in C drive. Now, check the version of GCC installed on your computer to verify that is it successfully installed by running the below command in CMD: " }, { "code": null, "e": 26747, "s": 26733, "text": "gcc --version" }, { "code": null, "e": 26797, "s": 26747, "text": "It must be 9.2 if it is installed successfully. " }, { "code": null, "e": 27072, "s": 26797, "text": "In Sublime Text editor while running a C++ code it gives warning for some newly added functions of C++17 STL and due to default build setting of C++ program would not run if it has any warning. To overcome this problem we will add our custom build code for C++ program as: " }, { "code": null, "e": 27391, "s": 27072, "text": "{\n \"cmd\" : [ \"g++.exe\", \"-std=c++17\", \"${file_name}\", \"-o\",\n \"${file_base_name}.exe\", \"&&\", \"start\", \"cmd\",\n \"/k\", \"${file_base_name}.exe\" ],\n \"file_regex\" : \"^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$\",\n \"shell\" : true,\n \"working_dir\" : \"$file_path\",\n \"selector\" : \"source.cpp\",\n}" }, { "code": null, "e": 27650, "s": 27391, "text": "Copy the above code and create new build system (Tool -> build system -> new build system). Name it anything you want and save it with sublime-build extension. Now Go to tool -> build system and select the build file that you saved earlier, and we are done. " }, { "code": null, "e": 27690, "s": 27650, "text": "Now, to run your code press Ctrl + B. " }, { "code": null, "e": 27762, "s": 27690, "text": "1. Go to global Compiler setting -> select compiler as GNU GCC compiler" }, { "code": null, "e": 27801, "s": 27762, "text": "2. Mark c++17 in compiler setting as: " }, { "code": null, "e": 27981, "s": 27801, "text": "3. Switch to Toolchain executables tab -> select MinGw folder from C drive in Compiler’s Installation directory and also update all the program files from C-> MinGw -> bin folder." }, { "code": null, "e": 28021, "s": 27981, "text": "Below is the illustration of the same: " }, { "code": null, "e": 28099, "s": 28021, "text": "Go to Tools -> Compiler Options -> ‘+’ button (Add a compiler set by folder)" }, { "code": null, "e": 28170, "s": 28099, "text": "Select the MinGW folder from C drive -> Click Ok to save the settings." }, { "code": null, "e": 28283, "s": 28170, "text": "Change the version/type of compiler anytime back to the previous one or this new one, using this drop-down menu:" }, { "code": null, "e": 28298, "s": 28283, "text": "menonkartikeya" }, { "code": null, "e": 28307, "s": 28298, "text": "sweetyty" }, { "code": null, "e": 28322, "s": 28307, "text": "how-to-install" }, { "code": null, "e": 28326, "s": 28322, "text": "C++" }, { "code": null, "e": 28350, "s": 28326, "text": "Competitive Programming" }, { "code": null, "e": 28369, "s": 28350, "text": "Installation Guide" }, { "code": null, "e": 28380, "s": 28369, "text": "Linux-Unix" }, { "code": null, "e": 28384, "s": 28380, "text": "CPP" }, { "code": null, "e": 28482, "s": 28384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28510, "s": 28482, "text": "Operator Overloading in C++" }, { "code": null, "e": 28530, "s": 28510, "text": "Polymorphism in C++" }, { "code": null, "e": 28563, "s": 28530, "text": "Friend class and function in C++" }, { "code": null, "e": 28587, "s": 28563, "text": "Sorting a vector in C++" }, { "code": null, "e": 28612, "s": 28587, "text": "std::string class in C++" }, { "code": null, "e": 28655, "s": 28612, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 28698, "s": 28655, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 28739, "s": 28698, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28817, "s": 28739, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Python | Method Overloading - GeeksforGeeks
19 Feb, 2021 Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But there are different ways to achieve method overloading in Python. The problem with method overloading in Python is that we may overload the methods but can only use the latest defined method. Python3 # First product method.# Takes two argument and print their# productdef product(a, b): p = a * b print(p) # Second product method# Takes three argument and print their# productdef product(a, b, c): p = a * b*c print(p) # Uncommenting the below line shows an error # product(4, 5) # This line will call the second product methodproduct(4, 5, 5) Output: 100 In the above code, we have defined two product method, but we can only use the second product method, as python does not support method overloading. We may define many methods of the same name and different arguments, but we can only use the latest defined method. Calling the other method will produce an error. Like here calling will produce an error as the latest defined product method takes three arguments. Thus, to overcome the above problem we can use different ways to achieve the method overloading. Method 1 (Not The Most Efficient Method):We can use the arguments to make the same function work differently i.e. as per the arguments. Python3 # Function to take multiple argumentsdef add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integeradd('int', 5, 6) # Stringadd('str', 'Hi ', 'Geeks') Output: 11 Hi Geeks The problem with above code is that makes code more complex with multiple if/else statement and is not the desired way to achieve the method overloading. Method 2 (Efficient One):By Using Multiple Dispatch Decorator Multiple Dispatch Decorator Can be installed by: pip3 install multipledispatch Python3 from multipledispatch import dispatch #passing one parameter@dispatch(int,int)def product(first,second): result = first*second print(result); #passing two parameters@dispatch(int,int,int)def product(first,second,third): result = first * second * third print(result); #you can also pass data type of any value as per requirement@dispatch(float,float,float)def product(first,second,third): result = first * second * third print(result); #calling product method with 2 argumentsproduct(2,3,2) #this will give output of 12product(2.2,3.4,2.3) # this will give output of 17.985999999999997 Output: 12 17.985999999999997 In Backend, Dispatcher creates an object which stores different implementation and on runtime, it selects the appropriate method as the type and number of parameters passed. YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Method Overloading | 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:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=jMQfA1cmFw8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Vidip shahid211099 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python Convert integer to string in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25419, "s": 25391, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25611, "s": 25419, "text": "Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But there are different ways to achieve method overloading in Python. " }, { "code": null, "e": 25738, "s": 25611, "text": "The problem with method overloading in Python is that we may overload the methods but can only use the latest defined method. " }, { "code": null, "e": 25746, "s": 25738, "text": "Python3" }, { "code": "# First product method.# Takes two argument and print their# productdef product(a, b): p = a * b print(p) # Second product method# Takes three argument and print their# productdef product(a, b, c): p = a * b*c print(p) # Uncommenting the below line shows an error # product(4, 5) # This line will call the second product methodproduct(4, 5, 5)", "e": 26112, "s": 25746, "text": null }, { "code": null, "e": 26121, "s": 26112, "text": "Output: " }, { "code": null, "e": 26125, "s": 26121, "text": "100" }, { "code": null, "e": 26538, "s": 26125, "text": "In the above code, we have defined two product method, but we can only use the second product method, as python does not support method overloading. We may define many methods of the same name and different arguments, but we can only use the latest defined method. Calling the other method will produce an error. Like here calling will produce an error as the latest defined product method takes three arguments." }, { "code": null, "e": 26635, "s": 26538, "text": "Thus, to overcome the above problem we can use different ways to achieve the method overloading." }, { "code": null, "e": 26771, "s": 26635, "text": "Method 1 (Not The Most Efficient Method):We can use the arguments to make the same function work differently i.e. as per the arguments." }, { "code": null, "e": 26779, "s": 26771, "text": "Python3" }, { "code": "# Function to take multiple argumentsdef add(datatype, *args): # if datatype is int # initialize answer as 0 if datatype =='int': answer = 0 # if datatype is str # initialize answer as '' if datatype =='str': answer ='' # Traverse through the arguments for x in args: # This will do addition if the # arguments are int. Or concatenation # if the arguments are str answer = answer + x print(answer) # Integeradd('int', 5, 6) # Stringadd('str', 'Hi ', 'Geeks')", "e": 27329, "s": 26779, "text": null }, { "code": null, "e": 27338, "s": 27329, "text": "Output: " }, { "code": null, "e": 27350, "s": 27338, "text": "11\nHi Geeks" }, { "code": null, "e": 27504, "s": 27350, "text": "The problem with above code is that makes code more complex with multiple if/else statement and is not the desired way to achieve the method overloading." }, { "code": null, "e": 27616, "s": 27504, "text": "Method 2 (Efficient One):By Using Multiple Dispatch Decorator Multiple Dispatch Decorator Can be installed by: " }, { "code": null, "e": 27646, "s": 27616, "text": "pip3 install multipledispatch" }, { "code": null, "e": 27654, "s": 27646, "text": "Python3" }, { "code": "from multipledispatch import dispatch #passing one parameter@dispatch(int,int)def product(first,second): result = first*second print(result); #passing two parameters@dispatch(int,int,int)def product(first,second,third): result = first * second * third print(result); #you can also pass data type of any value as per requirement@dispatch(float,float,float)def product(first,second,third): result = first * second * third print(result); #calling product method with 2 argumentsproduct(2,3,2) #this will give output of 12product(2.2,3.4,2.3) # this will give output of 17.985999999999997", "e": 28265, "s": 27654, "text": null }, { "code": null, "e": 28274, "s": 28265, "text": "Output: " }, { "code": null, "e": 28296, "s": 28274, "text": "12\n17.985999999999997" }, { "code": null, "e": 28471, "s": 28296, "text": "In Backend, Dispatcher creates an object which stores different implementation and on runtime, it selects the appropriate method as the type and number of parameters passed. " }, { "code": null, "e": 29318, "s": 28471, "text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Method Overloading | 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:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=jMQfA1cmFw8\" 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": 29324, "s": 29318, "text": "Vidip" }, { "code": null, "e": 29337, "s": 29324, "text": "shahid211099" }, { "code": null, "e": 29351, "s": 29337, "text": "python-basics" }, { "code": null, "e": 29358, "s": 29351, "text": "Python" }, { "code": null, "e": 29456, "s": 29358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29488, "s": 29456, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29510, "s": 29488, "text": "Enumerate() in Python" }, { "code": null, "e": 29552, "s": 29510, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29578, "s": 29552, "text": "Python String | replace()" }, { "code": null, "e": 29607, "s": 29578, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29651, "s": 29607, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29688, "s": 29651, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29730, "s": 29688, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29766, "s": 29730, "text": "Convert integer to string in Python" } ]
Two odd occurring elements in an array where all other occur even times - GeeksforGeeks
30 Apr, 2021 Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two. Examples: Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8} Output : 2 7 Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50} Output : 7 15 A simple solution is to use two nested loops. The outer loop traverses through all elements. The inner loop counts occurrences of the current element. We print the elements whose counts of occurrences are odd. Time complexity if this solution is O(n2) A better solution is to use hashing. Time complexity of this solution is O(n) but it requires extra space. An efficient solution is to use bitwise operators. The idea is based on approach used in two missing elements and two repeating elements. C++ Java Python3 C# PHP Javascript // CPP code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <bits/stdc++.h>using namespace std; void printOdds(int arr[], int n){ // Find XOR of all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the XOR (We find // rightmost set bit here) int set_bit = res & (~(res - 1)); // Traverse through all numbers and // divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if (arr[i] & set_bit) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different sets are our // required numbers. cout << x << " " << y;} // Driver codeint main(){ int arr[] = { 2, 3, 3, 4, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printOdds(arr, n); return 0;} // Java code to find two// odd occurring elements// in an array where all// other elements appear// even number of times. class GFG{static void printOdds(int arr[], int n){ // Find XOR of // all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the // XOR (We find rightmost // set bit here) int set_bit = res & (~(res - 1)); // Traverse through all // numbers and divide them // in two groups (i) Having // set bit set at same position // as the only set bit in // set_bit (ii) Having 0 bit at // same position as the only // set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if ((arr[i] & set_bit) != 0) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different // sets are our required // numbers. System.out.println( x + " " + y);} // Driver codepublic static void main(String [] args){ int arr[] = { 2, 3, 3, 4, 4, 5 }; int n = arr.length; printOdds(arr, n);}} // This code is contributed by// Smitha Dinesh Semwal # Python 3 code to find two# odd occurring elements in# an array where all other# elements appear even number# of times.def printOdds(arr, n): # Find XOR of all numbers res = 0 for i in range(0, n): res = res ^ arr[i] # Find a set bit in # the XOR (We find # rightmost set bit here) set_bit = res & (~(res - 1)) # Traverse through all numbers # and divide them in two groups # (i) Having set bit set at # same position as the only set # bit in set_bit # (ii) Having 0 bit at same # position as the only set # bit in set_bit x = 0 y = 0 for i in range(0, n): if (arr[i] & set_bit): x = x ^ arr[i] else: y = y ^ arr[i] # XOR of two different # sets are our # required numbers. print(x , y, end = "") # Driver codearr = [2, 3, 3, 4, 4, 5 ]n = len(arr)printOdds(arr, n) # This code is contributed# by Smitha // C# code to find two// odd occurring elements// in an array where all// other elements appear// even number of times.using System; class GFG{static void printOdds(int []arr, int n){ // Find XOR of // all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the // XOR (We find rightmost // set bit here) int set_bit = res & (~(res - 1)); // Traverse through all // numbers and divide them // in two groups (i) Having // set bit set at same position // as the only set bit in // set_bit (ii) Having 0 bit at // same position as the only // set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if ((arr[i] & set_bit) != 0) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different // sets are our required // numbers. Console.WriteLine(x + " " + y);} // Driver codepublic static void Main(){ int []arr = { 2, 3, 3, 4, 4, 5 }; int n = arr.Length; printOdds(arr, n);}} // This code is contributed by// Akanksha Rai(Abby_akku) <?php// PHP code to find two odd// occurring elements in an// array where all other elements// appear even number of times.function printOdds($arr, $n){ // Find XOR of all numbers $res = 0; for ($i = 0; $i < $n; $i++) $res = $res ^ $arr[$i]; // Find a set bit in the // XOR (We find rightmost // set bit here) $set_bit = $res & (~($res - 1)); // Traverse through all numbers // and divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit $x = 0; $y = 0; for ($i = 0; $i < $n; $i++) { if ($arr[$i] & $set_bit) $x = $x ^ $arr[$i]; else $y = $y ^ $arr[$i]; } // XOR of two different sets // are our required numbers. echo($x . " " . $y);} // Driver code$arr = array( 2, 3, 3, 4, 4, 5 );$n = sizeof($arr);printOdds($arr, $n); // This code is contributed by Smitha?> <script> // Javascript code to find two odd// occurring elements in an array// where all other elements appear// even number of times.function printOdds(arr, n){ // Find XOR of all numbers let res = 0; for(let i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the XOR (We find // rightmost set bit here) let set_bit = res & (~(res - 1)); // Traverse through all numbers and // divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit let x = 0, y = 0; for(let i = 0; i < n; i++) { if (arr[i] & set_bit) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different sets are our // required numbers. document.write(x + " " + y);} // Driver codelet arr = [ 2, 3, 3, 4, 4, 5 ];let n = arr.length; printOdds(arr, n); // This code is contributed by subhammahato348 </script> 5 2 Time Complexity : O(n) Auxiliary Space : O(1) Smitha Dinesh Semwal Akanksha_Rai subhammahato348 Bitwise-XOR Arrays Bit Magic Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 26065, "s": 26037, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26235, "s": 26065, "text": "Given an array where all elements appear even number of times except two, print the two odd occurring elements. It may be assumed that the size of array is at-least two." }, { "code": null, "e": 26246, "s": 26235, "text": "Examples: " }, { "code": null, "e": 26376, "s": 26246, "text": "Input : arr[] = {2, 3, 8, 4, 4, 3, 7, 8}\nOutput : 2 7\n\nInput : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50}\nOutput : 7 15" }, { "code": null, "e": 26628, "s": 26376, "text": "A simple solution is to use two nested loops. The outer loop traverses through all elements. The inner loop counts occurrences of the current element. We print the elements whose counts of occurrences are odd. Time complexity if this solution is O(n2)" }, { "code": null, "e": 26735, "s": 26628, "text": "A better solution is to use hashing. Time complexity of this solution is O(n) but it requires extra space." }, { "code": null, "e": 26875, "s": 26735, "text": "An efficient solution is to use bitwise operators. The idea is based on approach used in two missing elements and two repeating elements. " }, { "code": null, "e": 26879, "s": 26875, "text": "C++" }, { "code": null, "e": 26884, "s": 26879, "text": "Java" }, { "code": null, "e": 26892, "s": 26884, "text": "Python3" }, { "code": null, "e": 26895, "s": 26892, "text": "C#" }, { "code": null, "e": 26899, "s": 26895, "text": "PHP" }, { "code": null, "e": 26910, "s": 26899, "text": "Javascript" }, { "code": "// CPP code to find two odd occurring elements// in an array where all other elements appear// even number of times.#include <bits/stdc++.h>using namespace std; void printOdds(int arr[], int n){ // Find XOR of all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the XOR (We find // rightmost set bit here) int set_bit = res & (~(res - 1)); // Traverse through all numbers and // divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if (arr[i] & set_bit) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different sets are our // required numbers. cout << x << \" \" << y;} // Driver codeint main(){ int arr[] = { 2, 3, 3, 4, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); printOdds(arr, n); return 0;}", "e": 27956, "s": 26910, "text": null }, { "code": "// Java code to find two// odd occurring elements// in an array where all// other elements appear// even number of times. class GFG{static void printOdds(int arr[], int n){ // Find XOR of // all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the // XOR (We find rightmost // set bit here) int set_bit = res & (~(res - 1)); // Traverse through all // numbers and divide them // in two groups (i) Having // set bit set at same position // as the only set bit in // set_bit (ii) Having 0 bit at // same position as the only // set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if ((arr[i] & set_bit) != 0) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different // sets are our required // numbers. System.out.println( x + \" \" + y);} // Driver codepublic static void main(String [] args){ int arr[] = { 2, 3, 3, 4, 4, 5 }; int n = arr.length; printOdds(arr, n);}} // This code is contributed by// Smitha Dinesh Semwal", "e": 29120, "s": 27956, "text": null }, { "code": "# Python 3 code to find two# odd occurring elements in# an array where all other# elements appear even number# of times.def printOdds(arr, n): # Find XOR of all numbers res = 0 for i in range(0, n): res = res ^ arr[i] # Find a set bit in # the XOR (We find # rightmost set bit here) set_bit = res & (~(res - 1)) # Traverse through all numbers # and divide them in two groups # (i) Having set bit set at # same position as the only set # bit in set_bit # (ii) Having 0 bit at same # position as the only set # bit in set_bit x = 0 y = 0 for i in range(0, n): if (arr[i] & set_bit): x = x ^ arr[i] else: y = y ^ arr[i] # XOR of two different # sets are our # required numbers. print(x , y, end = \"\") # Driver codearr = [2, 3, 3, 4, 4, 5 ]n = len(arr)printOdds(arr, n) # This code is contributed# by Smitha", "e": 30041, "s": 29120, "text": null }, { "code": "// C# code to find two// odd occurring elements// in an array where all// other elements appear// even number of times.using System; class GFG{static void printOdds(int []arr, int n){ // Find XOR of // all numbers int res = 0; for (int i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the // XOR (We find rightmost // set bit here) int set_bit = res & (~(res - 1)); // Traverse through all // numbers and divide them // in two groups (i) Having // set bit set at same position // as the only set bit in // set_bit (ii) Having 0 bit at // same position as the only // set bit in set_bit int x = 0, y = 0; for (int i = 0; i < n; i++) { if ((arr[i] & set_bit) != 0) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different // sets are our required // numbers. Console.WriteLine(x + \" \" + y);} // Driver codepublic static void Main(){ int []arr = { 2, 3, 3, 4, 4, 5 }; int n = arr.Length; printOdds(arr, n);}} // This code is contributed by// Akanksha Rai(Abby_akku)", "e": 31200, "s": 30041, "text": null }, { "code": "<?php// PHP code to find two odd// occurring elements in an// array where all other elements// appear even number of times.function printOdds($arr, $n){ // Find XOR of all numbers $res = 0; for ($i = 0; $i < $n; $i++) $res = $res ^ $arr[$i]; // Find a set bit in the // XOR (We find rightmost // set bit here) $set_bit = $res & (~($res - 1)); // Traverse through all numbers // and divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit $x = 0; $y = 0; for ($i = 0; $i < $n; $i++) { if ($arr[$i] & $set_bit) $x = $x ^ $arr[$i]; else $y = $y ^ $arr[$i]; } // XOR of two different sets // are our required numbers. echo($x . \" \" . $y);} // Driver code$arr = array( 2, 3, 3, 4, 4, 5 );$n = sizeof($arr);printOdds($arr, $n); // This code is contributed by Smitha?>", "e": 32196, "s": 31200, "text": null }, { "code": "<script> // Javascript code to find two odd// occurring elements in an array// where all other elements appear// even number of times.function printOdds(arr, n){ // Find XOR of all numbers let res = 0; for(let i = 0; i < n; i++) res = res ^ arr[i]; // Find a set bit in the XOR (We find // rightmost set bit here) let set_bit = res & (~(res - 1)); // Traverse through all numbers and // divide them in two groups // (i) Having set bit set at same // position as the only set bit // in set_bit // (ii) Having 0 bit at same position // as the only set bit in set_bit let x = 0, y = 0; for(let i = 0; i < n; i++) { if (arr[i] & set_bit) x = x ^ arr[i]; else y = y ^ arr[i]; } // XOR of two different sets are our // required numbers. document.write(x + \" \" + y);} // Driver codelet arr = [ 2, 3, 3, 4, 4, 5 ];let n = arr.length; printOdds(arr, n); // This code is contributed by subhammahato348 </script>", "e": 33222, "s": 32196, "text": null }, { "code": null, "e": 33226, "s": 33222, "text": "5 2" }, { "code": null, "e": 33275, "s": 33228, "text": "Time Complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 33296, "s": 33275, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 33309, "s": 33296, "text": "Akanksha_Rai" }, { "code": null, "e": 33325, "s": 33309, "text": "subhammahato348" }, { "code": null, "e": 33337, "s": 33325, "text": "Bitwise-XOR" }, { "code": null, "e": 33344, "s": 33337, "text": "Arrays" }, { "code": null, "e": 33354, "s": 33344, "text": "Bit Magic" }, { "code": null, "e": 33361, "s": 33354, "text": "Arrays" }, { "code": null, "e": 33371, "s": 33361, "text": "Bit Magic" }, { "code": null, "e": 33469, "s": 33371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33496, "s": 33469, "text": "Count pairs with given sum" }, { "code": null, "e": 33527, "s": 33496, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33552, "s": 33527, "text": "Window Sliding Technique" }, { "code": null, "e": 33590, "s": 33552, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33611, "s": 33590, "text": "Next Greater Element" }, { "code": null, "e": 33638, "s": 33611, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33684, "s": 33638, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33752, "s": 33684, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33781, "s": 33752, "text": "Count set bits in an integer" } ]
Combinatorics on ordered trees - GeeksforGeeks
26 May, 2021 An ordered tree is an oriented tree in which the children of a node are somehow ordered. It is a rooted tree in which an ordering is specified for the children of each vertex. This is called a “plane tree” because the ordering of the children is equivalent to an embedding of the tree in the plane, with the root at the top and the children of each vertex lower than that vertex. The ordered trees can be further specified as labelled ordered trees and unlabelled ordered trees. Prerequisite: Catalan Numbers | Binomial Coefficient. Labelled ordered trees: A labeled tree is a tree where each vertex is assigned a unique number from 1 to n. If T1 and T2 are ordered trees. Then, T1 != T2 else T1 = T2. Unlabelled ordered trees: An unlabelled tree is a tree where every vertex is unlabelled. Given below are the possible unlabelled ordered tree having 3 vertices. The total number of unlabelled ordered trees having n nodes is equal to the (n – 1)-th Catalan Number.Given below are the possible unlabelled ordered trees having 4 nodes. This diagram will work as a reference example for the next few results. 1. Number of trees with exactly k leaves. Let us consider that we have ‘n’ edges. Then, the solution for the total possible ordered trees having ‘k’ leaves is given by : 2. Total number of nodes of degree d in these trees. Let us consider that we have ‘n’ edges. Then, the solution for the total number of nodes having a degree ‘d’ is given by : 3. Number of trees in which the root has degree r. Let us consider that we have ‘n’ edges. Then, the solution for the total possible ordered trees whose root has degree ‘r’ is given by : Below is the implementation of the above combinatorics functions using Binomial Coefficient : C++ Java Python3 C# PHP Javascript // C++ code to find the number of ordered trees// with given number of edges and leaves#include <bits/stdc++.h>using namespace std; // Function returns value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1] = { 0 }; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate the number// of trees with exactly k leaves.int k_Leaves(int n, int k){ int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; cout << "Number of trees having 4 edges" << " and exactly 2 leaves : " << ans << endl; return 0;} // Function to calculate total number of// nodes of degree d in these trees.int numberOfNodes(int n, int d){ int ans = binomialCoeff(2 * n - 1 - d, n - 1); cout << "Number of nodes of degree 1 in" << " a tree having 4 edges : " << ans << endl; return 0;} // Function to calculate the number of// trees in which the root has degree r.int rootDegreeR(int n, int r){ int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; cout << "Number of trees having 4 edges" << " where root has degree 2 : " << ans << endl; return 0;} // Driver program to test above functionsint main(){ // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); return 0;} // java code to find the number of ordered// trees with given number of edges and// leavesimport java.io.*; class GFG { // Function returns value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [][]C = new int[n+1][k+1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to calculate the number // of trees with exactly k leaves. static int k_Leaves(int n, int k) { int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; System.out.println( "Number of trees " + "having 4 edges and exactly 2 " + "leaves : " + ans) ; return 0; } // Function to calculate total number of // nodes of degree d in these trees. static int numberOfNodes(int n, int d) { int ans = binomialCoeff(2 * n - 1 - d, n - 1); System.out.println("Number of nodes " +"of degree 1 in a tree having 4 " + "edges : " + ans); return 0; } // Function to calculate the number of // trees in which the root has degree r. static int rootDegreeR(int n, int r) { int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; System.out.println("Number of trees " + "having 4 edges where root has" + " degree 2 : " + ans); return 0; } // Driver program to test above functions public static void main (String[] args) { // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); }} // This code is contributed by anuj_67. # Python3 code to find the number of ordered# trees with given number of edges and# leaves # Function returns value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k + 1)] for j in range(n + 1)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n + 1): for j in range(min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using # previously stored values else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) return C[n][k] # Function to calculate the number# of trees with exactly k leaves.def k_Leaves(n, k): ans = ((binomialCoeff(n, k) * binomialCoeff(n, k - 1)) // n) print("Number of trees ", "having 4 edges and exactly 2 ", "leaves : ", ans) # Function to calculate total number of# Nodes of degree d in these trees.def numberOfNodes(n, d): ans = binomialCoeff(2 * n - 1 - d, n - 1) print("Number of Nodes ", "of degree 1 in a tree having 4 ", "edges : ", ans) # Function to calculate the number of# trees in which the root has degree r.def rootDegreeR(n, r): ans = r * binomialCoeff(2 * n - 1 - r, n - 1) ans = ans // n print("Number of trees ", "having 4 edges where root has ", "degree 2 : ", ans) # Driver codeif __name__ == '__main__': # Number of trees having 3 # edges and exactly 2 leaves k_Leaves(3, 2) # Number of Nodes of degree # 3 in a tree having 4 edges numberOfNodes(3, 1) # Number of trees having 3 # edges where root has degree 2 rootDegreeR(3, 2) # This code is contributed by aashish1995 // C# code to find the number of ordered// trees with given number of edges and// leavesusing System; class GFG { // Function returns value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [,]C = new int[n+1,k+1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using // previously stored values else C[i,j] = C[i - 1,j - 1] + C[i - 1,j]; } } return C[n,k]; } // Function to calculate the number // of trees with exactly k leaves. static int k_Leaves(int n, int k) { int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; Console.WriteLine( "Number of trees " + "having 4 edges and exactly 2 " + "leaves : " + ans) ; return 0; } // Function to calculate total number of // nodes of degree d in these trees. static int numberOfNodes(int n, int d) { int ans = binomialCoeff(2 * n - 1 - d, n - 1); Console.WriteLine("Number of nodes " +"of degree 1 in a tree having 4 " + "edges : " + ans); return 0; } // Function to calculate the number of // trees in which the root has degree r. static int rootDegreeR(int n, int r) { int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; Console.WriteLine("Number of trees " + "having 4 edges where root has" + " degree 2 : " + ans); return 0; } // Driver program to test above functions public static void Main () { // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); }} // This code is contributed by anuj_67. <?php// PHP code to find the number of ordered// trees with given number of edges and// leaves // Function returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 or $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Function to calculate the number// of trees with exactly k leaves.function k_Leaves( $n, $k){ $ans = (binomialCoeff($n, $k) * binomialCoeff($n, $k - 1)) / $n; echo "Number of trees having 4 edges and ", "exactly 2 leaves : " , $ans ,"\n"; return 0;} // Function to calculate total number of// nodes of degree d in these trees.function numberOfNodes( $n, $d){ $ans = binomialCoeff(2 * $n - 1 - $d, $n - 1); echo "Number of nodes of degree 1 in" , " a tree having 4 edges : " , $ans,"\n" ; return 0;} // Function to calculate the number of// trees in which the root has degree r.function rootDegreeR( $n, $r){ $ans = $r * binomialCoeff(2 * $n - 1 - $r, $n - 1); $ans = $ans / $n; echo "Number of trees having 4 edges" , " where root has degree 2 : " , $ans ; return 0;} // Driver program to test above functions // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); // This code is contributed by anuj_67.?> <script> // javascript code to find the number of ordered // trees with given number of edges and leaves // Function returns value of // Binomial Coefficient C(n, k) function binomialCoeff(n, k) { let C = new Array(n+1); let i, j; for (i = 0; i <= n; i++) { C[i] = new Array(k + 1); for (j = 0; j <= k; j++) { C[i][j] = 0; } } // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to calculate the number // of trees with exactly k leaves. function k_Leaves(n, k) { let ans = parseInt((binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n, 10); document.write( "Number of trees " + "having 4 edges and exactly 2 " + "leaves : " + ans + "</br>"); return 0; } // Function to calculate total number of // nodes of degree d in these trees. function numberOfNodes(n, d) { let ans = binomialCoeff(2 * n - 1 - d, n - 1); document.write("Number of nodes " +"of degree 1 in a tree having 4 " + "edges : " + ans + "</br>"); return 0; } // Function to calculate the number of // trees in which the root has degree r. function rootDegreeR(n, r) { let ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = parseInt(ans / n, 10); document.write("Number of trees " + "having 4 edges where root has" + " degree 2 : " + ans + "</br>"); return 0; } // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); </script> Number of trees having 4 edges and exactly 2 leaves : 3 Number of nodes of degree 1 in a tree having 4 edges : 6 Number of trees having 4 edges where root has degree 2 : 2 Time Complexity : O(n*k). Auxiliary Space : O(n*k). vt_m nidhi_biet aashish1995 suresh07 Trees Combinatorial Competitive Programming Mathematical Technical Scripter Tree Mathematical Combinatorial Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to get all subsets of given size of a set Print all distinct permutations of a given string with duplicates Heap's Algorithm for generating permutations Distinct permutations of the string | Set 2 Make all combinations of size k Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 26239, "s": 26211, "text": "\n26 May, 2021" }, { "code": null, "e": 26718, "s": 26239, "text": "An ordered tree is an oriented tree in which the children of a node are somehow ordered. It is a rooted tree in which an ordering is specified for the children of each vertex. This is called a “plane tree” because the ordering of the children is equivalent to an embedding of the tree in the plane, with the root at the top and the children of each vertex lower than that vertex. The ordered trees can be further specified as labelled ordered trees and unlabelled ordered trees." }, { "code": null, "e": 26772, "s": 26718, "text": "Prerequisite: Catalan Numbers | Binomial Coefficient." }, { "code": null, "e": 26880, "s": 26772, "text": "Labelled ordered trees: A labeled tree is a tree where each vertex is assigned a unique number from 1 to n." }, { "code": null, "e": 26941, "s": 26880, "text": "If T1 and T2 are ordered trees. Then, T1 != T2 else T1 = T2." }, { "code": null, "e": 27103, "s": 26941, "text": "Unlabelled ordered trees: An unlabelled tree is a tree where every vertex is unlabelled. Given below are the possible unlabelled ordered tree having 3 vertices. " }, { "code": null, "e": 27347, "s": 27103, "text": "The total number of unlabelled ordered trees having n nodes is equal to the (n – 1)-th Catalan Number.Given below are the possible unlabelled ordered trees having 4 nodes. This diagram will work as a reference example for the next few results." }, { "code": null, "e": 27518, "s": 27347, "text": "1. Number of trees with exactly k leaves. Let us consider that we have ‘n’ edges. Then, the solution for the total possible ordered trees having ‘k’ leaves is given by : " }, { "code": null, "e": 27696, "s": 27518, "text": "2. Total number of nodes of degree d in these trees. Let us consider that we have ‘n’ edges. Then, the solution for the total number of nodes having a degree ‘d’ is given by : " }, { "code": null, "e": 27885, "s": 27696, "text": "3. Number of trees in which the root has degree r. Let us consider that we have ‘n’ edges. Then, the solution for the total possible ordered trees whose root has degree ‘r’ is given by : " }, { "code": null, "e": 27980, "s": 27885, "text": "Below is the implementation of the above combinatorics functions using Binomial Coefficient : " }, { "code": null, "e": 27984, "s": 27980, "text": "C++" }, { "code": null, "e": 27989, "s": 27984, "text": "Java" }, { "code": null, "e": 27997, "s": 27989, "text": "Python3" }, { "code": null, "e": 28000, "s": 27997, "text": "C#" }, { "code": null, "e": 28004, "s": 28000, "text": "PHP" }, { "code": null, "e": 28015, "s": 28004, "text": "Javascript" }, { "code": "// C++ code to find the number of ordered trees// with given number of edges and leaves#include <bits/stdc++.h>using namespace std; // Function returns value of// Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1] = { 0 }; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // Function to calculate the number// of trees with exactly k leaves.int k_Leaves(int n, int k){ int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; cout << \"Number of trees having 4 edges\" << \" and exactly 2 leaves : \" << ans << endl; return 0;} // Function to calculate total number of// nodes of degree d in these trees.int numberOfNodes(int n, int d){ int ans = binomialCoeff(2 * n - 1 - d, n - 1); cout << \"Number of nodes of degree 1 in\" << \" a tree having 4 edges : \" << ans << endl; return 0;} // Function to calculate the number of// trees in which the root has degree r.int rootDegreeR(int n, int r){ int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; cout << \"Number of trees having 4 edges\" << \" where root has degree 2 : \" << ans << endl; return 0;} // Driver program to test above functionsint main(){ // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); return 0;}", "e": 29873, "s": 28015, "text": null }, { "code": "// java code to find the number of ordered// trees with given number of edges and// leavesimport java.io.*; class GFG { // Function returns value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [][]C = new int[n+1][k+1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to calculate the number // of trees with exactly k leaves. static int k_Leaves(int n, int k) { int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; System.out.println( \"Number of trees \" + \"having 4 edges and exactly 2 \" + \"leaves : \" + ans) ; return 0; } // Function to calculate total number of // nodes of degree d in these trees. static int numberOfNodes(int n, int d) { int ans = binomialCoeff(2 * n - 1 - d, n - 1); System.out.println(\"Number of nodes \" +\"of degree 1 in a tree having 4 \" + \"edges : \" + ans); return 0; } // Function to calculate the number of // trees in which the root has degree r. static int rootDegreeR(int n, int r) { int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; System.out.println(\"Number of trees \" + \"having 4 edges where root has\" + \" degree 2 : \" + ans); return 0; } // Driver program to test above functions public static void main (String[] args) { // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); }} // This code is contributed by anuj_67.", "e": 32331, "s": 29873, "text": null }, { "code": "# Python3 code to find the number of ordered# trees with given number of edges and# leaves # Function returns value of# Binomial Coefficient C(n, k)def binomialCoeff(n, k): C = [[0 for i in range(k + 1)] for j in range(n + 1)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n + 1): for j in range(min(i, k) + 1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using # previously stored values else: C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) return C[n][k] # Function to calculate the number# of trees with exactly k leaves.def k_Leaves(n, k): ans = ((binomialCoeff(n, k) * binomialCoeff(n, k - 1)) // n) print(\"Number of trees \", \"having 4 edges and exactly 2 \", \"leaves : \", ans) # Function to calculate total number of# Nodes of degree d in these trees.def numberOfNodes(n, d): ans = binomialCoeff(2 * n - 1 - d, n - 1) print(\"Number of Nodes \", \"of degree 1 in a tree having 4 \", \"edges : \", ans) # Function to calculate the number of# trees in which the root has degree r.def rootDegreeR(n, r): ans = r * binomialCoeff(2 * n - 1 - r, n - 1) ans = ans // n print(\"Number of trees \", \"having 4 edges where root has \", \"degree 2 : \", ans) # Driver codeif __name__ == '__main__': # Number of trees having 3 # edges and exactly 2 leaves k_Leaves(3, 2) # Number of Nodes of degree # 3 in a tree having 4 edges numberOfNodes(3, 1) # Number of trees having 3 # edges where root has degree 2 rootDegreeR(3, 2) # This code is contributed by aashish1995", "e": 34177, "s": 32331, "text": null }, { "code": "// C# code to find the number of ordered// trees with given number of edges and// leavesusing System; class GFG { // Function returns value of // Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int [,]C = new int[n+1,k+1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i,j] = 1; // Calculate value using // previously stored values else C[i,j] = C[i - 1,j - 1] + C[i - 1,j]; } } return C[n,k]; } // Function to calculate the number // of trees with exactly k leaves. static int k_Leaves(int n, int k) { int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n; Console.WriteLine( \"Number of trees \" + \"having 4 edges and exactly 2 \" + \"leaves : \" + ans) ; return 0; } // Function to calculate total number of // nodes of degree d in these trees. static int numberOfNodes(int n, int d) { int ans = binomialCoeff(2 * n - 1 - d, n - 1); Console.WriteLine(\"Number of nodes \" +\"of degree 1 in a tree having 4 \" + \"edges : \" + ans); return 0; } // Function to calculate the number of // trees in which the root has degree r. static int rootDegreeR(int n, int r) { int ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = ans / n; Console.WriteLine(\"Number of trees \" + \"having 4 edges where root has\" + \" degree 2 : \" + ans); return 0; } // Driver program to test above functions public static void Main () { // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); }} // This code is contributed by anuj_67.", "e": 36590, "s": 34177, "text": null }, { "code": "<?php// PHP code to find the number of ordered// trees with given number of edges and// leaves // Function returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 or $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Function to calculate the number// of trees with exactly k leaves.function k_Leaves( $n, $k){ $ans = (binomialCoeff($n, $k) * binomialCoeff($n, $k - 1)) / $n; echo \"Number of trees having 4 edges and \", \"exactly 2 leaves : \" , $ans ,\"\\n\"; return 0;} // Function to calculate total number of// nodes of degree d in these trees.function numberOfNodes( $n, $d){ $ans = binomialCoeff(2 * $n - 1 - $d, $n - 1); echo \"Number of nodes of degree 1 in\" , \" a tree having 4 edges : \" , $ans,\"\\n\" ; return 0;} // Function to calculate the number of// trees in which the root has degree r.function rootDegreeR( $n, $r){ $ans = $r * binomialCoeff(2 * $n - 1 - $r, $n - 1); $ans = $ans / $n; echo \"Number of trees having 4 edges\" , \" where root has degree 2 : \" , $ans ; return 0;} // Driver program to test above functions // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); // This code is contributed by anuj_67.?>", "e": 38540, "s": 36590, "text": null }, { "code": "<script> // javascript code to find the number of ordered // trees with given number of edges and leaves // Function returns value of // Binomial Coefficient C(n, k) function binomialCoeff(n, k) { let C = new Array(n+1); let i, j; for (i = 0; i <= n; i++) { C[i] = new Array(k + 1); for (j = 0; j <= k; j++) { C[i][j] = 0; } } // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // Function to calculate the number // of trees with exactly k leaves. function k_Leaves(n, k) { let ans = parseInt((binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n, 10); document.write( \"Number of trees \" + \"having 4 edges and exactly 2 \" + \"leaves : \" + ans + \"</br>\"); return 0; } // Function to calculate total number of // nodes of degree d in these trees. function numberOfNodes(n, d) { let ans = binomialCoeff(2 * n - 1 - d, n - 1); document.write(\"Number of nodes \" +\"of degree 1 in a tree having 4 \" + \"edges : \" + ans + \"</br>\"); return 0; } // Function to calculate the number of // trees in which the root has degree r. function rootDegreeR(n, r) { let ans = r * binomialCoeff(2 * n - 1 - r, n - 1); ans = parseInt(ans / n, 10); document.write(\"Number of trees \" + \"having 4 edges where root has\" + \" degree 2 : \" + ans + \"</br>\"); return 0; } // Number of trees having 3 // edges and exactly 2 leaves k_Leaves(3, 2); // Number of nodes of degree // 3 in a tree having 4 edges numberOfNodes(3, 1); // Number of trees having 3 // edges where root has degree 2 rootDegreeR(3, 2); </script>", "e": 40948, "s": 38540, "text": null }, { "code": null, "e": 41120, "s": 40948, "text": "Number of trees having 4 edges and exactly 2 leaves : 3\nNumber of nodes of degree 1 in a tree having 4 edges : 6\nNumber of trees having 4 edges where root has degree 2 : 2" }, { "code": null, "e": 41175, "s": 41122, "text": "Time Complexity : O(n*k). Auxiliary Space : O(n*k). " }, { "code": null, "e": 41180, "s": 41175, "text": "vt_m" }, { "code": null, "e": 41191, "s": 41180, "text": "nidhi_biet" }, { "code": null, "e": 41203, "s": 41191, "text": "aashish1995" }, { "code": null, "e": 41212, "s": 41203, "text": "suresh07" }, { "code": null, "e": 41218, "s": 41212, "text": "Trees" }, { "code": null, "e": 41232, "s": 41218, "text": "Combinatorial" }, { "code": null, "e": 41256, "s": 41232, "text": "Competitive Programming" }, { "code": null, "e": 41269, "s": 41256, "text": "Mathematical" }, { "code": null, "e": 41288, "s": 41269, "text": "Technical Scripter" }, { "code": null, "e": 41293, "s": 41288, "text": "Tree" }, { "code": null, "e": 41306, "s": 41293, "text": "Mathematical" }, { "code": null, "e": 41320, "s": 41306, "text": "Combinatorial" }, { "code": null, "e": 41325, "s": 41320, "text": "Tree" }, { "code": null, "e": 41423, "s": 41325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41480, "s": 41423, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 41546, "s": 41480, "text": "Print all distinct permutations of a given string with duplicates" }, { "code": null, "e": 41591, "s": 41546, "text": "Heap's Algorithm for generating permutations" }, { "code": null, "e": 41635, "s": 41591, "text": "Distinct permutations of the string | Set 2" }, { "code": null, "e": 41667, "s": 41635, "text": "Make all combinations of size k" }, { "code": null, "e": 41710, "s": 41667, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 41753, "s": 41710, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 41794, "s": 41753, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 41872, "s": 41794, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Scala | Create Array with Range - GeeksforGeeks
12 Jun, 2019 Array is a special kind of collection in Scala. It is a fixed size data structure that stores elements of the same data type. By using range() method to generate an array containing a sequence of increasing integers in a given range. We can use final argument as jump to create the sequence. if we do not use final argument, then jump would be assumed as 1. Below are some examples of array with range: Example: // Scala program to create array with range import Array._ // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var array1 = range(1, 15) var array2 = range(1, 15, 3) // Print all the elements of array1 for ( i <- array1 ) { print( " " + i ) } println() // Print all the elements of array2 for ( i <- array2 ) { print( " " + i ) } }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 4 7 10 13 In above example, an array of range (1, 15). In this range difference is not given so by default difference of range will be 1 element. Elements in the array are 1, 4, 7, 10 and 13. Here, we are creating an array of range (1, 15, 3). Which means an array with elements between 1 and 15 and range difference is 3. Elements in the array are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, and 14. For some of the collections, such as List and Array, we can also create a Range and convert it to the desired sequence: The REPL shows the array that can be created directly from a Range is toArray. We can also use a Range to create a sequence of characters as below: Example: // Scala program to create array with range import Array._ // Creating objectobject GFG{ // Main method def main(args: Array[String]) { val array1 = ('A' to 'F').toArray val array2 = ('a' to 'f').by(2).toArray // Print all the elements of array1 for ( i <- array1 ) { print( " " + i ) } println() // Print all the elements of array2 for ( i <- array2 ) { print( " " + i ) } }} A B C D E F a c e In above example, an array of range (‘A’ to ‘F’).toArray. In this, range difference is not given so by default difference of range will be 1 character. characters in the array are A, B, C, D, E and F. Here, we are creating an array of range (‘a’ to ‘f’).by(2).toArray. Which means an array with characters between a and f and range difference is 2. Characters in the array are a, c, and e. Scala-Arrays Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in Scala Scala | Traits Scala ListBuffer Scala | Case Class and Case Object Hello World in Scala Scala | Functions - Basics Scala | Decision Making (if, if-else, Nested if-else, if-else if) Scala List map() method with example Comments In Scala Abstract Classes in Scala
[ { "code": null, "e": 25301, "s": 25273, "text": "\n12 Jun, 2019" }, { "code": null, "e": 25659, "s": 25301, "text": "Array is a special kind of collection in Scala. It is a fixed size data structure that stores elements of the same data type. By using range() method to generate an array containing a sequence of increasing integers in a given range. We can use final argument as jump to create the sequence. if we do not use final argument, then jump would be assumed as 1." }, { "code": null, "e": 25704, "s": 25659, "text": "Below are some examples of array with range:" }, { "code": null, "e": 25713, "s": 25704, "text": "Example:" }, { "code": "// Scala program to create array with range import Array._ // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var array1 = range(1, 15) var array2 = range(1, 15, 3) // Print all the elements of array1 for ( i <- array1 ) { print( \" \" + i ) } println() // Print all the elements of array2 for ( i <- array2 ) { print( \" \" + i ) } }}", "e": 26214, "s": 25713, "text": null }, { "code": null, "e": 26261, "s": 26214, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14\n 1 4 7 10 13\n" }, { "code": null, "e": 26651, "s": 26261, "text": "In above example, an array of range (1, 15). In this range difference is not given so by default difference of range will be 1 element. Elements in the array are 1, 4, 7, 10 and 13. Here, we are creating an array of range (1, 15, 3). Which means an array with elements between 1 and 15 and range difference is 3. Elements in the array are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, and 14." }, { "code": null, "e": 26919, "s": 26651, "text": "For some of the collections, such as List and Array, we can also create a Range and convert it to the desired sequence: The REPL shows the array that can be created directly from a Range is toArray. We can also use a Range to create a sequence of characters as below:" }, { "code": null, "e": 26928, "s": 26919, "text": "Example:" }, { "code": "// Scala program to create array with range import Array._ // Creating objectobject GFG{ // Main method def main(args: Array[String]) { val array1 = ('A' to 'F').toArray val array2 = ('a' to 'f').by(2).toArray // Print all the elements of array1 for ( i <- array1 ) { print( \" \" + i ) } println() // Print all the elements of array2 for ( i <- array2 ) { print( \" \" + i ) } }}", "e": 27452, "s": 26928, "text": null }, { "code": null, "e": 27472, "s": 27452, "text": "A B C D E F\n a c e\n" }, { "code": null, "e": 27862, "s": 27472, "text": "In above example, an array of range (‘A’ to ‘F’).toArray. In this, range difference is not given so by default difference of range will be 1 character. characters in the array are A, B, C, D, E and F. Here, we are creating an array of range (‘a’ to ‘f’).by(2).toArray. Which means an array with characters between a and f and range difference is 2. Characters in the array are a, c, and e." }, { "code": null, "e": 27875, "s": 27862, "text": "Scala-Arrays" }, { "code": null, "e": 27881, "s": 27875, "text": "Scala" }, { "code": null, "e": 27979, "s": 27881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28000, "s": 27979, "text": "Inheritance in Scala" }, { "code": null, "e": 28015, "s": 28000, "text": "Scala | Traits" }, { "code": null, "e": 28032, "s": 28015, "text": "Scala ListBuffer" }, { "code": null, "e": 28067, "s": 28032, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 28088, "s": 28067, "text": "Hello World in Scala" }, { "code": null, "e": 28115, "s": 28088, "text": "Scala | Functions - Basics" }, { "code": null, "e": 28181, "s": 28115, "text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)" }, { "code": null, "e": 28218, "s": 28181, "text": "Scala List map() method with example" }, { "code": null, "e": 28236, "s": 28218, "text": "Comments In Scala" } ]
HTML height Attribute - GeeksforGeeks
10 Dec, 2021 The HTML <td> height Attribute is used to specify the height of the table cell. If the <td> height attribute is not set then it takes default height according to content. Syntax: <td height="pixels | %"> Attribute Values: pixels: It sets the height of the table cell in terms of pixels. %: It sets the height of the table cell in terms of percentage (%). Note: The <td> height Attribute is not supported by HTML 5. Example: This example describes the HTML <td> height Attribute in order to add the height of the table cell. HTML <!DOCTYPE html><html> <head> <title> HTML td height Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML td height Attribute</h2> <table border="1" width="500"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td height="50">BITTU</td> <td height="50">22</td> <td height="50">CSE</td> </tr> <tr> <td height="100">RAKESH</td> <td height="100">25</td> <td height="100">EC</td> </tr> </table></body> </html> Output: HTML <td> height Attribute Supported Browsers: The browser supported by HTML <td> height Attribute are listed below: Google Chrome Internet Explorer Microsoft Edge Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 bhaskargeeksforgeeks HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25821, "s": 25793, "text": "\n10 Dec, 2021" }, { "code": null, "e": 25992, "s": 25821, "text": "The HTML <td> height Attribute is used to specify the height of the table cell. If the <td> height attribute is not set then it takes default height according to content." }, { "code": null, "e": 26001, "s": 25992, "text": "Syntax: " }, { "code": null, "e": 26026, "s": 26001, "text": "<td height=\"pixels | %\">" }, { "code": null, "e": 26046, "s": 26026, "text": "Attribute Values: " }, { "code": null, "e": 26111, "s": 26046, "text": "pixels: It sets the height of the table cell in terms of pixels." }, { "code": null, "e": 26179, "s": 26111, "text": "%: It sets the height of the table cell in terms of percentage (%)." }, { "code": null, "e": 26239, "s": 26179, "text": "Note: The <td> height Attribute is not supported by HTML 5." }, { "code": null, "e": 26349, "s": 26239, "text": "Example: This example describes the HTML <td> height Attribute in order to add the height of the table cell." }, { "code": null, "e": 26354, "s": 26349, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML td height Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML td height Attribute</h2> <table border=\"1\" width=\"500\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td height=\"50\">BITTU</td> <td height=\"50\">22</td> <td height=\"50\">CSE</td> </tr> <tr> <td height=\"100\">RAKESH</td> <td height=\"100\">25</td> <td height=\"100\">EC</td> </tr> </table></body> </html>", "e": 26951, "s": 26354, "text": null }, { "code": null, "e": 26959, "s": 26951, "text": "Output:" }, { "code": null, "e": 26988, "s": 26959, "text": " HTML <td> height Attribute " }, { "code": null, "e": 27078, "s": 26988, "text": "Supported Browsers: The browser supported by HTML <td> height Attribute are listed below:" }, { "code": null, "e": 27092, "s": 27078, "text": "Google Chrome" }, { "code": null, "e": 27110, "s": 27092, "text": "Internet Explorer" }, { "code": null, "e": 27125, "s": 27110, "text": "Microsoft Edge" }, { "code": null, "e": 27133, "s": 27125, "text": "Firefox" }, { "code": null, "e": 27140, "s": 27133, "text": "Safari" }, { "code": null, "e": 27146, "s": 27140, "text": "Opera" }, { "code": null, "e": 27283, "s": 27146, "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": 27297, "s": 27283, "text": "ManasChhabra2" }, { "code": null, "e": 27318, "s": 27297, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27334, "s": 27318, "text": "HTML-Attributes" }, { "code": null, "e": 27339, "s": 27334, "text": "HTML" }, { "code": null, "e": 27356, "s": 27339, "text": "Web Technologies" }, { "code": null, "e": 27361, "s": 27356, "text": "HTML" }, { "code": null, "e": 27459, "s": 27361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27507, "s": 27459, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27531, "s": 27507, "text": "REST API (Introduction)" }, { "code": null, "e": 27581, "s": 27531, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27631, "s": 27581, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27668, "s": 27631, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27708, "s": 27668, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27741, "s": 27708, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27786, "s": 27741, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27829, "s": 27786, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Stack DataFrame Columns in R? - GeeksforGeeks
19 Dec, 2021 A dataframe is a tubular structure composed of rows and columns. The dataframe columns can be stacked together to divide the columns depending on the values contained within them. The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns. The stack method in base R is used to transform data available in the form of separate columns within a data frame or a list into a single column. The stack method produces a result in the form of a data frame with two columns: values: the result produced by concatenating the selected vectors in x. ind: a factor indicating from which vector in x the observation originated. Syntax: stack(x) Arguments : x – a list or data frame to be stacked Original Data frame looks as: col1 semester quiz_sst quiz_maths 1 Yash A 1 2 2 Yash B 3 4 3 Mallika A 4 6 4 Mallika B 8 2 5 Muskan A 9 7 6 Muskan B 1 3 R # creating a data framedata <- data.frame(col1=c('Yash', 'Yash', 'Mallika', 'Mallika', 'Muskan', 'Muskan'), semester=c(rep(LETTERS[1:2],3)), quiz_sst=c(1, 3, 4, 8, 9, 1), quiz_maths=c(2, 4, 6, 2, 7, 3)) # binding the first two columns as it is # and stacking the third and fourth columnsdata_mod <- cbind(data[1:2], stack(data[3:4]))print(data_mod) Output col1 semester values ind 1 Yash A 1 quiz_sst 2 Yash B 3 quiz_sst 3 Mallika A 4 quiz_sst 4 Mallika B 8 quiz_sst 5 Muskan A 9 quiz_sst 6 Muskan B 1 quiz_sst 7 Yash A 2 quiz_maths 8 Yash B 4 quiz_maths 9 Mallika A 6 quiz_maths 10 Mallika B 2 quiz_maths 11 Muskan A 7 quiz_maths 12 Muskan B 3 quiz_maths The reshape2 package in R can be used to change the structure of the data supplied and can be installed and imported into the working space using the following command : install.packages("reshape2") library(reshape2) The melt method in this package can be used to stack data frame columns together. It is used to reshape and elongate the data frame. The melt() method has the following syntax : melt(data, id.var , variable.name) Arguments : data – The data frame to stack columns of id.ar – The columns to use as primary key variable.name – The new column name to append Original Data Frame looks as: col1 semester quiz_sst quiz_maths 1 Yash A 1 2 2 Yash B 3 4 3 Mallika A 4 6 4 Mallika B 8 2 5 Muskan A 9 7 6 Muskan B 1 3 R # importing the required librarylibrary("reshape2") # creating a data framedata <- data.frame(col1=c('Yash', 'Yash', 'Mallika', 'Mallika', 'Muskan', 'Muskan'), semester=c(rep(LETTERS[1:2],3)), quiz_sst=c(1, 3, 4, 8, 9, 1), quiz_maths=c(2, 4, 6, 2, 7, 3)) # binding the first two columns as it is # and stacking the third and fourth columnsdata_mod <- reshape2::melt(data, id.var = c('col1', 'semester'), variable.name = 'quiz_marks')print(data_mod) Output [1] "Modified DataFrame" col1 semester quiz_marks value 1 Yash A quiz_sst 1 2 Yash B quiz_sst 3 3 Mallika A quiz_sst 4 4 Mallika B quiz_sst 8 5 Muskan A quiz_sst 9 6 Muskan B quiz_sst 1 7 Yash A quiz_maths 2 8 Yash B quiz_maths 4 9 Mallika A quiz_maths 6 10 Mallika B quiz_maths 2 11 Muskan A quiz_maths 7 12 Muskan B quiz_maths 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. 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 Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n19 Dec, 2021" }, { "code": null, "e": 26668, "s": 26487, "text": "A dataframe is a tubular structure composed of rows and columns. The dataframe columns can be stacked together to divide the columns depending on the values contained within them. " }, { "code": null, "e": 26927, "s": 26668, "text": "The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns. " }, { "code": null, "e": 27155, "s": 26927, "text": "The stack method in base R is used to transform data available in the form of separate columns within a data frame or a list into a single column. The stack method produces a result in the form of a data frame with two columns:" }, { "code": null, "e": 27227, "s": 27155, "text": "values: the result produced by concatenating the selected vectors in x." }, { "code": null, "e": 27303, "s": 27227, "text": "ind: a factor indicating from which vector in x the observation originated." }, { "code": null, "e": 27311, "s": 27303, "text": "Syntax:" }, { "code": null, "e": 27320, "s": 27311, "text": "stack(x)" }, { "code": null, "e": 27333, "s": 27320, "text": "Arguments : " }, { "code": null, "e": 27372, "s": 27333, "text": "x – a list or data frame to be stacked" }, { "code": null, "e": 27402, "s": 27372, "text": "Original Data frame looks as:" }, { "code": null, "e": 27675, "s": 27402, "text": " col1 semester quiz_sst quiz_maths\n1 Yash A 1 2\n2 Yash B 3 4\n3 Mallika A 4 6\n4 Mallika B 8 2\n5 Muskan A 9 7\n6 Muskan B 1 3" }, { "code": null, "e": 27677, "s": 27675, "text": "R" }, { "code": "# creating a data framedata <- data.frame(col1=c('Yash', 'Yash', 'Mallika', 'Mallika', 'Muskan', 'Muskan'), semester=c(rep(LETTERS[1:2],3)), quiz_sst=c(1, 3, 4, 8, 9, 1), quiz_maths=c(2, 4, 6, 2, 7, 3)) # binding the first two columns as it is # and stacking the third and fourth columnsdata_mod <- cbind(data[1:2], stack(data[3:4]))print(data_mod)", "e": 28107, "s": 27677, "text": null }, { "code": null, "e": 28114, "s": 28107, "text": "Output" }, { "code": null, "e": 28608, "s": 28114, "text": " col1 semester values ind\n1 Yash A 1 quiz_sst\n2 Yash B 3 quiz_sst\n3 Mallika A 4 quiz_sst\n4 Mallika B 8 quiz_sst\n5 Muskan A 9 quiz_sst\n6 Muskan B 1 quiz_sst\n7 Yash A 2 quiz_maths\n8 Yash B 4 quiz_maths\n9 Mallika A 6 quiz_maths\n10 Mallika B 2 quiz_maths\n11 Muskan A 7 quiz_maths\n12 Muskan B 3 quiz_maths" }, { "code": null, "e": 28779, "s": 28608, "text": "The reshape2 package in R can be used to change the structure of the data supplied and can be installed and imported into the working space using the following command : " }, { "code": null, "e": 28826, "s": 28779, "text": "install.packages(\"reshape2\")\nlibrary(reshape2)" }, { "code": null, "e": 29005, "s": 28826, "text": "The melt method in this package can be used to stack data frame columns together. It is used to reshape and elongate the data frame. The melt() method has the following syntax : " }, { "code": null, "e": 29040, "s": 29005, "text": "melt(data, id.var , variable.name)" }, { "code": null, "e": 29053, "s": 29040, "text": "Arguments : " }, { "code": null, "e": 29095, "s": 29053, "text": "data – The data frame to stack columns of" }, { "code": null, "e": 29137, "s": 29095, "text": "id.ar – The columns to use as primary key" }, { "code": null, "e": 29183, "s": 29137, "text": "variable.name – The new column name to append" }, { "code": null, "e": 29213, "s": 29183, "text": "Original Data Frame looks as:" }, { "code": null, "e": 29485, "s": 29213, "text": " col1 semester quiz_sst quiz_maths\n1 Yash A 1 2\n2 Yash B 3 4\n3 Mallika A 4 6\n4 Mallika B 8 2\n5 Muskan A 9 7\n6 Muskan B 1 3" }, { "code": null, "e": 29487, "s": 29485, "text": "R" }, { "code": "# importing the required librarylibrary(\"reshape2\") # creating a data framedata <- data.frame(col1=c('Yash', 'Yash', 'Mallika', 'Mallika', 'Muskan', 'Muskan'), semester=c(rep(LETTERS[1:2],3)), quiz_sst=c(1, 3, 4, 8, 9, 1), quiz_maths=c(2, 4, 6, 2, 7, 3)) # binding the first two columns as it is # and stacking the third and fourth columnsdata_mod <- reshape2::melt(data, id.var = c('col1', 'semester'), variable.name = 'quiz_marks')print(data_mod)", "e": 30044, "s": 29487, "text": null }, { "code": null, "e": 30051, "s": 30044, "text": "Output" }, { "code": null, "e": 30556, "s": 30051, "text": "[1] \"Modified DataFrame\"\n col1 semester quiz_marks value\n1 Yash A quiz_sst 1\n2 Yash B quiz_sst 3\n3 Mallika A quiz_sst 4\n4 Mallika B quiz_sst 8\n5 Muskan A quiz_sst 9\n6 Muskan B quiz_sst 1\n7 Yash A quiz_maths 2\n8 Yash B quiz_maths 4\n9 Mallika A quiz_maths 6\n10 Mallika B quiz_maths 2\n11 Muskan A quiz_maths 7\n12 Muskan B quiz_maths 3" }, { "code": null, "e": 30563, "s": 30556, "text": "Picked" }, { "code": null, "e": 30584, "s": 30563, "text": "R DataFrame-Programs" }, { "code": null, "e": 30596, "s": 30584, "text": "R-DataFrame" }, { "code": null, "e": 30607, "s": 30596, "text": "R Language" }, { "code": null, "e": 30618, "s": 30607, "text": "R Programs" }, { "code": null, "e": 30716, "s": 30618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30768, "s": 30716, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30803, "s": 30768, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30841, "s": 30803, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30899, "s": 30841, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30942, "s": 30899, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31000, "s": 30942, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31043, "s": 31000, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31092, "s": 31043, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31142, "s": 31092, "text": "How to filter R dataframe by multiple conditions?" } ]
How to Install and Use bmon Real Time Bandwidth Monitor in Linux? - GeeksforGeeks
11 Feb, 2021 Bmon Stands is an open source tool for the bandwidth monitoring tool. bmon is a powerful CLI based network bandwidth monitoring and debugging tool for Unix / Linux systems to capture networking related statistics & present them visually on the command line in a human-friendly way. It captures the traffic usage over all the network interfaces on the system. It is an effective and fast real-time network bandwidth monitor and rate estimator. It features various output methods such as : HTML output ASCII output Graphical visualization An interactive curses user interface A programmable text output for scripting It can be easily installed from the default package manager as almost all Linux distributions has bmon package in the default repositories but the available version might be a little older. On RHEL/CentOS/Fedora: $ sudo yum install bmon On Fedora 22+: $ sudo dnf install bmon On Debian/Ubuntu/Mint: $ sudo apt-get install bmon On openSUSE system: $ sudo zypper in bmon On Arch Linux based systems: $ pacman -S bmon For the most recent version of bmon (i.e version 4.0), you have to build it from its source using the following commands for different Linux distros: For Debian based systems : $ git clone https://github.com/tgraf/bmon.git $ cd bmon $ sudo apt-get install build-essential make libconfuse-dev libnl-3-dev libnl-route-3-dev libncurses-dev pkg-config dh-autoreconf $ sudo ./autogen.sh $ sudo ./configure $ sudo make $ sudo make install $ bmon For CentOS 6, RHEL based systems: $ git clone https://github.com/tgraf/bmon.git $ cd bmon $ sudo yum install make libconfuse-devel libnl3-devel libnl-route3-devel ncurses-devel $ sudo ./autogen.sh $ sudo./configure $ sudo make $ sudo make install $ bmon For OSX installation : $ brew install bmon Full help is provided through the following command : $ bmon --help After completing the bmon installation successfully via the help of above commands for different distros, just type the following command to run the bmon tool : $ bmon To view the quick reference of bmon as below press [Shift + ?] : bmon shows only interface information by default. To load the graphics, enter g, i, or d (depending on the distro) for detailed graphical visualization of information. To monitor the enp1s0 network interface, we will use the flag -p to set policy defining which network interfaces to display as below : $ bmon -p enp1s0 To see the result in bit per second instead of bytes per second, use the -b flag like so : $ bmon -bp enp1s0 To define the intervals per second use -r flag as below : $ bmon -r 2 -p enp1s0 Netlink employs the Netlink protocol to collect interface and traffic control statistics from the kernel. By default, netlink is the input module. To explicitly set netlink as input module : $ bmon -i netlink proc is used to read interface statistics from the /proc/net/dev file. It is considered a legacy interface It is offered for backward compatibly and also as a fallback module in case the Netlink interface is not available. To explicitly set proc as input module : $ bmon -i proc dummy is the programmable input module for debugging & testing purposes. To explicitly set dummy as input module : $ bmon -i dummy Null is used to disable the data collection. $ bmon -i null To obtain more information about a specific module use the “help” flag with the input mode as below : $ bmon -i dummy:help curses is an interactive curses-based text user interface, It offers real-time rate estimations To get the graphical representation of each attribute curses output mode is used. By default, curses are the output mode. To get the output in curses : $ bmon -o curses ascii is a straightforward, , human-readable and programmable text output. Can be used to display a list of interfaces, detailed counters, and graphs to the console. By default, it is the fallback output mode when curses are not available. To get output in ascii : $ bmon -o ascii The format is a fully scriptable output mode. Meant for consumption by other programs i.e. we can use its output values at a later time in scripts/programs for analysis & other stuff. To get output in format mode : $ bmon -o format To get interactive curses output with graph : $ bmon -o curses:ngraph=2 To obtain more information about a specific module use “help” flag with the output mode as below : $ bmon -o ascii:help To get help or read more about bmon use the man page or “help” flag: $ bmon --help or $ man bmon linux Picked Technical Scripter 2020 How To Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to create a nested RecyclerView in Android How to Install Jupyter Notebook on MacOS? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26197, "s": 26169, "text": "\n11 Feb, 2021" }, { "code": null, "e": 26640, "s": 26197, "text": "Bmon Stands is an open source tool for the bandwidth monitoring tool. bmon is a powerful CLI based network bandwidth monitoring and debugging tool for Unix / Linux systems to capture networking related statistics & present them visually on the command line in a human-friendly way. It captures the traffic usage over all the network interfaces on the system. It is an effective and fast real-time network bandwidth monitor and rate estimator." }, { "code": null, "e": 26685, "s": 26640, "text": "It features various output methods such as :" }, { "code": null, "e": 26697, "s": 26685, "text": "HTML output" }, { "code": null, "e": 26710, "s": 26697, "text": "ASCII output" }, { "code": null, "e": 26734, "s": 26710, "text": "Graphical visualization" }, { "code": null, "e": 26771, "s": 26734, "text": "An interactive curses user interface" }, { "code": null, "e": 26812, "s": 26771, "text": "A programmable text output for scripting" }, { "code": null, "e": 27002, "s": 26812, "text": "It can be easily installed from the default package manager as almost all Linux distributions has bmon package in the default repositories but the available version might be a little older." }, { "code": null, "e": 27025, "s": 27002, "text": "On RHEL/CentOS/Fedora:" }, { "code": null, "e": 27049, "s": 27025, "text": "$ sudo yum install bmon" }, { "code": null, "e": 27064, "s": 27049, "text": "On Fedora 22+:" }, { "code": null, "e": 27088, "s": 27064, "text": "$ sudo dnf install bmon" }, { "code": null, "e": 27111, "s": 27088, "text": "On Debian/Ubuntu/Mint:" }, { "code": null, "e": 27139, "s": 27111, "text": "$ sudo apt-get install bmon" }, { "code": null, "e": 27159, "s": 27139, "text": "On openSUSE system:" }, { "code": null, "e": 27181, "s": 27159, "text": "$ sudo zypper in bmon" }, { "code": null, "e": 27210, "s": 27181, "text": "On Arch Linux based systems:" }, { "code": null, "e": 27227, "s": 27210, "text": "$ pacman -S bmon" }, { "code": null, "e": 27377, "s": 27227, "text": "For the most recent version of bmon (i.e version 4.0), you have to build it from its source using the following commands for different Linux distros:" }, { "code": null, "e": 27404, "s": 27377, "text": "For Debian based systems :" }, { "code": null, "e": 27667, "s": 27404, "text": "$ git clone https://github.com/tgraf/bmon.git\n$ cd bmon\n$ sudo apt-get install build-essential make libconfuse-dev libnl-3-dev libnl-route-3-dev libncurses-dev pkg-config dh-autoreconf\n$ sudo ./autogen.sh\n$ sudo ./configure\n$ sudo make\n$ sudo make install\n$ bmon" }, { "code": null, "e": 27701, "s": 27667, "text": "For CentOS 6, RHEL based systems:" }, { "code": null, "e": 27921, "s": 27701, "text": "$ git clone https://github.com/tgraf/bmon.git\n$ cd bmon\n$ sudo yum install make libconfuse-devel libnl3-devel libnl-route3-devel ncurses-devel\n$ sudo ./autogen.sh\n$ sudo./configure\n$ sudo make\n$ sudo make install\n$ bmon" }, { "code": null, "e": 27944, "s": 27921, "text": "For OSX installation :" }, { "code": null, "e": 27964, "s": 27944, "text": "$ brew install bmon" }, { "code": null, "e": 28018, "s": 27964, "text": "Full help is provided through the following command :" }, { "code": null, "e": 28032, "s": 28018, "text": "$ bmon --help" }, { "code": null, "e": 28193, "s": 28032, "text": "After completing the bmon installation successfully via the help of above commands for different distros, just type the following command to run the bmon tool :" }, { "code": null, "e": 28200, "s": 28193, "text": "$ bmon" }, { "code": null, "e": 28265, "s": 28200, "text": "To view the quick reference of bmon as below press [Shift + ?] :" }, { "code": null, "e": 28433, "s": 28265, "text": "bmon shows only interface information by default. To load the graphics, enter g, i, or d (depending on the distro) for detailed graphical visualization of information." }, { "code": null, "e": 28568, "s": 28433, "text": "To monitor the enp1s0 network interface, we will use the flag -p to set policy defining which network interfaces to display as below :" }, { "code": null, "e": 28585, "s": 28568, "text": "$ bmon -p enp1s0" }, { "code": null, "e": 28676, "s": 28585, "text": "To see the result in bit per second instead of bytes per second, use the -b flag like so :" }, { "code": null, "e": 28694, "s": 28676, "text": "$ bmon -bp enp1s0" }, { "code": null, "e": 28752, "s": 28694, "text": "To define the intervals per second use -r flag as below :" }, { "code": null, "e": 28774, "s": 28752, "text": "$ bmon -r 2 -p enp1s0" }, { "code": null, "e": 28880, "s": 28774, "text": "Netlink employs the Netlink protocol to collect interface and traffic control statistics from the kernel." }, { "code": null, "e": 28921, "s": 28880, "text": "By default, netlink is the input module." }, { "code": null, "e": 28965, "s": 28921, "text": "To explicitly set netlink as input module :" }, { "code": null, "e": 28984, "s": 28965, "text": "$ bmon -i netlink " }, { "code": null, "e": 29055, "s": 28984, "text": "proc is used to read interface statistics from the /proc/net/dev file." }, { "code": null, "e": 29091, "s": 29055, "text": "It is considered a legacy interface" }, { "code": null, "e": 29207, "s": 29091, "text": "It is offered for backward compatibly and also as a fallback module in case the Netlink interface is not available." }, { "code": null, "e": 29248, "s": 29207, "text": "To explicitly set proc as input module :" }, { "code": null, "e": 29263, "s": 29248, "text": "$ bmon -i proc" }, { "code": null, "e": 29336, "s": 29263, "text": "dummy is the programmable input module for debugging & testing purposes." }, { "code": null, "e": 29378, "s": 29336, "text": "To explicitly set dummy as input module :" }, { "code": null, "e": 29394, "s": 29378, "text": "$ bmon -i dummy" }, { "code": null, "e": 29439, "s": 29394, "text": "Null is used to disable the data collection." }, { "code": null, "e": 29454, "s": 29439, "text": "$ bmon -i null" }, { "code": null, "e": 29556, "s": 29454, "text": "To obtain more information about a specific module use the “help” flag with the input mode as below :" }, { "code": null, "e": 29577, "s": 29556, "text": "$ bmon -i dummy:help" }, { "code": null, "e": 29636, "s": 29577, "text": "curses is an interactive curses-based text user interface," }, { "code": null, "e": 29673, "s": 29636, "text": "It offers real-time rate estimations" }, { "code": null, "e": 29755, "s": 29673, "text": "To get the graphical representation of each attribute curses output mode is used." }, { "code": null, "e": 29795, "s": 29755, "text": "By default, curses are the output mode." }, { "code": null, "e": 29825, "s": 29795, "text": "To get the output in curses :" }, { "code": null, "e": 29842, "s": 29825, "text": "$ bmon -o curses" }, { "code": null, "e": 29917, "s": 29842, "text": "ascii is a straightforward, , human-readable and programmable text output." }, { "code": null, "e": 30008, "s": 29917, "text": "Can be used to display a list of interfaces, detailed counters, and graphs to the console." }, { "code": null, "e": 30082, "s": 30008, "text": "By default, it is the fallback output mode when curses are not available." }, { "code": null, "e": 30107, "s": 30082, "text": "To get output in ascii :" }, { "code": null, "e": 30124, "s": 30107, "text": "$ bmon -o ascii " }, { "code": null, "e": 30170, "s": 30124, "text": "The format is a fully scriptable output mode." }, { "code": null, "e": 30308, "s": 30170, "text": "Meant for consumption by other programs i.e. we can use its output values at a later time in scripts/programs for analysis & other stuff." }, { "code": null, "e": 30339, "s": 30308, "text": "To get output in format mode :" }, { "code": null, "e": 30356, "s": 30339, "text": "$ bmon -o format" }, { "code": null, "e": 30402, "s": 30356, "text": "To get interactive curses output with graph :" }, { "code": null, "e": 30428, "s": 30402, "text": "$ bmon -o curses:ngraph=2" }, { "code": null, "e": 30527, "s": 30428, "text": "To obtain more information about a specific module use “help” flag with the output mode as below :" }, { "code": null, "e": 30548, "s": 30527, "text": "$ bmon -o ascii:help" }, { "code": null, "e": 30617, "s": 30548, "text": "To get help or read more about bmon use the man page or “help” flag:" }, { "code": null, "e": 30632, "s": 30617, "text": "$ bmon --help " }, { "code": null, "e": 30635, "s": 30632, "text": "or" }, { "code": null, "e": 30647, "s": 30635, "text": "$ man bmon " }, { "code": null, "e": 30653, "s": 30647, "text": "linux" }, { "code": null, "e": 30660, "s": 30653, "text": "Picked" }, { "code": null, "e": 30684, "s": 30660, "text": "Technical Scripter 2020" }, { "code": null, "e": 30691, "s": 30684, "text": "How To" }, { "code": null, "e": 30702, "s": 30691, "text": "Linux-Unix" }, { "code": null, "e": 30721, "s": 30702, "text": "Technical Scripter" }, { "code": null, "e": 30819, "s": 30721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30853, "s": 30819, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 30911, "s": 30853, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 30960, "s": 30911, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 31007, "s": 30960, "text": "How to create a nested RecyclerView in Android" }, { "code": null, "e": 31049, "s": 31007, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 31089, "s": 31049, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 31129, "s": 31089, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 31156, "s": 31129, "text": "grep command in Unix/Linux" }, { "code": null, "e": 31191, "s": 31156, "text": "cut command in Linux with examples" } ]
SWING - JScrollBar Class
The class JScrollBar is an implementation of scrollbar. Following is the declaration for javax.swing.JScrollBar class − public class JScrollBar extends JComponent implements Adjustable, Accessible Following are the fields for javax.swing.ImageIcon class − protected int blockIncrement protected int blockIncrement protected BoundedRangeModel model − The model that represents the scrollbar's minimum, maximum, extent (aka "visibleAmount") and current value. protected BoundedRangeModel model − The model that represents the scrollbar's minimum, maximum, extent (aka "visibleAmount") and current value. protected int orientation protected int orientation protected int unitIncrement protected int unitIncrement JScrollBar() Creates a vertical scrollbar with the initial values. JScrollBar(int orientation) Creates a scrollbar with the specified orientation and the initial values. JScrollBar(int orientation, int value, int extent, int min, int max) Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum. void addAdjustmentListener(AdjustmentListener l) Adds an AdjustmentListener. protected void fireAdjustmentValueChanged(int id, int type, int value) Notifies listeners that the scrollbar's model has changed. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this JScrollBar. AdjustmentListener[] getAdjustmentListeners() Returns an array of all the AdjustmentListeners added to this JScrollBar with addAdjustmentListener(). int getBlockIncrement() For backwards compatibility with java.awt.Scrollbar. int getBlockIncrement(int direction) Returns the amount to change the scrollbar's value by, given a block (usually "page") up/down request. int getMaximum() The maximum value of the scrollbar is maximum - extent. Dimension getMaximumSize() The scrollbar is flexible along it's scrolling axis and rigid along the other axis. int getMinimum() Returns the minimum value supported by the scrollbar (usually zero). Dimension getMinimumSize() The scrollbar is flexible along it's scrolling axis and rigid along the other axis. BoundedRangeModel getModel() Returns data model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent. int getOrientation() Returns the component's orientation (horizontal or vertical). ScrollBarUI getUI() Returns the delegate that implements the look and feel for this component. String getUIClassID() Returns the name of the LookAndFeel class for this component. int getUnitIncrement() For backwards compatibility with java.awt.Scrollbar. int getUnitIncrement(int direction) Returns the amount to change the scrollbar's value by, given a unit up/down request. int getValue() Returns the scrollbar's value. boolean getValueIsAdjusting() True if the scrollbar knob is being dragged. int getVisibleAmount() Returns the scrollbar's extent, aka its "visibleAmount". protected String paramString() Returns a string representation of this JScrollBar. void removeAdjustmentListener(AdjustmentListener l) Removes an AdjustmentEvent listener. void setBlockIncrement(int blockIncrement) Sets the blockIncrement property. void setEnabled(boolean x) Enables the component so that the knob position can be changed. void setMaximum(int maximum) Sets the model's maximum property. void setMinimum(int minimum) Sets the model's minimum property. void setModel(BoundedRangeModel newModel) Sets the model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent. void setOrientation(int orientation) Set the scrollbar's orientation to either VERTICAL or HORIZONTAL. void setUI(ScrollBarUI ui) Sets the L&F object that renders this component. void setUnitIncrement(int unitIncrement) Sets the unitIncrement property. void setValue(int value) Sets the scrollbar's value. void setValueIsAdjusting(boolean b) Sets the model's valueIsAdjusting property. void setValues(int newValue, int newExtent, int newMin, int newMax) Sets the four BoundedRangeModel properties after forcing the arguments to obey the usual constraints. void setVisibleAmount(int extent) Set the model's extent property. void updateUI() Overrides JComponent.updateUI. This class inherits methods from the following classes − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingControlDemo.java 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.showScrollbarDemo(); } 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 showScrollbarDemo() { headerLabel.setText("Control in action: JScrollbar"); final JScrollBar horizontalScroller = new JScrollBar(JScrollBar.HORIZONTAL); final JScrollBar verticalScroller = new JScrollBar(); verticalScroller.setOrientation(JScrollBar.VERTICAL); horizontalScroller.setMaximum (100); horizontalScroller.setMinimum (1); verticalScroller.setMaximum (100); verticalScroller.setMinimum (1); horizontalScroller.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { statusLabel.setText("Horozontal: " +horizontalScroller.getValue() +" ,Vertical: " + verticalScroller.getValue()); } }); verticalScroller.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { statusLabel.setText("Horozontal: " +horizontalScroller.getValue() +" ,Vertical: "+ verticalScroller.getValue()); } }); controlPanel.add(horizontalScroller); controlPanel.add(verticalScroller); 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. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1819, "s": 1763, "text": "The class JScrollBar is an implementation of scrollbar." }, { "code": null, "e": 1883, "s": 1819, "text": "Following is the declaration for javax.swing.JScrollBar class −" }, { "code": null, "e": 1970, "s": 1883, "text": "public class JScrollBar\n extends JComponent\n implements Adjustable, Accessible\n" }, { "code": null, "e": 2029, "s": 1970, "text": "Following are the fields for javax.swing.ImageIcon class −" }, { "code": null, "e": 2058, "s": 2029, "text": "protected int blockIncrement" }, { "code": null, "e": 2087, "s": 2058, "text": "protected int blockIncrement" }, { "code": null, "e": 2231, "s": 2087, "text": "protected BoundedRangeModel model − The model that represents the scrollbar's minimum, maximum, extent (aka \"visibleAmount\") and current value." }, { "code": null, "e": 2375, "s": 2231, "text": "protected BoundedRangeModel model − The model that represents the scrollbar's minimum, maximum, extent (aka \"visibleAmount\") and current value." }, { "code": null, "e": 2401, "s": 2375, "text": "protected int orientation" }, { "code": null, "e": 2427, "s": 2401, "text": "protected int orientation" }, { "code": null, "e": 2455, "s": 2427, "text": "protected int unitIncrement" }, { "code": null, "e": 2483, "s": 2455, "text": "protected int unitIncrement" }, { "code": null, "e": 2496, "s": 2483, "text": "JScrollBar()" }, { "code": null, "e": 2550, "s": 2496, "text": "Creates a vertical scrollbar with the initial values." }, { "code": null, "e": 2578, "s": 2550, "text": "JScrollBar(int orientation)" }, { "code": null, "e": 2653, "s": 2578, "text": "Creates a scrollbar with the specified orientation and the initial values." }, { "code": null, "e": 2722, "s": 2653, "text": "JScrollBar(int orientation, int value, int extent, int min, int max)" }, { "code": null, "e": 2811, "s": 2722, "text": "Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum." }, { "code": null, "e": 2860, "s": 2811, "text": "void addAdjustmentListener(AdjustmentListener l)" }, { "code": null, "e": 2888, "s": 2860, "text": "Adds an AdjustmentListener." }, { "code": null, "e": 2959, "s": 2888, "text": "protected void fireAdjustmentValueChanged(int id, int type, int value)" }, { "code": null, "e": 3018, "s": 2959, "text": "Notifies listeners that the scrollbar's model has changed." }, { "code": null, "e": 3059, "s": 3018, "text": "AccessibleContext getAccessibleContext()" }, { "code": null, "e": 3119, "s": 3059, "text": "Gets the AccessibleContext associated with this JScrollBar." }, { "code": null, "e": 3165, "s": 3119, "text": "AdjustmentListener[] getAdjustmentListeners()" }, { "code": null, "e": 3268, "s": 3165, "text": "Returns an array of all the AdjustmentListeners added to this JScrollBar with addAdjustmentListener()." }, { "code": null, "e": 3292, "s": 3268, "text": "int getBlockIncrement()" }, { "code": null, "e": 3345, "s": 3292, "text": "For backwards compatibility with java.awt.Scrollbar." }, { "code": null, "e": 3382, "s": 3345, "text": "int getBlockIncrement(int direction)" }, { "code": null, "e": 3485, "s": 3382, "text": "Returns the amount to change the scrollbar's value by, given a block (usually \"page\") up/down request." }, { "code": null, "e": 3502, "s": 3485, "text": "int getMaximum()" }, { "code": null, "e": 3558, "s": 3502, "text": "The maximum value of the scrollbar is maximum - extent." }, { "code": null, "e": 3585, "s": 3558, "text": "Dimension getMaximumSize()" }, { "code": null, "e": 3669, "s": 3585, "text": "The scrollbar is flexible along it's scrolling axis and rigid along the other axis." }, { "code": null, "e": 3686, "s": 3669, "text": "int getMinimum()" }, { "code": null, "e": 3755, "s": 3686, "text": "Returns the minimum value supported by the scrollbar (usually zero)." }, { "code": null, "e": 3782, "s": 3755, "text": "Dimension getMinimumSize()" }, { "code": null, "e": 3866, "s": 3782, "text": "The scrollbar is flexible along it's scrolling axis and rigid along the other axis." }, { "code": null, "e": 3895, "s": 3866, "text": "BoundedRangeModel getModel()" }, { "code": null, "e": 4005, "s": 3895, "text": "Returns data model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent." }, { "code": null, "e": 4026, "s": 4005, "text": "int getOrientation()" }, { "code": null, "e": 4088, "s": 4026, "text": "Returns the component's orientation (horizontal or vertical)." }, { "code": null, "e": 4108, "s": 4088, "text": "ScrollBarUI getUI()" }, { "code": null, "e": 4183, "s": 4108, "text": "Returns the delegate that implements the look and feel for this component." }, { "code": null, "e": 4205, "s": 4183, "text": "String getUIClassID()" }, { "code": null, "e": 4267, "s": 4205, "text": "Returns the name of the LookAndFeel class for this component." }, { "code": null, "e": 4290, "s": 4267, "text": "int getUnitIncrement()" }, { "code": null, "e": 4343, "s": 4290, "text": "For backwards compatibility with java.awt.Scrollbar." }, { "code": null, "e": 4379, "s": 4343, "text": "int getUnitIncrement(int direction)" }, { "code": null, "e": 4464, "s": 4379, "text": "Returns the amount to change the scrollbar's value by, given a unit up/down request." }, { "code": null, "e": 4479, "s": 4464, "text": "int getValue()" }, { "code": null, "e": 4510, "s": 4479, "text": "Returns the scrollbar's value." }, { "code": null, "e": 4540, "s": 4510, "text": "boolean getValueIsAdjusting()" }, { "code": null, "e": 4585, "s": 4540, "text": "True if the scrollbar knob is being dragged." }, { "code": null, "e": 4608, "s": 4585, "text": "int getVisibleAmount()" }, { "code": null, "e": 4665, "s": 4608, "text": "Returns the scrollbar's extent, aka its \"visibleAmount\"." }, { "code": null, "e": 4696, "s": 4665, "text": "protected String paramString()" }, { "code": null, "e": 4748, "s": 4696, "text": "Returns a string representation of this JScrollBar." }, { "code": null, "e": 4800, "s": 4748, "text": "void removeAdjustmentListener(AdjustmentListener l)" }, { "code": null, "e": 4837, "s": 4800, "text": "Removes an AdjustmentEvent listener." }, { "code": null, "e": 4880, "s": 4837, "text": "void setBlockIncrement(int blockIncrement)" }, { "code": null, "e": 4914, "s": 4880, "text": "Sets the blockIncrement property." }, { "code": null, "e": 4941, "s": 4914, "text": "void setEnabled(boolean x)" }, { "code": null, "e": 5005, "s": 4941, "text": "Enables the component so that the knob position can be changed." }, { "code": null, "e": 5034, "s": 5005, "text": "void setMaximum(int maximum)" }, { "code": null, "e": 5069, "s": 5034, "text": "Sets the model's maximum property." }, { "code": null, "e": 5098, "s": 5069, "text": "void setMinimum(int minimum)" }, { "code": null, "e": 5133, "s": 5098, "text": "Sets the model's minimum property." }, { "code": null, "e": 5175, "s": 5133, "text": "void setModel(BoundedRangeModel newModel)" }, { "code": null, "e": 5281, "s": 5175, "text": "Sets the model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent." }, { "code": null, "e": 5318, "s": 5281, "text": "void setOrientation(int orientation)" }, { "code": null, "e": 5384, "s": 5318, "text": "Set the scrollbar's orientation to either VERTICAL or HORIZONTAL." }, { "code": null, "e": 5411, "s": 5384, "text": "void setUI(ScrollBarUI ui)" }, { "code": null, "e": 5460, "s": 5411, "text": "Sets the L&F object that renders this component." }, { "code": null, "e": 5501, "s": 5460, "text": "void setUnitIncrement(int unitIncrement)" }, { "code": null, "e": 5534, "s": 5501, "text": "Sets the unitIncrement property." }, { "code": null, "e": 5559, "s": 5534, "text": "void setValue(int value)" }, { "code": null, "e": 5587, "s": 5559, "text": "Sets the scrollbar's value." }, { "code": null, "e": 5623, "s": 5587, "text": "void setValueIsAdjusting(boolean b)" }, { "code": null, "e": 5667, "s": 5623, "text": "Sets the model's valueIsAdjusting property." }, { "code": null, "e": 5735, "s": 5667, "text": "void setValues(int newValue, int newExtent, int newMin, int newMax)" }, { "code": null, "e": 5837, "s": 5735, "text": "Sets the four BoundedRangeModel properties after forcing the arguments to obey the usual constraints." }, { "code": null, "e": 5871, "s": 5837, "text": "void setVisibleAmount(int extent)" }, { "code": null, "e": 5904, "s": 5871, "text": "Set the model's extent property." }, { "code": null, "e": 5920, "s": 5904, "text": "void updateUI()" }, { "code": null, "e": 5951, "s": 5920, "text": "Overrides JComponent.updateUI." }, { "code": null, "e": 6008, "s": 5951, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 6025, "s": 6008, "text": "java.lang.Object" }, { "code": null, "e": 6141, "s": 6025, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 6163, "s": 6141, "text": "SwingControlDemo.java" }, { "code": null, "e": 8707, "s": 6163, "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.showScrollbarDemo();\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\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 showScrollbarDemo() { \n headerLabel.setText(\"Control in action: JScrollbar\"); \n\n final JScrollBar horizontalScroller = new JScrollBar(JScrollBar.HORIZONTAL);\n final JScrollBar verticalScroller = new JScrollBar();\n verticalScroller.setOrientation(JScrollBar.VERTICAL);\n horizontalScroller.setMaximum (100);\n horizontalScroller.setMinimum (1);\n verticalScroller.setMaximum (100);\n verticalScroller.setMinimum (1);\n \n horizontalScroller.addAdjustmentListener(new AdjustmentListener() {\n @Override\n public void adjustmentValueChanged(AdjustmentEvent e) {\n statusLabel.setText(\"Horozontal: \"\n +horizontalScroller.getValue() \n +\" ,Vertical: \"\n + verticalScroller.getValue());\n }\n });\n verticalScroller.addAdjustmentListener(new AdjustmentListener() {\n @Override\n public void adjustmentValueChanged(AdjustmentEvent e) {\n statusLabel.setText(\"Horozontal: \"\n +horizontalScroller.getValue() \n +\" ,Vertical: \"+ verticalScroller.getValue());\n }\n });\n controlPanel.add(horizontalScroller);\n controlPanel.add(verticalScroller);\n \n mainFrame.setVisible(true); \n } \n}" }, { "code": null, "e": 8803, "s": 8707, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 8864, "s": 8803, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n" }, { "code": null, "e": 8969, "s": 8864, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 9024, "s": 8969, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingControlDemo\n" }, { "code": null, "e": 9053, "s": 9024, "text": "Verify the following output." }, { "code": null, "e": 9088, "s": 9053, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9108, "s": 9088, "text": " Pranjal Srivastava" }, { "code": null, "e": 9141, "s": 9108, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 9161, "s": 9141, "text": " Pranjal Srivastava" }, { "code": null, "e": 9196, "s": 9161, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9232, "s": 9196, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9267, "s": 9232, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9280, "s": 9267, "text": " Travis Rose" }, { "code": null, "e": 9313, "s": 9280, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9326, "s": 9313, "text": " Travis Rose" }, { "code": null, "e": 9333, "s": 9326, "text": " Print" }, { "code": null, "e": 9344, "s": 9333, "text": " Add Notes" } ]
What Can We Learn from Elon Musk’s Twitter Graph? | by Günter Röhrich | Towards Data Science
Graph mining allows us to collect data and build a diagram of nodes and edges from any given set of entities. Algorithms like Louvain method or PageRank provide meaningful tools to analyze graphs after being mined and built. This post describes the building process of a graph with just a few lines of Python code. Graph analysis is both an incredibly exciting and fast-developing field of data analytics. It reaches from community detection to other sophisticated tasks like pattern recognition. Graph analytics can also be seen as one of the powerhouses enabling search engine giants to add additional interconnected result dimensions to your search results (basically they are relying on so called knowledge graphs), relevant daily news to pop up on your phone or buying recommendations in your favorite online shops. As a side note: Google’s search is based on the former development of Freebase© which is discontinued, but still partially accessible — link here. While there are numerous algorithms available for analysis, Louvain method and PageRank are probably the ones that come to one’s mind first when thinking of graphs. The Louvain method allows detecting communities in all sorts of networks, whereas PageRank (named after web pages, not its co-inventor and Google co-founder Larry Page) finds the steady state probability (Markov chain) of reaching a node when randomly jumping between nodes throughout the graph — the latter is probably the best-known algorithm in this scientific field as it is regarded as the ground work of Google search. Another popular analytics approach is looking at graphs which are characterized through a large number of triangle connections. Finding such graphs is a real-world problem headhunters, social media and marketing experts might especially be interested in. “Triangle counting gained popularity in social network analysis, where it is used to detect communities and measure the cohesiveness of those communities. It can also be used to determine the stability of a graph, and is often used as part of the computation of network indices, such as the clustering coefficient.” — Neo4j An incredibly well written 6-page-only paper from Stanford University can be found in the APPENDIX at the end of this post. An easy way to integrate triangle count in your program is explained here: towardsdatascience.com In order to provide meaningful data for this kind of analysis, this article allows you to follow just a few simple steps to mine a real-world graph from Twitter. The below-shown functions start from the “RootNode” Elon Musk and iterate over his follows, the follows of his follows, etc. If you wanted to use your own account as a starting point, you need to obtain your starting ID first. This cannot be done through the frontend, but there is an easy script on Twitter’s GitHub (user lookup) to help you out. For this project I used Elon’s follows. Using follows makes sense because we would like to explore Elon’s network and not someone else’s network of which Elon is just a part. This logic applies to all other nodes as well— we only care about follows, not followers. Be aware that collecting nodes through Twitter takes quite a long time, for this reason the shown graph is only a small part of Elon’s whole network. The “Elon Musk Graph” can be visually explored (link), by simply clicking on the nodes — drag them around to organize them in a better way. Node sizes are characterized as having a higher PageRank value, which is also expressed through the coloring. Darker (blue) colors indicate a high PageRank score, yellow, lighter colors show low score nodes. Nodes can also be expressed through their degree (outdegree) if desired. Thanks to Prof. Duen Horng Chau (Georgia Tech) for providing the visualization tool. If you are interested in how Argo Lite works (it is using D3), follow the GitHub repository. Before exploring the chart and/or going into the mining functions please consider the following constraints: Twitter only allows 15 API calls per 15 minutes. This is an incredibly small number. Starting with 40 users in the initial iteration means, that we can only have 14 users analyzed in this run (1 run is used for the RootNode). So better have your Raspberry Pi up and running for this.There has to be a limit on the users obtained for the RootNode but alsofor the nodes of nodes. This limit should be even smaller than the first one. As a rule of thumb ≤ 5 — otherwise the graph would become extremely large and the API calls would be far too overwhelming. Twitter only allows 15 API calls per 15 minutes. This is an incredibly small number. Starting with 40 users in the initial iteration means, that we can only have 14 users analyzed in this run (1 run is used for the RootNode). So better have your Raspberry Pi up and running for this. There has to be a limit on the users obtained for the RootNode but also for the nodes of nodes. This limit should be even smaller than the first one. As a rule of thumb ≤ 5 — otherwise the graph would become extremely large and the API calls would be far too overwhelming. This whole thing starts with exploring the Twitter API. I am not the greatest fan of their documentation (especially this v1.0 to v2.0 is sometimes confusing), however their example code on GitHub is great. To start with your project you need the following two building blocks: A ready-to-go project on your Twitter developers page — This is required to obtain keys to authorize your API calls later on.The ID of your RootNode — this is the starting point for the script to iterate through all the “follows” A ready-to-go project on your Twitter developers page — This is required to obtain keys to authorize your API calls later on. The ID of your RootNode — this is the starting point for the script to iterate through all the “follows” The code shown below is just a copy from Twitter dev’s GitHub and build the starting point for our program. Additional imports like logging are not necessary, however, may turn out to be useful when it comes to track the progress of larger graphs. Again, as a reminder, Twitter only allows an unsatisfyingly tiny number of API calls — so logging may come in handy at some point. Given those prerequisites above, I simply packed the boilerplate code into a function which I call for every iteration. The code is basically taking the node identifier (id) we pass to the function and retrieves the full list of the node/person’s followers. We further need to set limitation parameters. This is a necessity because due to the size of the Twitter network for an average or even highly involved user this mining task would take an incredibly long time. iterations: This allows us to define how often we take the node’s follows and select those nodes as next iteration starting points. See also below*iteration = 0 simply defines a counter variable.request_count: is required to limit the number of calls. This counter makes sure we’re not hitting the (incredibly tiny) API limitstart_limit defines the number nodes retrieved in the very first iterationlimit defines the number of nodes for any following iteration iterations: This allows us to define how often we take the node’s follows and select those nodes as next iteration starting points. See also below* iteration = 0 simply defines a counter variable. request_count: is required to limit the number of calls. This counter makes sure we’re not hitting the (incredibly tiny) API limit start_limit defines the number nodes retrieved in the very first iteration limit defines the number of nodes for any following iteration * Iterations:0 — [RootNode -> n Users]1 — [RootNode -> n Users -> m Users ], 2 — [RootNode -> n Users -> m Users -> m Users]# where n is the start_limit and m is limit.# You can push this iterative process to any number you like, # just make sure it comes to end within the next decade. This first block of code is basically only defining the retrieval of users (get_follows) as well as setting parameters for the mining process. Now the real fun begins as we obtain the first follows of the initial node (RootNode). To emphasize this again, I am using Python’s built in logging library, a solid way of keeping track of the progress and identify problems the program may be confronted with — just be aware that your program might run many hours, days... — so “print” is probably not a good option. Another important aspect of this function is that we have a close look at propagated nodes. We are using follows_checked to keep track of the nodes we have already visited and remove them from our stack (new_nodes), otherwise we created an infinity loop. We are basically iterating over a user list and add all elements to the edges and nodes. The main challenge is to keep track of nodes we already used to get user lists. For this reason we keep: follows_check is just an exclusion list. Every entry in here will no longer be used to call the data retrievalnodes is the list of all nodes, appended during all iterationsnew_nodes: keeps track of nodes we just introducednext_nodes: is just a temporary array we use to compare to the exclusion list. follows_check is just an exclusion list. Every entry in here will no longer be used to call the data retrieval nodes is the list of all nodes, appended during all iterations new_nodes: keeps track of nodes we just introduced next_nodes: is just a temporary array we use to compare to the exclusion list. The first iteration is easy, we simply go over all nodes and append the nodes and edges lists. Note that nodes might not be unique in this list. Make sure you prepare to clean your output from duplicates if required for your use case. The more complex task arises when we see additional “layers” we want to follow. It is crucial here to keep track of the checked nodes and that we store the newly introduced nodes separately. Think through this again. This short post has demonstrated how you can iteratively collect data and store it in a structure that can be used to build a graph. The key take away is that the age of big data has brought us a variety of new challenges and graphs are one major way to better understand our data. Graphs can be stored easily, whether in a simple CSV file (for small graphs), in a data base or even distributed across several computers (e.g. Spark GraphX) and can be approached with powerful and proven algorithms to explore their contents. If PageRank was what you were looking for, I recommend going through this post, it is not too overwhelming and captures the essentials: towardsdatascience.com If you are not only interested in the connections between the users, but also what kind of tweets they made, the sentiment of their Tweets or just the content users write about, you might want to look at natural language processing and/or similarity measures. I once created an iterative method to evaluate the importance of certain words in a text, this could be useful for your project: towardsdatascience.com { See you next time and stay safe } Again, a huge thanks to Prof. Duen Horng (Polo) Chau and all involved fellow students (Georgia Tech) who provide the online graph visualization tool Argo Lite— Prof. Polo is also the one who really sparked my interest in graph analysis. Georgia Tech #CS 6242 Data and Visual Analytics
[ { "code": null, "e": 362, "s": 47, "text": "Graph mining allows us to collect data and build a diagram of nodes and edges from any given set of entities. Algorithms like Louvain method or PageRank provide meaningful tools to analyze graphs after being mined and built. This post describes the building process of a graph with just a few lines of Python code." }, { "code": null, "e": 868, "s": 362, "text": "Graph analysis is both an incredibly exciting and fast-developing field of data analytics. It reaches from community detection to other sophisticated tasks like pattern recognition. Graph analytics can also be seen as one of the powerhouses enabling search engine giants to add additional interconnected result dimensions to your search results (basically they are relying on so called knowledge graphs), relevant daily news to pop up on your phone or buying recommendations in your favorite online shops." }, { "code": null, "e": 1015, "s": 868, "text": "As a side note: Google’s search is based on the former development of Freebase© which is discontinued, but still partially accessible — link here." }, { "code": null, "e": 1605, "s": 1015, "text": "While there are numerous algorithms available for analysis, Louvain method and PageRank are probably the ones that come to one’s mind first when thinking of graphs. The Louvain method allows detecting communities in all sorts of networks, whereas PageRank (named after web pages, not its co-inventor and Google co-founder Larry Page) finds the steady state probability (Markov chain) of reaching a node when randomly jumping between nodes throughout the graph — the latter is probably the best-known algorithm in this scientific field as it is regarded as the ground work of Google search." }, { "code": null, "e": 1860, "s": 1605, "text": "Another popular analytics approach is looking at graphs which are characterized through a large number of triangle connections. Finding such graphs is a real-world problem headhunters, social media and marketing experts might especially be interested in." }, { "code": null, "e": 2184, "s": 1860, "text": "“Triangle counting gained popularity in social network analysis, where it is used to detect communities and measure the cohesiveness of those communities. It can also be used to determine the stability of a graph, and is often used as part of the computation of network indices, such as the clustering coefficient.” — Neo4j" }, { "code": null, "e": 2383, "s": 2184, "text": "An incredibly well written 6-page-only paper from Stanford University can be found in the APPENDIX at the end of this post. An easy way to integrate triangle count in your program is explained here:" }, { "code": null, "e": 2406, "s": 2383, "text": "towardsdatascience.com" }, { "code": null, "e": 2693, "s": 2406, "text": "In order to provide meaningful data for this kind of analysis, this article allows you to follow just a few simple steps to mine a real-world graph from Twitter. The below-shown functions start from the “RootNode” Elon Musk and iterate over his follows, the follows of his follows, etc." }, { "code": null, "e": 2916, "s": 2693, "text": "If you wanted to use your own account as a starting point, you need to obtain your starting ID first. This cannot be done through the frontend, but there is an easy script on Twitter’s GitHub (user lookup) to help you out." }, { "code": null, "e": 3752, "s": 2916, "text": "For this project I used Elon’s follows. Using follows makes sense because we would like to explore Elon’s network and not someone else’s network of which Elon is just a part. This logic applies to all other nodes as well— we only care about follows, not followers. Be aware that collecting nodes through Twitter takes quite a long time, for this reason the shown graph is only a small part of Elon’s whole network. The “Elon Musk Graph” can be visually explored (link), by simply clicking on the nodes — drag them around to organize them in a better way. Node sizes are characterized as having a higher PageRank value, which is also expressed through the coloring. Darker (blue) colors indicate a high PageRank score, yellow, lighter colors show low score nodes. Nodes can also be expressed through their degree (outdegree) if desired." }, { "code": null, "e": 3930, "s": 3752, "text": "Thanks to Prof. Duen Horng Chau (Georgia Tech) for providing the visualization tool. If you are interested in how Argo Lite works (it is using D3), follow the GitHub repository." }, { "code": null, "e": 4039, "s": 3930, "text": "Before exploring the chart and/or going into the mining functions please consider the following constraints:" }, { "code": null, "e": 4594, "s": 4039, "text": "Twitter only allows 15 API calls per 15 minutes. This is an incredibly small number. Starting with 40 users in the initial iteration means, that we can only have 14 users analyzed in this run (1 run is used for the RootNode). So better have your Raspberry Pi up and running for this.There has to be a limit on the users obtained for the RootNode but alsofor the nodes of nodes. This limit should be even smaller than the first one. As a rule of thumb ≤ 5 — otherwise the graph would become extremely large and the API calls would be far too overwhelming." }, { "code": null, "e": 4878, "s": 4594, "text": "Twitter only allows 15 API calls per 15 minutes. This is an incredibly small number. Starting with 40 users in the initial iteration means, that we can only have 14 users analyzed in this run (1 run is used for the RootNode). So better have your Raspberry Pi up and running for this." }, { "code": null, "e": 4950, "s": 4878, "text": "There has to be a limit on the users obtained for the RootNode but also" }, { "code": null, "e": 5151, "s": 4950, "text": "for the nodes of nodes. This limit should be even smaller than the first one. As a rule of thumb ≤ 5 — otherwise the graph would become extremely large and the API calls would be far too overwhelming." }, { "code": null, "e": 5358, "s": 5151, "text": "This whole thing starts with exploring the Twitter API. I am not the greatest fan of their documentation (especially this v1.0 to v2.0 is sometimes confusing), however their example code on GitHub is great." }, { "code": null, "e": 5429, "s": 5358, "text": "To start with your project you need the following two building blocks:" }, { "code": null, "e": 5659, "s": 5429, "text": "A ready-to-go project on your Twitter developers page — This is required to obtain keys to authorize your API calls later on.The ID of your RootNode — this is the starting point for the script to iterate through all the “follows”" }, { "code": null, "e": 5785, "s": 5659, "text": "A ready-to-go project on your Twitter developers page — This is required to obtain keys to authorize your API calls later on." }, { "code": null, "e": 5890, "s": 5785, "text": "The ID of your RootNode — this is the starting point for the script to iterate through all the “follows”" }, { "code": null, "e": 6269, "s": 5890, "text": "The code shown below is just a copy from Twitter dev’s GitHub and build the starting point for our program. Additional imports like logging are not necessary, however, may turn out to be useful when it comes to track the progress of larger graphs. Again, as a reminder, Twitter only allows an unsatisfyingly tiny number of API calls — so logging may come in handy at some point." }, { "code": null, "e": 6527, "s": 6269, "text": "Given those prerequisites above, I simply packed the boilerplate code into a function which I call for every iteration. The code is basically taking the node identifier (id) we pass to the function and retrieves the full list of the node/person’s followers." }, { "code": null, "e": 6737, "s": 6527, "text": "We further need to set limitation parameters. This is a necessity because due to the size of the Twitter network for an average or even highly involved user this mining task would take an incredibly long time." }, { "code": null, "e": 7198, "s": 6737, "text": "iterations: This allows us to define how often we take the node’s follows and select those nodes as next iteration starting points. See also below*iteration = 0 simply defines a counter variable.request_count: is required to limit the number of calls. This counter makes sure we’re not hitting the (incredibly tiny) API limitstart_limit defines the number nodes retrieved in the very first iterationlimit defines the number of nodes for any following iteration" }, { "code": null, "e": 7346, "s": 7198, "text": "iterations: This allows us to define how often we take the node’s follows and select those nodes as next iteration starting points. See also below*" }, { "code": null, "e": 7395, "s": 7346, "text": "iteration = 0 simply defines a counter variable." }, { "code": null, "e": 7526, "s": 7395, "text": "request_count: is required to limit the number of calls. This counter makes sure we’re not hitting the (incredibly tiny) API limit" }, { "code": null, "e": 7601, "s": 7526, "text": "start_limit defines the number nodes retrieved in the very first iteration" }, { "code": null, "e": 7663, "s": 7601, "text": "limit defines the number of nodes for any following iteration" }, { "code": null, "e": 7950, "s": 7663, "text": "* Iterations:0 — [RootNode -> n Users]1 — [RootNode -> n Users -> m Users ], 2 — [RootNode -> n Users -> m Users -> m Users]# where n is the start_limit and m is limit.# You can push this iterative process to any number you like, # just make sure it comes to end within the next decade." }, { "code": null, "e": 8093, "s": 7950, "text": "This first block of code is basically only defining the retrieval of users (get_follows) as well as setting parameters for the mining process." }, { "code": null, "e": 8461, "s": 8093, "text": "Now the real fun begins as we obtain the first follows of the initial node (RootNode). To emphasize this again, I am using Python’s built in logging library, a solid way of keeping track of the progress and identify problems the program may be confronted with — just be aware that your program might run many hours, days... — so “print” is probably not a good option." }, { "code": null, "e": 8716, "s": 8461, "text": "Another important aspect of this function is that we have a close look at propagated nodes. We are using follows_checked to keep track of the nodes we have already visited and remove them from our stack (new_nodes), otherwise we created an infinity loop." }, { "code": null, "e": 8910, "s": 8716, "text": "We are basically iterating over a user list and add all elements to the edges and nodes. The main challenge is to keep track of nodes we already used to get user lists. For this reason we keep:" }, { "code": null, "e": 9211, "s": 8910, "text": "follows_check is just an exclusion list. Every entry in here will no longer be used to call the data retrievalnodes is the list of all nodes, appended during all iterationsnew_nodes: keeps track of nodes we just introducednext_nodes: is just a temporary array we use to compare to the exclusion list." }, { "code": null, "e": 9322, "s": 9211, "text": "follows_check is just an exclusion list. Every entry in here will no longer be used to call the data retrieval" }, { "code": null, "e": 9385, "s": 9322, "text": "nodes is the list of all nodes, appended during all iterations" }, { "code": null, "e": 9436, "s": 9385, "text": "new_nodes: keeps track of nodes we just introduced" }, { "code": null, "e": 9515, "s": 9436, "text": "next_nodes: is just a temporary array we use to compare to the exclusion list." }, { "code": null, "e": 9750, "s": 9515, "text": "The first iteration is easy, we simply go over all nodes and append the nodes and edges lists. Note that nodes might not be unique in this list. Make sure you prepare to clean your output from duplicates if required for your use case." }, { "code": null, "e": 9967, "s": 9750, "text": "The more complex task arises when we see additional “layers” we want to follow. It is crucial here to keep track of the checked nodes and that we store the newly introduced nodes separately. Think through this again." }, { "code": null, "e": 10249, "s": 9967, "text": "This short post has demonstrated how you can iteratively collect data and store it in a structure that can be used to build a graph. The key take away is that the age of big data has brought us a variety of new challenges and graphs are one major way to better understand our data." }, { "code": null, "e": 10492, "s": 10249, "text": "Graphs can be stored easily, whether in a simple CSV file (for small graphs), in a data base or even distributed across several computers (e.g. Spark GraphX) and can be approached with powerful and proven algorithms to explore their contents." }, { "code": null, "e": 10628, "s": 10492, "text": "If PageRank was what you were looking for, I recommend going through this post, it is not too overwhelming and captures the essentials:" }, { "code": null, "e": 10651, "s": 10628, "text": "towardsdatascience.com" }, { "code": null, "e": 11040, "s": 10651, "text": "If you are not only interested in the connections between the users, but also what kind of tweets they made, the sentiment of their Tweets or just the content users write about, you might want to look at natural language processing and/or similarity measures. I once created an iterative method to evaluate the importance of certain words in a text, this could be useful for your project:" }, { "code": null, "e": 11063, "s": 11040, "text": "towardsdatascience.com" }, { "code": null, "e": 11099, "s": 11063, "text": "{ See you next time and stay safe }" }, { "code": null, "e": 11336, "s": 11099, "text": "Again, a huge thanks to Prof. Duen Horng (Polo) Chau and all involved fellow students (Georgia Tech) who provide the online graph visualization tool Argo Lite— Prof. Polo is also the one who really sparked my interest in graph analysis." } ]
Java String startsWith() Method
❮ String Methods Find out if the string starts with the specified characters: String myStr = "Hello"; System.out.println(myStr.startsWith("Hel")); // true System.out.println(myStr.startsWith("llo")); // false System.out.println(myStr.startsWith("o")); // false Try it Yourself » The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s). public boolean startsWith(String chars) true - if the string starts with the specified character(s) false - if the string does not start with the specified character(s) We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 80, "s": 19, "text": "Find out if the string starts with the specified characters:" }, { "code": null, "e": 271, "s": 80, "text": "String myStr = \"Hello\";\nSystem.out.println(myStr.startsWith(\"Hel\")); // true\nSystem.out.println(myStr.startsWith(\"llo\")); // false\nSystem.out.println(myStr.startsWith(\"o\")); // false" }, { "code": null, "e": 291, "s": 271, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 380, "s": 291, "text": "The startsWith() method checks whether a \nstring starts with the specified character(s)." }, { "code": null, "e": 475, "s": 380, "text": "Tip: Use the endsWith() method to check whether a string ends with the specified character(s)." }, { "code": null, "e": 516, "s": 475, "text": "public boolean startsWith(String chars)\n" }, { "code": null, "e": 576, "s": 516, "text": "true - if the string starts with the specified character(s)" }, { "code": null, "e": 645, "s": 576, "text": "false - if the string does not start with the specified character(s)" }, { "code": null, "e": 678, "s": 645, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 720, "s": 678, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 827, "s": 720, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 846, "s": 827, "text": "[email protected]" } ]
What is Ambiguous Grammar?
A Grammar that makes more than one Leftmost Derivation (or Rightmost Derivation) for the similar sentence is called Ambiguous Grammar. Example − Verify whether the following Grammar is Ambiguous or Not. E → E+E|E ∗ E|id Solution For string id + id * id, there exist two parse trees. E ⇒lm E_+E ⇒ id+ E_ ⇒ id+E_ ∗ E ⇒ id+id ∗ E_ ⇒ id+id ∗ id E ⇒lm E_ ∗ E ⇒ E_+E ∗ E ⇒ id+ E_ ∗ E ⇒ id+id ∗ E_ ⇒ id+id ∗ id So, the same string is generated using two different leftmost derivations. Each is having a different parse tree. ∴ Two different parse trees exist for string id + id * id. ∴ Grammar is Ambiguous. The productions containing more than one occurrence of a given non-terminal on its right-hand side are ambiguous productions. Example − E → E_ * E_ It contains two E’s on R.H.S. It can convert these types of Ambiguous productions to Unambiguous production by introducing a new Non-terminal to move right most of these non-terminal farther down the Parse Tree. Example1 − Consider the Grammar E → E+E|E ∗ E|(E)| id Convert this Ambiguous Grammar into Unambiguous Grammar. Solution Step1 − Introduction a non-terminal T (term) which cannot be further addition of two terms. E → E+T | T T → E * E | (E) |id Step2 − As we have production E → T. Substitute E with T to get T→T∗T Introduce another non-terminal F (factor) that cannot be further factorized or cannot be multiplication of two numbers. Substitute T with F to get, T → T * F | F F → (E) | id ∴ Unambiguous Grammar will be E → E+T | T T → T * F | F F → (E) | id Example2 − Prove that following Grammar is Ambiguous for the string if c then if c2 then s1 else s2. <statement> →if<cond> then<statement> | if<cond> then<statement> else<statement> | another statement Convert it into Unambiguous Grammar. Solution Given grammar is Ambiguous since there exists two Parse Trees for the same string because else condition can belong to any if statement. In the above Parse tree, else belongs to second if. In the above Parse tree, else belongs to first if. The Unambiguous Grammar will be − <statement>→<match−statement>|<Unmatch−statement> <match−statement>→if<cond>then<match−statement>else <match−statement>| other−statement <Unmatch−statement>→if<cond>then<statement>| if<cond>then <match−statement>else<Unmatch Statement>
[ { "code": null, "e": 1197, "s": 1062, "text": "A Grammar that makes more than one Leftmost Derivation (or Rightmost Derivation) for the similar sentence is called Ambiguous Grammar." }, { "code": null, "e": 1265, "s": 1197, "text": "Example − Verify whether the following Grammar is Ambiguous or Not." }, { "code": null, "e": 1282, "s": 1265, "text": "E → E+E|E ∗ E|id" }, { "code": null, "e": 1291, "s": 1282, "text": "Solution" }, { "code": null, "e": 1345, "s": 1291, "text": "For string id + id * id, there exist two parse trees." }, { "code": null, "e": 1356, "s": 1345, "text": "E ⇒lm E_+E" }, { "code": null, "e": 1366, "s": 1356, "text": " ⇒ id+ E_" }, { "code": null, "e": 1378, "s": 1366, "text": "⇒ id+E_ ∗ E" }, { "code": null, "e": 1391, "s": 1378, "text": "⇒ id+id ∗ E_" }, { "code": null, "e": 1404, "s": 1391, "text": "⇒ id+id ∗ id" }, { "code": null, "e": 1417, "s": 1404, "text": "E ⇒lm E_ ∗ E" }, { "code": null, "e": 1428, "s": 1417, "text": "⇒ E_+E ∗ E" }, { "code": null, "e": 1441, "s": 1428, "text": "⇒ id+ E_ ∗ E" }, { "code": null, "e": 1454, "s": 1441, "text": "⇒ id+id ∗ E_" }, { "code": null, "e": 1467, "s": 1454, "text": "⇒ id+id ∗ id" }, { "code": null, "e": 1581, "s": 1467, "text": "So, the same string is generated using two different leftmost derivations. Each is having a different parse tree." }, { "code": null, "e": 1640, "s": 1581, "text": "∴ Two different parse trees exist for string id + id * id." }, { "code": null, "e": 1664, "s": 1640, "text": "∴ Grammar is Ambiguous." }, { "code": null, "e": 1790, "s": 1664, "text": "The productions containing more than one occurrence of a given non-terminal on its right-hand side are ambiguous productions." }, { "code": null, "e": 1812, "s": 1790, "text": "Example − E → E_ * E_" }, { "code": null, "e": 1842, "s": 1812, "text": "It contains two E’s on R.H.S." }, { "code": null, "e": 2024, "s": 1842, "text": "It can convert these types of Ambiguous productions to Unambiguous production by introducing a new Non-terminal to move right most of these non-terminal farther down the Parse Tree." }, { "code": null, "e": 2056, "s": 2024, "text": "Example1 − Consider the Grammar" }, { "code": null, "e": 2078, "s": 2056, "text": "E → E+E|E ∗ E|(E)| id" }, { "code": null, "e": 2135, "s": 2078, "text": "Convert this Ambiguous Grammar into Unambiguous Grammar." }, { "code": null, "e": 2144, "s": 2135, "text": "Solution" }, { "code": null, "e": 2236, "s": 2144, "text": "Step1 − Introduction a non-terminal T (term) which cannot be further addition of two terms." }, { "code": null, "e": 2268, "s": 2236, "text": "E → E+T | T\nT → E * E | (E) |id" }, { "code": null, "e": 2332, "s": 2268, "text": "Step2 − As we have production E → T. Substitute E with T to get" }, { "code": null, "e": 2338, "s": 2332, "text": "T→T∗T" }, { "code": null, "e": 2458, "s": 2338, "text": "Introduce another non-terminal F (factor) that cannot be further factorized or cannot be multiplication of two numbers." }, { "code": null, "e": 2486, "s": 2458, "text": "Substitute T with F to get," }, { "code": null, "e": 2513, "s": 2486, "text": "T → T * F | F\nF → (E) | id" }, { "code": null, "e": 2543, "s": 2513, "text": "∴ Unambiguous Grammar will be" }, { "code": null, "e": 2582, "s": 2543, "text": "E → E+T | T\nT → T * F | F\nF → (E) | id" }, { "code": null, "e": 2683, "s": 2582, "text": "Example2 − Prove that following Grammar is Ambiguous for the string if c then if c2 then s1 else s2." }, { "code": null, "e": 2764, "s": 2683, "text": "<statement> →if<cond> then<statement>\n| if<cond> then<statement> else<statement>" }, { "code": null, "e": 2784, "s": 2764, "text": "| another statement" }, { "code": null, "e": 2821, "s": 2784, "text": "Convert it into Unambiguous Grammar." }, { "code": null, "e": 2830, "s": 2821, "text": "Solution" }, { "code": null, "e": 2967, "s": 2830, "text": "Given grammar is Ambiguous since there exists two Parse Trees for the same string because else condition can belong to any if statement." }, { "code": null, "e": 3019, "s": 2967, "text": "In the above Parse tree, else belongs to second if." }, { "code": null, "e": 3070, "s": 3019, "text": "In the above Parse tree, else belongs to first if." }, { "code": null, "e": 3104, "s": 3070, "text": "The Unambiguous Grammar will be −" }, { "code": null, "e": 3348, "s": 3104, "text": "<statement>→<match−statement>|<Unmatch−statement>\n<match−statement>→if<cond>then<match−statement>else\n <match−statement>| other−statement\n<Unmatch−statement>→if<cond>then<statement>| if<cond>then\n <match−statement>else<Unmatch Statement>" } ]
Convert UNIX Timestamp to Date Object in R - GeeksforGeeks
23 May, 2021 UNIX timestamp refers to the number of seconds that have elapsed since the epoch. The timestamp object is not easily understandable and should be converted to other user-friendly formats. The Date objects in R Programming Language can be used to display the specified timestamp in a crisp way. Date objects are stored as the number of days since January 1, 1970, where the negative numbers are used for earlier dates. Here we will see how to convert UNIX Timestamp to Date Object in R Programming. Method 1: Using lubridate package Lubridate package in R is responsible to make it easier to work with dates and times. It contains specialized parsing functions to manipulate and modify time stamps into various different formats and time zones available. The package needs to be installed into the R library using the following syntax : install.packages("lubridate") as_datetime() method in this package is used to convert UNIX Timestamp to Date Object. This method used the UTC timezone by default. Syntax: as_datetime(timestamp, tz) Arguments : tz – The corresponding time zone Code: R library("lubridate")timestamp <- 2012368256datetime <- as_datetime(timestamp) print ("DateTime Notation")print (datetime) Output: [1] "DateTime Notation" [1] "2033-10-08 07:10:56 UTC" Method 2: Using as.POSIXct method Timestamp can be first converted to a POSIXct object and then conversions can be carried out. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to the standard time zone, UTC. A timestamp object can be converted to a POSIXct object, using them as.POSIXct(date) method in R. as.POSIXct(timestamp, origin = "1970-01-01") This is followed by the application of as.Date method over the POSIXct object. The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer to earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a POSIXct date object and converts it to a Date object. as.Date(character date object) The difference that this method holds is that it just displays the date object, while the above method converts it to a complete DateTime object. Code: R # declaring the timestamptimestamp <- 2012368256 # converting to POSIXct notationposixt <- as.POSIXct(timestamp, origin = "1970-01-01") # converting to readable date # time objectdatetime <- as.Date(posixt)print ("DateTime Notation")print (datetime) Output: [1] "DateTime Notation" [1] "2033-10-08" Picked R-DateTime R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n23 May, 2021" }, { "code": null, "e": 25349, "s": 24851, "text": "UNIX timestamp refers to the number of seconds that have elapsed since the epoch. The timestamp object is not easily understandable and should be converted to other user-friendly formats. The Date objects in R Programming Language can be used to display the specified timestamp in a crisp way. Date objects are stored as the number of days since January 1, 1970, where the negative numbers are used for earlier dates. Here we will see how to convert UNIX Timestamp to Date Object in R Programming." }, { "code": null, "e": 25383, "s": 25349, "text": "Method 1: Using lubridate package" }, { "code": null, "e": 25688, "s": 25383, "text": "Lubridate package in R is responsible to make it easier to work with dates and times. It contains specialized parsing functions to manipulate and modify time stamps into various different formats and time zones available. The package needs to be installed into the R library using the following syntax : " }, { "code": null, "e": 25718, "s": 25688, "text": "install.packages(\"lubridate\")" }, { "code": null, "e": 25852, "s": 25718, "text": "as_datetime() method in this package is used to convert UNIX Timestamp to Date Object. This method used the UTC timezone by default. " }, { "code": null, "e": 25891, "s": 25852, "text": "Syntax: as_datetime(timestamp, tz) " }, { "code": null, "e": 25936, "s": 25891, "text": "Arguments : tz – The corresponding time zone" }, { "code": null, "e": 25942, "s": 25936, "text": "Code:" }, { "code": null, "e": 25944, "s": 25942, "text": "R" }, { "code": "library(\"lubridate\")timestamp <- 2012368256datetime <- as_datetime(timestamp) print (\"DateTime Notation\")print (datetime)", "e": 26070, "s": 25944, "text": null }, { "code": null, "e": 26078, "s": 26070, "text": "Output:" }, { "code": null, "e": 26133, "s": 26078, "text": "[1] \"DateTime Notation\" \n[1] \"2033-10-08 07:10:56 UTC\"" }, { "code": null, "e": 26167, "s": 26133, "text": "Method 2: Using as.POSIXct method" }, { "code": null, "e": 26541, "s": 26167, "text": "Timestamp can be first converted to a POSIXct object and then conversions can be carried out. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to the standard time zone, UTC. A timestamp object can be converted to a POSIXct object, using them as.POSIXct(date) method in R. " }, { "code": null, "e": 26586, "s": 26541, "text": "as.POSIXct(timestamp, origin = \"1970-01-01\")" }, { "code": null, "e": 27099, "s": 26586, "text": "This is followed by the application of as.Date method over the POSIXct object. The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer to earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a POSIXct date object and converts it to a Date object." }, { "code": null, "e": 27130, "s": 27099, "text": "as.Date(character date object)" }, { "code": null, "e": 27277, "s": 27130, "text": "The difference that this method holds is that it just displays the date object, while the above method converts it to a complete DateTime object. " }, { "code": null, "e": 27283, "s": 27277, "text": "Code:" }, { "code": null, "e": 27285, "s": 27283, "text": "R" }, { "code": "# declaring the timestamptimestamp <- 2012368256 # converting to POSIXct notationposixt <- as.POSIXct(timestamp, origin = \"1970-01-01\") # converting to readable date # time objectdatetime <- as.Date(posixt)print (\"DateTime Notation\")print (datetime)", "e": 27557, "s": 27285, "text": null }, { "code": null, "e": 27565, "s": 27557, "text": "Output:" }, { "code": null, "e": 27607, "s": 27565, "text": "[1] \"DateTime Notation\" \n[1] \"2033-10-08\"" }, { "code": null, "e": 27614, "s": 27607, "text": "Picked" }, { "code": null, "e": 27625, "s": 27614, "text": "R-DateTime" }, { "code": null, "e": 27636, "s": 27625, "text": "R Language" }, { "code": null, "e": 27734, "s": 27636, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27743, "s": 27734, "text": "Comments" }, { "code": null, "e": 27756, "s": 27743, "text": "Old Comments" }, { "code": null, "e": 27808, "s": 27756, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27846, "s": 27808, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27881, "s": 27846, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27939, "s": 27881, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27988, "s": 27939, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28031, "s": 27988, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28081, "s": 28031, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28098, "s": 28081, "text": "R - if statement" }, { "code": null, "e": 28135, "s": 28098, "text": "How to import an Excel File into R ?" } ]