code-rag-bench/online-tutorials huggingface dataset:
How to convert list to string in Python?

There may be some situations, where we need to convert a list into a string. We will discuss different methods to do the same.
Iterate through the list and append the elements to the string to convert list into a string. We will use for-in loop to iterate through the list elements.
 Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1=""
for i in list1:
   string1=string1+i
string2=""
for i in list1:
   string2=string2+i+" "
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
The list will be passed as a parameter inside the join method.
 Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1=""
print(string1.join(list1))
string2=" "
print(string2.join(list1))
WelcomeToTutorialsPoint
Welcome To Tutorials Point
We can use map() method for mapping str with the list and then use join() to convert list into string.
 Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1="".join(map(str,list1))
string2=" ".join(map(str,list1))
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
Comprehensions in Python provide a short way to construct new sequences using already provided sequences. We will access each element of the list as a string and then use join().
 Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1="".join(str(elem) for elem in list1)
string2=" ".join(str(elem) for elem in list1)
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
BFS using STL for competitive coding in C++?

The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again.
In The competitive coding, we have to solve problems very quickly. We will use the STL (Standard Library of C++) to implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue, when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again.
In Graph sometimes, we may get some cycles, so we will use an array to mark when a node is visited already or not.
Input : The Adjacency matrix of the graph.
A B C D E F
A 0 1 1 1 0 0
B 1 0 0 1 1 0
C 1 0 0 1 0 1
D 1 1 1 0 1 1
E 0 1 0 1 0 1
F 0 0 1 1 1 0
Output : BFS Traversal: B A D E C F
Input − The list of vertices, and the start vertex.
Output − Traverse all of the nodes, if the graph is connected.
Begin
   define an empty queue que
   at first mark all nodes status as unvisited
   add the start vertex into the que
   while que is not empty, do
      delete item from que and set to u
      display the vertex u
      for all vertices 1 adjacent with u, do
         if vertices[i] is unvisited, then
            mark vertices[i] as temporarily visited
            add v into the queue
         mark
      done
      mark u as completely visited
   done
End
 Live Demo
#include<iostream>
#include<queue>
#define NODE 6
using namespace std;
class node {
   public:
      int val;
      int state; //status
};
int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0, 0},
   {1, 0, 0, 1, 1, 0},
   {1, 0, 0, 1, 0, 1},
   {1, 1, 1, 0, 1, 1},
   {0, 1, 0, 1, 0, 1},
   {0, 0, 1, 1, 1, 0}
};
void bfs(node *vert, node s) {
   node u;
   int i, j;
   queue<node> que;
   for(i = 0; i<NODE; i++) {
      vert[i].state = 0; //not visited
   }
   vert[s.val].state = 1;//visited
   que.push(s); //insert starting node
   while(!que.empty()) {
      u = que.front(); //delete from queue and print
      que.pop();
      cout << char(u.val+'A') << " ";
      for(i = 0; i<NODE; i++) {
         if(graph[i][u.val]) {
            //when the node is non-visited
            if(vert[i].state == 0) {
               vert[i].state = 1;
               que.push(vert[i]);
            }
         }
      }
      u.state = 2;//completed for node u
   }
}
int main() {
   node vertices[NODE];
   node start;
   char s;
   for(int i = 0; i<NODE; i++) {
      vertices[i].val = i;
   }
   s = 'B';//starting vertex B
   start.val = s-'A';
   cout << "BFS Traversal: ";
   bfs(vertices, start);
   cout << endl;
}
BFS Traversal: B A D E C F
Mean of range in array in C++

In this problem, we are given an array of n integers and some m querries. Our task is to create a program that calculates the integral value(round down) of the mean of the ranges given by the querries.
Let’s take an example to understand the problem,
Input −
array = {5, 7, 8, 9, 10}
m = 2; [0, 3], [2, 4]
Output −
7
9
To solve this problem, we have two methods one is direct and the other is using prefix sum.
In the direct approach, for each query, we will loop from the start index to the end index of the range. And add all integers of the array and divide by count. This approach works fine and prints the result but is not an effective one.
In this approach, we will calculate the prefix sum array which will store the sum of all elements of the array till the ith index i.e. prefixSum(4) is the sum of all elements till index 4.
Now, using this prefixSum array we will calculate the mean for each query using the formula,
Mean = prefixSum[upper] - prefixSum(lower-1) / upper-lower+1
Upper and lower are the indexes given in the query. If lower = 0, prefixSum(lower-1) = 0.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#define MAX 100
using namespace std;
int prefixSum[MAX];
void initialisePrefixSum(int arr[], int n) {
   prefixSum[0] = arr[0];
   for (int i = 1; i < n; i++)
   prefixSum[i] = prefixSum[i - 1] + arr[i];
}
int queryMean(int l, int r) {
   int mean;
   if (l == 0)
      mean =(prefixSum[r]/(r+1));
   else
      mean =((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));
      return mean;
}
int main() {
   int arr[] = {5, 7, 8, 9, 10 };
   int n = sizeof(arr) / sizeof(arr[0]);
   initialisePrefixSum(arr, n);
   cout<<"Mean in 1st query: "<<queryMean(1, 4)<<endl;
   cout<<"Mean in 2st query: "<<queryMean(2, 4)<<endl;
   return 0;
}
Mean in 1st query: 8
Mean in 2st query: 9
C++ Program to Implement a Binary Search Tree using Linked Lists

Here is a C++ program to Implement a Binary Search Tree using Linked Lists.
Begin
   Take the nodes of the tree as input.
   Create a structure nod to take the data d, a left pointer l and a right r as input.
   Create a function create() to insert nodes into the tree:
      Initialize c = 0 as number of nodes.
      Perform while loop till c < 6:
         Enter the root.
         Enter the value of the node, if it is greater than root then entered as right otherwise left.
   Create a function inorder() to traverse the node as inorder as:
      Left – Root – Right.
   Create a function preorder() to traverse the node as preorder as:
      Root – Left – Right.
   Create a function postorder() to traverse the node as preorder as:
      Left – Right – Root
   From main(), call the functions and print the result.
End
 Live Demo
#include <iostream>
using namespace std;

struct nod {
   nod *l, *r;
   int d;
}*r = NULL, *p = NULL, *np = NULL, *q;

void create() {
   int v,c = 0;
   while (c < 6) {
      if (r == NULL) {
         r = new nod;
         cout<<"enter value of root node\n";
         cin>>r->d;
         r->r = NULL;
         r->l = NULL;
      } else {
         p = r;
         cout<<"enter value of node\n";
         cin>>v;
         while(true) {
            if (v< p->d) {
               if (p->l == NULL) {
                  p->l = new nod;
                  p = p->l;
                  p->d = v;
                  p->l = NULL;
                  p->r = NULL;
                  cout<<"value entered in left\n";
                  break;
               } else if (p->l != NULL) {
                  p = p->l;
               }
            } else if (v >p->d) {
               if (p->r == NULL) {
                  p->r = new nod;
                  p = p->r;
                  p->d = v;
                  p->l = NULL;
                  p->r = NULL;
                  cout<<"value entered in right\n";
                  break;
               } else if (p->r != NULL) {
                  p = p->r;
               }
            }
         }
      }
      c++;
   }
}

void inorder(nod *p) {
   if (p != NULL) {
      inorder(p->l);
      cout<<p->d<<endl;
      inorder(p->r);
   }
}

void preorder(nod *p) {
   if (p != NULL) {
      cout<<p->d<<endl;
      preorder(p->l);
      preorder(p->r);
   }
}

void postorder(nod *p) {
   if (p != NULL) {
      postorder(p->l);
      postorder(p->r);
      cout<<p->d<<endl;
   }
}

int main() {
   create();
   cout<<" traversal in inorder\n";
   inorder(r);
   cout<<" traversal in preorder\n";
   preorder(r);
   cout<<" traversal in postorder\n";
   postorder(r);
}
enter value of root node
7
enter value of node
6
value entered in left
enter value of node
4
value entered in left
enter value of node
3
value entered in left
enter value of node
2
value entered in left
enter value of node
1
value entered in left
traversal in inorder
1
2
3
4
6
7
traversal in preorder
7
6
4
3
2
1
traversal in postorder
1
2
3
4
6
7
Python Design Patterns - Factory

The factory pattern comes under the creational patterns list category. It provides one of the best ways to create an object. In factory pattern, objects are created without exposing the logic to client and referring to the newly created object using a common interface.
Factory patterns are implemented in Python using factory method. When a user calls a method such that we pass in a string and the return value as a new object is implemented through factory method. The type of object used in factory method is determined by string which is passed through method.
In the example below, every method includes object as a parameter, which is implemented through factory method.
Let us now see how to implement a factory pattern.
class Button(object):
   html = ""
   def get_html(self):
      return self.html

class Image(Button):
   html = "<img></img>"

class Input(Button):
   html = "<input></input>"

class Flash(Button):
   html = "<obj></obj>"

class ButtonFactory():
   def create_button(self, typ):
      targetclass = typ.capitalize()
      return globals()[targetclass]()

button_obj = ButtonFactory()
button = ['image', 'input', 'flash']
for b in button:
   print button_obj.create_button(b).get_html()
The button class helps to create the html tags and the associated html page. The client will not have access to the logic of code and the output represents the creation of html page.
The python code includes the logic of html tags, which specified value. The end user can have a look on the HTML file created by the Python code.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to combine two lists of same size to make a data frame in R?

If we have two lists of same size then we can create a data frame using those lists and this can be easily done with the help of expand.grid function. The expand.grid function create a data frame from all combinations of the provided lists or vectors or factors. For example, if we have two lists defined as List1 and List2 then we can create a data frame using the code expand.grid(List1,List2).
 Live Demo
Consider the below lists −
List1<-as.list(sample(LETTERS[1:5],5,replace=TRUE))
List1
[[1]]
[1] "C"
[[2]]
[1] "D"
[[3]]
[1] "E"
[[4]]
[1] "D"
[[5]]
[1] "D"
 Live Demo
List2<-as.list(sample(LETTERS[6:10],5,replace=TRUE))
List2
[[1]]
[1] "I"
[[2]]
[1] "J"
[[3]]
[1] "F"
[[4]]
[1] "I"
[[5]]
[1] "F"
Creating a data frame using List1 and List2 −
df1<-expand.grid(List1,List2)
df1
  Var1 Var2
1  C I
2  D I
3  E I
4  D I
5  D I
6  C J
7  D J
8  E J
9  D J
10 D J
11 C F
12 D F
13 E F
14 D F
15 D F
16 C I
17 D I
18 E I
19 D I
20 D I
21 C F
22 D F
23 E F
24 D F
25 D F
Let’s have a look at another example −
 Live Demo
List3<-as.list(c("India","China","USA","France","Germany"))
List3
[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] "USA"
[[4]]
[1] "France"
[[5]]
[1] "Germany"
 Live Demo
List4<-as.list(1:4)
List4
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
Creating a data frame using List3 and List4 −
df2<-expand.grid(List3,List4)
df2
Var1 Var2
1 India 1
2 China 1
3 USA 1
4 France 1
5 Germany 1
6 India 2
7 China 2
8 USA 2
9 France 2
10 Germany 2
11 India 3
12 China 3
13 USA 3
14 France 3
15 Germany 3
16 India 4
17 China 4
18 USA 4
19 France 4
20 Germany 4
C++ Program to Display Factors of a Number

Factors are those numbers that are multiplied to get a number.
For example: 5 and 3 are factors of 15 as 5*3=15. Similarly other factors of 15 are 1 and 15 as 15*1=15.
The program to display the factors of a number are given as follows.
 Live Demo
#include<iostream>
using namespace std;
int main() {
   int num = 20, i;
   cout << "The factors of " << num << " are : ";
   for(i=1; i <= num; i++) {
      if (num % i == 0)
      cout << i << " ";
   }
   return 0;
}
The factors of 20 are : 1 2 4 5 10 20
In the above program, the for loop runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of num and is printed.
for(i=1; i <= num; i++) {
   if (num % i == 0)
   cout << i << " ";
}
The same program given above can be created using a function that calculates all the factors of the number. This is given as follows −
 Live Demo
#include<iostream>
using namespace std;
void factors(int num) {
   int i;
   for(i=1; i <= num; i++) {
      if (num % i == 0)
      cout << i << " ";
   }
}
int main() {
   int num = 25;
   cout << "The factors of " << num << " are : ";
   factors(num);
   return 0;
}
The factors of 25 are : 1 5 25
In the above program, the function factors() finds all the factors of “num”. It is called from the main() function with one parameter i.e. “num”.
factors(num);
The for loop in the function factors() runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of “num” and is printed.
for(i=1; i <= num; i++) {
   if (num % i == 0)
   cout << i << " ";
}
What are obsolete attributes in C#?

If a method has an obsolete attribute, then the compiler issues a warning in the code after it is compiled.
When a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method.
The following is an example showing how obsolete attribute is used −
using System;

public class Demo {
   [Obsolete("Old Method shouldn't be used! Use New Method instead", true)]

   static void OldMethod() {
      Console.WriteLine("This is the old method!");
   }

   static void NewMethod() {
      Console.WriteLine("This is the new method!");
   }

   public static void Main() {
      OldMethod();
   }
}
As we have set the warning message above, it will show the following warning −
Compilation failed: 1 error(s), 0 warnings
error CS0619: `Demo.OldMethod()' is obsolete: `Old Method shouldn't be used! Use New Method instead'
Puppet - Installing and Configuring r10K

In Puppet, we have a code management tool known as r10k that helps in managing environment configurations related to different kind of environments that we can configure in Puppet such as development, testing, and production. This helps in storing environment-related configuration in the source code repository. Using the source control repo branches, r10k creates environments on Puppet master machine installs and updates environment using modules present in the repo.
Gem file can be used to install r10k on any machine but for modularity and in order to get the latest version, we will use rpm and rpm package manager. Following is an example for the same.
$ urlgrabber -o /etc/yum.repos.d/timhughes-r10k-epel-6.repo
https://copr.fedoraproject.org/coprs/timhughes/yum -y install rubygem-r10k 

Configure environment in /etc/puppet/puppet.conf
[main] 
environmentpath = $confdir/environments 

cat <<EOF >/etc/r10k.yaml 
# The location to use for storing cached Git repos 
:cachedir: '/var/cache/r10k' 
# A list of git repositories to create 
:sources: 
# This will clone the git repository and instantiate an environment per 
# branch in /etc/puppet/environments 
:opstree: 
#remote: 'https://github.com/fullstack-puppet/fullstackpuppet-environment.git' 
remote: '/var/lib/git/fullstackpuppet-environment.git' 
basedir: '/etc/puppet/environments' 
EOF

r10k deploy environment -pv 

As we need to continue updating the environment in every 15 minutes, we will create a cron job for the same.
cat << EOF > /etc/cron.d/r10k.conf 
SHELL = /bin/bash 
PATH = /sbin:/bin:/usr/sbin:/usr/bin 
H/15 * * * * root r10k deploy environment -p 
EOF

In order to test if everything works as accepted, one needs to compile the Puppet manifest for Puppet module. Run the following command and get a YAML output as the result.
curl --cert /etc/puppet/ssl/certs/puppet.corp.guest.pem \ 
--key /etc/puppet/ssl/private_keys/puppet.corp.guest.pem \ 
--cacert /etc/puppet/ssl/ca/ca_crt.pem \ 
-H 'Accept: yaml' \ 
https://puppet.corp.guest:8140/production/catalog/puppet.corp.guest 

 Print
 Add Notes
 Bookmark this page
Bucket Sort

In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form.
Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.
Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.
Space Complexity: O(nk) for worst case
Space Complexity: O(nk) for worst case
Input:
A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Output:
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
bucketSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   for i := 0 to size-1 do
      insert array[i] into the bucket index (size * array[i])
   done

   for i := 0 to size-1 do
      sort bucket[i]
   done

   for i := 0 to size -1 do
      gather items of bucket[i] and put in array
   done
End
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void display(float *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void bucketSort(float *array, int size) {
   vector<float> bucket[size];
   for(int i = 0; i<size; i++) { //put elements into different buckets
      bucket[int(size*array[i])].push_back(array[i]);
   }

   for(int i = 0; i<size; i++) {
      sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors
   }

   int index = 0;
   for(int i = 0; i<size; i++) {
      while(!bucket[i].empty()) {
         array[index++] = *(bucket[i].begin());
         bucket[i].erase(bucket[i].begin());
      }
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   float arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   bucketSort(arr, n);

   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter elements:
0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
How to count the number of characters (including spaces) in a text file using Java?

To count the number of lines in a file
Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
Read the contents of the file to a byte array using the read() method of FileInputStream class.
Read the contents of the file to a byte array using the read() method of FileInputStream class.
Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
Finally, find the length of the string.
Finally, find the length of the string.
import java.io.File;
import java.io.FileInputStream;

public class NumberOfCharacters {
public static void main(String args[]) throws Exception{
   File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];
      
      fis.read(byteArray);
      String data = new String(byteArray);
      System.out.println("Number of characters in the String: "+data.length());
   }
}
Number of characters in the String: 3
Randomize string in C#

To randomize string, firstly use Random class −
Random r = new Random();
Now, use the Next() method with OrderBy() −
string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
Here is the compete code that displays randomize string −
 Live Demo
using System;
using System.IO;
using System.Linq;
class Demo {
   static void Main() {
      const string str = "electronics";
      Random r = new Random();
      string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
      Console.WriteLine("String = {0}", str);
      Console.WriteLine("Random String = {0}",random);
      Console.Read();
   }
}
String = electronics
Random String = lericsecton
__init_subclass__ in Python - GeeksforGeeks

22 Jun, 2020
Prerequisites: Python Classes and Objects, Inheritance in Python
Regardless of any programming languages, Inheritance is one of the most important topics in Object-Oriented Programming Concepts. Inheritance is a concept of defining a class in terms of another class. As per inheritance, we know that a superclass reference can hold its subclass reference. We all know that the behavior of the superclass can be altered according to the implementation of its sub-class(es).
But now, we can alter the behavior of the sub-class(es) by using __init_subclass__
# defining a SuperClassclass SuperClass:       # defining __init_subclass__ method    def __init_subclass__(cls, **kwargs):        cls.default_name ="Inherited Class"  # defining a SubClassclass SubClass(SuperClass):       # an attribute of SubClass    default_name ="SubClass"     print(default_name)  subclass = SubClass()print(subclass.default_name)
Output :
SubClass
Inherited Class

Understanding the code
In the above example, there are 2 classes(i.e Super Class and SubClass) and SubClass is inherited from SuperClass. default_name is an attribute of SubClass.
The value of attribute default_name is altered by SuperClass by using __init_subclass__ method.
cls is referred to the subclass(es) which are inherited. Keyword arguments(**kwargs) which are given to a new class are passed to the parent’s class __init_subclass__.
For compatibility with other subclasses using __init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class(Super Class).
This __init_subclass__ closely look alike Decorator class. But where class decorators only affect the specific class they are applied to, __init_subclass__ solely applies to future sub-classes of the class defining the method. It means we can alter/define the behavior of any new classes which are inherited from super-class.Example:
# defining a SuperClassclass SuperClass:    def __init_subclass__(cls, default_name, **kwargs):        cls.default_name = default_name  # defining a subclassclass SubClass1(SuperClass, default_name ="SubClass1"):    pass  # defining another subclassclass SubClass2(SuperClass, default_name ="SubClass2"):    default_name = "InheritedClass"    # references for subclassessubClass1 = SubClass1()subClass2 = SubClass2()  print(subClass1.default_name)print(subClass2.default_name)
Output :
SubClass1
SubClass2

By this we can conclude that __init_subclass__ method is used to alter the behavior of subclasses which may be created in future.
Python-OOP
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to get first letter of each word using regular expression in Java?

The metacharacter “\b” matches for the word boundaries and [a-zA-Z] matches one character from the English alphabet (both cases). In short, the expression \\b[a-zA-Z] matches one single character from the English alphabet, both cases after every word boundary.
Therefore, to retrieve the first letter of each word −
Compile the above expression of the compile() method of the Pattern class.
Compile the above expression of the compile() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Finally, for each match get the matched characters by invoking the group() method.
Finally, for each match get the matched characters by invoking the group() method.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "\\b[a-zA-Z]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("First letter of each word from the given string: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}
Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W
Bootstrap 4 .float-right class

Use the float-right class in Bootstrap to place an element on the right.
The default text alignment is on the left and use the float-right class to align text on the right as in the following code snippet −
<div class="float-right">
  This text is on the right.
</div>
It can be used on any other element as well, for example, <h1>, <p>, etc −
<p class="float-right">
  On the right
</p>
You can try to run the following code to implement the float-right class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <h2>Example</h2>
    <div class="clearfix">
      <div class="float-right">This text is on the right.</div><br>
      <div class="float-left">This text is on the left.</div><br>
      <div class="float-none">Float Removed</div><br>
    </div>
  </div>

</body>
</html>
Multiply Large Numbers represented as Strings in C++

Given two numbers in the string formats. We need to multiply them. The idea to solve the problem is to maintain a previous digit multiplication answer and carry. We can use the previous digits multiplication answer and carry to get the next set digits multiplication.
Let's see an example.
Input
15
2
Output
30
Initialise the numbers in string.
Initialise the numbers in string.
Initialise a string of length number_one_length + number_two_length.
Initialise a string of length number_one_length + number_two_length.
Iterate over the first number from the end.Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string.
Iterate over the first number from the end.
Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string.
Iterate over the second number from the end.
Multiply two digits and add the corresponding previous row digit.
Multiply two digits and add the corresponding previous row digit.
Update the previous row digit.
Update the previous row digit.
Store the carry in the previous index of the result string.
Store the carry in the previous index of the result string.
Convert the char to digits by adding 0 character to every character in the result.
Convert the char to digits by adding 0 character to every character in the result.
Return the result by ignoring the leading zero.
Return the result by ignoring the leading zero.
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
string multiplyTwoNumbers(string num1, string num2) {
   if (num1 == "0" || num2 == "0") {
      return "0";
   }
   string product(num1.size() + num2.size(), 0);
   for (int i = num1.size() - 1; i >= 0; i--) {
      for (int j = num2.size() - 1; j >= 0; j--) {
            int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];
            product[i + j + 1] = n % 10;
            product[i + j] += n / 10;
      }
   }
   for (int i = 0; i < product.size(); i++) {
      product[i] += '0';
   }
   if (product[0] == '0') {
      return product.substr(1);
   }
   return product;
}
int main() {
   string num1 = "34";
   string num2 = "57";
   if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {
      cout << "-";
   }
   if(num1.at(0) == '-') {
      num1 = num1.substr(1);
   }
   if(num2.at(0) == '-') {
      num2 = num2.substr(1);
   }
   cout << multiplyTwoNumbers(num1, num2) << endl;
   return 0;
}
If you run the above code, then you will get the following result.
1938
QlikView - Fill Function

The Fill function in QlikView is used to fill values from existing fields into a new field. 
Let us consider the following input data, which represents the actual and forecasted sales figures.
Month,Forecast,Actual
March,2145,2247
April,2458,
May,1245,
June,5124,3652
July,7421,7514
August,2584,
September,5314,4251
October,7846,6354
November,6532,7451
December,4625,1424
January,8547,7852
February,3265,

The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data.
After clicking Next in the above step, we choose the Enable Transformation Step button
to carry out the required data transformation.
As we are going to use the Fill function, let us choose the Fill tab, which displays th empty values under the Actual Field.
On clicking the Fill button, the option to choose target column and the cell condition appears. We choose column three, as we want to fill the empty values of this column with values from same row in column two. Also, choose the Cell Value as empty so that only the empty cells will be overwritten with new values.
On completing the above steps, we get the transformed data as shown below.
The load script for the transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values.
The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Swing Examples - Open file Dialog with multi-select option

Following example showcase how to show a Open File dialog to select multiple files in swing based application.
We are using the following APIs.
JFileChooser − To create a file chooser.
JFileChooser − To create a file chooser.
JFileChooser.showOpenDialog() − To show an open file dialog.
JFileChooser.showOpenDialog() − To show an open file dialog.
JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file.
JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

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(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();

      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setMultiSelectionEnabled(true);

            int option = fileChooser.showOpenDialog(frame);
            if(option == JFileChooser.APPROVE_OPTION){
               File[] files = fileChooser.getSelectedFiles();
               String fileNames = "";
               for(File file: files){
                  fileNames += file.getName() + " ";
               }
               label.setText("File(s) Selected: " + fileNames);
            }else{
               label.setText("Open command canceled");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
} 
 Print
 Add Notes
 Bookmark this page
Java - The Set Interface

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
The methods declared by Set are summarized in the following table −
add( )
Adds an object to the collection.
clear( )
Removes all objects from the collection.
contains( )
Returns true if a specified object is an element within the collection.
isEmpty( )
Returns true if the collection has no elements.
iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an object.
remove( )
Removes a specified object from the collection.
 size( )
Returns the number of elements in the collection.
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality −
import java.util.*;
public class SetDemo {

  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);

         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
} 
This will produce the following result −
[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python | Get last N elements from given list - GeeksforGeeks

01 Jul, 2021
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must have the knowledge to perform the same. This article discusses ways to fetch the last N elements of list. Let’s discuss certain solution to perform this task.Method #1 : Using list slicingThis problem can be performed in 1 line rather than using a loop using the list slicing functionality provided by Python. Minus operator specifies slicing to be done from rear end. 
Python3
# Python3 code to demonstrate# Get last N elements from list# using list slicing # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing NN = 5 # using list slicing# Get last N elements from listres = test_list[-N:] # print resultprint("The last N elements of list are : " + str(res))
The original list : [4, 5, 2, 6, 7, 8, 10]
The last N elements of list are : [2, 6, 7, 8, 10]
 
 Method #2 : Using islice() + reversed()The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end. 
Python3
# Python3 code to demonstrate# Get last N elements from list# using islice() + reversed()from itertools import islice # initializing listtest_list = [4, 5, 2, 6, 7, 8, 10] # printing original listprint("The original list : " + str(test_list)) # initializing NN = 5 # using islice() + reversed()# Get last N elements from listres = list(islice(reversed(test_list), 0, N))res.reverse() # print resultprint("The last N elements of list are : " + str(res))
The original list : [4, 5, 2, 6, 7, 8, 10]
The last N elements of list are : [2, 6, 7, 8, 10]
 
gabaa406
Python list-programs
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python OOPs Concepts
Defaultdict in Python
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Program to print the DFS traversal step-wise using C++

In this tutorial, we will be discussing a program to print the steps of the traversal using Depth First Search in a given binary tree.
This would include every step that occurs in the depth-first search including the backtracking procedure as well.
During DFS, we will be traversing each node and simultaneously storing the parent node and the edge used. During the traversal, if the adjacent edge has been visited, then the exact node can be printed as a step in the depth-first search.
#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
vector<int> adj[N];
//printing the steps in DFS traversal
void dfs_steps(int u, int node, bool visited[],
vector<pair<int, int< > path_used, int parent, int it){
   int c = 0;
   for (int i = 0; i < node; i++)
   if (visited[i])
      c++;
   if (c == node)
      return;
//marking the node as visited
   visited[u] = true;
   path_used.push_back({ parent, u });
   cout << u << " ";
   for (int x : adj[u]){
      if (!visited[x])
         dfs_steps(x, node, visited, path_used, u, it + 1);
   }
   for (auto y : path_used)
   if (y.second == u)
   dfs_steps(y.first, node, visited,
   path_used, u, it + 1);
}
void dfs(int node){
   bool visited[node];
   vector<pair<int, int> > path_used;
   for (int i = 0; i < node; i++)
   visited[i] = false;
   dfs_steps(0, node, visited, path_used, -1, 0);
   }
void add_edge(int u, int v){
   adj[u].push_back(v);
   adj[v].push_back(u);
}
int main(){
   int node = 11, edge = 13;
   add_edge(0, 1);
   add_edge(0, 2);
   add_edge(1, 5);
   add_edge(1, 6);
   add_edge(2, 4);
   add_edge(2, 9);
   add_edge(6, 7);
   add_edge(6, 8);
   add_edge(7, 8);
   add_edge(2, 3);
   add_edge(3, 9);
   add_edge(3, 10);
   add_edge(9, 10);
   dfs(node);
   return 0;
}
0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10
Flow control in try catch  finally in C#

The flow control in try, catch, and finally can be understood using the following example. Here, we are dividing two numbers −
 Live Demo
using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in :0
Result: 0
The following shows the flow control in exceptions handling using try catch finally in C#
If an exception occurs in try block, then the control transfers to the catch block.
After the catch block finish, then the finally block works.
If no exception occurs, then firstly the try occurs and then the flow control to finally block
How to generate a random number in C++?

Let us see how to generate random numbers using C++. Here we are generating a random number in range 0 to some value. (In this program the max value is 100).
To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand.
The declaration of srand() is like below −
void srand(unsigned int seed)
It takes a parameter called seed. This is an integer value to be used as seed by the pseudorandom number generator algorithm. This function returns nothing.
To get the number we need the rand() method. To get the number in range 0 to max, we are using modulus operator to get the remainder.
For the seed value we are providing the time(0) function result into the srand() function.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
main(){
   int max;
   max = 100; //set the upper bound to generate the random number
   srand(time(0));
   cout >> "The random number is: ">>rand()%max;
}
The random number is: 51
The random number is: 29
The random number is: 47
How to swap two numbers without using the third or a temporary variable using C Programming?

With the help of addition and subtraction operations, we can swap two numbers from one memory location to another memory location.
The algorithm is explained below −
Step 1: Declare 2 variables x and y.
Step 2: Read two numbers from keyboard.
Step 3: Swap numbers.
//Apply addition and subtraction operations to swap the numbers.
   i. x=x+y
   ii. y=x-y
   iii. x=x-y
Step 4: Print x and y values.
Following is the C program which explains swapping of two numbers without using third variable or a temporary variable −
#include<stdio.h>
int main(){
   int x,y;
   printf("enter x and y values:");
   scanf("%d%d",&x,&y);// lets take x as 20 and y as 30
   x=x+y;// x=20+30=50
   y=x-y;//y=50-30=20
   x=x-y;//x=50-20=30
   printf("After swap x=%d and y=%d",x,y);
   return 0;
}
You will get the following output −
enter x and y values:20 30
After swap x=30 and y=20
Note − We can swap two numbers by using multiplication and division and bitwise XOR operators without taking third variable help.
Consider another example which explains how to swap two numbers by using multiplication and division operators.
Following is the C program to demonstrate the respective functioning of swapping two numbers −
#include<stdio.h>
int main(){
   int x,y;
   printf("enter x and y values:");
   scanf("%d%d",&x,&y);
   x=x*y;
   y=x/y;
   x=x/y;
   printf("After swap x=%d and y=%d",x,y);
   return 0;
}
When you execute the above program, you will get the following output −
enter x and y values:120 250
After swap x=250 and y=120
Passing an array to a query using WHERE clause in MySQL?

We can pass an array with the help of where IN clause. Let us first create a new table for our example.
mysql> create table PassingAnArrayDemo
   -> (
   -> id int,
   -> Firstname varchar(100)
   -> );
Query OK, 0 rows affected (1.60 sec)
Let us now insert records.
mysql> insert into PassingAnArrayDemo values(1,'John'),(2,'Carol'),(3,'Smith'),(4,'Bob'),(5,'Johnson'),(6,'David'),(7,'Sam'),(8,'Jessica');
Query OK, 8 rows affected (0.32 sec)
Records: 8  Duplicates: 0  Warnings: 0
To display all records.
mysql> select *from PassingAnArrayDemo;
The following is the output.
+------+-----------+
| id   | Firstname |
+------+-----------+
|    1 | John      |
|    2 | Carol     |
|    3 | Smith     |
|    4 | Bob       |
|    5 | Johnson   |
|    6 | David     |
|    7 | Sam       |
|    8 | Jessica   |
+------+-----------+
8 rows in set (0.00 sec)

The following is the syntax to send an array parameter with the help of where IN clause.
mysql> SELECT *
   -> FROM PassingAnArrayDemo where id IN(1,3,6);
The following is the output.
+------+-----------+
| id   | Firstname |
+------+-----------+
|    1 | John      |
|    3 | Smith     |
|    6 | David     |
+------+-----------+
3 rows in set (0.04 sec)
C++ String Library - length

It returns the length of the string, in terms of bytes.
Following is the declaration for std::string::length.
size_t length() const;
size_t length() const noexcept;
none
It returns the length of the string, in terms of bytes.
Never throw any exceptions.
In below example for std::string::length.
#include <iostream>
#include <string>

int main () {
   std::string str ("Sairamkrishna Mammahe");
   std::cout << "The size of str is " << str.length() << " bytes.\n";
   return 0;
}
The sample output should be like this −
The size of str is 21 bytes.

 Print
 Add Notes
 Bookmark this page