Monday, 29 February 2016

Stack and Queue

 

1.  Stack and Queue are data structures used not only to contain data/elements but more to operate data/elements in a per-specified manner. Even there are various ways to implement stack and queue, the built_in List is usually borrowed to create stack and queue in Python. This is why stack and queue are called adaptive data structure. With the same implementation, stack and queue are significantly different on how to access to and remove data contained. Stack accesses to and removes the data that are latest appended to (i.e., the data on the top), which is called 'Last in First Out' (LIFO). But Queue accesses to and remove the data that are earliest appended to (i.e, the data at the bottom), which is called "First In First Our"(FIFO). Notice both stack and queue append data to the list because they use list to store data.

2. Stack and queue makes it easy to operate data just based on the timing sequence without concerning the data itself. Let's see the examples below.

a. Stack: evaluate the post-fix notation

 As an alternative to infix notation like '5 * 7 + 2', a post-fix notation like '5 7 * 2 +' has the nice property that parentheses are unnecessary. Stack is pretty helpful to evaluate the post-fix notation. When '5 7 * 2 +' is evaluated from left to right, 5 and 7 are added to the stack: [5,7]. Next, the operator '*' is applied to 5 and 7 that are removed from the stack and the result (7*5 = 35) is added to the stack: [35].  2 is then add to stack: [35, 2].  '+' is applied to 35 and 2 that are removed from the stack and the result (2 + 35 =37) is added to the stack. Finally the stack just contain the final accumulated result: [37]. So the key is that the stack contains the numbers that are right before an operator. After the operator is applied to the numbers, the stack contains the accumulated result and then next new numbers.
        
class Stack():
               def __init__(self):
                    self.items = []
       
                def is_empty(self):
                    return len(self.items)
                  
                def add(self, item):
                    self.items.append(item)
                  
                def remove(self):
                    return self.items.pop()
      
def postfix(postfix_str):
                token_list = postfix_str.split()
                stack = Stack()
                for item in token_list:      
                    if  item == '+':
                        result = stack.remove() + stack.remove()
                        stack.add(result)
                    elif item == '*':
                        result = stack.remove() * stack.remove()
                        stack.add(result)
                    elif item =="-":
                        result = stack.remove() - stack.remove()
                        stack.add(result)
                    elif item == '/':
                        first = stack.remove()
                        second = stack.remove()
                        result = second / first
                        stack.add(result)          
                    else:
                        stack.add(int(item))
                return stack.remove()
              
b. Queue: queue a list that may contain sub-list(s)

First of all, we use a queue to store the list items like [1,[2,3],4].  Next the item is removed from the queue. If the item is non-list, just print it like 1, 4. If it is a sub-list, the items within are added to the queue as non-list items and then re_removed and printed like 2, 3. Notice that the sub-list items are appended to the queue. So they are not removed untill all non-list items are gone.
     
class Queue():
                def __init__(self):
                    self.items = []
       
                def is_empty(self):
                    return len(self.items) == 0
       
                def add(self, item):
                    self.items.append(item)
   
                def remove(self):
                    return self.items.pop(0)
         
def queue_list(lst):
                queue = Queue()
                for item in lst:
                    queue.add(item)
                while not queue.is_empty():
                    item = queue.remove()
                if isinstance(item, list):
                    for i in item:
                        queue.add(i)          
                 else:
                        print(item)

End of the post

Saturday, 13 February 2016

Inheritance and Composition

   
 The OOP allows us to create a number of classes (data types) for various purposes (i.e., implement a class through defining the attribute(s)) and the operations on the data within each class (i.e., define methods for a class). However, if there is no link between the classes, the class implementation is meaningless at all. It's pretty rare to use a single class even for a simple function. The link between the classes is either composition (horizontal link) or inheritance (vertical link).

 1. Composition

When a class is defined, it is independent to other classes. But the composition allows it to call the abstract object/instance of other classes and/or to define object/instance of other classes. As a result, this class is able to access to the object's attributes and methods defined by other classes. The composition is particularly helpful to simplify the design and implementation of an ADT class.
           
For example, we need an ADT class to register a student to a course. Before implementing the ADT class StuCourRegistry, we firstly implement two meaningful classes Student and Course. Hence the StuCourRegistry will be able to call the abstract object of Student and Course, which makes us focus on how to process the data without worrying about what is the data  and then develop complicated methods.
       
class Student():                 
                def __init__(self,_id=' ',name=' ',num=0):
                    self._id, self.name, self.num=str(_id), str(name), int(num)
       
                def __hash__(self):  # this method makes the object be elements of dict and set.
                    return hash((self._id, self.name, self.num))   
       
                def __eq__(self,other):
                    return type(self)==type(other) and (self._id, self.num)==(other._id, other.num)

class Course():                         
                def __init__(self,name=' ',_id=' ',dept=' '):
                    self.name, self._id,self.dept=str(name), str(_id), str(dept)       
   
                def __hash__(self):
                    return hash((self.name,self._id,self.dept))
       
                def __eq__(self,other):
                    return type(self)==type(other) and self._id==other._id
                   
class StuCourRegistry():                        
                def __init__(self,registry={}):
                    self.registry=registry
                                        
                def add_cour(self,course):  # course is the object of Course.
                    if not course in self.registry.keys():       
                        self.registry[course]=set() # set() just contains Unique data.
                    else:
                        raise Exception('Duplicate Course!!!')           
                                                                
                def add_stu(self,course,student):
                     # course and student are the object of Course and Student.
                    if course in self.registry.keys():         
                        self.registry[course].add(student)
                    else:
                        raise Exception("The course is NOT available!!!")                      
                                                        
                 def count_stu_for_dept(self,dept):
                    stu_dept=set()
                    for item in self.registry.items():
                        if item[0].dept==dept: # the object of Course has the attribute "dept".
                            stu_dept=stu_dept.union(item[1])
                     for s in stu_dept:
                         print(s.name)
                     return len(stu_dept)
               
2. Inheritance

When a class (called subclass) has a vertical link with another class (called super class), this link is called inheritance that allows the subclass to own everything (attributes and methods) defined by the super class. Inheritance, however, doesn't forbid the subclass having its own things and even allow it to rewrite the inherited attributes and methods. Inheritance saves a lot of time of writing duplicate codes and makes the code maintenance much easier because any change on the super class is automatically applied to the sub-classes. As a result, we create a super class mainly not for substantiation (i.e., creating objects of super class) but for the inheritance by the sub-classes.

The creation of a super class relies on how many common features the sub-classes share. For example, Python has a built_in class 'object' that is the super class of every built_in or self_defined class. The 'object' defines the methods used by every class like __init__,__repre__,__str__,
 __eq__ and __dir__. Notice when creating a subclass, we usually override the methods _init__,__str__,__repr__, and __eq__ but remains the method __dir__.

Now let's see another example. We create two sub-classes of the Stack. The 1st has nothing but inherits everything from Stack. But the 2nd overrides the Stack's attribute and related methods meanwhile inheriting other methods.
           
class Stack:   
                   def __init__(self, content=[]):
                        self.content=[]
       
                    def push(self,data):
                        self.content.append(data)
       
                    def pop(self):
                        try:
                            return self.content.pop()
                        except IndexError:
                            print('Empty Stack')
                            return None
   
                    def is_empty(self):
                        return len(self.content)==0
                   
class NumStack(Stack):  # explicitly declare the inheritance.
                    pass

class UniqueNumStack(Stack):   
                    def __init__(self,content=set()):   # override the inherited attribute
                        self.content=content
       
                    def push(self,data): # override the inherited method
                        self.content.add(data)
       
                    def pop(self): # override the inherited method
                        if not Stack.is_empty(self): # load the inherited method
                            num = list(self.content)[-1]
                            self.content.discard(num)
                            return num
                        else:
                            return None


End of this post