Monday, December 28, 2015

['Python Cheat Sheet' , 'Quick Reference', 'Note to Myself', 1]

python cheat sheet 
==================
Definitions : 
Empty String : guca='' or guca=""
empty list   : guca = []
empty dict   : guca = {}
empty tuple  : guca = ()
empty set    : guca = set ()




1. Convert int to list of string 
num=12345
arr = list(str(num))
2.Convert list of string to list of ints 
arr = list(map(int,arr))
3.Convert list to set 
    l1 = f.splitlines()
    s1 = set(list(map(int,l1)))
    another example: 
    first_list = [1,2,3,4]
    my_set=set(first_list)
4. Convert set to list 
        first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

5. random number generation 
import random 
random.randint(1, 10)  # Integer from 1 to 10, endpoints included
random.randrange(0, 101, 2)  # Even integer from 0 to 100

items = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)   # shuffle the items in the list
random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
6. Split, reverse and join 
>>> buf="cisco is a good place"
>>> list_buf = buf.split()
>>> print(list_buf)
['cisco', 'is', 'a', 'good', 'place']
>>> list_buf.reverse()
>>> print(list_buf)
['place', 'good', 'a', 'is', 'cisco']
>>> op=" ".join(list_buf)
>>> print(op)
place good a is cisco
>>>

7.List creation with list expression 
>>> my_list = [x**2 for x in range(10)]  # list of square of the num in given range
>>> my_list
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 

8. list comprehension : 
The idea of a list comprehension is to make code more compact to            accomplish tasks involving lists.
Converting year_of_birth to age 
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
    ages = [2015 - year for year in years_of_birth]

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

s3 = set(a).intersection(set(b))
print("Using the sets" ,s3)

l1 = [x for x in a for y in b if x==y]
print("using list comprehension", l1)

list_comprehension_output = [ ]

Another Note : 
Here is the list filtering syntax:
[mapping−expression for element in source−list if filter−expression]

This is an extension of the list comprehensions that you know and love. The first two thirds are the same; the last part,
starting with the if, is the filter expression. A filter expression can be any expression that evaluates true or false
(which in Python can be almost anything). Any element for which the filter expression evaluates true will be included
in the mapping. All other elements are ignored, so they are never put through the mapping expression and are not
included in the output list.



9. Adding the element to the dictionary 
>>> my_dict={'xyz': 100, 'def': 23, 'zxt': 400}
>>> my_dict['bcn']=400
>>> my_dict.update({'abc':200})
>>> my_dict
{'bcn': 400, 'xyz': 100, 'def': 23, 'zxt': 400, 'abc': 200}

10. Sorting the dict based on items

import operator
my_dict={'abc':32, 'def':23, 'xyz':100}
sorted_d = sorted(my_dict.items(), key=operator.itemgetter(1))
sorted_d = sorted(my_dict.items(),
 key=operator.itemgetter(1),
 reverse=True) 

11. Adding or merging two dictionary

def add_dict(l):
final_dict = {}
for dic in l:
final_dict.update(dic)
return final_dict

d1={1:10,2:20}
d2={3:30, 4:40}
d3 ={5:50, 6:60}
l1 =[d1,d2,d3]

new_dict = add_dict(l1)
print(new_dict)

12. Where does the python looks for it's imports ?
By default the current directory and if it is not found, it looks at below path
>>> import sys
>>> sys.path
Python will look through these directories (in this order) for a .py file matching the module name, being imported.

13. Negative indexing in python:
If the negative index is confusing to you, 
think of it this way: guca[−n] == guca[len(guca) − n]. 
So in this list, guca[−3] == guca[5 − 3] == guca[2].

14. Lists - The working horses of python:
Declare the emplty list : guca = []
Declare the list with some elements : guca =[1,2,3, "cisco", "hello"]
Add element to the list = guca.append(10)
Add element at a position : guca.add(3, "new")
concatinate two lists : guca.extend(["another", "list"])

15. The difference between append and extend
    >>> guca=[1,2,3]
>>> guca
[1, 2, 3]
>>> guca.append([4,5,6])
>>> guca
[1, 2, 3, [4, 5, 6]]  # Note this becomes list within a list
>>> #extend now
>>> guca=[1,2,3]
>>> guca
[1, 2, 3]
>>> guca.extend([4,5,6])
>>> guca
[1, 2, 3, 4, 5, 6]

16. Search operations on the lists : 
>>> guca.index(4)   # Returns the index of the item looking for
3
>>> guca.append(3)
>>> guca
[1, 2, 3, 4, 5, 6, 3]
>>> guca.index(3)  # Note .. the first found occurance's index is returned.
2
>>> 10 in guca  # Check if 10 is in list ..Note: Returns Boolean
False
>>> 4 in guca
True
>>> guca.index(200)  # Note : Catch the exception, if you want ur program to continue.
Traceback (most recent call last):
 File "", line 1, in
guca.index(200)
ValueError: 200 is not in list

17.Removing from the lists : 
>>> guca.remove(4)
>>> guca
[1, 2, 3, 5, 6, 3]
>>> guca.remove(3)  # Remove the first occurance
>>> guca
[1, 2, 5, 6, 3]
>>> guca.append(5)
>>> guca
[1, 2, 5, 6, 3, 5]
>>> guca.pop(5)  # Pop returns the elements being removed and notice it is indexing from -1
5
>>> guca
[1, 2, 5, 6, 3]

18. List operators usage 
>>> guca
[1, 2, 5, 6, 3]
>>> guca+[7,8]   # same as extend ..but extend is faster and in-place. This returns the new list
[1, 2, 5, 6, 3, 7, 8]
>>> new_list=[1,2]*3  # Repeat the same list for specified number of times
>>> new_list
[1, 2, 1, 2, 1, 2]
>>> 

19. Tuples : Immutable and enclosed within the pair of paranthesis .. otherwise pretty much like a list :)
>>> guca_tup=('hi', 2016, 'happy') #declaring the tuple
>>> guca_tup
('hi', 2016, 'happy')
>>> guca_tup[0],guca_tup[-1] # positive and negative indexing is possible
('hi', 'happy')
>>> guca_tup[1:2] #slicing is possible
(2016,)

20. Notes on Tuples:
can't add elements to a tuple. Tuples have no append or extend method.
can't remove elements from a tuple. Tuples have no remove or pop method.
can't find elements in a tuple. Tuples have no index method.
However, use "in" to see if an element exists in the tuple. ex: 2016 in guca_tup 

Use case : Tuples are faster than lists. If you're defining a constant set of values to iterate through use tuples. 
Since tuples are immutable, can be used as keys of the dictionary.

21. Converting tuple into list:
>>> guca_tup
('hi', 2016, 'happy')
>>> 
>>> guca_list = list(guca_tup)
>>> guca_list
['hi', 2016, 'happy']

22. Bringing the power of enum to python in a pythonic way: 
    >>> range(8)
[0, 1, 2, 3, 4, 5, 6,7]
>>> (NONE, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(8)

23. string Formatting : 
>>> #string formatting
>>> name='cisco'
>>> place = 'SJ'
>>> "%s=%s" %(name,place) # Notice it is tuple
'cisco=SJ'
>>> print("%s is in %s", %(name,place)) # Note to all C programmers about the comma before format specifier
SyntaxError: invalid syntax
>>> print("%s is in %s" %(name,place))
cisco is in SJ
>>> print(name+"is in" + place)
ciscois inSJ
>>> guca_number=10
>>> print("number = %d" %(guca_number)) # integers works the same way as string with their format specifier specified.
number = 10

24. The facts about string formatting: 
Trying to concatenate a string with a non−string raises an exception. 
Unlike string formatting, string concatenation works only when everything is already a string

25. Formatting numbers:
>>> print "Today's stock price: %f" % 50.4625
50.462500
>>> print "Today's stock price: %.2f" % 50.4625  # Truncate the output to two decimals
50.46
>>> print "Change since yesterday: %+.2f" % 1.5  # Notice the + sign in output.
+1.50

26. import module 2 ways : 
>>> import os   # import os as object and call every method using os. 
>>> os.getpid()
2620
>>> os.getppid()
10176
>>> getpid()  # Notice u can call getpid() as it does not belong to your local namespace
Traceback (most recent call last):
 File "", line 1, in
getpid()
NameError: name 'getpid' is not defined
>>> from os import getpid    # from import makes the methods local to ur module namespace
>>> getpid()
2620

27. Know about repr  - Return the string representation of any given input object 
__repr__ is a special method that is called when you call repr(instance). The repr function
is a built−in function that returns a string representation of an object. It works on any object, not just
class instances. You're already intimately familiar with repr and you don't even know it. In the
interactive window, when you type just a variable name and press the ENTER key, Python uses repr
to display the variable's value. Go create a dictionary d with some data and then print repr(d) to
see for yourself.

Tuesday, December 22, 2015

Plugin for VIM

Simple steps to have a plugin for for vim editor.

go to ~/.vimrc and put the below two lines in this file

filetype plugin indent on
syntax on

create .vim folder in home  and plugin directory under this .. something like below
/home/ravi/.vim/plugin

copy the plugin files to this folder with vim extension.

Example:
copy yang.vim from yang central

source the .vimrc file.  - Good to go now.

==============================
ctags

get taglist.vim from http://www.vim.org/scripts/download_script.php?src_id=7701 and put it in plugin dir
get
apt-get install exuberant-ctags

go to source dir and execute
ctags *.c or *.cc

for function list in vim
:TlistOpen
:TlistClose



Saturday, December 12, 2015

Google Test Framework

The place you get your stuff :
http://www.yolinux.com/TUTORIALS/Cpp-GoogleTest.html

Couple of the things one should remember for compilation:

If you make cribs for
makefile:7: *** missing separator.  Stop

Go to the makefile line in which there is a problem and split the line like below.
Original:
testAll: $(OBJS)
    $(CXX) Main_TestAll.cpp $(CXXFLAGS) $(INCS) -o testAll $(OBJS)

Fixed :

testAll: $(OBJS);\
$(CXX) Main_TestAll.cpp $(CXXFLAGS) $(INCS) -o testAll $(OBJS)

Again on compilation of the test framwork, if it cribs for

vagrant@guca-csa-dev:~/gen_work/gtf/gtest-1.7.0/test/src$ make
\
g++ -g -L/opt/gtest/lib -lgtest -lgtest_main -lpthread -I./ -I../../src -I/opt/gtest/include -o testAll  Main_TestAll.cpp ../../src/Addition.o Addition_Test.o ../../src/Multiply.o Multiply_Test.o
/usr/bin/ld: Addition_Test.o: undefined reference to symbol '_ZN7testing8internal9EqFailureEPKcS2_RKSsS4_b'
/opt/gtest/lib/libgtest.so: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make: *** [testAll] Error 1

Solution:
Go to makefile and place the .cpp file before header and library inclusion.

something like this below.
testAll: $(OBJS);\
$(CXX) Main_TestAll.cpp $(CXXFLAGS) $(INCS) -o testAll $(OBJS


Tuesday, March 17, 2015

Single Linked List : Operations

#include
#include

struct node {
    int data;
    struct node *link;
};


/* Function Prototypes */

void append (struct node **q, int data);
void display(struct node *q);
void addAtBegin(struct node **q, int data);
void addAtLocation(struct node **q, int pos, int data);
void count(struct node *q);
void delete(struct node **q, int data);


int main ()

{
    struct node *p = NULL;

    append(&p, 10);
    append(&p, 20);
    append(&p, 30);
    append(&p, 40);
    display(p);

    addAtBegin(&p, 3);
    addAtBegin(&p, 1);
    display(p);

    addAtLocation(&p, 4, 12);
    addAtLocation(&p, 6, 13);
    display(p);

    delete(&p, 40);
    display(p);
    //count(p);

}

void append (struct node **q, int data) /* Appends at the end of the list */
{
    struct node *temp;
    struct node *r;

    if (*q == NULL){ /* First node in the link */
        temp = (struct node *)(malloc(sizeof(struct node)));
        temp->data = data;
        temp->link = NULL;
        *q = temp;
    }else{
        r = *q;
        while(r->link != NULL){
            r = r->link;
        }
        temp = (struct node *)malloc (sizeof(struct node));
        temp->data = data;
        temp->link = NULL;
        r->link = temp;

    }
    return;
}
void display(struct node *q)
{
    if (q == NULL){
        printf("List is empty \n");
    }
    while(q != NULL){
        printf("%d\n", q->data);
        q = q->link;
    }
    printf("===============================\n");
}

void addAtBegin(struct node **q, int data)

{
    struct node *temp;

    if (*q == NULL){ /* This is the first node */
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = NULL;
        *q = temp;
    }else{
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = *q;
        *q = temp;
    }
    return;
}
void addAtLocation(struct node **q, int pos, int data)
{
    struct node *temp, *r;
    r = *q;
    int i;
    for (i = 1; i        r = r->link;
        if (r == NULL){
            printf("It is exceeded the no.of the links in the list\n");
            return;
        }
    }
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = r->link;
        r->link = temp;

   
}
void count(struct node *q)
{
    int count=0;
    while (q != NULL){
        count++;
        q = q->link;
    }
    printf("Count = %d\n", count);
}

void delete(struct node **q, int data)
{
    struct node *temp, *old;
    temp = *q;

    while (temp != NULL){

        if(temp->data == data)
        {
            if (temp == *q){
                *q = temp->link;
            }else{
                old->link = temp->link;
            }
            free(temp);
            return;
        }
        else
        {
            old = temp;
            temp = temp->link;
        }
    }
    printf("Data is not found in the list\n");
}

Friday, June 10, 2011

FAQ Interview

simple programs to ask
================
#STRCAT
#STRCPY
#SWAP
#SUM of Digits


Macros
======
#No of Seconds in a year
#Server IP address
#MIN/MAX of two
#Allocation and deallocation of mem
#FOREVER loop


Declarations
=========
Pointer to int
Array of pointers
Pointer to an array
Struct and Union
Function Pointers

BitWise Operators
=============
how bitwise operators are used in error status flags. ( check declaring bits for particular err, setting more than one error, reading what error occured, clearing the error)



Misc Quetions
==========
#Static, Extern vars and functions scopes
#const
#How do u copy two structs
#Linked lists


===================================================================================================
If he answers 3 out 5 for above questions(except link list) then ask below to judge the depth

#Program to eliminate the duplicate elements in array. (Chk array init syntax, loops, function fomal args)
#Program to reverse the array without using the temp storage array
#Sort array using bubble sort and search using binary.


#Fibonacci Or factorial using recursion. ( Good if he explains the stack flow b/w normal function and recursion)
===================================================================================================

If he answers 1 of above good to go deeper

#List list - Create, add the end, add at the begining, delete, sort

=================================================================================================

if he is 5+ then ask classical typical interview question like

Dictionary creation - Chk the approach, Data structure building, tree formation, binary search on trees. ( This is good enough to discuss for 2 hrs)

=================================================================================================

C++ Questions

# what is constructor and destructor - usage , declaration

# Can we overload cons and desc - why do we do so ?

# What are virtual function - usage ?

# Is it possible to ve virtual cons/dest - If no why ?

#scope - public, private and protected.

# Friend function and usage ..

# Different types of inheritance.

# Define a class and member functions to add and ask add to overload for any data type . (Chk class , object, functions, logic)

#what r pure virtual class .. - usage.

==============================================================================================


Operating system

# Memory Laypout of a program

# Job of OS. - how in between

# Difference b/w process and thread.

# IPC ( pipe, msg queques, shared memory, sockets )

# Socket programming : client side calls and server side calls ( Y for the difference)

# Virtual Memory concepts

=============================================================================================


Network questions

# TCP/IP 3 way hand shake
# MAC / IP address conversion

Wednesday, November 4, 2009

Check whether given number is Fibonacci OR not

Algo : A given number is said to be fibonacci, if 5*N*N -4 or 5*N*N +4 is a square

#include
int isSquare(int num);
main()
{
int num, temp;
printf("Enter the number\n");
scanf("%d", &num);

temp = 5 *(num * num) - 4;

if(isSquare(temp) || isSquare(temp+8)){
printf("It is finonacci number\n");
}else {
printf("It is NOT finonacci number\n");
}
}
int isSquare(int num)
{
int i=1;
while(num>0)
{
num = num - i;
i = i+2;
}
if(num==0)
return 1;
else
return 0;
}

Monday, November 2, 2009

Fibonacci Numbers

C program to generate Fibonacci numbers till the user entered value.

#include
main()
{
int num;
int *a, i;;
printf("Enter the number\n");
scanf("%d", &num);

a = (int *)malloc(sizeof(int)*num);

a[0] = 0;
a[1] = 1;
printf("FIBONACCI Numbers are\n");
printf("%d\n%d\n", a[0],a[1]);

for(i = 2; i
{
a[i] = a[i-1] + a[i-2];
printf("%d\n", a[i]);
}


}