Using Pep8 and autopep8

PEP 8:

Pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

For more info check this out:

https://www.python.org/dev/peps/pep-0008/

Installation:

1)

You can install pep8 using pip

$ pip install pep8

Usage:

1)

Here you are checking the file optparse.py to see if it has any errors. This will only give you the pep8 error and the line on which the error occurs. The ‘–first’ will only show you the first occurrence of each error.

$ pep8 –first optparse.py

2)

If you also want to see the code which has the error along with the pep8 error. The file E40.py is being checked.

$ pep8 –show-source –show-pep8 testsuite/E40.py

 

AutoPep8:

Autopep8 automatically formats Python code to conform to the PEP 8 style guide. Autopep8 is capable of fixing most of the formatting issues that can be reported by pep8. Also autoppep8 is awesome (USE IT!!!!!)

Installation:

$ pip install autopep8

Usage:

$autopep8 –in-place –aggressive –aggressive <filename>

(

-i, --in-place        make changes to files in place
-a, --aggressive      enable non-whitespace changes; multiple -a result in
                      more aggressive changes

)
Advertisements

How to run one last function before getting killed in Python?

”’

The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time they will be run in the order C, B, A.

Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.

This is an alternate interface to the functionality provided by the sys.exitfunc() variable.

Note: This module is unlikely to work correctly when used with other code that sets sys.exitfunc. In particular, other core Python modules are free to use atexit without the programmer’s knowledge. Authors who use sys.exitfunc should convert their code to use atexit instead. The simplest way to convert code that sets sys.exitfunc is to import atexit and register the function that had been bound to sys.exitfunc.

”’

import atexit

def print_count():

    print ‘This function is called on an OS exit or system exit’

atexit.register(print_message)

Binary search tree using and check if a given tree is binary serach tree Python

”’

Created on Aug 11, 2015

@author: ishaansutaria

”’

class Node():

    ”’

    Initialize a node with the data

    with both their childreen being null

    ”’

    def __init__(self,data):

        self.data = data

        self.left = None

        self.right = None

        

    

    ”’

    Using recursion

    1) If root is less/greater than data and null insert right/left.(return)

    2) Else if right/left node is not null call the function again with right/left node as root

    ”’

    def insertData(self,data):

        if self.data < data:

            if self.right == None:

                self.right = Node(data)

            else:

                self.right.insertData(data)

        elif self.data > data:

            if self.left == None:

                self.left = Node(data)

            else:

                self.left.insertData(data)

    

    

    ”’

    You need to traverse the list(in-order)

    Go to the leftmost node in the tree and print it

    Check if the node has right node and get to the leftmost node of that node

    and print the list.

    

    1) Check if root has a left child

    2) If yes call the function with the left child as the root node.

    3) print the root value

    4) Check if the root has right child

    5) If yes then call the function with the right child as the root    

    ”’

    def printBinaryList(self):

        if self.left != None:

            self.left.printBinaryList()

        print self.data

        if self.right != None:

            self.right.printBinaryList()

    

    

    

    ”’

    Recursion:

    1) Check if the root node matches the value is yes then return

    2) Else check if data to be found is less/greater than the root node.

    3) If yes/no call the function again with the left/right child as the root node.

    ”’

    def serachBinaryTree(self,data):

        if self.data == data:

            print ‘found’

            return data

        if self.data > data:

            if self.left != None:

                return self.left.serachBinaryTree(data)

        if self.data < data:

            if self.right != None:

                return self.right.serachBinaryTree(data)

    

    

    ”’

    Helper function for deleting a node

    Returns the number of childs a node has

    ”’

    def countChildreen(self):

        count = 0

        if self.left:

            count +=1

        if self.right:

            count +=1

        

        return count

    

    

    ”’

    

    ”’

    def delNode(self,data,parent=None):

        if self.data == data:

            if parent.data > data:

                self.right = self.left

                parent.left = self.right

            print ‘found’

            return data

        if self.data > data:

            if self.left != None:

                return self.left.serachBinaryTree(data,self)

        if self.data < data:

            if self.right != None:

                return self.right.serachBinaryTree(data,self)

        

    

    ”’

    Traverse a node in-order and append the values you print in an array.

    Check if the array and its sorted version are the same.

    (Here you can also use compare with the prev node removing the need to have an

    extra array)

    ”’ 

    def checkBinaryTree(self):

        

        temp = []

        stack = []

        while True:

            while self != None:

                temp.append(self)

                self = self.left

            if len(temp) == 0:

                break

            self = temp.pop()

            stack.append(self.data)

            while self.right != None and len(temp) != 0:

                self = temp.pop()

                #print  self.data

                stack.append(self.data)

            self = self.right

            break

        if sorted(stack) == stack:

            print ‘Binary tree’

        else:

            print ‘Not a binary tree’

    

            

            

        

            

root = Node(5)

root.insertData(8)

root.insertData(9)

root.insertData(6)

root.insertData(5)

#root.printBinaryList()

root.checkBinaryTree()

print root.serachBinaryTree(8)

            

Find the majority element in an array

”’

1) take the maj element as x

2) Loop through the array and

    – Increment counter if x

    – Decrement counter if not x

    – If counter 0 the maj element is the new element

”’

def checkMajorityElement(arr):

    x = arr[0]

    count = 1

    for i,index in enumerate(arr):

        

        if index == 1:

            continue

            

        if i == x:

            count = count +  1

        else:

            count = count – 1

        

    

    return x

    

Calculate the difference between two diagonals of a square matrix

”’

Created on Jun 15, 2015

@author: ishaansutaria

”’

“””

(Given N * N matrix)

1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

1)The first diagnal is add the element whenever the row and coloum is the same

2) The second diagonal is s

“””

def findDiagonalDifference(n,list1):

    diag_sum1 = 0

    diag_sum2 = 0

    n = n – 1

    for row_index,row in enumerate(list1):

        for col_index,col in enumerate(row):

            if col_index == row_index:

                diag_sum1 += col

            

            if col_index == n:

                diag_sum2 += col

                n = n – 1

                

    return abs(diag_sum1 – diag_sum2)

    

print findDiagonalDifference(4,[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])

Check if number belongs to the Fibonacci series using Memoization and recursion

”’

Created on Jun 17, 2015

@author: ishaansutaria

”’

#Using recursion

def checknumberBelongs(n):

    if n == 1 or n == 0:

        return n

    else:

        res = checknumberBelongs(n – 1) + checknumberBelongs(n – 2)

        print res

        return res

#Using memoization

memo = {0:0, 1:1}

def fibm(n):

    if not n in memo:

        memo[n] = fibm(n-1) + fibm(n-2)

        print memo[n]

    return memo[n]

fibm(5)