Showing posts with label Basic Programming. Show all posts
Showing posts with label Basic Programming. Show all posts

Sunday, 1 October 2017

How to check Palindrome

Check if a string is palindrome or not is one of most common question we encountered during our basic days.

Let's Solve this problem with a Naive but efficient approach in this case.

Pseudocode :

  1. i=0, j=n
  2. while i < j:
  3.    check if i'th element is not equal to j'th
  4.      then return False 
  5.   else i++,j--
  6. loop end
  7. return True

Monday, 27 June 2016

When to use our own copy constructor while compiler already provides it

Actually compiler provided copy constructor copies all the values of members. So we are using a dynamic allocated member then only address of that member is copied in new object's member. It does not allocate new memory.

  1. #include <iostream>
  2. #include<cstring>
  3. #include<cstdio>
  4. using namespace std;
  5. class XYZ
  6. {
  7.     public:
  8.     char *p;
  9.     XYZ(char *name,int l){
  10.         p=new char[l+1];
  11.         strcpy(p,name);
  13.     }
  14. };
  15. int main() {
  16.     XYZ obj1("str",3);
  17.     printf("content of obj1.p is : %u\n",obj1.p);
  18.     XYZ obj2=obj1;
  19.     printf("content of obj2.p is : %u",obj2.p);
  20. }
So here content of member p of obj1 and obj2 is same which is base address of string str
Note that memory is allocated once and pointer to that memory is set for both objects. So default copy constructor only copying members value that is value of obj1.p ( which is address of string "str" ) is copied to obj2.p

Saturday, 30 January 2016

Quick Python Pandas Basics

Lets Learn Pandas

In [1]:
import pandas as pd

Pandas series

pandas series is similar to numpy array, But it support lots of extra functionality like Pandaseries.describe()
Basic access is similar to numpy array, it support access by index( s[5] ) or slicing ( s[5:10] ).
It also support vectorise operation and looping like numpy array.
Implemented in C so it works very fast.

Note : Get Code for offline testing  Github_Link or nbviewer.jupyter link

Learn Basic of Numpy

Benfits of Pandas series

In [8]:
print s.describe()
count    5.000000
mean     4.000000
std      1.581139
min      2.000000
25%      3.000000
50%      4.000000
75%      5.000000
max      6.000000
dtype: float64

Friday, 29 January 2016

Basics of Numpy & Pandas

Numpy and pandas are very popular packages used for data analysis. this post provide you quick guide to learn the basics of these. We assume you are familiar with vector operation . 

Numpy is mostly written in C & pandas are written over numpy & also uses C programming language as core implementation So these two are fast as compare to general data structure provided with python.

Numpy array is similar to python list but it contain all data of same data-type & it is much faster.
we can also treat numpy array as a vector.

Pandas uses scalar instead of list or numpy array but we can also visualize it as numpy array with some advance functionalities. 


Numpy uses array whereas pandas used scaler
In [2]:
import numpy as np

Array are similar to python list , but it all element must be of same data type, and it faster than list

In [13]:
num = np.array([3,4,2,5,7,23,56,23,7,23,89,43,676,43])
array([  3,   4,   2,   5,   7,  23,  56,  23,   7,  23,  89,  43, 676,  43])

Lets see some of functionality

Importing CSV File in Python

CSV file is one of most common used format we encounter. Let see few technique to efficiently import these data to python for better & efficient use.
CSV is also known as comma separated format. you can easily write a code to import CSV data .
But today we will see some of very efficient way to do so.

Python provide few package like CSV, unicodecsv, pandas Thease packages help you to do your job.

  • CSV : package follow basic approach & slow , it reads data line by line & split.
  • unicodecsv : Import data & create a list of dictionaries each data is associated with its attribute as key. So it  coud be very usefull in many cases but this process is also slow
  • pandas : This technique is very fast as compare to  above two methods.
You can download & test in your computer using Ipython notebook [Github_link]


In [2]:
import unicodecsv
import pprint
import csv
In [3]:

Json Import of csv file

Import data in json formate, All data are imported as string

In [16]:
enrolment = []


reader =unicodecsv.DictReader(f)
#reader is a itterater so loop is possible only once
print "type(reader) =",reader

#for each_row in reader:
#    enrolment.append(each_row)
enrolment=list(reader) #shorthand for above two line

#close file

print "Total no of row : ",len(enrolment),"\n\n"

#print demo data
type(reader) = <unicodecsv.py2.DictReader instance at 0x04A10A08>
Total no of row :  1640 

{u'account_key': u'448',
 u'cancel_date': u'2014-11-10',
 u'days_to_cancel': u'5',
 u'is_canceled': u'True',
 u'is_udacity': u'True',
 u'join_date': u'2014-11-05',
 u'status': u'canceled'}

## Simple import

Thursday, 24 September 2015

Python In Sort

Python is one of most famous Programming Language. This is summary of python programming language for Quick Start to Python Programming .

{ Zoom or download picture}

Sunday, 13 September 2015

Array Aptitude

Divide array in two part such that sum of array left to partition index is equal to sum of array right to partition index i.

That is A[0]+A[1]...+A[i-1]=A[i+1]+....+A[n]

This is slightly tricky question but very easy to solve and code ,if you find the trick.


  • Find the cumulative sum at each index of array
  • loop through array and check  A[i-1]==A[n]-A[i] , If condition Satisfy for any index i, means array can be partition in two group with this condition,So print "YES" else "NO"
  • Use special case if array has only 1 element then print YES
  • if array has only two element then print "NO"

Saturday, 5 September 2015

Finding First and Last occurrence in sorted list

Finding first and last occurrence of given number in sorted list is a very easy problem and can easily solved by leaner search with worse case Time complexity O(n) .
But We can Achieve faster search of first and last occurrence of a number by exploiting sorted feature of list.
We can  search  occurrence of any number in sorted list in O(log(n)) Time Complexity by using Binary search Algorithm.

Saturday, 29 August 2015

Vigenere Cipher

A vigenere Cipher uses a different strategy to create the key stream. The key stream is repetition of initial key stream of length m  where we have  1<=key<=26 .

Auto Key Cipher

It is a very simple poly alphabetic cipher. In this cipher previous character of plain text used as key for encryption of next character using shift ( Caesar )cipher. And  for encryption of first character of plain text we use predetermine value secretly agreed upon by both communicator.

Thursday, 23 July 2015

Caesar Cipher

A Caesar cipher (shift cipher) is one of the simplest encryption methods. It is a Substitution Cipher that involves replacing each letter of the secret message with a different letter of the alphabet which is a fixed number of positions further in the alphabet.

Example : Apple -------------Shift By 2----------> Crrng 

Now write a C++ program to Encrypt data using shift cypher . 
  • Take care that small letters encrypted to small letters and  capital letters are encrypted to capital letters 
  • character except a...z and A...Z should not encripted
  • keep in mind that shift key may be from 1 to large number. 

Tuesday, 21 July 2015

Check Panagram

 Pangrams are sentences constructed by using every letter of the alphabet at least once.
Example : "The quick brown fox jumps over the lazy dog"
 Write a program to check given sentence to paragraph is pangrams or not.


  1. create a list of all char a...z  in small letters say list is ls.
  2. convert given string to small letters.
  3. Now chose char from given string one by one if that is found in ls then remove it from ls.
  4. Repeat step 3 until ls is empty of given string ends.
  5. if  ls is empty after step 4 then it is pangrams else not pangrams.

Saturday, 18 July 2015


Heap sort is very easy to implement and its time complexity is O(n log(n)).

Sorting Max-heap:

  1. Let array S is of size n. where  n is no of element to sort
  2. top=n
  3. Pop root from heap and put it at S[top]
  4. top=top-1
  5. heapify(A,1) //Heapify remaining heap again
  6. Repeate step 3 to 5 untill heap is empty

Sunday, 5 April 2015

Factorial of a Large Number

Idea : - we are going to find factorial of a large number number.
Factorial of large number

  • store num in array such that each element of array is a single digit.
  • Decrease num by 1 and multiply num with each element of array and then for each element we store them as the rightmost digit remains at it's location while the remaining part is added to the next element and the last element is again stored as single digit and the remaining is stored on next till remaining part becomes 0.

Monday, 30 March 2015

n'th Prime Number

The first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 5th prime is 11. 
What is the 10001st prime number???

This Question is quit direct but we try to solve it in very effective way.
i.e with less complexity .

First Of all we need to know best way to check a number is prime or not. Read this Play With Prime .

Thursday, 26 March 2015

Play With Binomial coefficient

Binomial Series has Very important role in mathematics .
Today we are going to discuss different approach of finding binomial coefficient .

Lets Start With Basic Approach 

Mathematical Formula to find binomial Coefficient 

Directly implement this mathematical formula  to find Binomial Coefficient 

Wednesday, 25 March 2015

Fibonacci Series

Fibonacci series => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

I`th number in series is sum of (i-1)th & (i-2)th number in series where first two number in series are 0 & 1 ,these are base case for Fibonacci series.

If Fibonacci(n) represent n`th number in Fibonacci series .
 Fibonacci(0) = 0
 Fibonacci(1) = 1
Fibonacci(n) = Fibonacci(n-1)+Fibonacci(n-2)

Using Iteration you can easily find nth Fibonacci number .

Recursive Method for Finding n`th fibonacci Number .

Friday, 26 September 2014

Number Of Occurence

One Of very commonly asked problem in Job Interviews is To find number of occurrence of given word in given paragraph . This very easy question but people still make mistakes .

How to do it  :-

  • Find first occurrence of first character of word in paragraph 
  • If found >>  from that point check next character of word match with next character of paragraph
  • Check until last character of word match with consecutive next character of paragraph
  • If all character match increment  count by 1.
  • Repeat all above statement but now search perform on paragraph started at index of end of last character until which our search is completed 

Reverse Integer

This Is one of Very Basic Programming Problem  for beginner . But If you never Did it , Try it once.

Reverse Given Number :- 

Example >> Let Number is 12345 then after reversing Number Should be 54321

There is two way to do it

Way 1:-

Pop Last Digit then push it to another variable and repeat procedure until       number == 0
  • temp = num%10
  • num = num/10
  • numr = numr*10 + temp
  • repeat above step until num==0

Thursday, 25 September 2014

Length of string using Recursion

Finding Out Length  of  a String Is very easy task . you can directly use inbuilt function like strlen() or len() . 
But if there is restriction to not use these function then how find length of a string .

Length Using Loop : count number of element using for loop or while loop

  1. # Using For LOOP
  2. count=0
  3. st=''
  4. for ch in st:
  5.     count +=1
  6. print count

Blogger Widgets