myDezigns

Unit Testing in Python

Posted by: Mohan Gulati on: October 8, 2009

Here are some unit tests for using pyunit for the balanced brackets function that was posted earlier. The idea is simply to demonstrate how unit testing for python works and in no way claims to be best coding practices or without errors.  Its simply a learning process at this point.

#!/usr/bin/env/python
import unittest
import BalancedBrackets
class SimpleTestCases(unittest.TestCase):
“”"All basic test cases”"”
def emptyString(self):
assert BalancedBrackets.isBalanced(“”) == False, ‘SimpleTestCase failed’
def stringWithNoBrackets(self):
assert BalancedBrackets.isBalanced(“there are no brackets in this string”), ‘SimpleTestCase failed’
def balancedSingleRoundBrackets(self):
assert BalancedBrackets.isBalanced(“(Test)”), ‘SimpleTestCase failed’
def unbalancedSingleRoundBrackets(self):
assert BalancedBrackets.isBalanced(“(Test”) == False, ‘SimpleTestCase failed’
def balancedSingleSquareBrackets(self):
assert BalancedBrackets.isBalanced(“[Test]“), ‘SimpleTestCase failed’
def unbalancedSingleSquareBrackets(self):
assert BalancedBrackets.isBalanced(“[Test") == False, 'SimpleTestCase failed'
def balancedSingleCurlyBrackets(self):
assert BalancedBrackets.isBalanced("{Test}"), 'SimpleTestCase failed'
def unbalancedSingleCurlyBrackets(self):
assert BalancedBrackets.isBalanced("{Test") == False, 'SimpleTestCase failed'
class ComplicatedTestCases(unittest.TestCase):
"""A bit more complicated test cases"""
def balancedMultipleRoundBrackets(self):
assert BalancedBrackets.isBalanced("(((Test)))"), 'Multiple Round Brakets Case failed'
def unbalancedMultipleRoundBrackets(self):
assert BalancedBrackets.isBalanced("(((Test))") == False, 'SimpleTestCase failed'
def balancedMultipleBrackets(self):
assert BalancedBrackets.isBalanced("({[Test]})”), ‘SimpleTestCase failed’
def unbalancedMultipleBrackets(self):
assert BalancedBrackets.isBalanced(“({[Test]}”) == False, ‘SimpleTestCase failed’
def wrongOrderMultipleBrackets(self):
assert BalancedBrackets.isBalanced(“({[Test])}”) == False, ‘SimpleTestCase failed’
def simpleTestSuite():
suite = unittest.TestSuite()
suite.addTest(SimpleTestCases(“emptyString”))
suite.addTest(SimpleTestCases(“stringWithNoBrackets”))
suite.addTest(SimpleTestCases(“balancedSingleRoundBrackets”))
suite.addTest(SimpleTestCases(“unbalancedSingleRoundBrackets”))
suite.addTest(SimpleTestCases(“balancedSingleSquareBrackets”))
suite.addTest(SimpleTestCases(“unbalancedSingleSquareBrackets”))
suite.addTest(SimpleTestCases(“balancedSingleCurlyBrackets”))
suite.addTest(SimpleTestCases(“unbalancedSingleCurlyBrackets”))
return suite
def complicatedTestSuite():
suite = unittest.TestSuite()
suite.addTest(ComplicatedTestCases(“balancedMultipleRoundBrackets”))
suite.addTest(ComplicatedTestCases(“unbalancedMultipleRoundBrackets”))
suite.addTest(ComplicatedTestCases(“balancedMultipleBrackets”))
suite.addTest(ComplicatedTestCases(“unbalancedMultipleBrackets”))
suite.addTest(ComplicatedTestCases(“wrongOrderMultipleBrackets”))
return suite
simpleTestSuite = simpleTestSuite()
complicatedTestSuite = complicatedTestSuite()
runner = unittest.TextTestRunner()
runner.run(simpleTestSuite)
runner.run(complicatedTestSuite)
#!/usr/bin/env/python

import unittest

import BalancedBrackets

 

class SimpleTestCases(unittest.TestCase):

    """All basic test cases"""

    def emptyString(self):

        assert BalancedBrackets.isBalanced("") == False, 'SimpleTestCase failed'

    def stringWithNoBrackets(self):

        assert BalancedBrackets.isBalanced("there are no brackets in this string"), 'SimpleTestCase failed'

    def balancedSingleRoundBrackets(self):

        assert BalancedBrackets.isBalanced("(Test)"), 'SimpleTestCase failed'

    def unbalancedSingleRoundBrackets(self):

        assert BalancedBrackets.isBalanced("(Test") == False, 'SimpleTestCase failed'

    def balancedSingleSquareBrackets(self):

        assert BalancedBrackets.isBalanced("[Test]"), 'SimpleTestCase failed'

    def unbalancedSingleSquareBrackets(self):

        assert BalancedBrackets.isBalanced("[Test") == False, 'SimpleTestCase failed'

    def balancedSingleCurlyBrackets(self):

        assert BalancedBrackets.isBalanced("{Test}"), 'SimpleTestCase failed'

    def unbalancedSingleCurlyBrackets(self):

        assert BalancedBrackets.isBalanced("{Test") == False, 'SimpleTestCase failed'

 

class ComplicatedTestCases(unittest.TestCase):

    """A bit more complicated test cases"""

    def balancedMultipleRoundBrackets(self):

        assert BalancedBrackets.isBalanced("(((Test)))"), 'Multiple Round Brakets Case failed'

    def unbalancedMultipleRoundBrackets(self):

        assert BalancedBrackets.isBalanced("(((Test))") == False, 'SimpleTestCase failed'

    def balancedMultipleBrackets(self):

        assert BalancedBrackets.isBalanced("({[Test]})"), 'SimpleTestCase failed'

    def unbalancedMultipleBrackets(self):

        assert BalancedBrackets.isBalanced("({[Test]}") == False, 'SimpleTestCase failed'

    def wrongOrderMultipleBrackets(self):

        assert BalancedBrackets.isBalanced("({[Test])}") == False, 'SimpleTestCase failed'

def simpleTestSuite():

    suite = unittest.TestSuite()suit

    suite.addTest(SimpleTestCases("emptyString"))

    suite.addTest(SimpleTestCases("stringWithNoBrackets"))

    suite.addTest(SimpleTestCases("balancedSingleRoundBrackets"))

    suite.addTest(SimpleTestCases("unbalancedSingleRoundBrackets"))

    suite.addTest(SimpleTestCases("balancedSingleSquareBrackets"))

    suite.addTest(SimpleTestCases("unbalancedSingleSquareBrackets"))

    suite.addTest(SimpleTestCases("balancedSingleCurlyBrackets"))

    suite.addTest(SimpleTestCases("unbalancedSingleCurlyBrackets"))

    return suite

def complicatedTestSuite():

    suite = unittest.TestSuite()

    suite.addTest(ComplicatedTestCases("balancedMultipleRoundBrackets"))

    suite.addTest(ComplicatedTestCases("unbalancedMultipleRoundBrackets"))

    suite.addTest(ComplicatedTestCases("balancedMultipleBrackets"))

    suite.addTest(ComplicatedTestCases("unbalancedMultipleBrackets"))

    suite.addTest(ComplicatedTestCases("wrongOrderMultipleBrackets"))

    return suite

 

simpleTestSuite = simpleTestSuite()

complicatedTestSuite = complicatedTestSuite()

runner = unittest.TextTestRunner()

runner.run(simpleTestSuite)

runner.run(complicatedTestSuite)

Balanced Brackets in Python

Posted by: Mohan Gulati on: September 22, 2009

Here is the a solution to the balanced brackets problem but done in python.  I would appreciate any python experts input on how to do this more concise or elegant.  Cheers!!

def isBalanced(strI
"""Validate if an input string is having balanced bracket pair
return def isBalanced(strInput):
def isBalanced(strInput):
    """Validate if an input string is having balanced bracket pairs
    this includes bracket ordering. i.e a round bracket must be closed
    by a round bracket.  Emtpy strings are treated as balanced."""
    if strInput:
        # list of all bracket kinds, in paired tuples
        brackets = [ ('(',')'), ('[',']'), ('{','}')]
        # define fake constants - python does not support the concept of constants
        kStart = 0
        kEnd = 1

        # internal stack used to push and pop brakets in the input string
        stack = []

        for char in strInput:
            for bracketPair in brackets:
                if char == bracketPair[kStart]:
                    stack.append(char)
                elif char == bracketPair[kEnd] and len(stack) > 0 and stack.pop() != bracketPair[kStart]:
                    return False

        if len(stack) == 0:
            return True

    return False
Tags:

Apple Tablet on its way, February

Posted by: Mohan Gulati on: September 17, 2009

The Apple Tablet is coming.  Thats a given.  This is interesting to me because, well quite frankly Apple is doing this.  So aside from the hardware side of things, there is a long term business strategy here and my gut tells me it has to do with software as a service.

For details about the Apple Tablet take a look here.  Its reportedly going to be a 9.6 inch screen and have awesome battery life.

In this post I want to simply pose the question, how can software a service on a tablet device change how we live.  Hmmmm… that’s a packed question.  I will share my thoughts but first I want to hear yours.  So what do you have to say?

Balanced Brackets

Posted by: Mohan Gulati on: August 14, 2009

Here was a simple programming assignment which showed up at an interview I had.  The task was to write a program which would tell if an input string had balanced brackets or not. Balanced brackets imply that for every open bracket there is a closing bracket. My solution took into consideration curly, round and square brackets. In order to save space I left the different checks out below.

#include <iostream>

#include <string>

#include <algorithm>

#include <list>

using namespace std; 

bool isBalanced( const std::string& input )

{

 bool balanced = false;

 if ( !input.empty() )

 {

 list<char> closingBracketStack;

 string::size_type inputLength = input.size();

 for( int i=0; i < inputLength; i++ ) {

 // Round Brackets

 if ( input[i] == '(' ){

 closingBracketStack.push_front(')');

 }

 else if ( input[i] == ')') {

 if ( ( closingBracketStack.size() > 0) &&

  ( closingBracketStack.front() == ')') ) {

 closingBracketStack.pop_front();

 }

 else return false;

 }

 // Square Brackets

 ... same code as above except check for [ and ]

 // Curley Brackets

 ... same code as above except check for { and }

 }

 if ( closingBracketStack.empty() )

 balanced = true;

 }

 return balanced;

}

void requestInput( std::string& input )

{
 cout << "Enter a string with brackets:\n";
 cin >> input;
}

void outputResult( bool isBalanced )
{
 if ( isBalanced )
 cout << "Input is a balanced";
 else
 cout << "Input is NOT balanced";
}

int main (int argc, char * const argv[])
{
 std::string input;
 requestInput( input );
 outputResult( isBalanced( input ) );
 return 0;
}
Tags:

iPhone missing key feature

Posted by: Mohan Gulati on: August 14, 2009

I think the iPhone is missing one key feature that if added would open the door to multiple new and interesting applications.  Have I got your attention?  I think its missing a second video camera facing the user.

Naturally a second video camera opens the door to video conferncing, think iChat for the iPhone. This is a big wow application and but I believe that much more that can be achieved.

A video camera on the front of the phone would open the door to motion or gesture detection. I believe is truly where new applications for the mobile phone will be developed.  Some Nokia phones have a second video camera and you can see already some far out applications being developed.

Below is a video of an application that can be downloaded from the Ovi store called eyeCall.  This application allows users to silence the mobile phone when there is an incoming call by simply making a wave gesture before the video camera or send out a text reply by holding your hand over the phone for more then 3 seconds.  Cool, eh?

Jeff Bezos on Customer Service and Zappos

Posted by: Mohan Gulati on: August 6, 2009

Excellent video that is both insightful and sincere.

Tags:

Bubbles – a new UI for Mobile Phones

Posted by: Mohan Gulati on: July 22, 2009

This just blew me away.   Watch this video to see an elegant user interface design for touch screen phones.

Operator Overloading vs Operator Overriding

Posted by: Mohan Gulati on: July 21, 2009

Operator Overloading in C++ refers to the case when a multiple methods with the same name exist but take arguments of different types as its input.  The classical example is an Add Method which can add different objects of different types.

Operator Overriding refers to a process of changing the implementation of a method from a base class which was declared as a virtual method.  A classical example is the getArea method for different shapes in an OOP shape model paradigm.

Tags:

Virtual Destructors and Constructors in C++

Posted by: Mohan Gulati on: July 21, 2009

In C++ you can have virtual destructors but NOT virtual constructors. This is because when an object has virtual functions it must have an associated v-table which keeps track of the addresses to the virtual functions for that class.  That would mean that an object must be instantiated firstly before a v-table for that object could exist.  Since constructors are intended to instantiate and create the object there can be no virtual constructor.

On the other hand a virtual destructor is allowed and should be used when ever there are virtual methods in the base class.  The misuse of virtual destructors can lead to memory leaks and bad side effects.  The following code tries to explain this problem.

void goodbye(const char* clsid) { std::cout << "Good-bye, " << clsid << "!" << std::endl; } class Foo { public: ~Foo() { goodbye("Foo"); } }; class Bar : public Foo { public: ~Bar() { goodbye("Bar"); } }; int main (int argc, char * const argv[]) { Foo* p = new Bar; delete p; return 0; }

In the above code example when the object that p is pointing to is destroyed the output will be “Good-bye, Foo!”.  The destructor for Bar will not be called.  That behavior is most likey not desired.  Making the destructor in Foo virtual will resolve this problem and the output would be:

Good-bye, Bar!
Good-bye,Foo!
Tags: ,

Bubble sort in C/C++

Posted by: Mohan Gulati on: July 18, 2009

// Bubble Sort has a performance of O(n^2) and is a comparison sort

void doBubbleSort(){

int a[4];

a[0] = 1;

a[1] = 0;

a[2] = 10;

a[3] = 6;

int len = sizeof(a)/sizeof(a[0]);

// The actual Bubble Sort Algorithm

bool bSwaps = true;

while ( bSwaps ){

bSwaps = false;

for( int i =1; i < len; i++ ){

if ( a[i] < a[i-1] ){

int temp = a[i-1];

a[i-1] = a[i];

a[i] = temp;

bSwaps = true;

}

}

}

// Print out the array now sorted

for ( int i=0; i < len; i++){

std::cout << a[i] << ” “;

}

}