Repository navigation
Expand file tree
/
Copy pathbasis.py
More file actions
269 lines (209 loc) · 4.58 KB
/
Copy pathbasis.py
File metadata and controls
269 lines (209 loc) · 4.58 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# Our first Python program
print('hello world') # hello world
# primitives & operations
number = 123
string = 'abc'
byte = b'abc'
truth = True
compx = 1 + 2j
nop = None
# id: returns object's identity.
id(number)
id(compx)
# dir: returns a list of valid attributes
dir(string)
dir(truth)
# type
type(number) # <class 'int'>
type(compx) # <class 'complex'>
# list & tuple
a = [1, 2, 3, 4, 5]
b = list(range(1, 6, 1)) # [1, 2, 3, 4, 5]
c = (1, 2, 3) # or c = tuple([1, 2, 3])
# list is a natural bidirectional queue
a = [1, 2, 3, 4, 5]
a.pop(0) # [2, 3, 4, 5]
a.pop() # [2, 3, 4]
a.insert(0, 7) # [7, 2, 3, 4]
a.append(8) # [7, 2, 3, 4, 8]
# slice operation
a = [1, 2, 3, 4, 5]
a[:] # [1, 2, 3, 4, 5]
a[1:-1:1] # [2, 3, 4]
a[-1::-2] # [5, 3, 1]
# dict
d = {} # or d = dict()
d[1] = 1
d[2] = 4
d[1] # 1
d.get(3, None) # None
d.update({3: 9, 4: 16})
# method items returns the key-value pairs
for k, v in d.items():
print(k, v)
# set
p = set('abc')
q = frozenset('cde')
p & q # {'c'}
p | q # {'a', 'e', 'b', 'c', 'd'}
p ^ q # {'e', 'a', 'b', 'd'}
p - q # {'a', 'b'}
# if statement
a = 1
b = int(input('enter a number:'))
if b == a:
print('equal')
elif b < a:
print('lower')
else:
print('higher')
if a < b < c: pass
if a < b and b < c: pass
# for statement
for i in range(0, 5):
if i == 5:
print('found the God!!!')
break
else:
print('not found')
# while statement
while True:
pass
else:
pass
# function
def func(a, b=1, *args, **kwargs):
print(a)
print(b)
for arg in args: print(arg)
for k, v in kwargs.items(): print(k, '=', v)
func('a', 'b', 1, 2, 3, c=4, d=5)
# lambda
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0) # 42
f(1) # 43
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
# exception handling
while 1:
try:
x = int(input('please enter a number:'))
print(10 / x)
break
except ValueError as e:
print('Not a valid number')
print(e)
except ZeroDivisionError as e:
print('Cannot divide by zero')
print(e)
except (ValueError, ZeroDivisionError) as e:
print(e)
# object oriengted programming
class Employee(object):
def __init__(self, name, empno):
self.name = name
self.empno = empno
e = Employee('Tom', 101010)
e.empno # 101010
e.name = 'Tommy'
e.mobile = '+86 021 12345678'
class Manager(Employee):
def __init__(self, name, empno, band):
super(Manager, self).__init__(name, empno)
self.__band = band
def __str__(self):
return '%s, %d' % (self.name, self.empno)
m = Manager('Jack', 123, 9)
m.name # Jack
m.__band # 'Manager' object has no attribute '__band'
print(m) # Jack, 123
class C(A, B): pass
# List Comprehensions
a = [i + 1 for i in range(10)]
a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Multiplication Table in one line python code
print('\n'.join([' '.join(['%d x %d = %-2d' % (i, j, i * j) for j in range(1, i + 1)]) for i in range(1, 10)]))
# slide: Decorator
def log(fn):
def wrapper():
print('start executing, %s' % fn.__name__)
fn()
print('end executing, %s' % fn.__name__)
return wrapper
@log
def foo():
print('I am foo')
foo()
# decorator - advanced example
from functools import wraps
def memo(fn):
cache = {}
miss = object()
@wraps(fn)
def wrapper(*args):
result = cache.get(args, miss)
if result is miss:
result = fn(*args)
cache[args] = result
return result
return wrapper
@memo
def fib(n):
if n < 2: return n
return fib(n - 1) + fib(n - 2)
# slide: Generator
def get_next_prime():
yield 2
yield 3
ret = 4
while True:
ret += 1 # starts from 5
for i in range(2, ret - 1):
if ret % i == 0: break
else: yield ret
prime_generator = get_next_prime()
next(prime_generator) # 2
next(prime_generator) # 3
for v in get_next_prime():
print(v) # endless
# coroutine
import sys
def produce(l, top):
i = 0
while i < top:
l.append(i)
yield i
i = i + 1
def consume(l, top):
p = produce(l, 10)
while 1:
try:
next(p)
while len(l) > 0: print(l.pop())
except StopIteration: sys.exit(0)
consume([], 10)
# gevent
import gevent
from gevent.queue import Queue
tasks = Queue()
def worker(n):
while not tasks.empty():
task = tasks.get()
print('Worker %s got task %s' % (n, task))
gevent.sleep(0)
def boss():
for i in xrange(1,25): tasks.put_nowait(i)
gevent.spawn(boss).join()
gevent.joinall([
gevent.spawn(worker, 'steve'),
gevent.spawn(worker, 'john'),
])
# Pony ORM
select(c for c in Customer if sum(c.orders.price) > 1000)
SELECT "c"."id"
FROM "Customer" "c"
LEFT JOIN "Order" "order-1"
ON "c"."id" = "order-1"."customer"
GROUP BY "c"."id"
HAVING coalesce(SUM("order-1"."total_price"), 0) > 1000