## Saturday, March 16, 2013

### 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.