You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1635 lines
34 KiB

6 years ago
7 years ago
5 years ago
5 years ago
7 years ago
6 years ago
6 years ago
5 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
7 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. <sup>[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md)
  4. or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet).
  5. </sup>
  6. ![Monty Python](web/image_888.jpeg)
  7. Main
  8. ----
  9. ```python
  10. if __name__ == '__main__':
  11. main()
  12. ```
  13. List
  14. ----
  15. ```python
  16. <list> = <list>[from_inclusive : to_exclusive : step_size]
  17. <list>.append(<el>)
  18. <list>.extend(<collection>)
  19. <list> += [<el>]
  20. <list> += <collection>
  21. ```
  22. ```python
  23. <list>.sort()
  24. <list>.reverse()
  25. <list> = sorted(<collection>)
  26. <iter> = reversed(<list>)
  27. ```
  28. ```python
  29. sum_of_elements = sum(<collection>)
  30. elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
  31. sorted_by_second = sorted(<collection>, key=lambda el: el[1])
  32. sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
  33. flattened_list = list(itertools.chain.from_iterable(<list>))
  34. list_of_chars = list(<str>)
  35. product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
  36. no_duplicates = list(dict.fromkeys(<list>))
  37. ```
  38. ```python
  39. index = <list>.index(<el>) # Returns first index of item.
  40. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  41. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  42. <list>.remove(<el>) # Removes first occurrence of item.
  43. <list>.clear() # Removes all items.
  44. ```
  45. Dictionary
  46. ----------
  47. ```python
  48. <view> = <dict>.keys()
  49. <view> = <dict>.values()
  50. <view> = <dict>.items()
  51. ```
  52. ```python
  53. value = <dict>.get(key, default) # Returns default if key does not exist.
  54. value = <dict>.setdefault(key, default) # Same, but also adds default to dict.
  55. <dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
  56. <dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
  57. ```
  58. ```python
  59. <dict>.update(<dict>) # Or: dict_a = {**dict_a, **dict_b}.
  60. <dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
  61. <dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
  62. <dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
  63. ```
  64. ```python
  65. value = <dict>.pop(key) # Removes item from dictionary.
  66. {k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
  67. ```
  68. ### Counter
  69. ```python
  70. >>> from collections import Counter
  71. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  72. >>> counter = Counter(colors)
  73. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  74. >>> counter.most_common()[0][0]
  75. 'blue'
  76. ```
  77. Set
  78. ---
  79. ```python
  80. <set> = set()
  81. <set>.add(<el>)
  82. <set>.update(<collection>)
  83. <set> |= {<el>}
  84. <set> |= <set>
  85. ```
  86. ```python
  87. <set> = <set>.union(<coll.>) # Or: <set> | <set>
  88. <set> = <set>.intersection(<coll.>) # Or: <set> & <set>
  89. <set> = <set>.difference(<coll.>) # Or: <set> - <set>
  90. <set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
  91. <bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
  92. <bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
  93. ```
  94. ### Frozenset
  95. ####Is hashable and can be used as a key in dictionary.
  96. ```python
  97. <frozenset> = frozenset(<collection>)
  98. ```
  99. Range
  100. -----
  101. ```python
  102. range(to_exclusive)
  103. range(from_inclusive, to_exclusive)
  104. range(from_inclusive, to_exclusive, step_size)
  105. range(from_inclusive, to_exclusive, -step_size)
  106. ```
  107. ```python
  108. from_inclusive = <range>.start
  109. to_exclusive = <range>.stop
  110. ```
  111. Enumerate
  112. ---------
  113. ```python
  114. for i, el in enumerate(<collection> [, i_start]):
  115. ...
  116. ```
  117. Named Tuple
  118. -----------
  119. ```python
  120. >>> Point = collections.namedtuple('Point', 'x y')
  121. >>> p = Point(1, y=2)
  122. Point(x=1, y=2)
  123. >>> p[0]
  124. 1
  125. >>> p.x
  126. 1
  127. >>> getattr(p, 'y')
  128. 2
  129. >>> p._fields # Or: Point._fields
  130. ('x', 'y')
  131. ```
  132. Iterator
  133. --------
  134. ```python
  135. <iter> = iter(<collection>)
  136. <iter> = iter(<function>, to_exclusive)
  137. ```
  138. #### Skips first element:
  139. ```python
  140. next(<iter>)
  141. for element in <iter>:
  142. ...
  143. ```
  144. #### Reads input until it reaches an empty line:
  145. ```python
  146. for line in iter(input, ''):
  147. ...
  148. ```
  149. #### Same, but prints a message every time:
  150. ```python
  151. from functools import partial
  152. for line in iter(partial(input, 'Please enter value: '), ''):
  153. ...
  154. ```
  155. Generator
  156. ---------
  157. **Convenient way to implement the iterator protocol.**
  158. ```python
  159. def step(start, step_size):
  160. while True:
  161. yield start
  162. start += step_size
  163. ```
  164. ```python
  165. >>> stepper = step(10, 2)
  166. >>> next(stepper), next(stepper), next(stepper)
  167. (10, 12, 14)
  168. ```
  169. Type
  170. ----
  171. ```python
  172. <type> = type(<el>) # <class 'int'> / <class 'str'> / ...
  173. ```
  174. ```python
  175. from numbers import Number, Integral, Real, Rational, Complex
  176. <bool> = isinstance(<el>, Number)
  177. ```
  178. ```python
  179. <bool> = callable(<el>)
  180. ```
  181. String
  182. ------
  183. ```python
  184. <str> = <str>.strip() # Strips all whitespace characters.
  185. <str> = <str>.strip('<chars>') # Strips all passed characters.
  186. ```
  187. ```python
  188. <list> = <str>.split() # Splits on any whitespace character.
  189. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
  190. <str> = <str>.join(<list>) # Joins elements using string as separator.
  191. ```
  192. ```python
  193. <str> = <str>.replace(old_str, new_str)
  194. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  195. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  196. <int> = <str>.index(<sub_str>) # Returns first index of a substring.
  197. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  198. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  199. ```
  200. ### Char
  201. ```python
  202. <str> = chr(<int>) # Converts int to unicode char.
  203. <int> = ord(<str>) # Converts unicode char to int.
  204. ```
  205. ```python
  206. >>> ord('0'), ord('9')
  207. (48, 57)
  208. >>> ord('A'), ord('Z')
  209. (65, 90)
  210. >>> ord('a'), ord('z')
  211. (97, 122)
  212. ```
  213. Regex
  214. -----
  215. ```python
  216. import re
  217. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  218. <list> = re.findall(<regex>, text) # Returns all occurrences.
  219. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  220. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  221. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  222. <Matches> = re.finditer(<regex>, text) # Searches for all occurrences of pattern.
  223. ```
  224. * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.**
  225. * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.**
  226. * **Use `r'\1'` or `'\\\\1'` for backreference.**
  227. * **Use `'?'` to make operators non-greedy.**
  228. ### Match Object
  229. ```python
  230. <str> = <Match>.group() # Whole match.
  231. <str> = <Match>.group(1) # Part in first bracket.
  232. <int> = <Match>.start() # Start index of a match.
  233. <int> = <Match>.end() # Exclusive end index of a match.
  234. ```
  235. ### Special Sequences
  236. **Use capital letter for negation.**
  237. ```python
  238. '\d' == '[0-9]' # Digit
  239. '\s' == '[ \t\n\r\f\v]' # Whitespace
  240. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  241. ```
  242. Print
  243. -----
  244. **Use `file=sys.stderr` for errors.**
  245. ```python
  246. print(<el_1> [, <el_2>, end='', sep='', file=<file>])
  247. ```
  248. ```python
  249. >>> from pprint import pprint
  250. >>> pprint(locals())
  251. {'__doc__': None,
  252. '__name__': '__main__',
  253. '__package__': None, ...}
  254. ```
  255. Format
  256. ------
  257. ```python
  258. <str> = f'{<el_1>}, {<el_2>}'
  259. <str> = '{}, {}'.format(<el_1>, <el_2>)
  260. ```
  261. ```python
  262. >>> Person = namedtuple('Person', 'name height')
  263. >>> person = Person('Jean-Luc', 187)
  264. >>> f'{person.height:10}'
  265. ' 187'
  266. >>> '{p.height:10}'.format(p=person)
  267. ' 187'
  268. ```
  269. ### General Options
  270. ```python
  271. {<el>:<10} # '<el> '
  272. {<el>:>10} # ' <el>'
  273. {<el>:^10} # ' <el> '
  274. {<el>:->10} # '------<el>'
  275. {<el>:>0} # '<el>'
  276. ```
  277. ### String Options
  278. **"!r" calls object's repr() method, instead of format(), to get a string.**
  279. ```python
  280. {'abcde'!r:<10} # "'abcde' "
  281. ```
  282. ```python
  283. {'abcde':.3} # 'abc'
  284. {'abcde':10.3} # 'abc '
  285. ```
  286. ### Number Options
  287. ```python
  288. {1.23456:.3f} # '1.235'
  289. {1.23456:10.3f} # ' 1.235'
  290. ```
  291. ```python
  292. { 123456:10,} # ' 123,456'
  293. { 123456:10_} # ' 123_456'
  294. { 123456:+10} # ' +123456'
  295. {-123456:=10} # '- 123456'
  296. { 123456: } # ' 123456'
  297. {-123456: } # '-123456'
  298. ```
  299. ```python
  300. {65:c} # 'A'
  301. {3:08b} # '00000011' -> Binary with leading zeros.
  302. {3:0<8b} # '11000000' -> Binary with trailing zeros.
  303. ```
  304. #### Float presentation types:
  305. * `'f'` - Fixed point: `.<precision>f`
  306. * `'%'` - Percent: `.<precision>%`
  307. * `'e'` - Exponent
  308. #### Integer presentation types:
  309. * `'c'` - Character
  310. * `'b'` - Binary
  311. * `'x'` - Hex
  312. * `'X'` - HEX
  313. Numbers
  314. -------
  315. ### Basic Functions
  316. ```python
  317. <num> = pow(<num>, <num>) # Or: <num> ** <num>
  318. <real> = abs(<num>)
  319. <real> = round(<real> [, ndigits])
  320. ```
  321. ### Constants
  322. ```python
  323. from math import e, pi
  324. ```
  325. ### Trigonometry
  326. ```python
  327. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  328. ```
  329. ### Logarithm
  330. ```python
  331. from math import log, log10, log2
  332. <float> = log(<real> [, base]) # Base e, if not specified.
  333. ```
  334. ### Infinity, nan
  335. ```python
  336. from math import inf, nan, isinf, isnan
  337. ```
  338. #### Or:
  339. ```python
  340. float('inf'), float('nan')
  341. ```
  342. ### Random
  343. ```python
  344. from random import random, randint, choice, shuffle
  345. <float> = random()
  346. <int> = randint(from_inclusive, to_inclusive)
  347. <el> = choice(<list>)
  348. shuffle(<list>)
  349. ```
  350. Datetime
  351. --------
  352. ```python
  353. from datetime import datetime, strptime
  354. now = datetime.now()
  355. now.month # 3
  356. now.strftime('%Y%m%d') # '20180315'
  357. now.strftime('%Y%m%d%H%M%S') # '20180315002834'
  358. <datetime> = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
  359. ```
  360. Arguments
  361. ---------
  362. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.**
  363. ```python
  364. args = (1, 2)
  365. kwargs = {'x': 3, 'y': 4, 'z': 5}
  366. func(*args, **kwargs)
  367. ```
  368. #### Is the same as:
  369. ```python
  370. func(1, 2, x=3, y=4, z=5)
  371. ```
  372. #### Splat operator can also be used in function declarations:
  373. ```python
  374. def add(*a):
  375. return sum(a)
  376. ```
  377. ```python
  378. >>> add(1, 2, 3)
  379. 6
  380. ```
  381. #### And in few other places:
  382. ```python
  383. >>> a = (1, 2, 3)
  384. >>> [*a]
  385. [1, 2, 3]
  386. ```
  387. ```python
  388. >>> head, *body, tail = [1, 2, 3, 4]
  389. >>> body
  390. [2, 3]
  391. ```
  392. Inline
  393. ------
  394. ### Lambda
  395. ```python
  396. lambda: <return_value>
  397. lambda <argument_1>, <argument_2>: <return_value>
  398. ```
  399. ### Comprehension
  400. ```python
  401. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  402. <set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
  403. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  404. <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
  405. ```
  406. ```python
  407. out = [i+j for i in range(10) for j in range(10)]
  408. ```
  409. #### Is the same as:
  410. ```python
  411. out = []
  412. for i in range(10):
  413. for j in range(10):
  414. out.append(i+j)
  415. ```
  416. ### Map, Filter, Reduce
  417. ```python
  418. from functools import reduce
  419. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  420. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
  421. <int> = reduce(lambda out, x: out + x, range(10)) # 45
  422. ```
  423. ### Any, All
  424. ```python
  425. <bool> = any(<collection>) # False if empty.
  426. <bool> = all(el[1] for el in <collection>) # True if empty.
  427. ```
  428. ### If - Else
  429. ```python
  430. <expression_if_true> if <condition> else <expression_if_false>
  431. ```
  432. ```python
  433. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  434. ['zero', 1, 'zero', 3]
  435. ```
  436. ### Namedtuple, Enum, Class
  437. ```python
  438. from collections import namedtuple
  439. Point = namedtuple('Point', 'x y')
  440. point = Point(0, 0)
  441. ```
  442. ```python
  443. from enum import Enum
  444. Direction = Enum('Direction', 'n e s w')
  445. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  446. ```
  447. ```python
  448. # Warning: Objects will share the objects that are initialized in the dictionary!
  449. Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
  450. creature = Creature()
  451. ```
  452. Closure
  453. -------
  454. ```python
  455. def get_multiplier(a):
  456. def out(b):
  457. return a * b
  458. return out
  459. ```
  460. ```python
  461. >>> multiply_by_3 = get_multiplier(3)
  462. >>> multiply_by_3(10)
  463. 30
  464. ```
  465. #### Or:
  466. ```python
  467. from functools import partial
  468. <function> = partial(<function>, <argument_1> [, <argument_2>, ...])
  469. ```
  470. ```python
  471. >>> multiply_by_3 = partial(operator.mul, 3)
  472. >>> multiply_by_3(10)
  473. 30
  474. ```
  475. Decorator
  476. ---------
  477. ```python
  478. @closure_name
  479. def function_that_gets_passed_to_closure():
  480. ...
  481. ```
  482. #### Debugger example:
  483. ```python
  484. from functools import wraps
  485. def debug(func):
  486. @wraps(func) # Needed for metadata copying (func name, ...).
  487. def out(*args, **kwargs):
  488. print(func.__name__)
  489. return func(*args, **kwargs)
  490. return out
  491. @debug
  492. def add(x, y):
  493. return x + y
  494. ```
  495. Class
  496. -----
  497. ```python
  498. class <name>:
  499. def __init__(self, a):
  500. self.a = a
  501. def __repr__(self):
  502. class_name = type(self).__name__
  503. return f'{class_name}({self.a!r})'
  504. def __str__(self):
  505. return str(self.a)
  506. @classmethod
  507. def get_class_name(cls):
  508. return cls.__name__
  509. ```
  510. ### Constructor Overloading
  511. ```python
  512. class <name>:
  513. def __init__(self, a=None):
  514. self.a = a
  515. ```
  516. ### Inheritance
  517. ```python
  518. class Person:
  519. def __init__(self, name, age):
  520. self.name = name
  521. self.age = age
  522. class Employee(Person):
  523. def __init__(self, name, age, staff_num):
  524. super().__init__(name, age)
  525. self.staff_num = staff_num
  526. ```
  527. ### Copy
  528. ```python
  529. from copy import copy, deepcopy
  530. <object> = copy(<object>)
  531. <object> = deepcopy(<object>)
  532. ```
  533. Enum
  534. ----
  535. ```python
  536. from enum import Enum, auto
  537. class <enum_name>(Enum):
  538. <member_name_1> = <value_1>
  539. <member_name_2> = <value_2_a>, <value_2_b>
  540. <member_name_3> = auto() # Can be used for automatic indexing.
  541. @classmethod
  542. def get_member_names(cls):
  543. return [a.name for a in cls.__members__.values()]
  544. ```
  545. ```python
  546. <member> = <enum>.<member_name>
  547. <member> = <enum>['<member_name>']
  548. <member> = <enum>(<value>)
  549. name = <member>.name
  550. value = <member>.value
  551. ```
  552. ```python
  553. list_of_members = list(<enum>)
  554. member_names = [a.name for a in <enum>]
  555. member_values = [a.value for a in <enum>]
  556. random_member = random.choice(list(<enum>))
  557. ```
  558. ### Inline
  559. ```python
  560. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  561. Cutlery = Enum('Cutlery', 'knife fork spoon')
  562. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  563. ```
  564. #### Functions can not be values, so they must be wrapped:
  565. ```python
  566. from functools import partial
  567. LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r),
  568. 'or' : partial(lambda l, r: l or r)})
  569. ```
  570. System
  571. ------
  572. ### Arguments
  573. ```python
  574. import sys
  575. script_name = sys.argv[0]
  576. arguments = sys.argv[1:]
  577. ```
  578. ### Read File
  579. ```python
  580. def read_file(filename):
  581. with open(filename, encoding='utf-8') as file:
  582. return file.readlines()
  583. ```
  584. ### Write to File
  585. ```python
  586. def write_to_file(filename, text):
  587. with open(filename, 'w', encoding='utf-8') as file:
  588. file.write(text)
  589. ```
  590. ### Path
  591. ```python
  592. from os import path, listdir
  593. <bool> = path.exists(<path>)
  594. <bool> = path.isfile(<path>)
  595. <bool> = path.isdir(<path>)
  596. <list> = listdir(<path>)
  597. ```
  598. ```python
  599. >>> from glob import glob
  600. >>> glob('../*.gif')
  601. ['1.gif', 'card.gif']
  602. ```
  603. ### Execute Command
  604. ```python
  605. import os
  606. <str> = os.popen(<command>).read()
  607. ```
  608. #### Or:
  609. ```python
  610. >>> import subprocess
  611. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  612. >>> a.stdout
  613. b'.\n..\nfile1.txt\nfile2.txt\n'
  614. >>> a.returncode
  615. 0
  616. ```
  617. ### Input
  618. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  619. ```python
  620. filename = input('Enter a file name: ')
  621. ```
  622. #### Prints lines until EOF:
  623. ```python
  624. while True:
  625. try:
  626. print(input())
  627. except EOFError:
  628. break
  629. ```
  630. ### Recursion Limit
  631. ```python
  632. >>> import sys
  633. >>> sys.getrecursionlimit()
  634. 1000
  635. >>> sys.setrecursionlimit(5000)
  636. ```
  637. JSON
  638. ----
  639. ```python
  640. import json
  641. ```
  642. ### Serialization
  643. ```python
  644. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  645. <dict> = json.loads(<str>)
  646. ```
  647. #### To preserve order:
  648. ```python
  649. from collections import OrderedDict
  650. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  651. ```
  652. ### Read File
  653. ```python
  654. def read_json_file(filename):
  655. with open(filename, encoding='utf-8') as file:
  656. return json.load(file)
  657. ```
  658. ### Write to File
  659. ```python
  660. def write_to_json_file(filename, an_object):
  661. with open(filename, 'w', encoding='utf-8') as file:
  662. json.dump(an_object, file, ensure_ascii=False, indent=2)
  663. ```
  664. SQLite
  665. ------
  666. ```python
  667. import sqlite3
  668. db = sqlite3.connect(<filename>)
  669. ...
  670. db.close()
  671. ```
  672. ### Read
  673. ```python
  674. cursor = db.execute(<query>)
  675. if cursor:
  676. <tuple> = cursor.fetchone() # First row.
  677. <list> = cursor.fetchall() # Remaining rows.
  678. ```
  679. ### Write
  680. ```python
  681. db.execute(<query>)
  682. db.commit()
  683. ```
  684. Pickle
  685. ------
  686. ```python
  687. >>> import pickle
  688. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  689. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  690. >>> pickle.load(open('data.p', 'rb'))
  691. {'lion': 'yellow', 'kitty': 'red'}
  692. ```
  693. Exceptions
  694. ----------
  695. ```python
  696. while True:
  697. try:
  698. x = int(input('Please enter a number: '))
  699. except ValueError:
  700. print('Oops! That was no valid number. Try again...')
  701. else:
  702. print('Thank you.')
  703. break
  704. ```
  705. #### Raising exception:
  706. ```python
  707. raise ValueError('A very specific message!')
  708. ```
  709. ### Finally
  710. ```python
  711. >>> try:
  712. ... raise KeyboardInterrupt
  713. ... finally:
  714. ... print('Goodbye, world!')
  715. Goodbye, world!
  716. Traceback (most recent call last):
  717. File "<stdin>", line 2, in <module>
  718. KeyboardInterrupt
  719. ```
  720. Bytes
  721. -----
  722. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  723. ```python
  724. <bytes> = b'<str>'
  725. <int> = <bytes>[<index>]
  726. <bytes> = <bytes>[<slice>]
  727. <bytes> = b''.join(<coll_of_bytes>)
  728. ```
  729. ### Encode
  730. ```python
  731. <bytes> = <str>.encode(encoding='utf-8')
  732. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  733. <bytes> = bytes.fromhex(<hex>)
  734. ```
  735. ### Decode
  736. ```python
  737. <str> = <bytes>.decode('utf-8')
  738. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  739. <hex> = <bytes>.hex()
  740. ```
  741. ### Read Bytes from File
  742. ```python
  743. def read_bytes(filename):
  744. with open(filename, 'rb') as file:
  745. return file.read()
  746. ```
  747. ### Write Bytes to File
  748. ```python
  749. def write_bytes(filename, bytes_obj):
  750. with open(filename, 'wb') as file:
  751. file.write(bytes_obj)
  752. ```
  753. Struct
  754. ------
  755. **This module performs conversions between Python values and C struct represented as Python bytes object. Machine’s native type sizes and byte order are used by default.**
  756. ```python
  757. from struct import pack, unpack, calcsize
  758. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  759. <tuple> = unpack('<format>', <bytes>)
  760. ```
  761. ### Example
  762. ```python
  763. >>> pack('>hhl', 1, 2, 3)
  764. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  765. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  766. (1, 2, 3)
  767. >>> calcsize('>hhl')
  768. 8
  769. ```
  770. ### Format
  771. #### For standard sizes start format string with:
  772. * `'='` - native byte order
  773. * `'<'` - little-endian
  774. * `'>'` - big-endian
  775. **Use capital leter for unsigned type. Standard size in brackets.**
  776. * `'x'` - pad byte
  777. * `'c'` - char (1)
  778. * `'h'` - short (2)
  779. * `'i'` - int (4)
  780. * `'l'` - long (4)
  781. * `'q'` - long long (8)
  782. * `'f'` - float (4)
  783. * `'d'` - double (8)
  784. Hashlib
  785. -------
  786. ```python
  787. >>> import hashlib
  788. >>> hashlib.md5(<str>.encode()).hexdigest()
  789. '33d0eba106da4d3ebca17fcd3f4c3d77'
  790. ```
  791. Threading
  792. ---------
  793. ```python
  794. from threading import Thread, RLock
  795. ```
  796. ### Thread
  797. ```python
  798. thread = Thread(target=<function>, args=(<first_arg>, ))
  799. thread.start()
  800. ...
  801. thread.join()
  802. ```
  803. ### Lock
  804. ```python
  805. lock = RLock()
  806. lock.acquire()
  807. ...
  808. lock.release()
  809. ```
  810. Itertools
  811. ---------
  812. **Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function!**
  813. ```python
  814. from itertools import *
  815. ```
  816. ### Combinatoric iterators
  817. ```python
  818. >>> combinations('abc', 2)
  819. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  820. >>> combinations_with_replacement('abc', 2)
  821. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  822. ('b', 'b'), ('b', 'c'),
  823. ('c', 'c')]
  824. >>> permutations('abc', 2)
  825. [('a', 'b'), ('a', 'c'),
  826. ('b', 'a'), ('b', 'c'),
  827. ('c', 'a'), ('c', 'b')]
  828. >>> product('ab', [1, 2])
  829. [('a', 1), ('a', 2),
  830. ('b', 1), ('b', 2)]
  831. >>> product([0, 1], repeat=3)
  832. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  833. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  834. ```
  835. ### Infinite iterators
  836. ```python
  837. >>> i = count(5, 2)
  838. >>> next(i), next(i), next(i)
  839. (5, 7, 9)
  840. >>> a = cycle('abc')
  841. >>> [next(a) for _ in range(10)]
  842. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  843. >>> repeat(10, 3)
  844. [10, 10, 10]
  845. ```
  846. ### Iterators
  847. ```python
  848. >>> chain([1, 2], range(3, 5))
  849. [1, 2, 3, 4]
  850. >>> compress('abc', [True, 0, 1])
  851. ['a', 'c']
  852. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  853. [2, 3]
  854. >>> people = [{'id': 1, 'name': 'Bob'},
  855. {'id': 2, 'name': 'Bob'},
  856. {'id': 3, 'name': 'Peter'}]
  857. >>> groups = groupby(people, key=lambda a: a['name'])
  858. >>> {name: list(group) for name, group in groups}
  859. {'Bob': [{'id': 1, 'name': 'Bob'},
  860. {'id': 2, 'name': 'Bob'}],
  861. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  862. ```
  863. Introspection and Metaprograming
  864. --------------------------------
  865. **Inspecting code at runtime and code that generates code. You can:**
  866. * **Look at the attributes**
  867. * **Set new attributes**
  868. * **Create functions dynamically**
  869. * **Traverse the parent classes**
  870. * **Change values in the class**
  871. ### Variables
  872. ```python
  873. <list> = dir() # Names of in-scope variables.
  874. <dict> = locals() # Dict of local variables. Also vars().
  875. <dict> = globals() # Dict of global variables.
  876. ```
  877. ### Attributes
  878. ```python
  879. >>> class Z:
  880. ... def __init__(self):
  881. ... self.a = 'abcde'
  882. ... self.b = 12345
  883. >>> z = Z()
  884. ```
  885. ```python
  886. >>> vars(z)
  887. {'a': 'abcde', 'b': 12345}
  888. >>> getattr(z, 'a')
  889. 'abcde'
  890. >>> hasattr(z, 'c')
  891. False
  892. >>> setattr(z, 'c', 10)
  893. ```
  894. ### Parameters
  895. ```python
  896. from inspect import signature
  897. sig = signature(<function>)
  898. no_of_params = len(sig.parameters)
  899. param_names = list(sig.parameters.keys())
  900. ```
  901. ### Type
  902. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).**
  903. ```python
  904. type(<class_name>, <parents_tuple>, <attributes_dict>)
  905. ```
  906. ```python
  907. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  908. >>> z = Z()
  909. ```
  910. ### Meta Class
  911. **Class that creates class.**
  912. ```python
  913. def my_meta_class(name, parents, attrs):
  914. attrs['a'] = 'abcde'
  915. return type(name, parents, attrs)
  916. ```
  917. #### Or:
  918. ```python
  919. class MyMetaClass(type):
  920. def __new__(klass, name, parents, attrs):
  921. attrs['a'] = 'abcde'
  922. return type.__new__(klass, name, parents, attrs)
  923. ```
  924. ### Metaclass Attribute
  925. **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type.**
  926. ```python
  927. class MyClass(metaclass=MyMetaClass):
  928. def __init__(self):
  929. self.b = 12345
  930. ```
  931. Operator
  932. --------
  933. ```python
  934. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  935. eq, ne, lt, le, gt, ge, \
  936. not_, and_, or_, \
  937. itemgetter
  938. ```
  939. ```python
  940. import operator as op
  941. product_of_elems = functools.reduce(op.mul, <list>)
  942. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  943. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  944. LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_})
  945. ```
  946. Eval
  947. ----
  948. ### Basic
  949. ```python
  950. >>> from ast import literal_eval
  951. >>> literal_eval('1 + 2')
  952. 3
  953. >>> literal_eval('[1, 2, 3]')
  954. [1, 2, 3]
  955. >>> ast.literal_eval('abs(1)')
  956. ValueError: malformed node or string
  957. ```
  958. ### Using Abstract Syntax Trees
  959. ```python
  960. import ast
  961. from ast import Num, BinOp, UnaryOp
  962. import operator as op
  963. legal_operators = {ast.Add: op.add,
  964. ast.Sub: op.sub,
  965. ast.Mult: op.mul,
  966. ast.Div: op.truediv,
  967. ast.Pow: op.pow,
  968. ast.BitXor: op.xor,
  969. ast.USub: op.neg}
  970. def evaluate(expression):
  971. root = ast.parse(expression, mode='eval')
  972. return eval_node(root.body)
  973. def eval_node(node):
  974. node_type = type(node)
  975. if node_type == Num:
  976. return node.n
  977. if node_type not in [BinOp, UnaryOp]:
  978. raise TypeError(node)
  979. operator_type = type(node.op)
  980. if operator_type not in legal_operators:
  981. raise TypeError(f'Illegal operator {node.op}')
  982. operator = legal_operators[operator_type]
  983. if node_type == BinOp:
  984. left, right = eval_node(node.left), eval_node(node.right)
  985. return operator(left, right)
  986. elif node_type == UnaryOp:
  987. operand = eval_node(node.operand)
  988. return operator(operand)
  989. ```
  990. ```python
  991. >>> evaluate('2 ^ 6')
  992. 4
  993. >>> evaluate('2 ** 6')
  994. 64
  995. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  996. -5.0
  997. ```
  998. Coroutine
  999. ---------
  1000. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1001. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1002. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1003. ### Helper Decorator
  1004. * **All coroutines must be "primed" by first calling next().**
  1005. * **Remembering to call next() is easy to forget.**
  1006. * **Solved by wrapping coroutines with a decorator:**
  1007. ```python
  1008. def coroutine(func):
  1009. def out(*args, **kwargs):
  1010. cr = func(*args, **kwargs)
  1011. next(cr)
  1012. return cr
  1013. return out
  1014. ```
  1015. ### Pipeline Example
  1016. ```python
  1017. def reader(target):
  1018. for i in range(10):
  1019. target.send(i)
  1020. target.close()
  1021. @coroutine
  1022. def adder(target):
  1023. while True:
  1024. item = (yield)
  1025. target.send(item + 100)
  1026. @coroutine
  1027. def printer():
  1028. while True:
  1029. item = (yield)
  1030. print(item)
  1031. reader(adder(printer())) # 100, 101, ..., 109
  1032. ```
  1033. <br><br>
  1034. Libraries
  1035. =========
  1036. Argparse
  1037. --------
  1038. ```python
  1039. import argparse
  1040. parser = argparse.ArgumentParser(description='calculate X to the power of Y')
  1041. group = parser.add_mutually_exclusive_group()
  1042. group.add_argument('-v', '--verbose', action='store_true')
  1043. group.add_argument('-q', '--quiet', action='store_true')
  1044. parser.add_argument('x', type=int, help='the base')
  1045. parser.add_argument('y', type=int, help='the exponent')
  1046. args = parser.parse_args()
  1047. answer = args.x ** args.y
  1048. if args.quiet:
  1049. print(answer)
  1050. elif args.verbose:
  1051. print(f'{args.x} to the power {args.y} equals {answer}')
  1052. else:
  1053. print(f'{args.x}^{args.y} == {answer}')
  1054. ```
  1055. #### Usage:
  1056. ```
  1057. $ python3 prog.py --help
  1058. usage: test2.py [-h] [-v | -q] x y
  1059. calculate X to the power of Y
  1060. positional arguments:
  1061. x the base
  1062. y the exponent
  1063. optional arguments:
  1064. -h, --help show this help message and exit
  1065. -v, --verbose
  1066. -q, --quiet
  1067. ```
  1068. Plot
  1069. ----
  1070. ```python
  1071. # $ pip3 install matplotlib
  1072. from matplotlib import pyplot
  1073. pyplot.plot(<data_1> [, <data_2>, ...])
  1074. pyplot.savefig(<filename>, transparent=True)
  1075. pyplot.show()
  1076. ```
  1077. Progress Bar
  1078. ------------
  1079. ```python
  1080. # $ pip3 install tqdm
  1081. from tqdm import tqdm
  1082. from time import sleep
  1083. for i in tqdm([1, 2, 3]):
  1084. sleep(0.2)
  1085. for i in tqdm(range(100)):
  1086. sleep(0.02)
  1087. ```
  1088. Table
  1089. -----
  1090. #### Prints CSV file as ASCII table:
  1091. ```python
  1092. # $ pip3 install tabulate
  1093. from csv import reader
  1094. from tabulate import tabulate
  1095. with open(<filename>, newline='') as csv_file:
  1096. reader = reader(csv_file, delimiter=';')
  1097. headers = [a.title() for a in next(reader)]
  1098. print(tabulate(reader, headers))
  1099. ```
  1100. Curses
  1101. ------
  1102. ```python
  1103. # $ pip3 install curses
  1104. from curses import wrapper
  1105. def main():
  1106. wrapper(draw)
  1107. def draw(screen):
  1108. screen.clear()
  1109. screen.addstr(0, 0, 'Press ESC to quit.')
  1110. while screen.getch() != 27:
  1111. pass
  1112. def get_border(screen):
  1113. from collections import namedtuple
  1114. P = namedtuple('P', 'x y')
  1115. height, width = screen.getmaxyx()
  1116. return P(width - 1, height - 1)
  1117. ```
  1118. Image
  1119. -----
  1120. #### Creates PNG image of greyscale gradient:
  1121. ```python
  1122. # $ pip3 install pillow
  1123. from PIL import Image
  1124. width, height = 100, 100
  1125. img = Image.new('L', (width, height), 'white')
  1126. img.putdata([255*a/(width*height) for a in range(width*height)])
  1127. img.save('out.png')
  1128. ```
  1129. ### Modes
  1130. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1131. * `'L'` - 8-bit pixels, greyscale.
  1132. * `'RGB'` - 3x8-bit pixels, true color.
  1133. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1134. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1135. Audio
  1136. -----
  1137. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1138. ```python
  1139. import wave, struct
  1140. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1141. wf = wave.open(<filename>, 'wb')
  1142. wf.setnchannels(1)
  1143. wf.setsampwidth(4)
  1144. wf.setframerate(44100)
  1145. wf.writeframes(b''.join(frames))
  1146. wf.close()
  1147. ```
  1148. Url
  1149. ---
  1150. ```python
  1151. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1152. ```
  1153. ### Encode
  1154. ```python
  1155. >>> quote("Can't be in URL!")
  1156. 'Can%27t%20be%20in%20URL%21'
  1157. >>> quote_plus("Can't be in URL!")
  1158. 'Can%27t+be+in+URL%21'
  1159. ```
  1160. ### Decode
  1161. ```python
  1162. >>> unquote('Can%27t+be+in+URL%21')
  1163. "Can't+be+in+URL!"'
  1164. >>> unquote_plus('Can%27t+be+in+URL%21')
  1165. "Can't be in URL!"
  1166. ```
  1167. Scraping
  1168. --------
  1169. ```python
  1170. # $ pip3 install requests beautifulsoup4
  1171. >>> import requests
  1172. >>> from bs4 import BeautifulSoup
  1173. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1174. >>> page = requests.get(url)
  1175. >>> document = BeautifulSoup(page.text, 'html.parser')
  1176. >>> table = document.find('table', class_='infobox vevent')
  1177. >>> rows = table.find_all('tr')
  1178. >>> link = rows[11].find('a')['href']
  1179. 'https://www.python.org/'
  1180. >>> latest_v = rows[6].find('div').text.split()[0]
  1181. '3.7.2'
  1182. ```
  1183. Web
  1184. ---
  1185. ```python
  1186. # $ pip3 install bottle
  1187. import bottle
  1188. from urllib.parse import unquote
  1189. ```
  1190. ### Run
  1191. ```python
  1192. bottle.run(host='localhost', port=8080)
  1193. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1194. ```
  1195. ### Static Request
  1196. ```python
  1197. @route('/img/<image>')
  1198. def send_image(image):
  1199. return static_file(image, 'images/', mimetype='image/png')
  1200. ```
  1201. ### Dynamic Request
  1202. ```python
  1203. @route('/<sport>')
  1204. def send_page(sport):
  1205. sport = unquote(sport).lower()
  1206. page = read_file(sport)
  1207. return template(page)
  1208. ```
  1209. ### REST Request
  1210. ```python
  1211. @post('/odds/<sport>')
  1212. def odds_handler(sport):
  1213. team = bottle.request.forms.get('team')
  1214. team = unquote(team).lower()
  1215. db = sqlite3.connect(<db_path>)
  1216. home_odds, away_odds = get_odds(db, sport, team)
  1217. db.close()
  1218. response.headers['Content-Type'] = 'application/json'
  1219. response.headers['Cache-Control'] = 'no-cache'
  1220. return json.dumps([home_odds, away_odds])
  1221. ```
  1222. Profile
  1223. -------
  1224. ### Basic
  1225. ```python
  1226. from time import time
  1227. start_time = time()
  1228. ...
  1229. duration = time() - start_time
  1230. ```
  1231. ### Timing a Snippet
  1232. ```python
  1233. from timeit import timeit
  1234. timeit('"-".join(str(a) for a in range(100))',
  1235. number=10000, globals=globals(), setup='pass')
  1236. ```
  1237. ### Line Profiler
  1238. ```python
  1239. # $ pip3 install line_profiler
  1240. @profile
  1241. def main():
  1242. a = [*range(10000)]
  1243. b = {*range(10000)}
  1244. main()
  1245. ```
  1246. ```
  1247. $ kernprof -lv test.py
  1248. Line # Hits Time Per Hit % Time Line Contents
  1249. ==============================================================
  1250. 1 @profile
  1251. 2 def main():
  1252. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1253. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1254. ```
  1255. ### Call Graph
  1256. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1257. ```python
  1258. # $ pip3 install pycallgraph
  1259. from pycallgraph import output, PyCallGraph
  1260. from datetime import datetime
  1261. graph = output.GraphvizOutput()
  1262. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1263. graph.output_file = f'profile-{time_str}.png'
  1264. with PyCallGraph(output=graph):
  1265. <code_to_be_profiled>
  1266. ```
  1267. NumPy
  1268. -----
  1269. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1270. ```python
  1271. # $ pip3 install numpy
  1272. import numpy as np
  1273. ```
  1274. ```python
  1275. <array> = np.array(<list>)
  1276. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1277. <array> = np.ones(<shape>)
  1278. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1279. ```
  1280. ```python
  1281. value = <array>.min([axis])
  1282. index = <array>.argmin([axis])
  1283. ```
  1284. ```python
  1285. <view> = <array>.reshape(<shape>)
  1286. <view> = np.broadcast_to(<array>, <shape>)
  1287. <array> = <array>[filter_expression]
  1288. ```
  1289. ### Broadcasting
  1290. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1291. ```python
  1292. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1293. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1294. ```
  1295. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1296. ```python
  1297. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1298. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1299. ```
  1300. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1301. ```python
  1302. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1303. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1304. ```
  1305. #### 3. If neither non-matching dimension has size 1, rise an error.
  1306. ### Example
  1307. #### For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]`
  1308. ```python
  1309. >>> points = np.array([0.1, 0.6, 0.8])
  1310. [ 0.1, 0.6, 0.8]
  1311. >>> wrapped_points = points.reshape(3, 1)
  1312. [[ 0.1],
  1313. [ 0.6],
  1314. [ 0.8]]
  1315. >>> distances = wrapped_points - points
  1316. [[ 0. , -0.5, -0.7],
  1317. [ 0.5, 0. , -0.2],
  1318. [ 0.7, 0.2, 0. ]]
  1319. >>> distances = np.abs(distances)
  1320. [[ 0. , 0.5, 0.7],
  1321. [ 0.5, 0. , 0.2],
  1322. [ 0.7, 0.2, 0. ]]
  1323. >>> i = np.arange(3)
  1324. [0, 1, 2]
  1325. >>> distances[i, i] = np.inf
  1326. [[ inf, 0.5, 0.7],
  1327. [ 0.5, inf, 0.2],
  1328. [ 0.7, 0.2, inf]]
  1329. >>> distances.argmin(1)
  1330. [1, 2, 1]
  1331. ```
  1332. Basic Script Template
  1333. ---------------------
  1334. ```python
  1335. #!/usr/bin/env python3
  1336. #
  1337. # Usage: .py
  1338. #
  1339. from collections import namedtuple
  1340. from enum import Enum
  1341. import re
  1342. import sys
  1343. def main():
  1344. pass
  1345. ###
  1346. ## UTIL
  1347. #
  1348. def read_file(filename):
  1349. with open(filename, encoding='utf-8') as file:
  1350. return file.readlines()
  1351. if __name__ == '__main__':
  1352. main()
  1353. ```