Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Tuesday, August 17, 2021

Email Slicer in Python


 

We will slice the email address and get the username and domain using three different methods: 

1) The conventional method of slicing

2) Using split function

3) Regex(Regular Library) Library 

So, let's start looking at each method in detail with the code.

1) Slicing

 First of all we will ask for the email-address. Then we will write two expressions to slice the email address each for username and domain.

 
 email=input("Enter email address : ")

username=email[:email.index('@')]
domain=email[email.index('@')+1:]

print("\nUsername : "+ username + "\nDomain name : "+ domain)
 

Finally we will print the username and domain.

2) Using Split function

Here we will input the email-address. Then we will split the email address from '@' using just one statement. i.e. email.split('@'). It will split the string from '@' and return list. Then we will print the list

 
 email=input("Enter email address : ")

l1=email.split('@')

print(f"\n\nUsername : {l1[0]} \nDomain name : {l1[1]}")
 

3)Using Regex

Here, we will first import the re module. Then we will ask for the user input (Email address to be sliced).

import re
email=input("Enter email address : ")

 Then we will write a regular expression which will split our string from  '@'. We can also split from more than one element by just adding more elements with a space with @. The print(result) will print a sliced list because the regex expression will return a list which is been splitted by '@'

result=re.split('[@]',email)
print(result)

 For example if I want my email address to split from '.' and '#' too, then I will write the expression as follows,

result=re.split('[@ . #]',email)

Then we will print the list which was splitted, here specifically we will print using the f string. Although we can use any method to print.  Below is the complete code for the Email Slicer using regex library

 
import re
email=input("Enter email address : ")

result=re.split('[@ .]',email)
print(result)

print(f"\n\nUsername is {result[0]} \nDomain name {result[1]}")
 

 

 

Monday, June 21, 2021

Set up Sublime-Text for Competitive Coding | C/C++,Python

Hii everyone! Setting up sublime text for competitive coding is easy but not at the very first try. 

Today, your that first try will be made simpler and easier by bringing the right things in fron of you. This is specifically done for mac os x.

So let's get started.

1) C/C++

Step -1 : Create and save three files 

                1) input.in

                2) output.in

                3) hello.cpp / hello.c file 

Step - 2 : Install gcc(GNU Compiler Collection) by running the command below in the terminal.

Install gcc -

$ brew install gcc

If you already have gcc installed, check the version of gcc by 

$ gcc-10 -v

 OR

$ gcc-9 -v

 Now to install gtimeout, run the command

$ brew install coreutils

 Since we will require gtimeout which is a part of coreutils library, we are installing coreutils.

As a next step, create a new build system using the following steps.

Tools->Build System->New Build System

 Now copy the following code in the current file


{
"cmd" : ["g++-10 $file_name -o $file_base_name &&
 gtimeout 4s ./$file_base_name<inp.in>out.in"],
"selector" : "source.c,source.cpp",
"shell": true,
"working_dir" : "$file_path"
} 

Now, Save the buile fie with any name your want with an extension '.sublime-build'

For example, C++.sublime-build

Now setup the column view,

1) View -> Layout -> Columns: 3

2) View -> Group -> Max Columns: 2

Here's how it will look,

Now you're all set to go!

Write some code in .cpp/.c file, select the build system as C++, the one which you just created and write the input in inp.in file and run the code.

You will see the output in out.in.

Final setup 


2) Python

For Python, if you already have created inp.in and out.in for C/C++, you don't need to create them again. And create the files if you have not already created them before.

Now, Create a .py file. For example, sample.py

1.Tools->Build System->New Build System

In the file, paste the code given below,

{
"cmd" : ["Python3 $file_name -o $file_base_name 4s ./$file_base_name<inp.in>out.in"],
"selector" : "source.py",
"shell": true,
"working_dir" : "$file_path"
}

Now you can save the build file with any name like Python3.sublime-build. 

Run the code in sample.py code, write th input in inp.in file and you will see the output in out.in






Friday, April 23, 2021

Insertion at the end of a Linked List

 

The new node will be added at the end of the linked list.

Example:

Input

Linked List : 1➞ 2➞ 3➞ 4➞ NULL

5

Output

Linked list : 1➞ 2➞ 3➞ 4➞ 5➞ NULL 

Shown below is a simple visual representation of the insertion of a node at the end of a linked list...

Insertion at the end will be done in four steps,

1) create a new node i.e. temp

2) the next of temp should be NULL

3) Now, tail➞next = temp

4) Lastly, tail = temp

Also if there is no prior list created after which you want to insert a node, then, head = tail = temp since after inserting in a NULL list, you will be left with only one node, so head will be equal to tail.

Let's create a function that will contain the main logic for insertion.

void end(int n)

The function end() will take an integer argument n which will contain the value we want to insert at the end of a linked list.

Now we will create a new node named temp and assign it the value n.

temp➞data will assign n to the node temp.

node *temp=new node;
temp->data=n;

Now assigning NULL to the next of temp since it will be the last node of our linked list and it will point to NULL.

temp->next=NULL;

Also, let's write a condition for if there is no prior list already created. In that case it will assign head and tail to temp. Although, in our program, this will never happen because we are going to input five elements to create a linked list at the very beginning and then we will insert a new node at the end.

if(head==NULL)
{
head=temp;
tail=temp;
}

 Otherwise if a list is already existing, then we eill assign the next to tail to temp and then assign temp to tail.

else
{
tail->next=temp;
tail=temp;
}

 So, the complete function looks like the one given below,

void end(int n)
{
node *temp=new node;
temp->data=n;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}

 

Now, lets look at the complete program to insert a node at the end.

In the program below we have the following,

1) structure node

2) class linked_list

3) a constructor linked_list() inside the class linked_list to initialize the value of head and tail to NULL at the very beginning

4) a function end() to insert  node at the end

5) a function display() to display the linked list

 

In the main() function, we are taking in 5 elements as an input to kind of create a new node which is though just inserting in the end the elements one after another. But for understanding purpose, assume it is creating a linked list having five nodes or five elements. Later then, we are inputting a value to be inserted at the end and then we are passing the value to the function end() and then displaying it by calling the function display().

#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
}*head,*tail;
class linked_list
{
public:
linked_list()
{
head=NULL;
tail=NULL;
}
void end(int n)
{
node *temp=new node;
temp->data=n;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
}
}
void display(node *h)
{
if(h==NULL)
{
cout<<"\tNULL";
}
else
{
cout<<"\t"<<h->data;
display(h->next);
}
}
};
int main()
{
linked_list a;
int info[10],end;
cout<<"\nEnter 5 values for a new node : ";
for(int i=0;i<5;i++)
{
cin>>info[i];
}
for(int i=0;i<5;i++)
{
a.end(info[i]);
}
a.display(head);
     cout<<"\nEnter a value that you want to insert in the end : ";
cin>>end;
a.end(end);
a.display(head);
}

 

 

 

 

Thursday, April 15, 2021

Insertion at the beginning of a Linked List


It was all going well until the pointers came in!
Has this statement ever crossed your mind? 

But you should know that the pointer is an important concept to know. A pointer is used to implement a lot many things in C++. Linked List is one of them. Linked List uses pointers for its operation. 

Today we will be looking at how to insert a node at the beginning of a Linked List. 

In the picture below you can see, we want to insert node d at the beginning of the list given. To insert it at the beginning, we followed three steps,

1) create a new node i.e. temp

2) the next of temp should be head now

3) At last, head = temp

Now, the new node temp is inserted at the beginning.

Lets look at the code!

Below is the function for inserting at the beginning. It will take an integer argument which will contain the value to be inserted in the node that is to be inserted at the beginning.

void front(int n)

In the function, at the very first, we will create a new node by the code given below. I will create a new node named temp.

node *temp=new node; 

Now we will assign the data n to the new node temp.

temp->data=n;

After assigning the data to the node now the next to temp should have the address of the current head of the linked list before which we want to insert the new node temp. We will do it by assigning temp->next = head,

temp->next=head;

Now that our node temp is holding the address of its next node, we will assign temp to head. Since now, the temp is the first node of our linked list.

head=temp;

So here we are done with inserting the node temp at the beginning of the linked list. 

So the entire function looks like, 

    void front(int n)
{
node *temp=new node;
temp->data=n;
temp->next=head;
head=temp;
display(head);
}

In the above code, display(head) is another function which is used to display the entire linked list. So lets take a brief look at display function.

Below give is the entire display function. This function takes in pointer as an argument. This pointer will bring the address of the node to be printed.Recursion is used hear where we again pass h->next to the function display until the value of the pointer is equal to NULL.


    void display(node* h)
{
if(h==NULL)
{
cout<<"\tNULL";
}
else
{
cout<<"\t"<<h->data;
display(h->next);
}
}


Now we will look at the entire program to insert a node at the beginning.


#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
}*head,*tail;
class linked_list
{
public:
linked_list()
{
head=NULL;
tail=NULL;
}
void front(int n)
{
node *temp=new node;
temp->data=n;
temp->next=head;
head=temp;
display(head);
}
void display(node* h)
{
if(h==NULL)
{
cout<<"\tNULL";
}
else
{
cout<<"\t"<<h->data;
display(h->next);
}
}
};
int main()
{
linked_list a;
int info,beg;
cout<<"\nEnter a value for the new node....";
cin>>info;
a.front(info);

cout<<"\nEnter the element you want to insert in the beginning : ";
cin>>beg;
a.front(beg);
}

In the above program we have the following,

1) structure node

2) class linked_list

3) a constructor linked_list() inside the class linked_list to initialise the value of head and tail to NULL at the very beginning

4) a function front() to insert at the beginning

5) a function display() to display the linked list



Thursday, December 10, 2020

Binary Search Algorithm

 

Binary search is basically a searching algorithm used to search for a particular element in any given array. There are in fact many searching algorithms available, but what matters more is the efficiency with which an algorithm searches for an element in any given array because we would never want our algorithm to do less work in more time. In other words we can say that time complexity and space complexity tells us all about how efficient an algorithm.

 

Lets get started...

 

First of all lets look at what Binary Search does!

 

Process to search..

 

To search an element in a sorted array, here lets assume array is sorted in ascending order.

 

1. We find the middlemost element of an array lets say a[i] (Here 'a' is an array and 'i' refers to index number).

 

2.  Check whether a[i] is greater then or less than the element to be searched for.

 

    a. If a[i] == val, then we just found out the value....


    b. Else if a[i] > val, then discard the remaining array after the middle element.

 

    c. Else if a[i] < val, then discard the array beforehand the middle element.

 

 

Fig (a)
 

 

Above two points can be considered as the main logic in Binary Search. Now we are good start.

 

Now lets see how it actually works.

 

Starting with our function, we will create a function named Binary Search and declare the variables needed.

 

                int BinarySearch( int n, int a[], int val)   

        

Here, n = number of array elements

          a[] =  given array

          val = value to be searched for in the array

 

Now we will write the body of the function of BinarySearch ().

 

int first=0,mid,last=(n-1),val;

 

 Here we declared two variables named 'first' and 'last' and then we stored the first and the last index value of the array 'a[]' respectively in those variables.

 

How to find the middle element?

 

We will use the formula mid = first + (last-first)/2  
 
  mid=first+(last-first)/2;
 
 
This is because the above formula proves to be more reliable the the formula
mid=(first+last)/2

                           
Now to find the value in the array a[], we will look for three conditions on the basis of the value of middle element
  
//One
    if(val==a[mid])
{
return mid;
}

 

In 'one' we get our middle element.

 

//Two 
    else if(val>a[mid])
{
first=mid+1;
}


In 'two' if value is greater than middle element, we eliminate the leftmost array from the middle element along with middle element.

In fig (a), the array elements 1, 2, 3 and 4 will be eliminated and now on wards our new array elements will be 5, 6, 7 with indices 4, 5, 6.


//Three 
    else
{
last=mid-1;
}



In 'three' if value is less than the middle element, we will eliminate the rightmost array from the middle element along with middle element.

In fig (a), the array elements 4, 5, 6 and 7 will be eliminated and now on wards our new array elements will be 1, 2, 3 with indices 0, 1, 2.

 

Here our while loop gets completed.

 

  while(first<=last)
{
mid=first+(last-first)/2;
if(val==a[mid])
{
return mid;
}
else if(val>a[mid])
{
first=mid+1;
}
else
{
last=mid-1;
}
}

 

Now we will basically return -1 if any of the conditions in the above loop does not come out to be true.

 

Here's the complete function.


int BinarySearch(int a[], int n, int val)
{
int first=0,mid,last=(n-1),val;
while(first<=last)
{
mid=first+(last-first)/2;
if(val==a[mid])
{
return mid;
}
else if(val>a[mid])
{
first=mid+1;
}
else
{
last=mid-1;
}
}
return -1;
}




Time

  A brief look at time......  

Popular Posts