Friday, 5 October 2012

Generators In Python

  

Generators


         A generator is a special routine that can be used to control the iteration behavior of a loop.A generator is similar to a function returning an array. A generator has parameters, it can be called and it generates a sequence of numbers. But unlike functions, which return a whole array, a generator yields one value at a time. This requires less memory.

Generators in Python

  • Are defined with the def keyword.
  • Use the yield keyword.
  • May use several yield keywords.
  • Return an iterator.
This is an example of generators used in a python program


                 def gen():
                    x, y = 1, 2
                    yield x, y
                    x += 1
                    yield x, y


                 it = gen()

                 print it.next()
                 print it.next()

                 try:
                    print it.next()
                 except StopIteration:
                    print "Iteration finished"
 

Representing infinite sequences

       
     Generators present us with some fun ways to manipulate infinite sequences
  
                 from __future__ import generators

                 def foo():
             i = 0
             while 1:
         yield i
         i = i 
 

Recursive Generators

     
     Generator functions can call themselves recursively.
 
                from __future__ import generators

                def abc():
            a = deff()
            for i in a:
     yield i
            yield 'abc'

               def deff():
           a = ijk()
           for i in a:
       yield i
              yield 'deff'

               def ijk():
           for i in (1,2,3):
       yield i
              yield 'ijk'

 

Thursday, 4 October 2012

Functional programming in Python

 

Functional Programming


           In Functional programming a problem can be decomposes into a set of functions. The functions take inputs and produce outputs, and don’t have any internal state that affects the output produced.Some of the examples off functional programming languages are Lisp,Scala,Scheme, Haskell, ML, OCAML, Clean, Mercury, or Erlang,etc

Pure Functions: Functions that have no side effects at all are called purely functional. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input.

First class function

          
        This is an example of first class function.he absence of any special notation; we are manipulating functions as if they were objects like arrays and numbers.    
>>>
>>>def cube(x): return x*x*x
...
>>>def sqr(x): return x*x
...
>>>cube
<function cube at 0xa1fb10c>
>>>a = [cube, sqr]
>>>a[0](2)
>>>def compose(f, g): return f(g(x))
...
>>>compose(cube, sqr, 3)
729
>>>

 

Higher Order Function

    
        A `function' (or a subroutine, subprogram, procedure) is considered to be a mechanism for capturing patterns.The ability to pass functions as arguments to functions greatly broadens the scope of this `pattern capturing' mechanism. Let's examine a simple function, `sum': 
 
                 def sum(a, b):
                    if (a > b): return 0
                    else: return a + sum(a+1, b)
                 def sigma(term, a, next, b):
                    if(a > b): return 0
                       return term(a) + sigma(term, next(a), next, b) 
                 def term(x): return 1.0/(x * (x+2))
                 def next(x): return x + 4
call the Function 
                 sigma(term, 1, next, 1000)
 
  

Using `lambda'

         
          The lambda keyword is used for creating anonymous functions. The body of a lambda should be composed of simple expressions only. In this example, The lambda is used to create a function which accepts an argument and returns it after multiplication.
>>>
>>>lambda y: y*10
<function <lambda;> at  0x9f751b4>
>>>f = lambda y: y*10
>>>f(10)
100
>>>

Closures 

     The main idea of Closures can be explained in this example

>>> def mul3(x): return lambda y: lambda z: x*y*z
>>> mul3(10)(2)(3)
60
>>>
 

Thursday, 27 September 2012

A Simple Python Program for Moving a Car

        This is a program in python for develop a GUI for moving car using buttons 

from Tkinter import *
import Tkinter as tk
class Carcontrol(Frame):
    def __init__(self,name):
        Frame.__init__(self,bg='white')
        self.pack(expand=YES,fill=BOTH)
        self.master.title("Control the CAR")       

        f=Frame(self,width=500,height=500,bg='white')
        f.pack()
       
        self.f1=Frame(f)
        self.f1.pack(side=TOP,padx=10,pady=10)
        f2=Frame(f)
        f2.pack(side=TOP)

        self.w=Canvas(self.f1)
        self.w.canvasx ( 500, gridspacing=None )
        self.w.canvasy ( 500, gridspacing=None )
        self.p=self.w.create_polygon( 50,50,100,50,125,75,25,75,fill="green")
        self.r=self.w.create_rectangle(10,75,140,100,fill="red")
        self.o1=self.w.create_oval(20,95,45,125,fill="black")
        self.o2=self.w.create_oval(105,95,130,125,fill="black")
        self.w.pack()
       
        b1=Button(f2,text="LEFT",command=self.left)
        b1.pack(side=LEFT)
   
        b2=Button(f2,text="RIGHT",command=self.right)
        b2.pack(side=RIGHT)

    def left(self):
        print "left"
        self.w.move(self.p,-10,0)
        self.w.move(self.r,-10,0)
        self.w.move(self.o1,-10,0)
        self.w.move(self.o2,-10,0)
       
    def right(self):
        print "right"
        self.w.move(self.p,10,0)
        self.w.move(self.r,10,0)
        self.w.move(self.o1,10,0)
        self.w.move(self.o2,10,0)
       
def main():
    Carcontrol("").mainloop()

if __name__=="__main__":
    main()





Tuesday, 11 September 2012

Constructing Procedures Using Lambda in Functional Programming

A powerful programming language is the ability to build abstractions by assigning names to common patterns and then to work in terms of the abstractions directly.Procedures provide this ability.Procedures that manipulate procedures are called higher-order procedures.

 The higher-order procedures can serve as powerful abstraction mechanisms, vastly increasing the expressive power of our language

 (lambda (x) (+ x 4))

 and

 (lambda (x) (/ 1.0 (* x (+ x 2))))
.

This is pi-sum  procedure
  
(define (pi-sum a b)
  (if (> a b)
      0
      (+ (/ 1.0 (* a (+ a 2))) (pi-sum (+ a 4) b))))



pi-sum procedure can be expressed without defining any auxiliary procedures as


(define (pi-sum a b)
  (sum (lambda (x) (/ 1.0 (* x (+ x 2))))
       a
       (lambda (x) (+ x 4))
       b))


using lambda, we can write the integral procedure without having to define the auxiliary procedure add-dx:


(define (integral f a b dx)
  (* (sum f
          (+ a (/ dx 2.0))
          (lambda (x) (+ x dx))
          b)
     dx))


In general, lambda is used to create procedures in the same way as define, except that no name is specified for the procedure

(lambda (<formal-parameters>) <body>)

We can read a lambda expression as follows:
    (lambda             (x)             (+    x     4))
                                                
 the procedure   of an argument x  that adds  x and 4


a procedure as its value, a lambda expression can be used as the operator in a combination such as


((lambda (x y z) (+ x y (square z))) 1 2 3)
12


 

Wednesday, 15 August 2012

Nose testing

For Unix like systems the nose will install by using following methods

Install nose using setuptools/distribute:
      easy_install nose
Or pip:
      pip install nose
Or, if you don’t have setuptools/distribute installed, use the download link at right to download the source package, and install it in the normal fashion:
     python setup.py install
 
After installation of the nose you can run tests for your projects by using the following commands  on terminal

     cd path/to/project       
     nosetests

The output like this
..........................................................................................................
   Ran 20 tests in 1.220s
   OK
 
For help with nosetests’ many command-line options, try:
 
   nosetests -h 
 
  -h, --help            show this help message and exit
  -V, --version         Output nose version and exit
  -p, --plugins         Output list of available plugins and exit. Combine
                        with higher verbosity for greater detail
  -v, --verbose         Be more verbose. [NOSE_VERBOSE]
  --verbosity=VERBOSITY
                        Set verbosity; --verbosity=2 is the same as -v
  -q, --quiet           Be less verbose
  -c FILES, --config=FILES
                        Load configuration from config file(s). May be
                        specified multiple times; in that case, all config
                        files will be loaded and combined
   etc

Python3

  • nose supports python3. 
  • Building from source on python3 requires distribute.
  • If you don’t have distribute installed, python3 setup.py install will install . 

Testing with nose 

 

Writing tests is easier

   nose collects tests from unittest,TestCase subclasses.
   you can also write simple test functions, as well as test classes

 

Running tests is easier

   nose collects tests automatically, as long as you follow some simple 
   guidelines for organizing your library and test code 
   Running tests is responsive

 

Setting up your test environment is easier

  nose supports fixtures at the package, module, class, and test case  level

 

 Doing what you want to do is easier

  nose comes with a number ofbuiltin plugins to help you with output capture,  
  error introspection, code coverage, doctests, and more. 

 

Developing with nose

 

Get the code

The stable branch of nose is hosted at googlecode. You should clone this branch if you’re developing a plugin or working on bug fixes for nose:
         hg clone http://python-nose.googlecode.com/hg/ nose-stable
 
The unstable branch of nose is hosted at bitbucket. You should fork this branch if you are developing new features for nose. you can clone the branch:
        hg clone http://bitbucket.org/jpellerin/nose/ nose-unstable

 




 

 

Tuesday, 14 August 2012

Unit Testing

        unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use.Unit tests are created by programmers or occasionally by white box testers during the development process.The goal of unit testing is to isolate each part of the program and show that the individual parts are correct

 

Benefits  

 

Find problems early

Unit tests find problems early in the development cycle.Unit tests are created before the code itself is written. When the tests pass, that code is considered  complete. 

Facilitates change

Unit testing allows the programmer to re factor code at a later date, and make sure the module still works correctly.Readily available unit tests make it easy for the programmer to check whether a piece of code is still working properly.

Simplifies integration

Unit testing may reduce uncertainty in the units themselves and can be used in a bottom up testing style approach. By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier.

Documentation

Unit testing provides a sort of living documentation of the system.Unit tests provides a basic understanding of what functionality is provided by a unit and how to use it.

Design

Each unit test can be seen as a design element specifying classes, methods, and observable behaviour. The following  example is the Testing toRoman against fromRoman
.
class SanityCheck(unittest.TestCase):        
    def testSanity(self):                    
        """fromRoman(toRoman(n))==n for all n"""
        for integer in range(1, 4000):         
            numeral = roman.toRoman(integer) 
            result = roman.fromRoman(numeral)
            self.assertEqual(integer, result) 


  This example is a test class that checks the correctness of program that converts the integer given to roman numeral and viceversa. Here the test class checks whether the given integer falls in the
 range (0,3999)


Parameterized Unit Testing (PUT)

In Parameterized Unit Tests (PUTs) , that take parameters.PUTs have been supported by JUnit 4 and various .NET test frameworks.


Unit testing limitations

Testing cannot be expected to catch every error in the program. It is impossible to evaluate every execution   path in most trivial programs.
It will not catch system errors or broader system level errors
Writing the unit tests is the difficulty of setting up realistic and useful tests.
Challenge of setting relevant initial condition so that the part of the code being tested behaves as the part of the whole system
Use of a version control system is essential for unit testing.

Applications

 

Extreme Programming

Unit testing is the cornerstone of extreme programming, which relies on an automated unit testing framework.This automated unit testing framework can be either third party, e.g., xUNIT, or created within the development group.

Techniques

Unit testing is commonly automated but may still be performed manually.

 unit testing frame work

Unit testing frameworks are most often third-party products that are not distributed as part of the compiler suite. They help simplify the process of unit testing, having been developed for a wide variety of languages.

Language-level unit testing support

Languages that directly support unit testing include:
  • C
  • Java
  • Obix
  • D

 






 


Saturday, 11 August 2012

Python Coding Style

 

Python Programming Style

         Programming style is a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers to read and understand source code conforming to the style, and help to avoid introducing errors.

        In python readability counts.Python community has its own standards  as that of C,C++,etc.
Python Enhancement Proposal(PEP)8 is a style guide for python which describe what a python code should look like .

 

White spaces

  • 4 spaces per indentation .
  • Never mix spaces and tabs.
  • Add a space after ',' in dictionaries and argument list and after ':' in dictionaries
  • Put spaces around assignments and comparisions.

 

Naming

  • Lower case for functions,methods,attributes
  • All caps for constants
  • _name becomes _classname__name avoid such usage as it may create problems when a subclass may need to access the same variable
  • The above situation requires either the super class or the sub class has to changed

 

Long Lines 

  • Keep lines below 79 characters
  • Use backslashes as a last resort

 

Compound Statements

  • Avoid the over use of ';' in blocks of codes,as it effect the readability of the code drastically
  • May be used at some circumstances,if this sacrifice may result in a better readability.

 

Docstrings and Comments

  • Docs string are used to specify how to use code
  • Comments Specify why and how code works
  • It is better not to specify a comment rather then a miss-leading comment.

 

Building Strings

  • Make use of ''.join() method as far as possible as it improves the performance during passing

     

Testing for Truth Values

   if x :
       print something

   Is  Better than

   if x==0 True:
      print something

 

variables

  • In python identifier are like parcel tag attached to an object.
  • Hence an identifier can becomes a tag of any object

 

Importing

  • While importing we have to import standard modules.First followed by third party modules and at last the local modules