Friday, 8 April 2016

Algorithms Analysis


1. Any function programmed is purely consisted of multiple lines of code. Each line of code represent a step of operation like variable initialization (x = 3) and logical choice (if x == 3). Running a function is actually to walk through the steps by executing the lines of code. As a result, the Algorithm in computer science is the step-by-step set of the operations. Note an algorithm is independent as it can be implemented in various programming languages like Java, C++ and Python.
  
2. In order to measure different algorithms, we use the running time of an algorithm as an indicator (called time complexity). The running time solely relies on the operation steps (i.e., lines of codes) but  ignores the hardware environment. Obviously an algorithm is a function of the amount of data (called input size): more data, longer running time. So, when measuring an algorithm, we assume that every step of the algorithm is executed with the given input size (infinite or large enough). This is called worst-case running-time  or worst-case time complexity.

3. An algorithm must include one or more loop to process multiple data. As a result, some steps in the algorithm are repeated when the data is looped over. For a loop, the total number of repeated steps is iterations * steps in this loop. So, worst-case running time = total number of non-repeated steps + total number of repeated steps within loop(s) = total number of non-repeated steps + loop iterations * steps in the loop(s).

Below are some simple but typical loop-over and subsequent iterations. (Note we only focus on the while/for loop but ignore the recurrence because the it is covered in CSC263). All the data are assumed to be stored in a list and then the input size (n) is equal to the length of this list (len(list)). We initialize pointer (s) to start the loop-over and then to update the pointer(s) to keep moving. When the pointer moves from one item to another, one iteration is finished or multiple iterations are finished. So the pointer(s) can be used as an indicator of the iterations.

a.
i = 0
   while i < len(list):
...
i += 1

i = 0, 1, 2, 3,..., n-1.
iterations = number of items scanned * 1 iteration per item = ((n-1)-0 + 1) * 1 = n

b.
i = 0
   while i < len(list)//2:
...
i += 1

i = 0, 1, 2, 3, ..., (n//2)-1
iterations = number of items scanned * 1 iteration per item = ((n/2 - 1) -0 + 1) * 1 = n/2

c.
i = 1
   while i < len(list):
...
i = i*2

i = 1, 2, 4, 8,..., n-1 = 2^0, 2^1, 2^2, 2^3, ..., 2^k where 2^k <= n ---> k = log_2(n)
iterations = number of items scanned * 1 iteration per item = log_2(n) * 1 = log_2(n)

d.
i = len(list)
   while i >= 0:
...
i = i//2

i = n//(2^0), n//(2^1), n//(2^2), ..., n//(2^k) where n/(2^k) = 1 ---> k = log_2(n)
iterations = number of items scanned * 1 iteration per item = (log_2(n)) * 1 = log_2(n)

e.
i = 0
    while i < len(list)*len(lst):
...
i += 1

i = 0, 1, 2, 3, ..., n^2
iterations = number of items scanned * 1 iteration per item = ((n^2 - 1) -0 + 1) * 1 = n^2

f.
for i in range(len(list)):
for j in range(len(list)):
...

i = 0, 1, 2, 3, ..., n
j = 0, 1, 2, 3, ..., n
iterations of j = number of items scanned * 1 iterations per item  = (n-1) - 0 + 1 = n
iterations of i = number of items scanned * j iterations per i iteration  = ((n-1) - 0 + 1) * n = n*n = n^2

g.
for i in range(1, len(list)):
for j in range(1, i+1):
...

i = 1, 2, 3, 4, ..., n-1
j = 1, 2, 3, 4, ..., i

iterations of j = number of items scanned * 1 iterations per item  = (i -1 + 1) * 1 = i
# different i includes different j iterations.
iterations of i = sum of j iterations at each i iteration = 1 + 2 + 3 + ... + (n-1) = ((n-1)(n))/2

 4. When the input size is assumed infinite (or large enough), how can we evaluate the performance of different algorithms? Actually at this time what we're concerned is not how long an algorithm handle the infinite data (the time is infinite as well) but how efficient the algorithm can handle the infinite data because the efficiency can be measured: how the running time might be changed when the input size is changed. This is why the big_O is introduced: different algorithms with the same efficiency may be represented by the same O notation. For example, 3n^2 + 2n + 1 in O(n^2) because, when n is assumed large enough, the running time of  3n^2 + 2n + 1 grows no faster than that of n^2. So n^2 is the upper-bound of 3n^2 + 2n + 1 regarding the time complexity.

End of this post     

Thursday, 7 April 2016

Binary Tree & Binary Search Tree (cont'd) 

 

The property of  Binary Search Tree (BST) (value of left child node < value of parent node < value of right node) makes the operations on the BST much more complicated than those on tree or BT because we must remain the property after any operation  to keep the BST balanced.  Now let's see two typical BST operations Insert and Delete that works on  a simple BST like:

                   5
         2                  7
   1        3          6      8

1. Insert a node.

Actually we can only add any new node as a leaf node because it's either larger than or less than the parent node rather than equal to the parent node. So it's impossible to insert a duplicate element. For example, if we want to insert 4, the insertion is like:
4  <  5 ---> 4  >  2 ---> 4 > 3 ---> 3.right = 4. The BST after the insertion is like:

                    5
         2                   7
   1        3           6      8
                4

Below is the recursive insert function.The base case is if the BST node is not existed. When the base is reached, a new BST node is established. But the difficulty of the BST insertion is to update the links between the new node and all its upper parent nodes (not just its direct parent node). So the core of the recursive function is to bring each parent node downward (current_bn = bn) until the base case is reached and the new node is established and then to update all the upper parent nodes (bn.left =  or bn.right =) one by one  until the root is reached.

def bst_insert_leaf(bn, item):
    current_bn = bn
    if not bn:
        current_bn = BinaryNode(item)
    elif item < bn.data:
        bn.left = bst_insert_leaf(bn.left, item)   
    elif item > bn.data:
        bn.right = bst_insert_leaf(bn.right, item)       
    else:
        pass
    return current_bn

2. Delete a node.

When trying to delete a BST node, we must take into account of 3 cases: (1). the node doesn't have children (root or leaf); (2). the node has one child; (3). the node has two children. Below is an iterative delete function that covers all the 3 cases. So the algorithm of the function is:

if node is not in BST,
            return False

if node is in BST
      
       if node doesn't have children,
            if node is leaf,
                   parent node's left or right = None
            if node is root,
                   BST's root = None

       if node has one child,
            if node is not root:
                   parent node' left or right = the node's child node (node.left or node.right)
            if node is root,
                   BST's root = node's child

       if node has two children,
            find rightmost node in node's left sub-tree
            node's value = rightmost node's value
            if rightmost node is a leaf,
                  parent node's right = None
            if rightmost node is not a leaf (i.e., it has a left child),
                 parent node's left = rightmost node's left child

Note, for the case 3, we use the rightmost node in the left sub-tree (called in-order predecessor ) to replace the deleted node's value but remain its links to the child nodes. Another option is the leftmost node in the right sub-tree (called in-order successor). For example, as to the BST above, in-order predecessor is 3 and, after deleting the root (5), the BST is like:
                   3
          2                  7
   1                     6      8

In-order successor is 6 and, after deleting the root (5), the BST is like:
                   6
          2               7
   1         3                   8

With either the node, the BST property is satisfied after the deletion.

def bst_del(bn, item):
    node_list = find_bst_node(bn, item)
    parent_node, curr_node = node_list[0], node_list[1]
    if not curr_node:
        return False
    else:
        children_count = count_children(curr_node)
       
        if children_count == 0:
            if parent_node:
                if parent_node.left == curr_node:
                    parent_node.left = None
                else:
                    parent_node.right = None
            else:
                bn.data = None
               
        elif children_count == 1:          
            new_child = curr_node.left if curr_node.left else curr_node.right               
            if parent_node:
                if parent.left == curr_node:
                    parent.left = new_child
                else:
                    parent.right = new_child
            else:
                bn.data = new_child.data
                bn.left, bn.right = new_child.left, new_child.right
        else:           
            temp_parent, rightmost = curr_node, curr_node.left
            while rightmost.right:
                temp_parent = rightmost
                rightmost = rightmost.right
            curr_node.data = rightmost.data
            if temp_parent.right == rightmost:
                temp_parent.right = rightmost.left
            else:
                temp_parent.left = rightmost.left

 # help function

def find_bst_node(bn, item):
    parent_node, curr_node = None, bn
    while curr_node and curr_node.data != item:
        if item < curr_node.data:
            parent_node = curr_node
            curr_node = parent_node.left
        elif item > curr_node.data:
            parent_node = curr_node
            curr_node = parent_node.right
        else:
            pass
    return [parent_node, curr_node]


def count_children(bn, count=0):
    if bn.left:
        count += 1
    if bn.right:
        count += 1
    return count   

End of this post

Sunday, 3 April 2016

Binary Tree & Binary Search Tree 

 

1. Binary Tree (BT) is a special type of tree data structure because any parent node has 2 child nodes at most. Below is the implementation of BT in Python.

class BinaryNode():   
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left, self.right = left, right

Unlike the parent node in a  tree that uses a list to contain the child nodes, the parent node in a BT directly connects to child nodes, which is more like a node in the linked list. This structure result in different orders of walking though the nodes as deep as possible: in-order, pre-order and post-order.

 A simple BT is like:
                   1
           2              3      
       4      5       6      7

In-order visit is like:  (4-->2-->5)--->1--->(6-->3-->7)
Pre-order visit is like: 1---> (2-->4-->5)--->(3-->6-->7)
Post-order visit is like: (4-->5-->2)--->(6-->7-->3)--->1

We may image that the ordering is applied firstly to each simple sub-trees (just parent and child nodes), and then to the larger sub-trees, and finally to the entire tree.

2. The recursive Depth-First-Search (BFS) for a BT is almost same as that for a tree except the data structure of the child nodes. Below is a recursive DFS function used to print each root-to-leaf path of a BT. The base case is if the leaf node (bn.left is None and bn.right is None) is reached. The core of the function is to avoid the list mutation when the recursion moves downward to left and/right right child nodes.

def print_path_recurr(bn, path = []):
    if not bn.left and not bn.right:
        path += str(bn.data)
        print('---> '.join(path))
    else:
        path += [str(bn.data)]
        if bn.left:
            print_path_recurr(bn.left, path.copy())
        if bn.right:
            print_path_recurr(bn.right, path.copy())

3. As mentioned before, the recursion is not a good choice for the Breadth-First-Search (BFS) of a BT. So the queue is regularly used to code the iterative BFS function, which is discussed in details in the previous post "Stack and Queue: More Application".

4. Binary Search Tree (BST) is a branch of BT if we use the condition: value of left child node < value of parent node < value of right node to set up a sorted BT. Accordingly the implementation of a BST is identical to that of a BT. A simple BST is like:

                   5
         2                  7
   1        3          6      8

So the oder of the nodes in the BST is straightforward:  (1  <  2  <  3)  <  5  <  (6  <  7  <  8).

The DFS of a BT requires to search both left and right node. But the DFS of a BST just need to search either left or right child node (not both). For example,  as to the BST above, the path of searching 8 is:

 5--->7--->8.

But, if the tree was a BT, the paths include:

5--->2--->1,  5--->2--->3,
5--->7--->6,  5--->7--->8.

Below is a recursive DFS function used to check if an item is contained in the BST.  Note the function relies on the implementation of BT. The base case is if a BT node is existed or not (not if a leaf node is reached because the function check all nodes including leaf nodes). The core of the function is to always choose between left and right child node before the function moves downward.

def bst_contain(bn, item):
    if not bn:
        return False
    elif item == bn.data:
        return True
    elif item < bn.data:
        return bst_contain(bn.left, item)
    else:
        return bst_contain(bn.right, item)

Below is another recursive function used to check if a BT is BST. Recall that the left child nodes is less than the parent node and the right child node is larger than that. So the core of the function is to bring the parent nodes' values downward when the function is visiting the lower nodes. 

def is_bst(bn, mini=-10000, maxm=10000):           
    if not bn:
        return True       
    elif bn.data < mini or bn.data > maxm:
        return False               
    else:        
        return is_bst(bn.left, mini, bn.data) and is_bst(bn.right, bn.data, maxm)



End of this post

Saturday, 2 April 2016

Tree

 

1.  Tree is an important and wildly used data structure. Each element/data in a tree is named after node. Initially a tree just has a root node  which links to nothing. When we establishes a one-way link from the root node to other data, the root node is also called parent node and those data become the child nodes. We can repeat the extension process from each child node to other data. Finally a hierarchical tree is set up. The nodes at the bottom of the tree is called leaf because they don't have child nodes.

A single parent node and its child nodes creates a miniature of the entire tree, called sub-tree. The operations on the sub-tree is applicable to the larger tree. This recursive nature has the recursion regularly used to code the functions for a tree

2. It's easy to implement a tree. Below is the implementation in Python. A typical node includes it own value and a list of its child nodes.

 class TreeNode():
    def __init__(self, data, children=None):
        self.data = data
        self.children = children.copy if children else []

 3. A simple tree is like:
                      1
           2         3       4
       5      6              7


There are two ways to walk through/traverse the tree. The first is to traverse always from the root, to upper node, to lower node, finally to leaf. This process is like:

1--->2--->5 and 1--->2--->6
1--->3
1-->4--->7

Another way is to traverse from root, to the nodes in the same upper level (i.e., the nodes in same children list), to those in the same lower level, finally to the leaf at the bottom level. This process is like:

 1--->2, 3, 4
 1--->2, 3, 4--->5, 6, 7

The two traversal ways result in two search algorithm of a tree: Depth-First-Search (DFS) and Breadth-First Search (BFS).

4 .The DFS is to search the tree as deep as possible until the leaf node is reached. For example, the root-to-leaf paths listed above are consisted of the possible DFS paths. The DFS function can be modeled for a simple sub-tree and then applied to the entire tree. So the recursion is regularly used to code the DFS functions.

Below is a recursive DFS function used to print each root-leaf path of a tree.  The base case is naturally if the leaf node is reached. The core of the function is to avoid the mutation of the path list when the function recursively moves downward: print_path_recurr(child, path.copy()).

def print_path_recurr(tn, path = []):
    if not tn.children:
        path += [str(tn.data)]
        print('---> '.join(path))        
    else:
        path += [str(tn.data)]
        for child in tn.children:           
            print_path_recurr(child, path.copy()) 

5. The BFS is to search the tree through searching all nodes at the same level before moving to next level until the bottom level is reached. For example, the level paths listed above are consisted of the possible BFS paths. Recursion is not a good choice for the BFS because of the non-recursive nature. So the queue is regularly used to code the iterative BFS function. Below is an iterative BFS function used to print the tree's level. The previous post "Stack and Queue: More Application" discusses the iterative BFS in more details.

def print_level(tn):
    curr_queue, next_level = [tn], []   
    print(tn.data)
    while len(curr_queue) > 0:       
        node = curr_queue.pop(0)
        if len(node.children) > 0:
            next_level += node.children
        if len(curr_queue) == 0:           
            print(' '.join([str(node.data) for node in next_level]))
            curr_queue = next_level
            next_level = []     

End of this post

Thursday, 31 March 2016

Stack and Queue : More Application

 

1.  Stack and Queue are data structures used to operate data/elements in a pre-defined manner. Stack accesses to and removes the data that are latest added (i.e., the data on the top), which is called "Last in First Out" (LIFO). But Queue accesses to and removes the data that are earliest added (i.e, the data at the bottom), which is called "First In First Out"(FIFO).

2. Theoretically every recursive function can be converted to an iterative function (for loop and/or while loop). Sometimes we must use Stack as an alternative for the recursion even the stack_based function is much more complicated. For example, the recursion is naturally used for the Depth-First-Search (DFS) of a tree or binary tree (called recursive DFS). But an iterative DFS can be implemented with the Stack. It usually traverses the tree in the pre-order and uses the stack to contain and pop the nodes in the tree within a while-loop. A simple binary tree is like:

                     1
          2                   3
    4         5        6         7

For the iterative DFS, the key is to add the nodes to the stack and then removes the nodes in LIFO until the stack is empty. As to the tree above, the process is like:


stack = []            ---> add 1                                       --->
stack = [1]          ---> stack.pop() = 1: add 3, 2         --->
stack = [3, 2]      ---> stack.pop() = 2: add 5, 4         --->
stack = [3, 5, 4]  ---> stack.pop() = 4: nothing to do --->
stack = [3, 5]      ---> stack.pop() = 5: nothing to do --->
stack = [3]          ---> stack.pop() = 3: add 7, 6          --->
stack = [7, 6]      ---> stack.pop() = 6: nothing to do --->
stack = [7]          ---> stack.pop() = 7: nothing to do --->
stack = []

Below is an iterative DFS function used to print every root-to-leaf path of a binary tree. The core of the function is to reserve the path between current node (node) and its lower nodes (node.left or node.right) and add to the stack before the function moves downward. When a leaf is reached, the path can be printed directly because the path between the leaf and all its upper nodes are already saved to the stack.  

class BinaryNode():   
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left, self.right = left, right

def print_dfs_path(bn):   
    stack = [bn, [bn]]
    while len(stack) > 0:
        path_list = stack.pop()
        node = stack.pop()
        if node.right is not None:
            right_path_list = path_list + [node.right]        
            stack += [node.right] + [right_path_list]
        if node.left is not None:
            left_path_list = path_list + [node.left]           
            stack += [node.left] + [left_path_list]
        if node.left is None and node.right is None:
            print_path(path_list)

def print_path(path):
    path_str = ''
    for node in path:
        path_str += '{}-->'.format(node.data)   
    print(path_str + '|\n')

3. Even the recursion is better than the iteration for the DFS, it's not a good choice for Breadth-First-Search (BFS) of a tree or binary tree because this kind of search is not of recursive nature. Accordingly, the queue_base iterative function is regularly used for BFS. It traverses the tree level by level and uses the queue to contain and remove the nodes in the tree within a while-loop.

For the iterative BFS, the key is to add the nodes to the queue and then removes the nodes in FIFO until the queue is empty. As to the tree above, the process is like:


queue = []                     ---> add 1                                           --->
queue = [1]                   ---> queue.pop(0) = 1: add 2, 3          --->
queue = [2, 3]               ---> queue.pop(0) = 2: add 4, 5          --->
queue = [3, 4, 5]           ---> queue.pop(0) = 3: add 6, 7          --->
queue = [4, 5, 6, 7]       ---> queue.pop(0) = 4: nothing to do  --->
queue = [5, 6, 7]           ---> queue.pop(0) = 5: nothing to do  --->
queue = [6, 7]               ---> queue.pop(0) = 6: nothing to do  --->
queue = [7]                   ---> queue.pop(0) = 7: nothing to do  --->
queue = []

Below is an iterative BFS function used to print every level of a binary tree. The core of the function is to use two queues to contain the upper/current and lower nodes separately. When the queue of upper/current nodes  becomes empty, the level of lower nodes is printed out immediately before the function moves to next level. 

def print_bfs_level(bn):
    curr_queue, next_level = [], []
    curr_queue.append(bn)
    print(bn.data)
    while len(curr_queue) > 0:       
        node = curr_queue.pop(0)        
        if node.left is not None:
            next_level.append(node.left)           
        if node.right is not None:
            next_level.append(node.right)
        if len(curr_queue) == 0:
            print_level(next_level)
            curr_queue = next_level
            next_level = []

def print_level(level):
    level_str = ''
    for node in level:
        level_str += '{}  '.format(node.data)   
    print(level_str)    


End of the post

Thursday, 3 March 2016

Recursion


1. Recursion is an important programming technique that helps to write simple but powerful codes. Recursion means repeating the same jobs in a smaller scale until the pre-defined end (called base case) is reached. In this sense, a recursion is actually a loop. Recursive function is a function that continuously calls itself (called recursive call) to do the same jobs in the smaller and smaller range of the same data structure until the base case is reached. Hence such data structure is called recursive structure. For the recursive data structure, the most common base case is the empty state of the data structure like empty list ([ ]) and empty string (' '). Another common base case is "if the base case is/is not something" like "if the base case is not a list" and "if the base case is an even integer". Notice a recursive function may define multiple base cases.

2. A recursive function has a regular format:
   
        if base case is reached:
                do something
                return something (or return nothing)
        else:
               do something
               recursive call
               do something
               return something (or return nothing)
   
As mentioned above, a recursion is somewhat a loop because it has entry (1st recursive call) and exit (base case). But the recursion is not really ended when the base case is reached because it keeps coming back to the points of recursive calls until the point of 1st call is reached. So the recursive process can be divided into two sub-process: (1). coming down to the base case as a result of the recursive calls, and (2). coming back to the points of the recursive calls. Each recursive call is to repeat the same jobs in a smaller range of the same data structure. The results at the lower recursive calls can be returned to the upper recursive calls. So we get the final accumulated result when the highest recursive call (1st call) is reached. 
   
3. Now let's see the examples of recursion. 

a. recursively reverse a string like "abc" where the base case is the natural empty string (' ').
   
To reverse the string, we need to retrieve the characters one by one and then re-combine the characters.  At first, the recursion comes down to the natural base case: empty string ' ' as a result of recursive calls. The process is like:

1st call('abc') --> 2nd call'bc') --> 3rd call('c') --> 4th call(' ')

Next, we need to the lower recursive call to return character(s) in the smaller range of the string to the upper recursive call which combines with its 1st character of the smaller string. This process is like:

4th call(' '): return ' ' --> 3rd call('c'): return' ' + 'c' = 'c' --> 2nd call('bc'): return 'c' + 'b' = 'cb' --> 1st call('abc'): return 'cb' + 'a' = 'cba'   

So the recursive function is defined below:
      
 def reverse_str_recur(s):
                if len(s.strip())== 0:
                    return ''
                else:       
                    reversed = reverse_str_recur(s[1:]) + s[0]
                    return reversed

b. recursively count items of a nested list like [1,[2,3]] where the base case is "if the item is not a list".   

To count non-list items, we need to check if an item is a list or not. This is why the base case is defined as "if the item is not a list". As this is not a natural base case like empty string, the defined base case is applied to multiple items. At first, the base case is reached as a result of the recursive calls. The process is like:
   
1st call([1,[2,3]]) --> 2nd call(1) --> 3rd call([[2,3]]) --> 4th call(2) -> 5th call(3)

If the base case is reached, the non-list item is counted 1. With the List Comprehensions, we do not accumulate the results between the recursive calls but need a list to contain the results. This process is like:
   
5th call(3): return 1 --> 4th call(2):  return 1 --> 3rd call([2,3]): return sum([1,1]) = 2 --> 2nd call(1): return 1 --> 1st call([1,[2,3]]): return sum([1,2]) = 3

So the recursive function is defined below:
      
def count_items_recur(expr):
            if not isinstance(expr, list) :
                return 1
            else:       
                return sum([count_items_recur(i) for i in expr])

End of this post     

Wednesday, 2 March 2016

Linked List


1.  Linked list is a data structure where each element (called Node) is linked each other. So when accessing to any element, we just  need a pointer to traverse the link from the head/front node to reach the target node. This feature is indeed strong where the List (i.e., array) is weak. When a list is defined to store elements, one block of memory is allocated to the list to contain the memory    address of each element. Hence we can directly access to any element using list_name[index]. Notice the index refers to  the number of iterations required to reach the target element from the start. However, when removing or inserting an element, the list has to re-organize the entire structure and every element is then affected. For a linked list, the removal and insertion of a node do not affect the entire structure but just the link between previous node,target node, and/or next node.

2. Implementation of Linked List
  
 (1). Set up Node: each node has it's own value and the attribute 'next_'
      
class Node:
                def __init__(self, value, next_ = None)
                    self.value = value
                    self.next_ = next_       
      
(2). Set up Linked List: a linked list can be initialized as an empty structure with empty 'front' and/or 'back' node.
      
class LinkedList:
                def __init__(self):
                    self.front = None
                    self.back = None
                    self.size = 0
      
(3). Set up operations: Append and Reverse

 Append is to add new element to the linked list after current back node. So, for a non-empty linked list, the first step is to have the back node link to a new node. Next we reconfigure the back node as the node newly added.
        
 class LinkedList:
               
                def append(self, value):
                    new_node = Node(value)
                    if self.size == 0:
                        self.front = self.back = new_node
                    else:
                        self.back.next_ = new_node
                        self.back = new_node
                    self.size += 1
                      
Reverse is to reconfigure every node by breaking and rebuilding its link: from "front-->node1-->node2-->back" to "back<--node1<--node2<--front". So we just change the direction of link for each node rather than the entire structure. First of all, we need a pointer to traverse the linked list. Next a while loop is established for the pointer to loop over the linked list. At each iteration, the pointer firstly store its next node because the link to the next node will be broken. Then the pointer has the node currently scanned link to the previous node, which simultaneously breaks the link to the next node. To exit the iteration, the pointer moves to next node (this is why we must store the next node at the beginning of the iteration). Finally, after the loop is ended, we reconfigure the front and back node.             
          
class LinkedList:

         def reverse(self):
                    if self.size < 2:
                       return
                   else:
                       current_node = self.front.next_
                       previous_node = self.front
                       self.front.next_ = None
                       while current_node:                        
                                 next_node = current_node.next_
                                current_node.next_ = previous_node
                                previous_node = current_node
                               current_node = next_node               
                        self.back = self.front
                        self.front = previous_node 

End of the post 

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

Saturday, 23 January 2016


Preface


This blog is created because I am taking CSC148 at the University of Toronto in Winter 2016.  As a fundamental course, CSC148 lays a solid base for the computer science (CS) undergraduate students. The topics covered in CSC148 includes: Object Oriented Programming (OOP), Recursion, basic Data Structure (Stack, Queue, Linked List, Tree and Heap), and preliminary Algorithm (sorting). With this course, the students will be able to learn advanced CS courses that deepen and broaden their knowledge ans skills in the CS.  Unfortunately this course is also a high threshold for those students who want to major the CS in the University of Toronto. Thus I expect this course will help me to enter the CS specialist program.

Currently the blog is used to share my experience of learning CSC148. I hope, however,this blog will be beyond CSC148 and even my study in the University of Toronto to  keep tack of my footprints in the computer science. 


Data and Data Type

 

1.  Data Type
The data in the real world are countless. How to process the data becomes the core of the Computer Science. The programmers produce numerous applications to help process data. When a programmer writes the codes for an application with Java, Python or C++, he assumes this application to process a lot of data instead of one by one specific data. This is why the data type is introduced.

A data type is defined as a collection of data that shares same attribute(s). For example,  a data type "Student" can be created to represent the data like "John A" and "Tom B". The number of data types is infinite because a new data type can be created whenever  mandatory and/or necessary. For the previous example, 'John A' and 'Tom B' might belong to another data type "Senior Student".

2. Abstract Data Type (ADT)

Most of data are meaningful as they are used  to correspond to real things. For example, "John A" represents a student. Accordingly their data types are meaningful like "Student". But some data are meaningless or abstract because they represent nothing at all. For instance, a data is ["John A", "Tom B"]. Obviously the content within the [ ] are meaningful. But can we say the data type is "Student"? It seems that this data is different from 'John A' and 'Tom B'. So the answer relies on what is the [ ]. To my knowledge, nobody knows its real meaning because it's just an abstract symbol. Of course, a programmer knows it represents a list and use to store data. The list ["John A", "Tom B"] results from the operation (storage in this example ) on the meaningful data "John A" and "Tome B".  Hence, we define an ADT like List to represent a collection of abstract data like ["John A", "Tom B"] with the same data structure and operations on the data.

Considering the universal use of  ADTs, most programming languages usually provides built_in basic ADTs (like str, int, list, dictionary and set in Python) from which the programmers can create more complicated ADTs. An ADT does not only represent a collection of abstract data but more importantly indicates a data structure. This is why the ADTs are very important to the programmers.

In the Object_Oriented Programming (OOP), a data type is created through defining a Class. This provides the programmers strong flexibility to handle a diversity of data with different attributes.When creating a Class, we must define its attribute(s) (called "class implementation"). It might be easy to define the attribute(s) for a concrete Class like Student, Course, and Department. But how about an ADT Class?  For example, we want an ADT class to store a course and registered students together. Notice this ADT Class is different from the meaningful class Course and Student because it's nothing until it is used to store the data from both Course and Student. In the non-OOP, we can directly assign an empty dictionary (a built_in ADT in Python) to a variable and subsequently assign keys and/or values to the dictionary as needed. The code would be:

course_registry = {}

def add_course(course):
            course_registry[course] = []

def add_student(course,student):
            if course in course_registry.keys():
                   if student not in course_registry[course]:
                                course_registry[course].append(student)
 

In the OOP, all the same jobs are finished through defining an ADT class Course_Registry. The code would be:

class Course_Registry:
   
    def  __init__(self):
           self.course_registry = {}
       
    def  add_course(self,course):
           self.course_registry[course] = []
           
    def add_student(self,course,student):
           if course in self.course_registry.keys():
                  if student not in self.course_registry[course]:
                                self.course_registry[course].append(student)
              
We implement this ADT class with nothing but an empty Dictionary (i.e., self.course_registry = {}) whose data structure is best suited to this example. But the more important work is to define the methods (like add_course and add_student) to provide an interface of operating the ADT Class. So we can get that the attribute of an ADT Class is nothing but a data structure indicated by the ADT. Notice that, in this example,  why the Class is named after Course_Registry other than Dictionary is because its use is limited ( just serving the class Course and Student). But its data structure is the same as a Dictionary.

The interface of an ADT Class determines the operations on the objects (i.e., data) of the Class , which makes this Class different from another even they have the same data structure. For example, Stack and Queue may have the same data structure List but they have difference interface. Stack always removes the element that is most recently added to the list (called "Last In First Out " (LIFO)) but Queue removes the element that are most early added (called "First In First Out" (FIFO)).      




End of this post.