Sunday, 27 October 2013

Week4

         In this week class, we learn about recursion and testing function that mutate values. A recursive function is a function that calls itself. We also introduce recursive thinking as an approach to problem solving (Tower of Hanoi). For testing function that mutate values, we learn about unittest, basically we do test by compare the output of the function with the expected output by using some bulif-in function like ‘asserequal’.


def r_sum(l:list) -> int:
    if l == []:
        return 0
    else:
        temp = 0
        for i in l:
            if isinstance(i,list):
                temp = temp + r_sum(i)
            else:
                temp = temp + i
        return temp



#print(r_sum([1,2,[2]]))
#print(sum([1,2,3]))

def remove_shared(l1, l2):
    for v in l2:
        if v in l1:
            l1.remove(v)


l1=[1,2,3,4]
l2=[3,4,5,6]
remove_shared(l1,l2)
print(l1,l2)

import unittest

class TestRemoveShared(unittest.TestCase):
    def test_genereal_case(self):
        list_1 = [1, 2, 3, 4, 5, 6]
        list_2 = [2, 4, 6, 7]
        list_1_expected = [1, 3, 5]
        list_2_expected = [2, 4, 6, 7]

        remove_shared(list_1,list_2)

        self.assertEqual(list_1, list_1_expected)
        self.assertEqual(list_2, list_2_expected)

if __name__ == '__main__':
    unittest.main(exit=False)

Tuesday, 15 October 2013

Week 3 2013

In this week class, we learn about inheritance and exception. Inheritance is the ability to define a new class that is a modified version of an existing class. The new class inherits all of the methods of the existing lass and if we add the new method in child class will not affect the parent class. We also learn about exception, Whenever a runtime error occurs, it creates an exception object. The program stops running at this point and Python prints out the trace back, which ends with a message describing the exception that occurred.
import time
from week2test import Stack
def get_age():
    age = int(input("please enter your age:"))
    if age < 0:
        my_error = ValueError("{0} is not a valid age".format(age))
        raise my_error
    return age

'''
for i in range (1,101):
    print (i)
'''

def error_try():
    start = time.time()
 
    results_list = []
    errors_list = []

    for i in range(-10,10):
        try:
            val = 100/i
            print(val)
        except ZeroDivisionError as Err:
            errors_list.append('Expected Error :' + str(Err))
            print('Error on number :' + str(i))
        except Exception as Err:
            errors_list.append('Unexpected Error :' + str(Err))
            print('Error on number :' + str(i))
        else:
            results_list.append(val)

    print(results_list)
    print(errors_list)

    end = time.time()

    print (end-start)
         
#error_try()

class IntStack(Stack):
    '''
    a sub class of Stack only accept integer
    '''

    def push(self: 'IntStack', n: int) -> None:
        if isinstance(n, int):
            Stack.push(self,n)
        else:
            raise PushNonIntegerException('not a integer')

    def pop(self: 'IntStack') -> int:
        #note for the empty list
        if self.is_empty():
            raise PopEmptyStackException
        else:
            Stack.pop(self)
            #use super class method

class PushNonIntegerException(Exception):
    pass

class PopEmptyStackException(Exception):
    pass

'''
its = IntStack()

try:
 
    its.push(1)
    print(its)
    its.push(2)
    print(its)
    its.push('2')
    print(its)
    its.push('sd')
    its.pop()
    print(its)

except PushNonIntegerException as Err:
    print('Error1')
except PopEmptyStackException as Err:
    print('Error2')
except Exception as Err:
    print('Unknown Error')
'''


class SpecialException(Exception):
    pass

class ExtremeException(SpecialException):
    pass


if __name__ == '__main__':
    try:
        raise ExtremeException('i m an extremeexception')
        raise SpecialException('i m a specialexception')
        #raise Exception('I am an Exception')

    except ExtremeException as ee:
        print(ee)
        print ('caugh as extremeexception')
        raise

    except SpecialException as se:
        print (se)
        print ('caught as specialexcetion')
        raise
    except Exception as ep:
        print(ep)
        print('caugh as excetion')
        raise      

Week 2 2013

         In the second week class, we talking about ADTs, Stacks and little bit about recursive. The ADTs stand for abstract data types, specifies a set of operations (or methods ) and the semantics of the operation, but it does not specify the implementation of the operations. The Stacks is a common ADT. The stack is a collection, which contains multiple elements. And we did some example about calculate the sum of the all elements in a nested list by use recursion.


#create the new class called Stack(ADT)
class Stack:
    #Inittialize a new empty stack.
    def __init__(self: 'Stack' ) -> None:
        self.items = []
    #Add a new item in top of stack.
    def push(self: 'Stack', item: object) -> None:
        self.items.append(item)
        #self.items.insert(0,item)
    #remove and return the last item in the stack.FIFO
    def pop(self: 'Stack') -> None:
        return self.items.pop()
    #campare stack to a empty to check the stack is empty or not.
    #which is boolean.
    def is_empty(self: 'Stack') -> bool:
        return (self.items == [])
        #return (len(self.items) == 0)
    #empty the stack and return a empty stack.
    def empty_list(self: 'Stack') -> "empty list":
        if ((self.items==[])==True):
            return self.items
        else:
            self.items = []
            return self.items
    #conver the stack to String, which we can use print method
    def __str__(self: 'Stack') -> 'String':

        return ("{}".format(self.items))
 
#Stack is generic data structure,which mean we can add any type of item to it.

'''
x=Stack()
x.push(1)
x.push(2)
print(x)
print(x.pop())
print(x)
print(x.is_empty())
print(x)
x.empty_list()
print(x)
'''

#infix and postfix
#infix: 1 + 2
#postfix: 1 2 +
'''
print("mother fuck".split(" "))
import re
print(re.split("([^0-90])", "123+456*/"))
'''
def eval_postfix(expr: object) -> int:
    token_list = re.split("([^0-9])", expr)
    stack = Stack()
    for token in token_list:
        if token == "" or token == " ":
            continue
        elif token == "+":
            sum = stack.pop() + stack.pop()
            stack.push(sum)
        elif token == "*":
            product = stack.pop() * stack.pop()
            stack.push(product)
        elif token == "-":
            defrent = stack.pop() - stack.pop()
            stack.push(defrent)
        elif token == "/":
            devide = stack.pop() - stack.pop()
            stack.push(devide)
        else:
            stack.push(int(token))
    return stack.pop()
'''
test_postfix="10 10 + 2 * 10 - 5 / "
print(eval_postfix(test_postfix))
'''


# account time for push and pop 100 object in the stock
if __name__ == '__main__':
    import time
    s = Stack()
    items = range(1)
    #start account
    start = time.time()

    for i in items:
        s.push(i)
     #   print(s)
    for i in items:
        x=s.pop()
    #    print(x)
    #end account
    end  = time.time()
    #print (end-start)


#Test
import unittest

#My test case

class StackEmptyTestCase(unittest.TestCase):
    #test a empty stack
 
    def setUp(self):
        #set up a empty stack
        self.stack = Stack()

    def tearDown(self):
        #clean up
        self.stack = None

    def testIsEmpty(self):

        assert self.stack.is_empty(),\
               'is_empty returned False on an empty Stack'

    def testPush(self):
        self.stack.push("foo")
        assert self.stack.pop() == "foo",\
               'Wrong item on top od the Stack! Expected "foo" here.'


class StackAllTestCase(unittest.TestCase):
    #test non-empty stack

    def setUp(self):
        #set up a non-empty stack
        self.stack = Stack()

    def tearDown(self):
        self.stack = None

    def testAll(self):
        for item in range(20):
            self.stack.push(item)
            assert not self.stack.is_empty(),\
                   ' return ture for non- empty stack'

        expect = 19
        while not self.stack.is_empty():
            assert self.stack.pop() == expect,\
                ('Something wrong on top of the Stack! Expected ' +
                str(expect) + '.')
            expect = expect - 1

def empty_suite():

    return unittest.TestLoader().loadTestsFromTestCase(StackEmptyTestCase)

def all_suite():

    return unittest.TestLoader().loadTestsFromTestCase(StackAllTestCase)



runner = unittest.TextTestRunner()
runner.run(empty_suite())
runner.run(all_suite())




'''
#prof test case
import unittest


class StackEmptyTestCase(unittest.TestCase):
    """Test behaviour of an empty Stack."""
 
    def setUp(self):
        """Set up an empty stack."""
     
        self.stack = Stack()
     
    def tearDown(self):
        """Clean up."""
     
        self.stack = None
         
    def testIsEmpty(self):
        """Test is_empty() on empty Stack."""
     
        assert self.stack.is_empty(),\
               'is_empty returned False on an empty Stack!'
     
    def testPush(self):
        """Test push to empty Stack."""

        self.stack.push("foo")
        assert self.stack.pop() == "foo",\
               'Wrong item on top of the Stack! Expected "foo" here.'
             
class StackAllTestCase(unittest.TestCase):
    """Comprehensive tests of (non-empty) Stack."""

    def setUp(self):
        """Set up an empty stack."""
     
        self.stack = Stack()
     
    def tearDown(self):
        """Clean up."""
     
        self.stack = None

    def testAll(self):
        """Test pushing and popping multiple elements."""

        for item in range(20):
            self.stack.push(item)
            assert not self.stack.is_empty(),\
                   'is_empty() returned True on a non-empty Stack!'

        expect = 19
        while not self.stack.is_empty():
            assert self.stack.pop() == expect,\
                   ('Something wrong on top of the Stack! Expected ' +
                    str(expect) + '.')
            expect = expect - 1
     
def empty_suite():
    """Return a test suite for an empty Stack."""
 
    return unittest.TestLoader().loadTestsFromTestCase(StackEmptyTestCase)

def all_suite():
    """Return a comprehensive test suite for a non-empty Stack."""

    return unittest.TestLoader().loadTestsFromTestCase(StackAllTestCase)

# go!
runner = unittest.TextTestRunner()
runner.run(empty_suite())
runner.run(all_suite())
'''  


# recursion


def sum_list(L: list) -> float:

    return sum([sum_list(x) if isinstance(x,list) else x for x in L])


print(sum_list([1,2,3,[2,3,[3,4,5,[6,[7]]]]]))




class s2(Stack):
    pass