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