Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, April 28, 2012

Lambda in Python

Lambda in Python is the function building tool. In Python you can build functions either by "def" or by "lambda" keywords. Lambda functions are extremely useful in building GUI applications using Tkinter. Lambda is extremely useful in these cases :
  • When the lambda function is being used only once.
  • When a function takes another function as parameter like in filter() , map() and reduce() functions.
  •  When you want your code to be clearer and cleaner.  

Normal Function definition using "def"

def cube(x):
    return x*x*x
cube(3)

Using Lambda Functions

cube = lambda x : x*x*x
cube(3) 

Both the above code snippets achieve a similar task of finding the cube. 
As you can see lambda syntax is cleaner. No return statement required.

Lambda's are used extensively in functions such as filter() , map() and reduce() which need function objects as parameters.

filter() 

It is used to filter the list on some condition. It does return the filtered list.

list = [1,2,3,4,5,6]
filtered_list = filter(lambda x : x%2 ==0 ,list)
filtered_list


The Output is [2,4,6] as it is filtered.Note the use of lambda function passed as parameter.It filters only multiples of 2.

map() 

This function is used to map the list to some other list. Mutate the values of one list and generate another list.

list = [1,2,3,4,5]
mappped_list = map(lambda x:x**2,list)
mapped_list
The output is [1,4,9,16,25] . The values in the list are mapped to their squares generating mapped_list.

reduce()

This function is used to reduce the list to a value. It takes the first two values in a list ,operates on them (depending on the lambda definition) and then he result of the first two is used to operate on the third and so on.

list = [1,2,3,4,5]
reduce = reduce(lambda x,y:x*y , list)
reduce
The output is 120 as (1*2 = 2 * 3 =6 *4 =24 *5 =120 ). Observe that lambda takes two parameters x and y and reduces the list to a value based on the definition of the lambda function.
This function seems to be deprecated in Python 3.0.

Lambda's are use once Throw away functions.  
Lambda's return function objects.
Lambda use cases are very rare but make the code a lot cleaner.

Note : If you do have any specific use cases for Lambda's which you have implemented or used in you project ,Please Let me . Do leave a comment.

Friday, April 27, 2012

Classes in Python

Class creation and instantiation is cleaner and a lot more easier in Python.
 
class Student:
    def __init__(self):
        pass
    def getName(self,name):
        self.name = name
        print self.name
    def totalMarks(self,fmarks,smarks,tmarks):
        self.fmarks = fmarks
        self.smarks = smarks
        self.tmarks = tmarks
        tot_marks = fmarks+smarks+tmarks
        print tot_marks


Messi = Student()
Messi.getName('Rajeev')
Messi.totalMarks(23,24,34)


In the above Python code snippet we  have created a class template Student.
Now let us analyze it :

  • We have a method __init__ which acts as a constructor in Python. This function is automatically called when the class in instantiated. We have used "pass" just to pass the method and do nothing.
  • We also see that all the functions in the class take the first argument as "self" ."self" is actually a placeholder used in Python set as a first argument in functions.This is replaced with the object which is used to call that function. For Example if we created an instance of student as "Messi" , then when we call a function using this object,then the self is replaced with the object "Messi".
  • getName() method takes the name of the Student and assigns it to the Object's name parameter which called this function.
  • totalMarks() method takes the marks scored by students in 3 tests and calculates the Total Marks.
  • Further Down we have a created an instance of the class Student "Messi".
  • Using the Object Messi we called the getName() and totalMarks() methods using dot(.) notation.
  • As you can observe we do not pass anything in place of self parameter of methods , as we already know that it is just a place holder.

That's it , Class creation is that's simple and fun.

Friday, April 6, 2012

Input in Python

Recently, I have been exploring a lot of Python programming language.I came across this prime security concern in Python.
There are basically two ways of taking input from the user . The input() and the raw_input() functions.

For Ex :

var foo = input( " Enter the number")
var foo_raw = raw_input("Enter the Number")

Both of the functions accept input from the user. But, raw_input() should always be preferred over input().

What the Heck is the difference between raw_input() and input() in Python ?

raw_input() is considered to be safe to use as it takes the parameters entered by user as a string whereas input() takes the parameters entered as a command. input() is harmful as a user can easily harm or hack the program behavior by providing parameters such as "eval" which are executed as command by input().Thus it is considered safe and reliable to always use raw_input() for taking input from the user in Python. 

So 

For ex :

var foo = input("Enter ")  # input eval , eval command is executed "Unsafe" "Harmful" 

var foo_raw = raw_input("Enter") # input eval , it is interpreted as a string "Harmless"




Note : In Python 3.x , input() also returns string .