Labels

Tuesday 15 January 2013

Programming Interview Questions

Programming Interview Questions

Below programs written in Java but you can use your favorite programming language drive the results.

Scenario #1:
You are given a linked list with nodes containing characters. The number of characters in each node might differ
Question: Check if the data stored in the linked list is a palindrome?



import java.util.*;

public class LList {

public boolean isPal(List<String> ll){
String forward = "";
String bacward = "";

for (int i=0; i < ll.size();i++)
{
forward  = forward + ll.get(i);
bacward = bacward + reverse(ll.get(ll.size()-1-i));

}

System.out.println("Forward:"+forward);
System.out.println("Backward:"+bacward);
if (forward.equalsIgnoreCase(bacward)){
return true;
}
return false;
}

public String reverse(String ss){
String rev="";
for (int i=(ss.length()-1); i >= 0 ; i--){
rev = rev + ss.charAt(i);
}
return rev;
}
public static void main(String args[]){
List<String> ll = new LinkedList<String>();
ll.add("su");
ll.add("n");
ll.add("us");
LList l = new LList();
System.out.println("List is:"+ ll);
System.out.println("Is palindrome:"+ l.isPal(ll));
}
}



Result is:
List is:[su, n, us]
Forward:sunus
Backward:sunus
Is palindrome:true

Scenario #2:
Reverse the given string as well as reverse individual word in a sentence.

import java.util.*;

public class StringRev {
public String reverseString(String s) {
        if (s.length() <= 1) {
            return s;
        } 
        return reverseString(s.substring(1,s.length())) + s.charAt(0);
    }
public static void main(String args[]){
String str ="I love India";
System.out.println("Given string is:"+ str);
String word = "";
List<String> ll = new LinkedList<String>();
StringRev sr = new StringRev();
System.out.println("Entire string reverse:"+sr.reverseString(str));
for (int i=0; i< str.length();i++){
if (str.charAt(i)!=' '){
word = word + str.charAt(i);
} else{
ll.add(word);
word = "";
}
if (i == str.length()-1){
ll.add(word);
}
}
String backward = "";
for (int i=0; i < ll.size();i++){
backward  = backward +' ' +sr.reverseString(ll.get(i));
}
System.out.println("Individual word string reverse:"+backward);
}
}

Output is:
Given string is:I love India
Entire string reverse:aidnI evol I
Individual word string reverse: I evol aidnI

Tuesday 1 January 2013

Python Tricks

What is 'if __name__ == "__main__"' for?

Basically  __name__ is a built-in variable which help to self identify whether the program is running as standalone or it has been imported into some other programs. If it is run as standalone then __name__ variable would be assigned with value of __main__, otherwise not.

For example, create two files one.py and two.py as mentioned below. When you run the one.py from the command line, it prints 'aa' as the __name__ would have the value __main__. But it will be different when you run the two.py script which has imported the one.py:
one.py file has following code:
if __name__ == '__main__':

    print ('aa')
else:
    print ('bbb')

two.py has below code:
import one

Run the-- python two.py:
Output will be: 
>>> 
bbb

Run the-- python one.py:
>>> 
aa

How to implement arbitrary arguments in python? 
*args in a function declaration would help to accept and retrieve arbitrary number of arguments. For example:

create the following code and run it:

def argu(*args):
    #print(arg)
    print (args)
    for arg in args:
        print(arg)
    
argu(1,2,3,"test")

Output would be like this
(1,2,3,"test")
1
2
3
test

Similarly, **kwargs accepts arbitrary number of dictionary elements:
For example,

def argu(**kwargs):
    #print(arg)
    print (kwargs)
    for arg in kwargs:
        print(arg)
argu(one=1,two=2)   

And output would be something like this:
{'two': 2, 'one': 1}
two
one

And even if you don't pass any arguments (for example, call the function as argu()), the script still execute well.

Tuesday 18 December 2012

First step into Junit 4.10

Junit  is a very popular unit testing framework for Java applications which helps to build a fully automated unit tests.

The main objectives of any unit testing framework would be:
>> Each unit test should run independently of all other unit tests.
>> The framework should detect and report errors test by test.
>> It should be easy to define which unit tests will run.

Setting up Junit:
 Download the Junit JAR file from junit.org/downloads and add them into your projects compilation path.
If you are using windows shell, extract downloaded file into C:\ and run as below:



 If you are using any IDE's like Eclipse then right click on the project > Properties > Libraries > Add JARs





Lets create a java program for factorial:
Fact.java
public class Fact {

    public int factorial(int i){
        if (i < 1) throw new IllegalArgumentException();
        if (i ==1 ) return 1;
        return i*factorial(i-1);
       
    }
}

And its Junit cases which validates both positive and negative cases (given number less than 1).
FactTest.Java

import static org.junit.Assert.*;
import org.junit.Test;

public class FactTest {
    @Test
    public void testfactorial() {
        Fact f = new Fact();
        int res = f.factorial(2);
        assertEquals(2,res,0);
        int res1 = f.factorial(5);
        assertEquals(120,res1,0);
        //fail("Not yet implemented");
    }
    @Test
    public void testZero(){
        Fact f = new Fact();
    try{
        int res2=f.factorial(0);
    } catch (IllegalArgumentException e){
    }
    }
}

Right click the Junit test file and Run As 'Junit Test' and you will get the results as below:



Notes:
- In Junit 3.x version we needed to extends the TestCase class but it has been removed from Junit 4.
- It is good practice if the Junit class named as XXXTest and also its methods are named as testXxxx()
- Annotations are important for Junit tests and as soon as the program sees @Test, it will start executing the test.

Reference:
Junit pocket guide by Kent Beck