Wednesday 30 May 2018

Python any()

Python built-in module provides method any()  which  returns True if any element of an iterable is true. If not this method would  return False.

syntax :

any(iterable)    ##   iterable could be list, string dict etc

return value:

  • True  ##   if any 1 of iterable is True
  • False ##   if all are false  or the list is empty  
Examples :
>>> a = [0,0]  ## 0 defaults to False
>>> any(a)
False
>>> a = [1,2]  ## Both are True
>>> any(a)
True
>>> a = []   ## empty list False 
>>> any(a)
False
>>> a = [0,0,0,1]  ## If any element is True
>>> any(a)
True

Using any() with 2 lists :

Suppose We have two lists a and b and we want to check if element in a exists in b. 
So we define function :

def func(a, b):
    for i in a:
       if i in b:
          return True
    return False

This could be easily realised with any() in one line as :

any(i in b for i in a)
For Example:

>>> a = [1,2,3,4]
>>> b = [4,5,6,7]
False
>>> def func(a, b):
        for i in a:
           if i in b:
              return True
 return False
>>> print func(a,b)
True
>>> any(i in b for i in a)
True

Saturday 26 May 2018

Class Inheritance

Through Classes we can define many new data types. But suppose we have to define some datatype with some common properties. Then should we go about creating datatypes with bunch of repetitive properties for all of them, that will be wasteful job.  Many built-in types have properties in common with other types. For example, types list and str each have len function that mean the same thing.
 So how is this achieved? 
Inheritance provides a convenient mechanism for building groups of related abstractions. It allows programmers to create a type hierarchy in which each type inherits attributes from the types above it in the hierarchy.

The class object is at the top of the hierarchy. This make sense, since in Python everything that exists at runtime is an object. Because Python inherits all of the properties of objects programs can bind a variable to a Person, append a Person to a list , e.tc.

A subclass inherits the attributes of its superclass in addition to this a subclass can :
  • add new attributes like class variables, instance variable and methods
  • override attributes of the superclass.  For example , if same method is defined in class and subclass, then the method defined in subclass overrides the method defined in superclass.


For Example :

class human(object):
    name = " "
    def __init__(self, name):
        self.name = name 
    def printName(self):
        print "Name  = " + self.name

class parent(human):
    def __init__(self, name):
        self.name = name
    def work(self):
        print "working"

class children(human):
    def __init__(self, name):
        self.name = name
    def study(self):
        print "studying"

In the code above class human is the superclass and class parent and class children are called subclasses as they inherits from superclass human. Now when we create instance of class human and class parent :

latika = human("latika")
latika.printName()
at = parent("lat")
lat.printName()
lat.work()

will give output :

Name  = latika
Name  = lat
working

Wednesday 23 May 2018

Python enumerate()


Enumerate is a built-in function in Python. It is used when we want to access anumber or a variable in a list along with its counter.
For e,g
>>> A= [2,5,6,7,8,9]
>>> for i in enumerate(A):
print i

will give the output:
(0, 2)
(1, 5)
(2, 6)
(3, 7)
(4, 8)
(5, 9)

See in the output we get tuples in the form ( index,value)

Using list comprehension we can also write:
>>> A= [2,5,6,7,8,9]
>>> B = [i  for i in enumerate(A)]
>>> print B

will give the output:
[(0, 2), (1, 5), (2, 6), (3, 7), (4, 8), (5, 9)] 



We can get output as list of list using the below format:
>>> A= [2,5,6,7,8,9]  
>>> B = [ [i,v]  for i,v in enumerate(A)]  
>>> print B  

will give output:
[[0, 2], [1, 5], [2, 6], [3, 7], [4, 8], [5, 9]]


Enumerate also takes argument that allows to start the counter from that argument.
example:
>>> A= [2,5,6,7,8,9] 
>>> B = [ [i,v] for i,v in enumerate(A,1)] 
>>> print B 

will now give output  : 

[[1, 2], [2, 5], [3, 6], [4, 7], [5, 8], [6, 9]]


















https://docs.python.org/2.3/whatsnew/section-enumerate.html

Tuesday 22 May 2018

Recursion in Python

What is Recursion?
Recursion means defining something by its own meaning. In programming language recursion can be explained as a function calling itself repeatedly.

The best example of using recursion is factorial.
A factorial is calculated by :

n! = n*( n-1)!

The factorial of a number is calculated by multiplying the number with factorial of a number less than itself. So, this process will run until  1! is reached which is equal to 1. This condition is called termination condition. If a termination condition is not specified recursion will run till infinity.
While defining a function using recursion this termination condition is called as base case.

How is recursion achieved?
A recursive definition is made up of two parts .

  • Base Case - as specified above its the termination condition else the loop will run till infinty.
  • Recursive or Inductive Case - the process of calling the function again with another input
Recursive implementation of Factorial :
    

def fact(n): if n==1: #Base Case
return n
else:
   return n*fact(n-1) #Inductive case

Another famous problem that is solved through recursion is Fibonacci Series which is given by :

fib() = 0,1,1,2,3,5,8,13............
an element at (x+2) position  is calculated in fib by:
fib(x+2) = fib(x+1)+fib(x)
  • it has two base case: x=0, or x=1, in general htere can be as many base cases as needed.
  • It has two recursive calls as well, again it depends on the need of function

Recursive implementation of Fibonacci Series :

def fib(x): if x==0 or x==1: #Base Case
return 1
else:
return fib(x-1)+ fib (x-2) #Inductive Case




Monday 21 May 2018

Exception Handling with Python


When an exception is raised it causes the program to terminate and it is called as an Unhandled Exception. If we know that a line of code might raise an exception when executed we should handle the exception.

What is an Exception
An exception is an event , which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When a python script encounters a situation that it cannot cope with , it raises an exception . An exception basically represents an error.


Handling an Exception 
Exceptions can be handled to avoid program from crashing , this is called Exception handling.
When we can anticipate an error in the program we can use exception handling to stop the program from crashing.

Syntax for exception handling : 

try:

except.............

print 

Example
If we know that in a program we can get such values that a ZeroDivisionError can occur , so we can handle this by except ZeroDivisionError :

>>> while True:
try:
    x = int(raw_input("Please enter a number: "))
    y = int(raw_input("Please enter a number: "))
    z = x/y
    break
        except ZeroDivisionError:
            print "Oops!  That was no valid number.  Try again..."

            
Please enter a number: 3
Please enter a number: 0
Oops!  That was no valid number.  Try again...
Please enter a number: 

First the try clause is executed, if an exception occurs the try block code execution is stopped and handled in except block.. The message given in exception block is printed and execution again passes to try block.

Saturday 19 May 2018

Errors and Exceptions in Python

In Python there are two kinds of Errors :

Syntax Error and Exceptions

Syntax Errors are also known as parsing errors and are the one which occur due to wrong syntax , means  the mistake we did in use of Python language. They are analogous to grammatical mistakes in English language. The parser immediately points to the error without further executing the code.

For e.g


>>> for i in range(3):
print i
    int i = 9.0

SyntaxError : invalid syntax


Exceptions

An "exception" is defined as "something that does not conform to the norm "". Even if a statement is syntactically correct it might give error in execution . Error detected during execution are called exceptions.

Exceptions occur with different types and type is printed as message with error.

The most common types are:

Index Error : It is the type of exception that raises when a program tries to access an element that is not within the bounds of an indexable type.
The string followed by index error provide information about what caused the exception to occur.
For example :

>>> a = [1,2,3,4]
>>> print a[5]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print a[5]
IndexError: list index out of range

Name Error : It is a type of exception that raises when a name is not defined in the program
For example :

>>> print b
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print b
NameError: name b is not defined
                             


Value Error  : It is a type of exception that raises when a value mismatch occurs in the program
For example:
>>> x = int(raw_input("Enter a number: ")) enter a number: d
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x = int(raw_input("Enter a number"))
ValueError: invalid literal for int() with base 10: 'd'

Type Error  : It is a type of exception that raises when a type mismatch occurs in the program.
For example
>>> 2 + '7' Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
2 + '7'
TypeError: unsupported operand type(s) for +: 'int' and 'str'



Sunday 13 May 2018

Download ubuntu on Virtual Machine for Windows7

Many times you don't want to change your operating system because you are very comfortable using it(for e.g Windows)  but need some upgradation to do certain things which are not supported by Windows. 
This article tells you about how to install Ubuntu on your system using a Virtual Box.

What is a Virtual Machine?

A  Virtual Machine  is like another system on your system.  A Virtual Machine allows you to install an operating system without changing your main operating system.
Every virtual machine has virtual devices that provide the same functionality as physical hardware and have additional benefits in terms of portability, manageability and security.

How to download Virtual Machine

A virtual machine is a powerful  x86 and AMD64/Intel64 virtualisation product for enterprise as well as home use. It is the only professional solution freely available as Open Source Software under the terms of GNU General Public License(GPL) version2.

You can download Virtual box Machine from the website  https://www.virtualbox.org/

Now  you can run the .exe file in your system and install Virtual Box following the onscreen instructions.


Steps to download Ubuntu on Virtual Machine

1. First download latest version of ubuntu from  https://www.ubuntu.com/download/desktop ,
    this will be an .iso file.

2. Open the virtual box you have installed and go to settings.

3. In here click the storage sub-category.

4. In the storage tee click on the disc icon that says "empty". 

5. Click on the small disc icon with a down arrow on the right hand corner of the storage window .

6. Locate the .iso file  that you downloaded earlier.

7. Click "ok" the settings window to return to the virtual box window.

8. Click start

At this point the .iso file will act like a boot cd and ubuntu will be installed.
The Virtual machine will ask for restart and after it just make sure that the IDE storage is empty again.

Referral links :

http://www.instructables.com/id/Introduction-38/
https://www.wikihow.com/Install-Ubuntu-on-VirtualBox
http://searchservervirtualization.techtarget.com/definition/virtual-machine

Monday 7 May 2018

Implementing a class in Python

Classes can be looked upon as a mechanism that allows programmers to define new types. An abstract data type is a set of objects and the operations on those objects. These are bound together so that one can pass an object from one part of a program to another and in doing so provide access not only to the data attributes of the object but also to operations that make it easy to manipulate that data.

The int, string, float, list, dict are all built in types using classes.

The process of creating an object of type class is callled instantion of class (calling a class object). Some classes can be be xreated with a specific initial state. This is done by a special method __init__.  As we see in code below. We create a class calulator which has instances value1,value2and operand.

Example :

class calculator():
   
    def __init__(self,value1 , value2, operand):
        self.value1 = int(value1)
        self.value2 = int(value2)
        self.operand = operand

    def calculate (self):
        if self.operand == '+' :
            return self.value1 + self.value2

        if self.operand == '*':
            return self.value1 * self.value2

        if self.operand == '-' :
            return self.value1 - self.value2
   
        if self.operand == '/' :
            try:
                self.value1 / self.value2
            except ZeroDivisionError:
                print "Zero division error"
            else:
                print "a"
                return self.value1 / self.value2

Test cases : 
r = calculator(6,7, '+')
print r.calculate()

r = calculator(3,7, '-')
print r.calculate()

r = calculator(6,0, '*')
print r.calculate()

r = calculator(9,0, '/')
print r.calculate()

r = calculator(9,8, '/')
print r.calculate()
 
So r is an instance of class calculator.
The only operations understood by instance objects is attribute reference. There are two kind of attributes one data attributes and second method attributes.
Data attribute are variables defined in the class.
Method attributes are functions that a class object can do. These attributes are reffered using . name notation.
In the example above the class object has method function which is called once the instance object is created by command  r.calculate .


Saturday 5 May 2018

Mutable objects : Dictionary (Dict)


Objects of type dict are like lists except that "indices " need not be integers , they can be values of any immutable types . Since they are not ordered, the indices are referred as keys.  Dictionaries can be thought of a key/value pairs where each key has a corresponding value. Literals of type dict are enclosed in curly braces and each element is written as a key followed by a colon followed by a value. Each key value pair is seperated by a comma.

For example:
>>>d  = {1:red, 2:blue, 3:yellow , 4: orange, 5:black, 6: white}
>>>print d[1]
>>>red

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of immutable data type such as strings ,numbers, or tuples.


Operators on Dictionaries:

lend(d)  :  returns the number of stored entries i.e. the number of key/value pairs

del d[k]  : deletes the key k together with its value

k in d     :  True if a key k exists in dictionary d

k not in d : True if a key deosn't exists in dictionary d

Methods on Dictionaries

1. Iterating over dictionary
    for key in d:
        print key 

2. dict.setdefault(key,default=None)
    will set dict[key] = default if key not in dict

3. dict.clear()
    removes all elements of dictionary dict

4. dict.copy
    returns a copy of dictionary dict

5. dict.items()
    returns a list of dict's(key,value) pairs

6.dict.keys()
    returns a list of keys

7.dict.values()
    returns a list of values





  

Python Data structures : Linked Lists

Linked lists is a linear data structure in which each element is a node that comprise of data and pointer to next node.
like this:

In arrays we can access the elements of the list by using index numbers. But suppose we want to insert tan element at the second position of the list , so we need to shift all the elements of list one step towards right to push just a single value. Where as in Linked list implementation we will just add a new node storing the data we want to insert and change pointer at first position towards this new node and pointer of this new node towards the initially second element. In same way we can define the remove function, the pointer from current node will point towards next to next node. And the next node will be automatically removed from Linkedlist.

So for implementing linked list we will first create a node class:

class Node(object):
    def __init__(self,data, next=None):
        self.data = data
        self.next = next

Next we will create a class LinkedList in which we define various operations on linked  lists:

class LinkedList(object):

    def __init__(self):
        self.head = None
        self.size =0


    def extend(self, seq = None):
        """extends list with the given sequence"""

        for i in range(0, len(seq)):
            node = Node(seq[i])
            self.size +=1
            node.next = self.head
            self.head = node

    def append(self, item):
        """append item to the end of list"""
        node = Node(item)
        node.next = self.head
        self.head = node
        self.size += 1

    def printdata(self):
        """print elements of linked list"""
        node = self.head 
        while node:
            print node.data
            node = node.next

    def __iter__(self):
        node = self.head
        while node:
            yield node.data
            node = node.next

    def __contains__(self, item):
        """checks whether given item in list"""
        node = self.head 
        while node:
            if node.data == item:
                return True
            node = node.next


    def len(self):
        """returns the length of list"""
        return self.size


    def remove(self, item):
        """removes item from list"""
        node = self.head
        current = self.head.next
        if node.data == item:
            self.size -= 1
            self.head = current
            current = current.next
        while current:
            if current.data == item:
                current = current.next
                node.next = current
                self.size -= 1
            node = current
            current = current.next




    def __str__(self):
        return  str(self.data) + str(self.size)

Then we will define our main()  function and give inputs to the  Linked list.

def main():
    llist = LinkedList()

    llist.extend([98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,
    97,0,63,25,85,24])

    print "Length of linked list is ", llist.len()

    llist.append(222)

    print "Length of linked list is ", llist.len()

    llist.remove(22)

    print "Elements of linked list  \n", llist.printdata()
    print "Length of linked list is ", llist.len()

   ## Search for an element in list   
    while True:
        item = int(raw_input("Enter a number to search for: "))
        if item in llist:
            print "It's in there!"
        else:
            print "Sorry, don't have that one"
if __name__ == "__main__":
    main()







.




Loan Prediction Analysis

In this post I will share my visuals ,learning and understanding of a dataset and using various algorithms of Machine Learning to analyse i...