Skip to content

Commit c492f5b

Browse files
committed
Pycon India 2013 talk
1 parent 4503d45 commit c492f5b

32 files changed

+391680
-0
lines changed

pyconindia2013/.ipynb_checkpoints/idiomatic_workshop-checkpoint.ipynb

Lines changed: 952 additions & 0 deletions
Large diffs are not rendered by default.

pyconindia2013/examples/caching.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
""" Caching decorator example """
2+
3+
def cache(f):
4+
results = {}
5+
def wrapper(*args):
6+
if args in results:
7+
print 'From cache'
8+
return results[args]
9+
res = f(*args)
10+
results[args] = res
11+
return res
12+
13+
return wrapper
14+
15+
@cache
16+
def factorial(n):
17+
""" Factorial of a number """
18+
19+
return reduce(lambda x,y: x*y, range(1,n+1))
20+
21+
if __name__ == "__main__":
22+
print factorial(5)
23+
print factorial(10)
24+
print factorial(5)

pyconindia2013/examples/decorator.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
""" Simple decorator for type checking """
2+
3+
def isNumber(f):
4+
def wrapper(*args):
5+
if not all(type(item) in (int, float) for item in args):
6+
raise TypeError,'Wrong type!'
7+
return f(*args)
8+
return wrapper
9+
10+
@isNumber
11+
def add(x,y):
12+
return x+y
13+
14+
@isNumber
15+
def mul(x,y):
16+
return x*y
17+
18+
if __name__ == "__main__":
19+
print add(3, 4)
20+
print mul(5,6)
21+
add(4, 'me')

pyconindia2013/examples/grouping.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
""" Grouping with dictionaries """
2+
3+
import collections
4+
5+
fruit_bag = ['apple','grapes','apple','mango','mango','apple',
6+
'banana','orange','guava','sapota','apple','orange',
7+
'litchi','strawberry','lemon','apple','grapes']
8+
9+
def group_solution_a():
10+
11+
fruit_group = {}
12+
for fruit in fruit_bag:
13+
if fruit not in fruit_group:
14+
fruit_group[fruit] = 0
15+
fruit_group[fruit] += 1
16+
17+
return fruit_group
18+
19+
def group_solution_b1():
20+
21+
fruit_group = {}
22+
for fruit in fruit_bag:
23+
fruit_group[fruit] = fruit_group.get(fruit, 0) + 1
24+
25+
return fruit_group
26+
27+
def group_solution_b2():
28+
29+
fruit_group = collections.defaultdict(int)
30+
for fruit in fruit_bag:
31+
fruit_group[fruit] += 1
32+
33+
return fruit_group
34+
35+
if __name__ == "__main__":
36+
print group_solution_a()
37+
print group_solution_b1()
38+
print group_solution_b2()

pyconindia2013/examples/indent.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
""" Indenting context manager """
2+
3+
from contextlib import contextmanager
4+
5+
spaces = 0
6+
7+
@contextmanager
8+
def indent():
9+
global spaces
10+
spaces += 1
11+
print '\t'*spaces,
12+
yield
13+
spaces -= 1
14+
15+
class Indent(object):
16+
17+
def __init__(self):
18+
self.spaces = 0
19+
20+
def __enter__(self):
21+
self.spaces += 1
22+
print '\t'*self.spaces,
23+
24+
def __exit__(self, type, value, traceback):
25+
self.spaces -= 1
26+
27+
if __name__ == "__main__":
28+
for i in range(2,5):
29+
with indent():
30+
print 'This is number',i
31+
with indent():
32+
print 'This is its square',i*i
33+
34+
for i in range(2,5):
35+
indenter = Indent()
36+
with indenter:
37+
print 'This is number',i
38+
with indenter:
39+
print 'This is its square',i*i
40+
41+
42+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
""" Itertools examples """
2+
3+
import itertools
4+
import collections
5+
import operator
6+
import os
7+
8+
# itertools.count can provide an infinite counter.
9+
for i in itertools.count(step=1):
10+
print i
11+
if i == 20: break
12+
13+
# itertools.cycle cycles through an iterator
14+
# Will keep printing 'python'
15+
16+
for i,j in enumerate(itertools.cycle(['python'])):
17+
print j
18+
if i==10: break
19+
20+
# itertools.repeat keeps repeating from an iterator
21+
# Will keep producing range(10) when called in a loop
22+
print itertools.repeat(range(10))
23+
24+
# chain returns elements from 'n' iterators until they are exhausted.
25+
26+
# Make a dictionary of count of letters in a list of strings.
27+
birds = ['parrot','crow','dove','peacock','macaw','hen']
28+
frequency = collections.defaultdict(int)
29+
for letter in itertools.chain(*birds):
30+
frequency[letter] += 1
31+
32+
print frequency
33+
# takewhile returns elements as long as a predicate(condition) is True.
34+
35+
# Give list of favorable countries
36+
countries=['U.S','U.K','India','Australia','Malaysia','Pakistan']
37+
print list(itertools.takewhile(lambda x: x != 'Pakistan', countries))
38+
39+
40+
# dropwhile keeps dropping elements while predicate is True.
41+
42+
# Produce iterator of files > a minimum size in current folder.
43+
files = sorted([(file, os.path.getsize(file)) for file in os.listdir(".")],
44+
key=operator.itemgetter(1))
45+
print list(itertools.dropwhile(lambda x: x[1] < 8192, files))

pyconindia2013/examples/matrix.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
""" Matrix class as an example for zip to transpose lists """
2+
3+
import random
4+
5+
class MatrixA:
6+
def __init__(self,m,n):
7+
self.m, self.n = m,n
8+
self.rows=[[random.randrange(1,10) for j in range(n)] for i in range(m)]
9+
10+
def __str__(self):
11+
s='\n'.join([' '.join([str(item) for item in row]) for row in self.rows])
12+
return s + '\n'
13+
14+
def transpose(self):
15+
16+
rows2 = [[0]*self.m for i in range(self.n)]
17+
for x in range(self.m):
18+
for y in range(self.n):
19+
rows2[y][x] = self.rows[x][y]
20+
21+
self.rows = rows2
22+
# Swap m and n
23+
tmp = self.m
24+
self.m = self.n
25+
self.n = tmp
26+
27+
class MatrixB(MatrixA):
28+
29+
def transpose(self):
30+
self.m, self.n = self.n, self.m
31+
self.rows = zip(*self.rows)
32+
33+
if __name__ == "__main__":
34+
m = MatrixA(3,4)
35+
print m
36+
m.transpose()
37+
print m
38+
39+
m = MatrixB(3,4)
40+
print m
41+
m.transpose()
42+
print m

pyconindia2013/examples/primes.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
""" Prime number generation """
2+
3+
import random
4+
from itertools import cycle,imap,dropwhile,takewhile
5+
6+
def is_prime(n):
7+
""" Is the number 'n' prime ? """
8+
prime = True
9+
for i in range(2,int(pow(n,0.5))+1):
10+
if n % i==0:
11+
prime = False
12+
break
13+
return prime
14+
15+
def prime_solution_a(n):
16+
17+
count, numbers = 0, []
18+
19+
while count<n:
20+
num = random.randrange(1,1000)
21+
if num not in numbers and is_prime(num):
22+
numbers.append(num)
23+
count += 1
24+
25+
return numbers
26+
27+
def prime_solution_b(n):
28+
29+
sieve = lambda n: not any(n % num==0 for num in range(2, int(pow(n,0.5))+1))
30+
nums = set()
31+
32+
for i in takewhile(lambda x:len(nums)<=20,
33+
dropwhile(sieve,imap(random.randrange,cycle([1]),
34+
cycle([100])))):
35+
nums.add(i)
36+
37+
return nums
38+
39+
if __name__ == "__main__":
40+
print prime_solution_a(20)
41+
print prime_solution_b(20)

pyconindia2013/examples/selectors.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
""" Selecting values from an iterable using multiple conditions """
2+
3+
import itertools
4+
import collections
5+
6+
cutoffs = {'maths': 40, 'elec': 35,
7+
'lab' : 45, 'cs': 30,
8+
'phy' : 25, 'chem': 35}
9+
10+
marks_dict = { 'Karan': {'maths': 39, 'elec': 78, 'cs': 83,
11+
'lab': 32, 'phy': 60, 'chem': 91},
12+
'Arjun': {'maths': 49, 'elec': 45, 'lab': 53,
13+
'cs': 43, 'phy': 86, 'chem': 54},
14+
'Rancho': {'maths': 86, 'elec': 85, 'cs': 95,
15+
'lab': 83, 'phy': 91, 'chem': 75},
16+
'Raju': {'maths': 32, 'elec': 36, 'lab': 50,
17+
'cs': 26, 'phy': 35, 'chem': 41},
18+
'Farhan': {'maths': 30, 'elec': 56, 'cs': 21,
19+
'lab': 33, 'phy': 27, 'chem': 56}}
20+
21+
def find_passed(marks_dict,cutoffs):
22+
23+
# Initialize dictionary
24+
pass_dict = {subject:[] for subject in cutoffs}
25+
26+
for subject, cutoff in cutoffs.iteritems():
27+
for student, student_marks in marks_dict.iteritems():
28+
if student_marks[subject] >= cutoff:
29+
pass_dict[subject].append(student)
30+
31+
return pass_dict
32+
33+
def find_passedi(marks_dict, cutoffs):
34+
35+
# defaultdict
36+
pass_dict = collections.defaultdict(list)
37+
38+
# Dict comprehensions
39+
selectors = {(subject, student) :cutoffs[subject]<=val[subject] for subject in cutoffs for student,val in marks_dict.items()}
40+
# itertools compress
41+
passd = list(itertools.compress(selectors.keys(), selectors.values()))
42+
43+
for subject,student in passd:
44+
pass_dict[subject].append(student)
45+
46+
return pass_dict
47+
48+
if __name__ == "__main__":
49+
passd = find_passed(marks_dict, cutoffs)
50+
print 'Passed =>',passd
51+
52+
passd = find_passedi(marks_dict, cutoffs)
53+
print 'Passed =>',passd

pyconindia2013/examples/sentinel.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
""" Checking for sentinel values """
2+
3+
from itertools import takewhile,imap,cycle
4+
import functools
5+
import random
6+
7+
def solution_a(sentinel):
8+
9+
# Solution A
10+
# Append numbers till you hit sentinel
11+
nums = []
12+
13+
while True:
14+
num = random.randrange(1, 100)
15+
if num == sentinel: break
16+
nums.append(num)
17+
18+
return nums
19+
20+
def solution_b1(sentinel):
21+
22+
func = functools.partial(random.randrange, 1, 100)
23+
nums = []
24+
25+
for num in iter(func, sentinel):
26+
nums.append(num)
27+
28+
return nums
29+
30+
def solution_b2(sentinel):
31+
return list(takewhile(lambda x: x!=sentinel,
32+
imap(random.randrange, cycle([1]), cycle([100]))))
33+
34+
35+
if __name__ == "__main__":
36+
print solution_a(41)
37+
print solution_b1(41)
38+
print solution_b2(41)

pyconindia2013/examples/timing.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
""" Timing tests for punctuation replace functions """
2+
3+
from itertools import imap, chain, ifilter
4+
from functimer import functimer
5+
6+
import string
7+
import re
8+
9+
punc = string.punctuation
10+
11+
def repl_listcomp(strings):
12+
return [''.join(i for i in s if i not in punc) for s in strings]
13+
14+
def repl_functional(strings):
15+
return map(lambda x: ''.join(i for i in x if i not in punc),strings)
16+
17+
def repl_itertools1(strings):
18+
return list(imap(lambda x: ''.join(i for i in x if i not in punc),strings)
19+
20+
def repl_itertools2(strings):
21+
return ''.join(ifilter(lambda x: x not in punc, chain(*strings)))
22+
23+
def repl_re(strings):
24+
return [re.sub('[' + punc + ']+', '', x) for x in strings]
25+
26+
if __name__ == "__main__":
27+
strings = ['#I love,@,#',' PyCon India..$#,']
28+
print 'Listcomp =>',functimer(repl_listcomp, strings)
29+
print 'Functional =>',functimer(repl_functional, strings)
30+
print 'Itertools #1 =>',functimer(repl_itertools1, strings)
31+
print 'Itertools #2 =>',functimer(repl_itertools2, strings)
32+
print 'Re =>',functimer(repl_re, strings)

0 commit comments

Comments
 (0)