Tuesday, March 19, 2013

Sets in python


A set is an unordered collection of zero or more immutable Python data objects. Sets do not allow duplicates and are written as comma-delimited values enclosed in curly braces. The empty set is represented by set(). Sets are heterogeneous, and the collection can be assigned to a variable as below.
1
2
3
4
5
6
>>> {3,6,"cat",4.5,False}
{False, 4.5, 3, 6, 'cat'}
>>> mySet = {3,6,"cat",4.5,False}
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>>
Even though sets are not considered to be sequential, they do support a few of the familiar operations presented earlier. Table  reviews these operations and the following session gives examples of their use.
Operation Name Operator Explanation
membership in Set membership
length len Returns the cardinality of the set
| aset | otherset Returns a new set with all elements from both sets
& aset & otherset Returns a new set with only those elements common to both sets
- aset - otherset Returns a new set with all items from the first set not in second
<= aset <= otherset Asks whether all elements of the first set are in the second
Operations on a Set in Python
1
2
3
4
5
6
7
8
9
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>> len(mySet)
5
>>> False in mySet
True
>>> "dog" in mySet
False
>>>
Sets support a number of methods that should be familiar to those who have worked with them in a mathematics setting. Table  provides a summary. Examples of their use follow. Note that union, intersection, issubset, and difference all have operators that can be used as well.
Method Name Use Explanation
union aset.union(otherset) Returns a new set with all elements from both sets
intersection aset.intersection(otherset) Returns a new set with only those elements common to both sets
difference aset.difference(otherset) Returns a new set with all items from first set not in second
issubset aset.issubset(otherset) Asks whether all elements of one set are in the other
add aset.add(item) Adds item to the set
remove aset.remove(item) Removes item from the set
pop aset.pop() Removes an arbitrary element from the set
clear aset.clear() Removes all elements from the set


aset.clear() Removes all elements from the set
Methods Provided by Sets in Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> mySet
{False, 4.5, 3, 6, 'cat'}
>>> yourSet = {99,3,100}
>>> mySet.union(yourSet)
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet | yourSet
{False, 4.5, 3, 100, 6, 'cat', 99}
>>> mySet.intersection(yourSet)
{3}
>>> mySet & yourSet
{3}
>>> mySet.difference(yourSet)
{False, 4.5, 6, 'cat'}
>>> mySet - yourSet
{False, 4.5, 6, 'cat'}
>>> {3,100}.issubset(yourSet)
True
>>> {3,100}<=yourSet
True
>>> mySet.add("house")
>>> mySet
{False, 4.5, 3, 6, 'house', 'cat'}
>>> mySet.remove(4.5)
>>> mySet
{False, 3, 6, 'house', 'cat'}
>>> mySet.pop()
False
>>> mySet
{3, 6, 'house', 'cat'}
>>> mySet.clear()
>>> mySet
set()
>>>
 From:http://interactivepython.org/courselib/static/pythonds/Introduction/introduction.html

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.

Monday, March 18, 2013

Strings in Python

Before you read my stuff have a look at official documentation.Get some vague idea and come back here.
Check the pleac project...I love that site,last but not least tutorials point,even then you don't understand you're in right place. :)).

1.Introduction to strings.



#!usr/bin/env/python
###############################################################################
mystr = "\n"        #a new line character.

mystr_raw=r"\n"     #two characters,\ and n.
print mystr_raw 
print "Length of mystr_raw:",len(mystr_raw),'\n'

###############################################################################
mystr_dq="Matthew 'Mark' Luke" #Single quote inside double quote.
print mystr_dq+"\n"            #'+' is used for adding(concatenating the strings.)

mystr_sq='Matthew "Mark" Luke' #dq(double quote) inside sq(single quote).
print mystr_sq+"\n"           

################################################################################
mystr_1_multiplelines="""These examples are
taken from pleac project.Really inspiring"""    #used triple double quotes.
print mystr_1_multiplelines+'\n'

mystr_2_multiplelines='''These examples are     
taken from pleac project.Really inspiring'''    #used triple single quotes.
print mystr_2_multiplelines+'\n'
################################################################################


Output:

\n
Length of mystr_raw: 2
Matthew 'Mark' Luke
Matthew "Mark" Luke
These examples are
taken from pleac project.Really inspiring
These examples are
taken from pleac project.Really inspiring



2.String Slicing.


#!usr/bin/env/python
"""Python strings are immutable once created they cann't be modified"""
mystr="Python is awesome!!!!"#P(0 or -21) y(1 or-20) t(2 or 19)....awesome(10,11,12,13,14,15,16 or -11,-10...-5 )
#     +012345678901234567890  Indexing forwards  (left to right)
#      109876543210987654321- Indexing backwards (right to left)
print'Printing..the full string ===>',mystr +'\n'

print mystr[0] +'\n'  #using forward indexing to print 'P'.
#Output:P
print mystr[-21]+'\n' #using backward indexing to print 'P'
#Output:P
print mystr[-1],mystr[len(mystr)-1]+'\n' #length=21,Since indexing is started at 0 we'll have one less 
#len(mystr)=lenght of the string.
""" 
mystr[a:b]
Case 1:Forward Indexing 
0<=a<b<=(len(mystr)-1)
mystr[a:b]==>Start from a till b-1
mystr[:b]==>assume a=0,start from a till b-1
mystr[a:]==>start from a till end.
Case2:Backward Indexing===>here we are using negative numbers,So do look
at couple of examples.
-len(mystr)<=a<b<=-1
"""
print mystr[0:5]+'\n' #start from 0 to 5-1==>(Pytho)
print mystr[1:]+'\n'  #start from one till end==>(ython is awesome!!!!)
print mystr[:18]+'\n' #start from 0 to 18-1==>(Python is awesome!)
print mystr[-20:-5]+'\n'#start from -20 till -5==>(ython is awesom)
#mystr[-5:-20] will return an empty string.
print mystr[-5:]+'\n' #start from -5(e) till end(!)===>(e!!!!)
print mystr[:-18]     #start from -21 till (-18-1=-19)===>(Pyt)

mystr = mystr[:9] + " easier than C" + mystr[17:]
print mystr
 

Output: 

Printing..the full string ===> Python is awesome!!!!
P
P
! !
Pytho
ython is awesome!!!!
Python is awesome!
ython is awesom
e!!!!
Pyt
Python is easier than C!!!!

3.String Methods.

 
#!usr/bin/env/python
"""String Methods """

mystr="Try 'import this' in your python interpreter"
print mystr.count('in')
#Counts number of occurences of 'in'.
#Output:2 
print mystr.find('i') # index of first occurence of i==&gt;5('i' in import)
print mystr.find('in')#index of first occurence of in==&gt;18(returns position of i in in i.e 18)
print mystr.find('in',19)#start from 19 and find first occurence of in
#There's an 'in' in interpreter.
print "Ajay".find('a')
#Output is 2

print "AJAY".lower()
#Return a copy of AJAY, but with upper case letters converted to lower case.
print "ajay".upper()

print mystr.replace("import this","import string")
#Dude strings do not change in python....but what happened right now?? It just return a copy of mystr.

print mystr
#mystr is same unmodified.

import string  #All string methods can be done like this.Try lower,upper and find in the simlar way.
print string.replace(mystr,"import this","import string")

"""Below are some useful oneline methods.
Replace str with a variable mystr or strings like "Ajay is dumb"."""

# str.capitalize()
print mystr.capitalize()
"""Return a copy of the string with its first character capitalized and the rest lowercased."""

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""

#str.split()==&gt;Creates a list.

print "Ajay is dumb,idiot,mining engineer".split()
#Split after a whitespace(space)
#Output:['Ajay', 'is', 'dumb,idiot,mining', 'engineer']

print "Ajay is dumb,idiot,mining engineer".split(',')
#splits after a coma ',' and forms a list of words.
#Output:['Ajay is dumb', 'idiot', 'mining engineer']

print "Ajay is dumb,idiot,mining engineer".split(None,1)
#None is nothing but your telling to split after whitespace.but number of splits should be one.
#In place of None you can use ',' or anything.In place of 1 you can use any number
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.strip()
#Return a copy of the string with the leading and trailing characters removed.
print "    Ajay loves space(white space)   ".strip()
#Output:Ajay loves space(white space)
print 'www.example.com'.strip('cmowz.')
#Output:example
#??? What happened let's try some more examples.
print 'www.example.com'.strip('cmoz.')
#Output:www.example
#'cmoz.'==&gt;'.comz'===&gt;'.com' can be removed because it's in a sequence.z is ignored.
print 'www.example.com'.strip('cmz.')
#Output:www.example.co
#'.cmz'==&gt;'m'==&gt;So m is removed.
"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.join
seq = ['1','2','3','4','5']   #'1','2'....are strings.
print '+'.join(seq)
#Output:1+2+3+4+5

print '*_*'.join("Ajay's blog is the dumbest".split())
#Output:Ajay's*_*blog*_*is*_*the*_*dumbest
#Just combined the split and join.To understand this first we did a split on the string.
# 1)"Ajay's blog is the dumbest".split() 
#2)later i joined the list elements using str.join

"""----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------"""
#str.partition
print("Python programmers are awesome :) ".partition('are'))
#Output:('Python programmers ', 'are', ' awesome :) ')
#It's gives a tuple of 3 elements.
#1)Everything before the partition element==&gt;here it's "Python programmers"
#2)Partition element itself.===&gt;'are'
#3)Everything after Partition element.==&gt;'awesome'

#Check out the original documentation for more examples and methods. 

Output:
2
5
18
33
2
ajay AJAY
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
Try 'import string' in your python interpreter
Try 'import this' in your python interpreter
['Ajay', 'is', 'dumb,idiot,mining', 'engineer']
['Ajay is dumb', 'idiot', 'mining engineer']
['Ajay', 'is dumb,idiot,mining engineer']
Ajay loves space(white space)
example
www.example
www.example.co
1+2+3+4+5
Ajay's*_*blog*_*is*_*the*_*dumbest
('Python programmers ', 'are', ' awesome :) ')

Check out the questions from SO,some day you gonna be same place so practice them.One more i missed here is string formatting,translate method which are important.I'll be posting when i'm free :)).

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.

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.

Iterables and Generators,yield explained

http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained
This would be the best explanation.

To understand what yield does, you must understand what generators are. And before generators come iterables.

Iterables

When you create a list, you can read its items one by one, and it's called iteration:
>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3
Mylist is an iterable. When you use a comprehension list, you create a list, and so an iterable:
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4
Everything you can use "for... in..." on is an iterable: lists, strings, files... These iterables are handy because you can read them as much as you wish, but you store all the values in memory and it's not always what you want when you have a lot of values.

Generators

Generators are iterables, but you can only read them once. It's because they do not store all the values in memory, they generate the values on the fly:
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
...    print(i)
0
1
4
It just the same except you used () instead of []. BUT, you can not perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1 and ends calculating 4, one by one.

Yield

Yield is a keyword that is used like return, except the function will return a generator.
>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
...     print(i)
0
1
4
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is bit tricky :-)
Then, your code will be run each time the for uses the generator.
Now the hard part:
The first time your function will run, it will run from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to ends, or because you do not satisfy a "if/else" anymore.

Python's itertools.tee() explained with examples

Input:
 
#!usr/bin/env/python
from itertools import *
r=islice(count(),5)
iterator_1,iterator_2=tee(r)
print "iterator_1,iterator_2:",list(iterator_1),list(iterator_2)
#you can create n number of iterators,but default is set to tw0 iterators.
print"\nExample 2:"
r_2=islice(count(),5)
i1,i2=tee(r_2)
print 'r_2:',
for i in r_2:
 print i,
 if i>1:
  break
print
print'i1,i2:',list(i1),list(i2)
Output:
 
iterator_1,iterator_2: [0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

Example 2:
r_2: 0 1 2
i1,i2: [3, 4] [3, 4]
 

 




 Itertools is a great library, but some methods definitely receive more attention than others – for instance, I’d wager that chain is a lot more well-known than tee. Python’s documentation describes tee as follows:

Return n independent iterators from a single iterable.
It also adds this caveat:
Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.(Example-2 is Illustrated).
Caution:Don't read the rest....you may feel boring.Learn about Iterators,Generators and come back.

More on this is covered in this url: http://jezng.com/2012/06/inside-python-tee/



However, the documentation doesn’t really explain why you might want to use tee, instead of copying the iterable n times. The short answer is that tee() uses some heuristics and strategies to make the generation of these n iterators more memory efficient. This article will peek inside Python’s internals and explore these strategies in more detail.

Iterables, Iterators, and the Iterator Protocol

To understand the basis for the optimizations, it is essential to know how Python’s iterator protocol works. (More experienced Pythonistas might want to skim this section – it’s here for completeness.)
Iterables are Python objects that define an __iter__() method, which, when called, returns an iterator. Iterators define the __iter__() method as well, but implement it by simply returning the iterator itself. Iterators also implement a next() method, which returns the next element in a sequence. To signal the end of a sequence, next() raises a StopIteration exception. Any object that implements both __iter__ and next in the aforementioned manner is said to implement the iterator protocol.
To actually use these iterators and iterables, we turn to Python’s classic for item in sequence loop. Here, sequence can be either an iterator or an iterable – it doesn’t matter, because the loop will begin by implicitly invoking seq’s __iter__ method, which will return an iterator. Now, on each round through the loop, the Python interpreter will invoke the iterator’s next method and assign it to item, and will continue to do so until next raises StopIteration.
Perhaps you are wondering why Python makes the distinction between iterables and iterators, and why iterators don’t have prev or rewind methods. These two questions are in fact related. It can be expensive or complicated to implement these other methods – for instance, reading sequentially forwards from a file corresponds simply to fread() in C, but rewinding to the start is a more expensive fseek call, and there is no efficient way to read sequentially in reverse.
More importantly, prev and rewind are not essential for iteration – they can be built upon the primitive next method. For instance, if we really wish to access the earlier contents of the file in Python, we could buffer the earlier results ourselves. However, buffering all the earlier values is generally inefficient and wasteful: many programs have no need to access earlier values of an iterator, and those that do tend to limit themselves to one or two elements before the current one. Rewinding an iterable is a more common use case, but the same thing can be achieved by obtaining an entirely new iterator that points to the start of the sequence. To do that, we need a factory that produces iterators – which is exactly what an iterable is.
In sum, Python’s iterator protocol is simple to implement, and it works well for the common use case of for .. in loops.

Sometimes Buffering is Useful

The starkness of Python’s iterator design means that more complicated use cases will need to build their own abstractions on top of it. Fortunately, its simplicity also means that it is easy to build upon.
tee() is one such abstraction, built to efficiently create n independent iterators. Consider file I/O again: we might not want to create n file iterations by calling fopen() over and over, especially if n is large. Nor would we want to copy iterators that do heavy computation each time we called next(). In both cases buffering is a better solution, and this is what tee does, collating in one central list the values returned by the original iterator. Its return value consists of n tee iterator objects,1 each of which stores a single integer index that indicates the next element it should return from the list. The list itself is populated lazily – whenever any of the n iterators asks for a value at an index that is not yet in the buffer, tee() calls next on the underlying iterator, then caches and returns the new value.
With this implementation detail in mind, the reasoning behind the documentation’s caveat becomes clearer – using the iterator outside of tee() would cause some (or all) values to be lost from the cache.

Sometimes Buffering is Not Useful

Buffering is not always the most efficient way to create n independent iterators. For example, next could be a computationally cheap function, and it would be more efficient for us to just copy it n times. We can indicate this fact by defining a __copy__ method on our iterator.2 If tee() detects the presence of __copy__, it will copy the iterator instead of doing buffering. Moreover, it will only do this copying n - 1 times – the last iterator will simply be the original one that was passed in! Since the original iterator should never be used after being passed to tee(), this makes perfect sense; the end result will appear the same to the library consumer.
In fact, tee objects themselves implement __copy__! Since any tee object is backed by a central buffer, the most efficient way to duplicate one is to have the copy point to the same buffer. So not only does tee duplicate any iterator efficiently, it also ensures that future duplications are efficient.
Notably, as a consequence of this optimization, passing in a non-tee object that implements __copy__ will return a tuple of copies of that object, not tee objects. In practice, the type of the object should not matter as long as one sticks to using it solely as an iterator.

Efficient Buffering: The gritty details

If the total number of items generated by the iterator is very large, storing all of the generated values might take up a lot of memory. If we can keep track of all the indices of the tee objects generated by a tee() function call, we can delete old values once all of the indices have passed it. (Since iterators can only progress forwards, we know that these values will never be used again.) With CPython’s reference counting, this is actually quite simple: the buffer can be implemented as a singly linked list, with each tee object holding a pointer to the next element that it will return. As a natural consequence, once the last tee iterator is done with a buffer element, the element’s reference count goes to zero and it gets garbage collected.

Tee linked list buffer with 3 tee iterators using it. The grey cell has no pointers to it, so the reference counting mechanism will free it up.
However, linked lists perform worse than arrays in terms of memory fragmentation. Moreover, they incur lots of overhead in memory allocations and deallocations. As a compromise, CPython uses linked arrays – a linked list with arrays as individual elements. Moreover, these arrays are sized such that the entire array element is 64 bits in size, fitting nicely into cache lines.

A Python Implementation

Python’s documentation gives pure-Python implementation of tee(), but it simplifies things and leaves out the buffering and copy semantics. I’ve written up a slightly more involved one that reflects the optimizations described above. Unlike the version in the docs, this implementation passes the standard library’s test suite. It still makes some concessions to simplicity: for instance, buffering uses a single list, instead of the linked arrays described above.
    class TeeIterator(object):

        def __new__(cls, tee_data):
            if isinstance(tee_data, TeeData):
                self = super(TeeIterator, cls).__new__(cls)
                self.tee_data = tee_data
            else:
                self = TeeIterator.from_iterable(tee_data)
            self.index = 0
            return self

        def __copy__(self):
            return TeeIterator(self.tee_data)

        def __iter__(self):
            return self

        def next(self):
            rv = self.tee_data[self.index]
            self.index += 1
            return rv

        @classmethod
        def from_iterable(cls, iterable):
            if isinstance(iterable, cls):
                return iterable.__copy__()
            tee_data = TeeData(iter(iterable))
            return TeeIterator(tee_data)

    class TeeData(object):

        def __init__(self, iterator):
            self.iterator = iterator
            self.buffer = []

        def __getitem__(self, index):
            if index == len(self.buffer):
                self.buffer.append(next(self.iterator))
            return self.buffer[index]

    def tee(iterable, n=2):

        if n < 0:
            raise ValueError("n must be >= 0")
        elif n == 0:
            return ()

        if hasattr(iterable, '__copy__'):
            copyable = iterable
        else:
            copyable = TeeIterator.from_iterable(iterable)

        result = [ copyable ]

        for i in xrange(1, n):
            result.append(copyable.__copy__())

        return tuple(result)

  1. Yes, the returned objects are called tee as well, but they are completely distinct from the itertools.tee() function.
  2. copy.copy() looks for this method too.
http://code.activestate.com/recipes/305588-simple-example-to-show-off-itertoolstee/








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.

izip() explained

Input:Give two Iterators Output:Get a tuple of combined iterators.
#!usr/bin/env/python
"""izip() returns an iterator(lists,strings,tuples,files are iterators geneally.)
 that combines the elements of several iterators 
 into tuples."""
from itertools import *
 #Example 1(with equal sized lists)
print "Equal Sized lists:"
#==>Out put will always be a tuple for izip()

for i in izip([1,2,3],['a','b','c']):
  print i,
print "\nUnEqual Sized lists:"
#==>Out put will always be a tuple for izip()
for i in izip([1,2,3],['x','y']):
  print i,
print "\nUnequal Sized tuples:"
#==>Out put will always be a tuple for izip()
for i in izip((1,2,3,4,5),(99,100)):
  print i,
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.

Python: Nicest way to pad zeroes to string

Python: Nicest way to pad zeroes to string

Strings:

>>> n = '4'
>>> print n.zfill(3)
>>> '004'
 
And for numbers:
>>> n = 4
>>> print '%03d' % n
>>> 004
>>> print "{0:03d}".format(4)  # python >= 2.6
>>> 004
>>> print("{0:03d}".format(4))  # python 3
>>> 004
String formatting documentation.

 

 








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 Random String Generation

Answer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
...    return ''.join(random.choice(chars) for x in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.
string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a generator expression to create a list of 'n' elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for x in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for x in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:
>>> [random.choice('abcde') for x in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for x in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for x in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for x in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for x in range(3))
'dac'





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.

Sunday, March 10, 2013

Python FizzBuzz oneliner soluton

Solution-1
for x in range(100):print x%3/2*'Fizz'+x%5/4*'Buzz'or x+1
"""These one liners are not preferred,can be used when min num chars are to be used(when ur being graded based 
on nums of chars"""
Solution-2

for i in range(1,101):print"FizzBuzz"[i*i%3*4:8--i**4%5]or i


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.