Friday, September 27, 2013

Exception (Python)

Beside, preventing the user to break your code, I find that exception is useful whenever there is a special case that I can't think about at the moment that is needed to be handled. You can also make it to return a message saying that it had caught a special case, then you will know where the special cases you had missed. Before showing how to catch an error, let's define what is exception.

Exception is a class in Python library, which it handles every error that occurs during the runtime. Every time an error occurs in the runtime, the program stops running and it creates an exception object, then it prints out the trackbacks which contain the code line and a message of the error. The message describes the type of error that had been thrown. Python exception's keyword are raise (thrown: java), except(catch), try and finally. When catching the thrown exception object, list the most specific exception first before the general ones, because Python will search the except from top to bottom. The following example shows that the other except will never reach cause the "except Exception" will always catch the thown error:

________________________________________________________________________________
#Danny Heap
#http://www.cdf.toronto.edu/~heap/148/F13/Lectures/W3/exceptions.py

class SpecialException(Exception):
    pass

class ExtremeException(SpecialException):
    pass

if __name__ == '__main__':
    try:
        1/0
        #raise SpecialException('I am a SpecialException')
        #raise Exception('I am an Exception')
        raise ExtremeException('I am an ExtremeException')
        #1/0
    except Exception as e:
        print(e)
        print('caught as Exception')
except SpecialException as se: print(se) print('caught as SpecialException') raise except ExtremeException as ee: print(ee) print('caught as ExtremeException') #raise
________________________________________________________________________________

Now that you recall how to use Exception, lets go back to the idea that you can catch a special case with exception. Before you go out telling your friends this great idea, let me warn you that this is not a good programming practice, it is just a quick-and-dirty way to keep your code running. If you want to test it propery, create a test class for your code. 
_________________________________________________________________________________
def mean(list, n):
 try:
result = sum(list)/0
except:
print("special case in mean function")
print("List: " + list)
print(n)
_______________________________________________________________________________
Is a good practice to code in an exception handler to ever user input code to prevent them messing up with your code.

Wednesday, September 25, 2013

Stack (Python)

Beyond Python Stack

First of all, there is no stack class in Python library, therefore there is no way you can import stack from the library, you have to implement your own stack class. This piece of information cost my friend an hour of searching in google how to import stack from the library. But after you implemented the stack class onto your library, it will be very handy to have it around. Lets quickly define what is a stack.

A stack is a collection of objects that represents a simple last in - first out order. The collection mostly visualizes it vertically. Imagine a pile of cards, the rules are: you can only pick a card from the top of the pile and you can only put a card on top of the pile.
The functions of stack class are is_empty, pop, push, top. 
is_empty: return true if the collection is empty
pop: remove the object from the collection and then return the object
push: add the object on top of the collection
top: return the last added object of the collection

In Python, we can use a list as the collection. For push, append the new object to the list, for pop, remove last object from the list, and for top, remove the last object from the list. This is just how we learned how to implement a stack with a list. It might seems a small concept for this course and you might think why I am making stack such a big deal. It is because when we learned stack with java, we still didn't know about link. So, we have to implement stack with array. It is important to note that java has to initialize an array, so every array occupy limited amount of memory. Therefore if the array is full, we need to create another array that duplicate the data into it. Here are the code:
________________________________________________________________________________
//********************************************************************
//  ArrayStack.java       Java Foundations
//
//  Represents an array implementation of a stack. The bottom of
//  the stack is kept at array index 0.
//
//
//********************************************************************

package javafoundations;

import javafoundations.exceptions.*;

public class ArrayStack<T> implements Stack<T>
{
   private final int DEFAULT_CAPACITY = 10;
   private int count;
   private T[] stack;

   //-----------------------------------------------------------------
   //  Creates an empty stack using the default capacity.
   //-----------------------------------------------------------------
   public ArrayStack()
   {
      count = 0;
      stack = (T[]) (new Object[DEFAULT_CAPACITY]);
   }

   //-----------------------------------------------------------------
   //  Adds the specified element to the top of this stack, expanding
   //  the capacity of the stack array if necessary.
   //-----------------------------------------------------------------
   public void push (T element)
   {
      if (count == stack.length)
         expandCapacity();

      stack[count] = element;
      count++;
   }

   //-----------------------------------------------------------------
   //  Returns a string representation of this stack.
   //-----------------------------------------------------------------
   public String toString()
   {
      String result = "<top of stack>\n";

      for (int index=count-1; index >= 0; index--)
         result += stack[index] + "\n";

      return result + "<bottom of stack>";
   }

   //-----------------------------------------------------------------
   //  Creates a new array to store the contents of this stack with
   //  twice the capacity of the old one.
   //-----------------------------------------------------------------
   private void expandCapacity()
   {
      T[] larger = (T[])(new Object[stack.length*2]);

      for (int index=0; index < stack.length; index++)
         larger[index] = stack[index];

      stack = larger;
   }

   //-----------------------------------------------------------------
   //  The following methods are left as Programming Projects.
   //-----------------------------------------------------------------
   public T pop () throws EmptyCollectionException 
 {
  if(count == 0)
   throw new EmptyCollectionException("Pop operation failed. Stack is empty.");
   
  T temp = stack[count - 1];
  count--;
  return temp;
 }
   public T peek () throws EmptyCollectionException 
 {
  if(count == 0)
   throw new EmptyCollectionException("Peek operation failed. Stack is empty.");
   
  return stack[count - 1];
 }
   public boolean isEmpty() 
 {
  return count == 0;
 }
   public int size() 
 {
  return count;
 }
}
________________________________________________________________________________


You might think that this concept seems pretty lame. However, the concept of stack goes beyond every code. Almost every complex code uses stack. Everything you do on the computer uses stack, even your calculator uses stack. This is because how the assembly language create functions so that cpu knows where to go back to run the code. So that your code will be run from the top to the bottom, unless you tell is to jump to other section of the code. 

Tuesday, September 24, 2013

Object (Python)

Functions are objects in Python

I was playing around with objects in Python to seek out the differences between Java object. I found out that functions are objects in Python. It's useful to know; you can do all sort of despicable things that other programing languages would freak out. Let's me show you why with some examples.

__________________________________________________________________________
def happy(word = “I’m happy”):
return word.capitalize() + “!”

>>>print(happy())
# output: I’m happy!

x = happy
>>>print(x)
# output: <function happy at 0x0311D9C0>

>>>print(x())
#output: I’m happy!
______________________________________________________________________________


Since happy() is a function, it is also an object. So that means you can assign the function to a variable like any other object. Notice that it's not using parentheses, cause we are not calling the function, we are assigning the function happy to the variable x. It means you can then call the function happy from x. Moreover, you can delete the name happy and the function will still be accessible from x

____________________________________________________________________________
>>>del happy

>>>print(happy())
# output: Traceback (most recent call last File "<pyshell#9>", line 1, in <module> happy() NameError: name # 'happy' is not defined

>>>print(x())
#output: I’m happy!
______________________________________________________________________________

You may ask, what's the big deal that a function can be assigned to a variable. How about if I tell you that since a function is an object; a function can be defined inside another function, which means a function can return another function! Is pure evil doing that, but no one can stop you. Let me show you how to do it, but don't tell your professor that you learn it from here.
_______________________________________________________________________________

def punch(type="cry"):
    def cry(word="whooa!"):
        return word.capitalize() + "!"

    def punch_back(word="let's fight"):
        return word.capitalize() + "!!!!"

    if type == "cry":
        return cry
    else:
        return punch_back

>>>print( punch())
#output: Whooa!

>>>print(punch("punch_back")()):
#output: Let's fight!!!!
_________________________________________________________________________

You can even pass a function as a parameter!

_________________________________________________________________________
def greetings(word="hey"):
    return word

def foo(func):
    return func + " you!"

>>> print(greetings())
#outputs: hey

>>>print(foo(greetings()))
#outputs: hey you!
____________________________________________________________________________

Those are some examples of the power of Python variable that one can abuse.