Skip to content

Commit 4bb1646

Browse files
committed
functional programming done
1 parent 1b54641 commit 4bb1646

File tree

12 files changed

+365
-0
lines changed

12 files changed

+365
-0
lines changed

decorator.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import functools
2+
3+
def log(func):
4+
@functools.wraps(func)
5+
def wrapper(*args,**kw):
6+
print("call %s():" % func.__name__)
7+
return func(*args, **kw)
8+
return wrapper
9+
10+
@log
11+
def now():
12+
print("2015-3-25")
13+
14+
now()
15+
print(now.__name__)
16+
17+
def logger(text):
18+
def decorator(func):
19+
@functools.wraps(func)
20+
def wrapper(*args,**kw):
21+
print("%s %s():" % (text, func.__name__))
22+
return func(*args,**kw)
23+
return wrapper
24+
return decorator
25+
26+
@logger("DEBUG")
27+
def today():
28+
print("2015-3-25")
29+
30+
today()
31+
print(today.__name__)
32+
33+
def beginend(func):
34+
def wrapper(*args,**kw):
35+
print("call %s():" % func.__name__)
36+
func(*args,**kw)
37+
print("end %s():" % func.__name__)
38+
return
39+
return wrapper
40+
41+
@beginend
42+
def printdate():
43+
print("2015-7-3")
44+
45+
printdate()

do_filter.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def is_odd(n):
2+
return n%2==1
3+
4+
L=range(100)
5+
6+
print(list(filter(is_odd,L)))
7+
8+
def not_empty(s):
9+
return s and s.strip()
10+
11+
print(list(filter(not_empty,["A", "", "B", None, "C", " "])))
12+
13+
def is_palindrome(n):
14+
s=str(n)
15+
return s==s[::-1]
16+
17+
print(list(filter(is_palindrome,range(1,1000))))

do_generator.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
s=(x*x for x in range(5))
2+
print(s)
3+
for x in s:
4+
print(x)
5+
6+
def fib(max):
7+
n,a,b=0,0,1
8+
while n< max:
9+
yield b
10+
a,b=b,a+b
11+
n=n+1
12+
return "done"
13+
14+
15+
f=fib(10)
16+
print("fib(10):",f)
17+
for x in f:
18+
print(x)
19+
20+
21+
g=fib(5)
22+
while 1:
23+
try:
24+
x=next(g)
25+
print("g:",x)
26+
except StopIteration as e:
27+
print("Generator return value:", e.value)
28+
break
29+
30+
31+
32+
def triangles():
33+
y=[1]
34+
yield y
35+
while 1:
36+
y=[y[i]+y[i+1] for i in range(0,len(y)-1)]
37+
y.append(1)
38+
y.insert(0,1)
39+
yield y
40+
41+
n=0
42+
for t in triangles():
43+
print(t)
44+
n=n+1
45+
if n==10:
46+
break

do_iter.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from collections import Iterable, Iterator
2+
3+
def g():
4+
yield 1
5+
yield 2
6+
yield 3
7+
8+
print("Iterable? [1,2,3]:", isinstance([1,2,3],Iterable))
9+
print("Iterable? \'abc\':", isinstance('abc',Iterable))
10+
print("Iterable? 123:", isinstance(123,Iterable))
11+
print("Iterable? g():", isinstance(g(),Iterable))
12+
13+
14+
print("Iterator? [1,2,3]:", isinstance([1,2,3],Iterator))
15+
print("Interator? iter([1,2,3]):", isinstance(iter([1,2,3]),Iterator))
16+
print("Iterator? \'abc\':", isinstance('abc',Iterator))
17+
print("Itertor? 123:", isinstance(123,Iterator))
18+
print("Itertor? g():", isinstance(g(),Iterator))
19+
20+
print ("for x in [1,2,3,4,5]:")
21+
for x in [1,2,3,4,5]:
22+
print(x)
23+
24+
25+
print("for x in iter([1,2,3,4,5]:)")
26+
for x in iter([1,2,3,4,5]):
27+
print(x)
28+
29+
print("next():")
30+
it=iter([1,2,3,4,5])
31+
print(next(it))
32+
print(next(it))
33+
print(next(it))
34+
print(next(it))
35+
print(next(it))
36+
37+
d={"a":1,"b":2, "c":3}
38+
39+
print("iter key:",d)
40+
for k in d.keys():
41+
print("key:", k)
42+
43+
print("iter value:",d)
44+
for v in d.values():
45+
print("value",v)
46+
47+
print("iter item:",d)
48+
for k,v in d.items():
49+
print("item:", k,v)
50+
51+
print("iter enumerate([\'A\',\'B\',\'C\'])")
52+
for i,value in enumerate(['A','B','C']):
53+
print(i,value)
54+
55+
print("iter [(1,1), (2,4),(3,9)]:")
56+
for x,y in [(1,1), (2,4),(3,9)]:
57+
print(x,y)

do_listcompr.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
print([x*x for x in range(1,11)])
2+
print([x*x for x in range(1,11) if x%2 ==0])
3+
print([m+n for m in "ABC" for n in "XYZ"])
4+
5+
d = {"x": "A", "y": "B", "z":"C"}
6+
print([k+"=" +v for k,v in d.items()])
7+
8+
L=["Hello", "World",18, "IBM", "Apple"]
9+
print([s.lower() for s in L if isinstance(s,str)])

do_map.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def f(x):
2+
return x*x
3+
4+
5+
print(list(map(f,[1,2,3,4,5,6,7,8,9])))

do_partial.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import functools
2+
3+
int2=functools.partial(int,base=2)
4+
5+
print("1000000=", int2("1000000"))
6+
print("1010101=", int2("1010101"))
7+

do_reduce.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
from functools import reduce
2+
3+
CHAR_TO_INT ={
4+
"0":0,
5+
"1":1,
6+
"2":2,
7+
"3":3,
8+
"4":4,
9+
"5":5,
10+
"6":6,
11+
"7":7,
12+
"8":8,
13+
"9":9
14+
}
15+
16+
def str2int(s):
17+
ints=map(lambda ch: CHAR_TO_INT[ch],s)
18+
return reduce(lambda x,y:x*10+y,ints)
19+
20+
print(str2int("0"))
21+
print(str2int("12300"))
22+
print(str2int("0012345"))
23+
24+
25+
CHAR_TO_FLOAT ={
26+
"0":0,
27+
"1":1,
28+
"2":2,
29+
"3":3,
30+
"4":4,
31+
"5":5,
32+
"6":6,
33+
"7":7,
34+
"8":8,
35+
"9":9,
36+
".":-1
37+
}
38+
39+
def str2float(s):
40+
nums=map(lambda ch: CHAR_TO_FLOAT[ch],s)
41+
point=0
42+
def to_float(f,n):
43+
nonlocal point
44+
if n==-1:
45+
point=1
46+
return f
47+
if point == 0:
48+
return f*10+n
49+
else:
50+
point = point*10
51+
return f+n/point
52+
return reduce(to_float,nums,0.0)
53+
54+
print(str2float("0"))
55+
print(str2float("123.456"))
56+
print(str2float("123.45600"))
57+
print(str2float("0.1234"))
58+
print(str2float(".1234"))
59+
print(str2float("120.0034"))
60+
61+
62+
63+
def normalize(name):
64+
return name[0:1].upper() + name[1:].lower()
65+
66+
L1=["adam", "LISA", "barT"]
67+
print(list(map(normalize,L1)))
68+
69+
70+
def prod(L):
71+
return reduce(lambda x,y: x*y, L)
72+
73+
print("3*5*7*9= ", prod([3,5,7,9]))
74+
75+
def str22float(s):
76+
def str2list(s):
77+
return {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,".":"."}[s]
78+
ss=list(map(str2list,s))
79+
l=len(ss)-1-ss.index(".")
80+
ss.remove(".")
81+
return reduce(lambda x,y: x*10+y,ss)/10.0**l
82+
83+
print(str22float("123.4567"))

do_slice.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
L=["Michael", "Sarah", "Tracy", "Bob", "Jack"]
2+
3+
print("L[0:3]= ", L[0:3])
4+
print("L[:3]= ", L[:3])
5+
print("L[1:3]= ", L[1:3])
6+
print("L[-2:]= ", L[-2:])
7+
8+
9+
R=list(range(100))
10+
print("R[:10]= ", R[:10])
11+
print("R[-10:]= ", R[-10:])
12+
print("R[10:20]= ", R[10:20])
13+
print("R[:10:2]= ", R[:10:2])
14+
print("R[::5]= ", R[::5])

do_sorted.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from operator import itemgetter
2+
3+
L=["bob", "about", "Zoo", "Credit"]
4+
5+
print(sorted(L))
6+
print(sorted(L,key=str.lower))
7+
8+
students =[("Bob",75), ("Adam", 92), ("Bart",66), ("Lisa",88)]
9+
10+
print(sorted(students,key=itemgetter(0)))
11+
print(sorted(students,key=lambda t: t[1]))
12+
print(sorted(students,key=itemgetter(1),reverse=True))

0 commit comments

Comments
 (0)