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