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.

1689 lines
35 KiB

7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 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
6 years ago
6 years ago
7 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
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
6 years ago
7 years ago
7 years ago
7 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
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 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
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
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
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
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
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
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
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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
6 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
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 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
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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
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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 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
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 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
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
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
7 years ago
6 years ago
7 years ago
6 years ago
7 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
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
7 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
7 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
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
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
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
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
7 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
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
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
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
  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. ### Sequence
  528. ```python
  529. class <name>:
  530. def __init__(self, seq):
  531. self.seq = seq
  532. def __len__(self):
  533. return len(self.seq)
  534. def __getitem__(self, i):
  535. return self.seq[i]
  536. def __iter__(self):
  537. for el in self.seq:
  538. yield el
  539. ```
  540. ### Copy
  541. ```python
  542. from copy import copy, deepcopy
  543. <object> = copy(<object>)
  544. <object> = deepcopy(<object>)
  545. ```
  546. Enum
  547. ----
  548. ```python
  549. from enum import Enum, auto
  550. class <enum_name>(Enum):
  551. <member_name_1> = <value_1>
  552. <member_name_2> = <value_2_a>, <value_2_b>
  553. <member_name_3> = auto() # Can be used for automatic indexing.
  554. @classmethod
  555. def get_member_names(cls):
  556. return [a.name for a in cls.__members__.values()]
  557. ```
  558. ```python
  559. <member> = <enum>.<member_name>
  560. <member> = <enum>['<member_name>']
  561. <member> = <enum>(<value>)
  562. name = <member>.name
  563. value = <member>.value
  564. ```
  565. ```python
  566. list_of_members = list(<enum>)
  567. member_names = [a.name for a in <enum>]
  568. member_values = [a.value for a in <enum>]
  569. random_member = random.choice(list(<enum>))
  570. ```
  571. ### Inline
  572. ```python
  573. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  574. Cutlery = Enum('Cutlery', 'knife fork spoon')
  575. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  576. ```
  577. #### Functions can not be values, so they must be wrapped:
  578. ```python
  579. from functools import partial
  580. LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r),
  581. 'or' : partial(lambda l, r: l or r)})
  582. ```
  583. System
  584. ------
  585. ### Arguments
  586. ```python
  587. import sys
  588. script_name = sys.argv[0]
  589. arguments = sys.argv[1:]
  590. ```
  591. ### Read File
  592. ```python
  593. def read_file(filename):
  594. with open(filename, encoding='utf-8') as file:
  595. return file.readlines()
  596. ```
  597. ### Write to File
  598. ```python
  599. def write_to_file(filename, text):
  600. with open(filename, 'w', encoding='utf-8') as file:
  601. file.write(text)
  602. ```
  603. ### Path
  604. ```python
  605. from os import path, listdir
  606. <bool> = path.exists(<path>)
  607. <bool> = path.isfile(<path>)
  608. <bool> = path.isdir(<path>)
  609. <list> = listdir(<path>)
  610. ```
  611. ```python
  612. >>> from glob import glob
  613. >>> glob('../*.gif')
  614. ['1.gif', 'card.gif']
  615. ```
  616. ### Execute Command
  617. ```python
  618. import os
  619. <str> = os.popen(<command>).read()
  620. ```
  621. #### Or:
  622. ```python
  623. >>> import subprocess
  624. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  625. >>> a.stdout
  626. b'.\n..\nfile1.txt\nfile2.txt\n'
  627. >>> a.returncode
  628. 0
  629. ```
  630. ### Input
  631. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  632. ```python
  633. filename = input('Enter a file name: ')
  634. ```
  635. #### Prints lines until EOF:
  636. ```python
  637. while True:
  638. try:
  639. print(input())
  640. except EOFError:
  641. break
  642. ```
  643. ### Recursion Limit
  644. ```python
  645. >>> import sys
  646. >>> sys.getrecursionlimit()
  647. 1000
  648. >>> sys.setrecursionlimit(5000)
  649. ```
  650. JSON
  651. ----
  652. ```python
  653. import json
  654. ```
  655. ### Serialization
  656. ```python
  657. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  658. <dict> = json.loads(<str>)
  659. ```
  660. #### To preserve order:
  661. ```python
  662. from collections import OrderedDict
  663. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  664. ```
  665. ### Read File
  666. ```python
  667. def read_json_file(filename):
  668. with open(filename, encoding='utf-8') as file:
  669. return json.load(file)
  670. ```
  671. ### Write to File
  672. ```python
  673. def write_to_json_file(filename, an_object):
  674. with open(filename, 'w', encoding='utf-8') as file:
  675. json.dump(an_object, file, ensure_ascii=False, indent=2)
  676. ```
  677. SQLite
  678. ------
  679. ```python
  680. import sqlite3
  681. db = sqlite3.connect(<filename>)
  682. ...
  683. db.close()
  684. ```
  685. ### Read
  686. ```python
  687. cursor = db.execute(<query>)
  688. if cursor:
  689. <tuple> = cursor.fetchone() # First row.
  690. <list> = cursor.fetchall() # Remaining rows.
  691. ```
  692. ### Write
  693. ```python
  694. db.execute(<query>)
  695. db.commit()
  696. ```
  697. Pickle
  698. ------
  699. ```python
  700. >>> import pickle
  701. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  702. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  703. >>> pickle.load(open('data.p', 'rb'))
  704. {'lion': 'yellow', 'kitty': 'red'}
  705. ```
  706. Exceptions
  707. ----------
  708. ```python
  709. while True:
  710. try:
  711. x = int(input('Please enter a number: '))
  712. except ValueError:
  713. print('Oops! That was no valid number. Try again...')
  714. else:
  715. print('Thank you.')
  716. break
  717. ```
  718. #### Raising exception:
  719. ```python
  720. raise ValueError('A very specific message!')
  721. ```
  722. ### Finally
  723. ```python
  724. >>> try:
  725. ... raise KeyboardInterrupt
  726. ... finally:
  727. ... print('Goodbye, world!')
  728. Goodbye, world!
  729. Traceback (most recent call last):
  730. File "<stdin>", line 2, in <module>
  731. KeyboardInterrupt
  732. ```
  733. Bytes
  734. -----
  735. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  736. ```python
  737. <bytes> = b'<str>'
  738. <int> = <bytes>[<index>]
  739. <bytes> = <bytes>[<slice>]
  740. <bytes> = b''.join(<coll_of_bytes>)
  741. ```
  742. ### Encode
  743. ```python
  744. <bytes> = <str>.encode(encoding='utf-8')
  745. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  746. <bytes> = bytes.fromhex(<hex>)
  747. ```
  748. ### Decode
  749. ```python
  750. <str> = <bytes>.decode('utf-8')
  751. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  752. <hex> = <bytes>.hex()
  753. ```
  754. ### Read Bytes from File
  755. ```python
  756. def read_bytes(filename):
  757. with open(filename, 'rb') as file:
  758. return file.read()
  759. ```
  760. ### Write Bytes to File
  761. ```python
  762. def write_bytes(filename, bytes_obj):
  763. with open(filename, 'wb') as file:
  764. file.write(bytes_obj)
  765. ```
  766. Struct
  767. ------
  768. **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.**
  769. ```python
  770. from struct import pack, unpack, calcsize
  771. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  772. <tuple> = unpack('<format>', <bytes>)
  773. ```
  774. ### Example
  775. ```python
  776. >>> pack('>hhl', 1, 2, 3)
  777. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  778. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  779. (1, 2, 3)
  780. >>> calcsize('>hhl')
  781. 8
  782. ```
  783. ### Format
  784. #### For standard sizes start format string with:
  785. * `'='` - native byte order
  786. * `'<'` - little-endian
  787. * `'>'` - big-endian
  788. #### Use capital leter for unsigned type. Standard size in brackets:
  789. * `'x'` - pad byte
  790. * `'c'` - char (1)
  791. * `'h'` - short (2)
  792. * `'i'` - int (4)
  793. * `'l'` - long (4)
  794. * `'q'` - long long (8)
  795. * `'f'` - float (4)
  796. * `'d'` - double (8)
  797. Array
  798. -----
  799. **List that can only hold elements of predefined type. Available types are listed above.**
  800. ```python
  801. from array import array
  802. <array> = array(<typecode> [, <collection>])
  803. ```
  804. Deque
  805. -----
  806. **Short for “double-ended queue” and pronounced “deck”. They are thread-safe lists with efficient appends and pops from either side.**
  807. ```python
  808. from collections import deque
  809. <deque> = deque(<collection>, maxlen=None)
  810. ```
  811. ```python
  812. <deque>.appendleft(<el>)
  813. <deque>.extendleft(<collection>) # Collection gets reversed.
  814. <el> = <deque>.popleft()
  815. <deque>.rotate(n=1) # Rotates elements to the right.
  816. ```
  817. Threading
  818. ---------
  819. ```python
  820. from threading import Thread, RLock
  821. ```
  822. ### Thread
  823. ```python
  824. thread = Thread(target=<function>, args=(<first_arg>, ))
  825. thread.start()
  826. ...
  827. thread.join()
  828. ```
  829. ### Lock
  830. ```python
  831. lock = RLock()
  832. lock.acquire()
  833. ...
  834. lock.release()
  835. ```
  836. Hashlib
  837. -------
  838. ```python
  839. >>> import hashlib
  840. >>> hashlib.md5(<str>.encode()).hexdigest()
  841. '33d0eba106da4d3ebca17fcd3f4c3d77'
  842. ```
  843. Itertools
  844. ---------
  845. **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!**
  846. ```python
  847. from itertools import *
  848. ```
  849. ### Combinatoric iterators
  850. ```python
  851. >>> combinations('abc', 2)
  852. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  853. >>> combinations_with_replacement('abc', 2)
  854. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  855. ('b', 'b'), ('b', 'c'),
  856. ('c', 'c')]
  857. >>> permutations('abc', 2)
  858. [('a', 'b'), ('a', 'c'),
  859. ('b', 'a'), ('b', 'c'),
  860. ('c', 'a'), ('c', 'b')]
  861. >>> product('ab', [1, 2])
  862. [('a', 1), ('a', 2),
  863. ('b', 1), ('b', 2)]
  864. >>> product([0, 1], repeat=3)
  865. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  866. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  867. ```
  868. ### Infinite iterators
  869. ```python
  870. >>> i = count(5, 2)
  871. >>> next(i), next(i), next(i)
  872. (5, 7, 9)
  873. >>> a = cycle('abc')
  874. >>> [next(a) for _ in range(10)]
  875. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  876. >>> repeat(10, 3)
  877. [10, 10, 10]
  878. ```
  879. ### Iterators
  880. ```python
  881. >>> chain([1, 2], range(3, 5))
  882. [1, 2, 3, 4]
  883. >>> compress('abc', [True, 0, 1])
  884. ['a', 'c']
  885. >>> # islice(<collection>, from_inclusive, to_exclusive)
  886. >>> islice([1, 2, 3], 1, None)
  887. [2, 3]
  888. >>> people = [{'id': 1, 'name': 'Bob'},
  889. {'id': 2, 'name': 'Bob'},
  890. {'id': 3, 'name': 'Peter'}]
  891. >>> groups = groupby(people, key=lambda a: a['name'])
  892. >>> {name: list(group) for name, group in groups}
  893. {'Bob': [{'id': 1, 'name': 'Bob'},
  894. {'id': 2, 'name': 'Bob'}],
  895. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  896. ```
  897. Introspection and Metaprograming
  898. --------------------------------
  899. **Inspecting code at runtime and code that generates code. You can:**
  900. * **Look at the attributes**
  901. * **Set new attributes**
  902. * **Create functions dynamically**
  903. * **Traverse the parent classes**
  904. * **Change values in the class**
  905. ### Variables
  906. ```python
  907. <list> = dir() # Names of in-scope variables.
  908. <dict> = locals() # Dict of local variables. Also vars().
  909. <dict> = globals() # Dict of global variables.
  910. ```
  911. ### Attributes
  912. ```python
  913. >>> class Z:
  914. ... def __init__(self):
  915. ... self.a = 'abcde'
  916. ... self.b = 12345
  917. >>> z = Z()
  918. ```
  919. ```python
  920. >>> vars(z)
  921. {'a': 'abcde', 'b': 12345}
  922. >>> getattr(z, 'a')
  923. 'abcde'
  924. >>> hasattr(z, 'c')
  925. False
  926. >>> setattr(z, 'c', 10)
  927. ```
  928. ### Parameters
  929. ```python
  930. from inspect import signature
  931. sig = signature(<function>)
  932. no_of_params = len(sig.parameters)
  933. param_names = list(sig.parameters.keys())
  934. ```
  935. ### Type
  936. **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!).**
  937. ```python
  938. type(<class_name>, <parents_tuple>, <attributes_dict>)
  939. ```
  940. ```python
  941. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  942. >>> z = Z()
  943. ```
  944. ### Meta Class
  945. **Class that creates class.**
  946. ```python
  947. def my_meta_class(name, parents, attrs):
  948. attrs['a'] = 'abcde'
  949. return type(name, parents, attrs)
  950. ```
  951. #### Or:
  952. ```python
  953. class MyMetaClass(type):
  954. def __new__(klass, name, parents, attrs):
  955. attrs['a'] = 'abcde'
  956. return type.__new__(klass, name, parents, attrs)
  957. ```
  958. ### Metaclass Attribute
  959. **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.**
  960. ```python
  961. class MyClass(metaclass=MyMetaClass):
  962. def __init__(self):
  963. self.b = 12345
  964. ```
  965. Operator
  966. --------
  967. ```python
  968. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  969. eq, ne, lt, le, gt, ge, \
  970. not_, and_, or_, \
  971. itemgetter
  972. ```
  973. ```python
  974. import operator as op
  975. product_of_elems = functools.reduce(op.mul, <list>)
  976. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  977. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  978. LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_})
  979. ```
  980. Eval
  981. ----
  982. ### Basic
  983. ```python
  984. >>> from ast import literal_eval
  985. >>> literal_eval('1 + 2')
  986. 3
  987. >>> literal_eval('[1, 2, 3]')
  988. [1, 2, 3]
  989. >>> ast.literal_eval('abs(1)')
  990. ValueError: malformed node or string
  991. ```
  992. ### Using Abstract Syntax Trees
  993. ```python
  994. import ast
  995. from ast import Num, BinOp, UnaryOp
  996. import operator as op
  997. legal_operators = {ast.Add: op.add,
  998. ast.Sub: op.sub,
  999. ast.Mult: op.mul,
  1000. ast.Div: op.truediv,
  1001. ast.Pow: op.pow,
  1002. ast.BitXor: op.xor,
  1003. ast.USub: op.neg}
  1004. def evaluate(expression):
  1005. root = ast.parse(expression, mode='eval')
  1006. return eval_node(root.body)
  1007. def eval_node(node):
  1008. node_type = type(node)
  1009. if node_type == Num:
  1010. return node.n
  1011. if node_type not in [BinOp, UnaryOp]:
  1012. raise TypeError(node)
  1013. operator_type = type(node.op)
  1014. if operator_type not in legal_operators:
  1015. raise TypeError(f'Illegal operator {node.op}')
  1016. operator = legal_operators[operator_type]
  1017. if node_type == BinOp:
  1018. left, right = eval_node(node.left), eval_node(node.right)
  1019. return operator(left, right)
  1020. elif node_type == UnaryOp:
  1021. operand = eval_node(node.operand)
  1022. return operator(operand)
  1023. ```
  1024. ```python
  1025. >>> evaluate('2 ^ 6')
  1026. 4
  1027. >>> evaluate('2 ** 6')
  1028. 64
  1029. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1030. -5.0
  1031. ```
  1032. Coroutine
  1033. ---------
  1034. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1035. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1036. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1037. ### Helper Decorator
  1038. * **All coroutines must be "primed" by first calling next().**
  1039. * **Remembering to call next() is easy to forget.**
  1040. * **Solved by wrapping coroutines with a decorator:**
  1041. ```python
  1042. def coroutine(func):
  1043. def out(*args, **kwargs):
  1044. cr = func(*args, **kwargs)
  1045. next(cr)
  1046. return cr
  1047. return out
  1048. ```
  1049. ### Pipeline Example
  1050. ```python
  1051. def reader(target):
  1052. for i in range(10):
  1053. target.send(i)
  1054. target.close()
  1055. @coroutine
  1056. def adder(target):
  1057. while True:
  1058. item = (yield)
  1059. target.send(item + 100)
  1060. @coroutine
  1061. def printer():
  1062. while True:
  1063. item = (yield)
  1064. print(item)
  1065. reader(adder(printer())) # 100, 101, ..., 109
  1066. ```
  1067. <br><br>
  1068. Libraries
  1069. =========
  1070. Argparse
  1071. --------
  1072. ```python
  1073. import argparse
  1074. parser = argparse.ArgumentParser(description='calculate X to the power of Y')
  1075. group = parser.add_mutually_exclusive_group()
  1076. group.add_argument('-v', '--verbose', action='store_true')
  1077. group.add_argument('-q', '--quiet', action='store_true')
  1078. parser.add_argument('x', type=int, help='the base')
  1079. parser.add_argument('y', type=int, help='the exponent')
  1080. args = parser.parse_args()
  1081. answer = args.x ** args.y
  1082. if args.quiet:
  1083. print(answer)
  1084. elif args.verbose:
  1085. print(f'{args.x} to the power {args.y} equals {answer}')
  1086. else:
  1087. print(f'{args.x}^{args.y} == {answer}')
  1088. ```
  1089. ### Usage
  1090. ```text
  1091. $ python3 prog.py --help
  1092. usage: test2.py [-h] [-v | -q] x y
  1093. calculate X to the power of Y
  1094. positional arguments:
  1095. x the base
  1096. y the exponent
  1097. optional arguments:
  1098. -h, --help show this help message and exit
  1099. -v, --verbose
  1100. -q, --quiet
  1101. ```
  1102. Plot
  1103. ----
  1104. ```python
  1105. # $ pip3 install matplotlib
  1106. from matplotlib import pyplot
  1107. pyplot.plot(<data_1> [, <data_2>, ...])
  1108. pyplot.savefig(<filename>, transparent=True)
  1109. pyplot.show()
  1110. ```
  1111. Progress Bar
  1112. ------------
  1113. ```python
  1114. # $ pip3 install tqdm
  1115. from tqdm import tqdm
  1116. from time import sleep
  1117. for i in tqdm([1, 2, 3]):
  1118. sleep(0.2)
  1119. for i in tqdm(range(100)):
  1120. sleep(0.02)
  1121. ```
  1122. Table
  1123. -----
  1124. #### Prints CSV file as ASCII table:
  1125. ```python
  1126. # $ pip3 install tabulate
  1127. from csv import reader
  1128. from tabulate import tabulate
  1129. with open(<filename>, encoding='utf-8', newline='') as csv_file:
  1130. reader = reader(csv_file, delimiter=';')
  1131. headers = [a.title() for a in next(reader)]
  1132. print(tabulate(reader, headers))
  1133. ```
  1134. Curses
  1135. ------
  1136. ```python
  1137. # $ pip3 install curses
  1138. from curses import wrapper
  1139. def main():
  1140. wrapper(draw)
  1141. def draw(screen):
  1142. screen.clear()
  1143. screen.addstr(0, 0, 'Press ESC to quit.')
  1144. while screen.getch() != 27:
  1145. pass
  1146. def get_border(screen):
  1147. from collections import namedtuple
  1148. P = namedtuple('P', 'x y')
  1149. height, width = screen.getmaxyx()
  1150. return P(width - 1, height - 1)
  1151. ```
  1152. Image
  1153. -----
  1154. #### Creates PNG image of greyscale gradient:
  1155. ```python
  1156. # $ pip3 install pillow
  1157. from PIL import Image
  1158. width, height = 100, 100
  1159. img = Image.new('L', (width, height), 'white')
  1160. img.putdata([255*a/(width*height) for a in range(width*height)])
  1161. img.save('out.png')
  1162. ```
  1163. ### Modes
  1164. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1165. * `'L'` - 8-bit pixels, greyscale.
  1166. * `'RGB'` - 3x8-bit pixels, true color.
  1167. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1168. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1169. Audio
  1170. -----
  1171. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1172. ```python
  1173. import wave, struct
  1174. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1175. wf = wave.open(<filename>, 'wb')
  1176. wf.setnchannels(1)
  1177. wf.setsampwidth(4)
  1178. wf.setframerate(44100)
  1179. wf.writeframes(b''.join(frames))
  1180. wf.close()
  1181. ```
  1182. Url
  1183. ---
  1184. ```python
  1185. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1186. ```
  1187. ### Encode
  1188. ```python
  1189. >>> quote("Can't be in URL!")
  1190. 'Can%27t%20be%20in%20URL%21'
  1191. >>> quote_plus("Can't be in URL!")
  1192. 'Can%27t+be+in+URL%21'
  1193. ```
  1194. ### Decode
  1195. ```python
  1196. >>> unquote('Can%27t+be+in+URL%21')
  1197. "Can't+be+in+URL!"
  1198. >>> unquote_plus('Can%27t+be+in+URL%21')
  1199. "Can't be in URL!"
  1200. ```
  1201. Scraping
  1202. --------
  1203. ```python
  1204. # $ pip3 install requests beautifulsoup4
  1205. >>> import requests
  1206. >>> from bs4 import BeautifulSoup
  1207. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1208. >>> page = requests.get(url)
  1209. >>> document = BeautifulSoup(page.text, 'html.parser')
  1210. >>> table = document.find('table', class_='infobox vevent')
  1211. >>> rows = table.find_all('tr')
  1212. >>> link = rows[11].find('a')['href']
  1213. 'https://www.python.org/'
  1214. >>> latest_v = rows[6].find('div').text.split()[0]
  1215. '3.7.2'
  1216. ```
  1217. Web
  1218. ---
  1219. ```python
  1220. # $ pip3 install bottle
  1221. import bottle
  1222. from urllib.parse import unquote
  1223. ```
  1224. ### Run
  1225. ```python
  1226. bottle.run(host='localhost', port=8080)
  1227. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1228. ```
  1229. ### Static Request
  1230. ```python
  1231. @route('/img/<image>')
  1232. def send_image(image):
  1233. return static_file(image, 'images/', mimetype='image/png')
  1234. ```
  1235. ### Dynamic Request
  1236. ```python
  1237. @route('/<sport>')
  1238. def send_page(sport):
  1239. sport = unquote(sport).lower()
  1240. page = read_file(sport)
  1241. return template(page)
  1242. ```
  1243. ### REST Request
  1244. ```python
  1245. @post('/odds/<sport>')
  1246. def odds_handler(sport):
  1247. team = bottle.request.forms.get('team')
  1248. team = unquote(team).lower()
  1249. db = sqlite3.connect(<db_path>)
  1250. home_odds, away_odds = get_odds(db, sport, team)
  1251. db.close()
  1252. response.headers['Content-Type'] = 'application/json'
  1253. response.headers['Cache-Control'] = 'no-cache'
  1254. return json.dumps([home_odds, away_odds])
  1255. ```
  1256. Profile
  1257. -------
  1258. ### Basic
  1259. ```python
  1260. from time import time
  1261. start_time = time() # Seconds since Epoch.
  1262. ...
  1263. duration = time() - start_time
  1264. ```
  1265. ### High Performance
  1266. ```python
  1267. from time import perf_counter as pc
  1268. start_time = pc() # Seconds since restart.
  1269. ...
  1270. duration = pc() - start_time
  1271. ```
  1272. ### Timing a Snippet
  1273. ```python
  1274. from timeit import timeit
  1275. timeit('"-".join(str(a) for a in range(100))',
  1276. number=10000, globals=globals(), setup='pass')
  1277. ```
  1278. ### Line Profiler
  1279. ```python
  1280. # $ pip3 install line_profiler
  1281. @profile
  1282. def main():
  1283. a = [*range(10000)]
  1284. b = {*range(10000)}
  1285. main()
  1286. ```
  1287. #### Usage:
  1288. ```text
  1289. $ kernprof -lv test.py
  1290. Line # Hits Time Per Hit % Time Line Contents
  1291. ==============================================================
  1292. 1 @profile
  1293. 2 def main():
  1294. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1295. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1296. ```
  1297. ### Call Graph
  1298. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1299. ```python
  1300. # $ pip3 install pycallgraph
  1301. from pycallgraph import output, PyCallGraph
  1302. from datetime import datetime
  1303. graph = output.GraphvizOutput()
  1304. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1305. graph.output_file = f'profile-{time_str}.png'
  1306. with PyCallGraph(output=graph):
  1307. <code_to_be_profiled>
  1308. ```
  1309. NumPy
  1310. -----
  1311. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1312. ```python
  1313. # $ pip3 install numpy
  1314. import numpy as np
  1315. ```
  1316. ```python
  1317. <array> = np.array(<list>)
  1318. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1319. <array> = np.ones(<shape>)
  1320. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1321. ```
  1322. ```python
  1323. first_column = <array>[:, 0] # Or: <array>[..., 0]
  1324. value = <array>.min([axis])
  1325. index = <array>.argmin([axis])
  1326. ```
  1327. ```python
  1328. <array>.shape = <shape>
  1329. <view> = <array>.reshape(<shape>)
  1330. <view> = np.broadcast_to(<array>, <shape>)
  1331. <el_or_array> = <array>[filter_expression]
  1332. ```
  1333. ### Broadcasting
  1334. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1335. ```python
  1336. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1337. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1338. ```
  1339. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1340. ```python
  1341. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1342. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1343. ```
  1344. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1345. ```python
  1346. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1347. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1348. ```
  1349. #### 3. If neither non-matching dimension has size 1, rise an error.
  1350. ### Example
  1351. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1352. ```python
  1353. >>> points = np.array([0.1, 0.6, 0.8])
  1354. [ 0.1, 0.6, 0.8]
  1355. >>> wrapped_points = points.reshape(3, 1)
  1356. [[ 0.1],
  1357. [ 0.6],
  1358. [ 0.8]]
  1359. >>> distances = wrapped_points - points
  1360. [[ 0. , -0.5, -0.7],
  1361. [ 0.5, 0. , -0.2],
  1362. [ 0.7, 0.2, 0. ]]
  1363. >>> distances = np.abs(distances)
  1364. [[ 0. , 0.5, 0.7],
  1365. [ 0.5, 0. , 0.2],
  1366. [ 0.7, 0.2, 0. ]]
  1367. >>> i = np.arange(3)
  1368. [0, 1, 2]
  1369. >>> distances[i, i] = np.inf
  1370. [[ inf, 0.5, 0.7],
  1371. [ 0.5, inf, 0.2],
  1372. [ 0.7, 0.2, inf]]
  1373. >>> distances.argmin(1)
  1374. [1, 2, 1]
  1375. ```
  1376. Basic Script Template
  1377. ---------------------
  1378. ```python
  1379. #!/usr/bin/env python3
  1380. #
  1381. # Usage: .py
  1382. #
  1383. from collections import namedtuple
  1384. from enum import Enum
  1385. import re
  1386. import sys
  1387. def main():
  1388. pass
  1389. ###
  1390. ## UTIL
  1391. #
  1392. def read_file(filename):
  1393. with open(filename, encoding='utf-8') as file:
  1394. return file.readlines()
  1395. if __name__ == '__main__':
  1396. main()
  1397. ```