Showing posts with label basics. Show all posts
Showing posts with label basics. Show all posts

Saturday, March 16, 2013

imap and map in python.

  •  The imap() function returns an "iterator" that calls a function on the values in the input
    iterators and returns the results.
  • Like map() but stops when the shortest iterable is exhausted instead
of filling in None for shorter iterables.The sentence is bit odd but let's go through it.

>>>from itertools import *
>>> list(imap(pow, xrange(10), count()))
[1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]


  1. pow is a builtin function which caluclates power of two numbers(pow(2,5==>2**5==>32)
  2. In the above example we passed 3 arguments,1 pow function,xrange(10) ,count.
  3. imap maps the power function over those other two arguments.This is equivalent to pow(xrange(10),count())
  4. xrange(10) will exhaust after 10 values,despite count() being infinite iteration it stops because xrange(10) has exhausted.
  5. we make a list of all the powers by calling list()
  6.  
Input:
#!usr/bin/env/python
from itertools import *
#Using imap from itertools.
print 'Triples:'
for i in imap(lambda x:3*x,xrange(5)):
    print i
print "\nMultiples:"
for i in imap(lambda x,y:(x, y, x*y), xrange(5), xrange(5,10)):
    print '%d * %d = %d' % i
print "\n Zip"
print list(map(pow, xrange(10), count()))
Output:
Triples:
0
3
6
9
12

Multiples:
0 * 5 = 0
1 * 6 = 6
2 * 7 = 14
3 * 8 = 24
4 * 9 = 36

 Zip
Traceback (most recent call last):
  File "/home/ubuntu/Desktop/map_imap.py", line 11, in 
    print list(map(pow, xrange(10), count()))
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'
[Finished in 0.2s with exit code 1]
The error is expected because count() is infinite iteration,but xrange() is exhausted so it can't perform operations which have "None" argument.
     











Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

islice python implementation with examples

Pure Pyhton Implemntation:
def islice(iterable, *args):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(*args)
    it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
    nexti = next(it)
    for i, element in enumerate(iterable):
        if i == nexti:
            yield element
            nexti = next(it)

Give a look at this pdf.It's wonderful for all itertools examples
http://www-igm.univ-mlv.fr/~vialette/teaching/2009-2010/Python/itertools.pdf


#!usr/bin/env/python
"""
islice==>It performs slicing operation on iterable(sequence)and returns an iterator.
negative indexing is not possible.
It can have optional start,step values.If start is not given,it defaults to 0.If step is not given 
it takes default value 1.
"""
from itertools import *
print 'Example-1[Give a string(iterable) and u can get a selected strings into a list]'
print'\n',list(islice('Ajay kumar',2))
#start=0,stop at 2nd element but don't include it.step=1
print'\n',list(islice('Ajay kumar',2,4))
#start=2,stop=4-1,step=1
print'\n',list(islice('Ajay kumar',2,None))
#start=2,stop=till the end,step=1
print'\n',list(islice('Ajay kumar',0,None,2))
#start=0,stop=till the end,step=2
print '\nExample-2 ==>using count with islice(it does same thing as range.)'
for i in islice(count(),5):
 print i,


Output:

Example-1[Give a string(iterable) and u can get a selected strings into a list]

['A', 'j']

['a', 'y']

['a', 'y', ' ', 'k', 'u', 'm', 'a', 'r']

['A', 'a', ' ', 'u', 'a']

Example-2 ==>using count with islice(it does same thing as range.)
0 1 2 3 4
 
 

The above  Examples can be seen in the image attached.














Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

ZIP in python with examples

#!usr/bin/env/python
"""This(zip) builtin function returns a list of tuples"""
x=(1,2,3)
y=(4,5,6)
z=zip(x,y)
print "\nz will be a list:",z

print "\nExample 1:zip(string,list)"
for i in zip("Ajay kumar",[0,1,2,3,4,5,6,7,8,9]):
 print i,
print "\nExample 2:zip(list,list)"
for i in zip([1,2,3],[4,5,6]):
 print i,
print "\n Example 3:zip(tuple,tuple)"
for i in zip((1,2,3),('a','b','c')):
 print i,

Output:

z will be a list: [(1, 4), (2, 5), (3, 6)]

Example 1:zip(string,list)
('A', 0) ('j', 1) ('a', 2) ('y', 3) (' ', 4) ('k', 5) ('u', 6) ('m', 7) ('a', 8) ('r', 9) 
Example 2:zip(list,list)
(1, 4) (2, 5) (3, 6) 
 Example 3:zip(tuple,tuple)
(1, 'a') (2, 'b') (3, 'c')

Output can be seen in the image

 
 
 
One More version from some online book:
 
z = zip(list1, list2)
newlist1, newlist2 = zip(*z)

This works becauses the * syntax unpacks a list of values. The above code zips and unzips two lists, which is pointless, but the same syntax can be used to convert from a list of columns of data to a list of rows of data. For example, the following list comprehension reads in a file of tab-delimited data as a list of rows, where each row is a tuple of values:
rows = [line.rstrip().split('\t') for line in file(filename)]
If you want to flip the data through 90 degrees (i.e. convert from rows or data to columns of data), then you use:
columns = zip(*rows)
For example, if the data was originally (a, 1), (b, 2), (c, 3), it becomes (a, b, c), (1, 2, 3).
 Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Friday, March 15, 2013

Itertools chain function

Few examples are from the book Python standard library by example.

From the
Documentation====>The chain() function takes several iterators as arguments and returns a single iterator that produces the contents of all of them as though they came from a single iterator.


In Python programming language, an iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence.



#!usr/bin/env/python 
from itertools import * #chain function  
"""
From the
Documentation====>The chain() function takes several iterators 
as arguments and returns a single iterator that produces the contents of all of them as though they came from a single iterator.

"""
from itertools import *
#Example 1(with equal sized lists)
print "Equal Sized lists:"
for i in chain([1,2,3],['a','b','c']):
    print i,
    # ',' is for horizontal printing of output.

#Example 2:(with inequal size of lists)
print "\n inequal size of lists:"
for i in chain([1,2,3],['a','b']):
    print i,

#Example 3:Tuples and strings
print "\n For tuples and strings"
for i in chain((1,2,3),"Ajay kumar Medepalli"):
    #Ajay kumar Medepalli==>It's my name :P
    print i,



The output is shown in the screenshot

 Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Reverse a string in Python


Reverse a string in Python

How about:
Method-1
>>> 'hello world'[::-1]
'dlrow olleh'
 

This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.


Method-2
s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) approach is  
''.join(reversed(s)).

Method-3
c = list(string1)
c.reverse()
print ''.join(c)
 
 
 

 



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

The Python Slice Notation clear explaination

It's pretty simple really:


    a[start:end] # items start through end-1
    a[start:]    # items start through the rest of the array
    a[:end]      # items from the beginning through end-1
    a[:]         # a copy of the whole array


There is also the `step` value, which can be used with any of the above:

    a[start:end:step] # start through not past end, by step

The key point to remember is that the `:end` value represents the first value that is *not* in the selected slice. So, the difference beween `end` and `start` is the number of elements selected (if `step` is 1, the default).

The other feature is that `start` or `end` may be a *negative* number, which means it counts from the end of the array instead of the beginning. So:

    a[-1]    # last item in the array
    a[-2:]   # last two items in the array
    a[:-2]   # everything except the last two items


Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for `a[:-2]` and `a` only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

 Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Python Idioms

Source:
http://courses.cms.caltech.edu/cs11/material/python/misc/python_idioms.html

Every computer language has "idioms", that is, typical ways of accomplishing given tasks. Python is no exception. Some of the idioms are not that well known, so we thought we'd collect them here. We're also adding some material on other interesting features of the python language that you might miss when reading an introductory tutorial. These items are roughly in order of their difficulty and how commonly they're used.
WARNING! Some of this material is probably outdated. See the latest python documentation for, well, the latest python documentation.

See the documentation about...

These language features aren't really idioms, but you should know they exist:
  1. long integers
  2. optional arguments to functions
  3. keyword arguments to functions
  4. getattr and __getattr__ for classes
  5. operator overloading
  6. multiple inheritance
  7. docstrings
  8. the regular expression (re) library

Iterating through an array

Python's for statement is not like C's; it's more like a "foreach" statement in some other languages. If you need to use the loop index explicitly, the standard way is like this:
    array = [1, 2, 3, 4, 5]  # or whatever

    for i in range(len(array)):
        # Do something with 'i'.
This is quite clumsy. A somewhat cleaner way to do this is:
    array = [1, 2, 3, 4, 5]  # or whatever

    for i, e in enumerate(array):
        # Do something with index 'i' and its corresponding element 'e'.

Breaking out of an infinite loop

Python has no "do/while" loop like C does; it only has a while loop and a for loop. Sometimes you don't know in advance when the loop is going to be finished or you need to break out of the interior of a loop; the classic example is when iterating through the lines in a file. The standard idiom is this:
    file = open("some_filename", "r")

    while 1:   # infinite loop
        line = file.readline()
        if not line:  # 'readline()' returns None at end of file.
            break

        # Process the line.
This is admittedly clumsy, but it's still pretty standard. For files there is a nicer way:
    file = open("some_filename", "r")

    for line in file:
        # Process the line.
Note that python also has a continue statement (like in C) to jump to the next iteration of the current loop. Note also that the file() built-in function does the same thing as open() and is preferred nowadays (because the name of the constructor of an object should be the same as the name of the object).

Sequence multiplication

In python, lists and strings are both examples of sequences and many of the same operations (like len) work similarly for both of them. One non-obvious idiom is sequence multiplication; what this means is that to get a list of 100 zeroes, you can do this:
    zeroes = [0] * 100
Similarly, to get a string containing 100 spaces, you can do this:
    spaces = 100 * " "
This is often convenient.

xrange

Sometimes you want to generate a long list of numbers but you don't want to have to store all of them in memory at once. For instance, you might want to iterate from 0 to 1,000,000,000 but you don't want to store one billion integers in memory at once. Therefore, you don't want to use the range() built-in function. Instead, you can use the xrange function, which is a "lazy" version of range, meaning that it only generates the numbers on demand. So you could write:
    for i in xrange(1000000000):
        # do something with i...
and memory usage will be constant.

"Print to" syntax

Recently, the ">>" operator was overloaded so you can use it with the "print" statement as follows:
    print >> sys.stderr, "this is an error message"
The right-hand side of the ">>" operator is a file object. We personally consider this syntax to be a somewhat dubious addition to the language, but it's there, so you can use it if you want.

Exception classes

Back in the Bad Old Days, exceptions in python were simply strings. However, representing exceptions as classes has many advantages. In particular, you can subclass exceptions and selectively catch a particular exception or alternatively an exception and all of its superclasses. As a rule, exception classes are not very complicated. A typical exception class might look like this:
    class MyException:
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return `self.value`
and will be used like this:
    try:
        do_stuff()
        if something_bad_has_happened():
            raise MyException, "something bad happened"
    except MyException, e:
        print "My exception occurred, value: ", e.value

List comprehensions

This is a fairly new addition to python, inspired by the functional programming language Haskell (which is a very cool language, by the way; you should check it out). The idea is this: sometimes you want to make a list of objects with some particular quality. For instance, you might want to make a list of the even integers between 0 and 20. Of course, you could do this:
    results = []
    for i in range(20):
        if i % 2 == 0:
            results.append(i)
and results would hold the list [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] (20 is not included because range(20) goes from 0 to 19). But with list comprehensions, you can do the same thing much more concisely:
    results = [x for x in range(20) if x % 2 == 0]
Basically, the list comprehension is syntactic sugar for the explicit loop. You can also do more complex stuff like this:
    results = [(x, y)
               for x in range(10)
               for y in range(10)
               if x + y == 5
               if x > y]
and results will be set to [(3, 2), (4, 1), (5, 0)]. So you can put any combination of for and if statements inside the square brackets (and maybe more; see the documentation for details). Using this, you can encode the quicksort algorithm very concisely as follows:
    def quicksort(lst):
        if len(lst) == 0:
            return []
        else:
            return quicksort([x for x in lst[1:] if x < lst[0]]) + [lst[0]] + \
                   quicksort([x for x in lst[1:] if x >= lst[0]])
Neat, huh? ;-)

Functional programming idioms

For some time now, python has possessed a few functions and features that are usually only found in functional programming languages like lisp or ML. These include:
  1. The map, reduce, and filter higher-order functions. The map function takes a function and a number of lists as arguments (usually just one) and applies the function to each element of the list, collecting the elements together into a new list. For instance, if you have a list of strings that represent integers (possibly from command-line argument list) and want to convert them to a list of integers, you can do this:

        lst = ["1", "2", "3", "4", "5"]
        nums = map(string.atoi, lst)  # [1, 2, 3, 4, 5]
    
    You can use map with functions of two arguments as well if you provide two lists:

        def add(x, y):
            return x + y
    
        lst1 = [1, 2, 3, 4, 5]
        lst2 = [6, 7, 8, 9, 10]
        lst_sum = map(add, lst1, lst2)
    
        # lst_sum == [7, 9, 11, 13, 15]
    
    You can use reduce to reduce a list to a single value by applying a function to the first two elements, then apply the same function to the result of the first function call and the next element, etc. until all the elements have been processed. This is often a convenient way to do things like sum a list:
        lst = [1, 2, 3, 4, 5]
        sum_lst = reduce(add, lst)  # == 1 + 2 + 3 + 4 + 5 == 15
    
    where 'add' is as defined above. You can use filter to create a list which contains a subset of the elements of an input list. For example, to get all the odd integers between 0 and 100, you can do this:
        nums = range(0,101)  # [0, 1, ... 100]
    
        def is_odd(x):
            return x % 2 == 1
    
        odd_nums = filter(is_odd, nums)  # [1, 3, 5, ... 99]
    
  2. The lambda keyword. A lambda statement represents an anonymous function i.e. a function with no name. If you look at the previous examples for map, reduce and filter, you'll see that they all use trivial one-line functions that are only used once. These can be more concisely expressed as lambda expressions:

        lst1 = [1, 2, 3, 4, 5]
        lst2 = [6, 7, 8, 9, 10]
        lst_elementwise_sum = map(lambda x, y: x + y, lst1, lst2)
        lst1_sum = reduce(lambda x, y: x + y, lst1)
        nums = range(101)
        odd_nums = filter(lambda x: x % 2 == 1, nums)
    
    Note that you can also use variables inside a lambda which were defined outside the lambda. This is called "lexical scoping" and was only introduced officially into the python language as of python 2.2. It works like this:

        a = 1
        add_a = lambda x: x + a
        b = add_a(10)  # b == 11
    
    The 'a' referred to in the lambda is the 'a' defined on the previous line. If this seems obvious, good! It turns out that getting this right has taken the python developers much longer than it should have.
    For more details on lambda, see any textbook on lisp or scheme.
  3. The apply function. Functions are objects in python; you can manipulate them just like you do numbers or strings (store them in variables, etc.). Sometimes you have a function value that you want to apply to an argument list which you have generated in the program; you can use the apply function for this:

        # Sorry about the long variable names ;-)
    
        args = function_returning_list_of_numbers()
        f    = function_returning_a_function_which_operates_on_a_list_of_numbers()
    
        # You want to do f(arg[0], arg[1], ...) but you don't know how many
        # arguments are in 'args'.  For this you have to use 'apply':
    
        result = apply(f, args)
    
        # A trivial example:
        args = [1, 1]
        two = apply(lambda x, y: x + y, args)  # == 2
    

Generators and iterators

This is an advanced (but very cool) topic that we don't have the space to go into here. If you're curious, look it up in the python documentation.

PEPs

The python community is very active; the newsgroup "comp.lang.python" is full of discussions of what features to add to the language. Occasionally somebody writes up a more detailed and formal suggestion of this sort as a "python enhancement proposal" or "PEP". These are archived here. Note that not all proposed PEPs are accepted into the language. However, they give a good idea of what the top python programmers feel are promising future directions for the language.

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Friday, March 8, 2013

Interactive "_"




Interactive "_"

This is a really useful feature that surprisingly few people know.

In the interactive interpreter, whenever you evaluate an expression or call a function, the result is bound to a temporary name, _ (an underscore):

>>> 1 + 1
2
>>> _
2

_ stores the last printed expression.

When a result is None, nothing is printed, so _ doesn't change. That's convenient!

This only works in the interactive interpreter, not within a module.

It is especially useful when you're working out a problem interactively, and you want to store the result for a later step:

>>> import math
>>> math.pi / 3
1.0471975511965976
>>> angle = _
>>> math.cos(angle)
0.50000000000000011
>>> _
0.50000000000000011

Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

Swap Values(variables,lists) in python



In other languages:
temp = a
a = b
b = temp


In Python:
b, a = a, b
 
 
Perhaps you've seen this before. But do you know how it works?
  • The comma is the tuple constructor syntax.
  • A tuple is created on the right (tuple packing).
  • A tuple is the target on the left (tuple unpacking).
The right-hand side is unpacked into the names in the tuple on the left-hand side.
This is vald for lists aswell


Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.