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