From a2cd072b4e5179efcee341c0defd14137e24ea81 Mon Sep 17 00:00:00 2001 From: Mark Devlin Date: Tue, 5 Feb 2019 00:10:22 -0800 Subject: [PATCH 001/136] Slight correction to .strip descriptions Removes (or whitespace) from start of up to the first non- and from the end of up to the last non-. https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6e429db21..c4a272fb4 100644 --- a/README.md +++ b/README.md @@ -226,8 +226,8 @@ from numbers import Number, Integral, Real, Rational, Complex String ------ ```python - = .strip() # Strips all whitespace characters. - = .strip('') # Strips all passed characters. + = .strip() # Strips all whitespace characters from start and end. + = .strip('') # Strips all passed characters from start and end. ``` ```python From c20abfff6803d1671c322d1f8e4a989c7220366c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 11:48:41 +0100 Subject: [PATCH 002/136] String update --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c4a272fb4..b433f8073 100644 --- a/README.md +++ b/README.md @@ -226,8 +226,8 @@ from numbers import Number, Integral, Real, Rational, Complex String ------ ```python - = .strip() # Strips all whitespace characters from start and end. - = .strip('') # Strips all passed characters from start and end. + = .strip() # Strips all whitespace characters from both ends. + = .strip('') # Strips all passed characters from both ends. ``` ```python From 25d6465c340a00f2378c18d9637bcfb4a6946183 Mon Sep 17 00:00:00 2001 From: Til Boerner Date: Tue, 5 Feb 2019 20:08:10 +0100 Subject: [PATCH 003/136] Fix element skipping for empty iterators `next()` raises `StopIteration` when the iterator is empty. Providing a default returns that value instead, allowing to skip elements gracefully when you don't care if they exist. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b433f8073..3146c2a5a 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ Iterator #### Skips first element: ```python -next() +next(, None) # default of `None` avoids exception for empty for element in : ... ``` From 88d66b4f43b0375dd6eb2633f0aa3261e83ef7c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:19:28 +0100 Subject: [PATCH 004/136] Iterator section rearranged --- README.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3146c2a5a..11b4bac6a 100644 --- a/README.md +++ b/README.md @@ -168,13 +168,6 @@ Iterator = iter(, to_exclusive) ``` -#### Skips first element: -```python -next(, None) # default of `None` avoids exception for empty -for element in : - ... -``` - #### Reads input until it reaches an empty line: ```python for line in iter(input, ''): @@ -188,6 +181,17 @@ for line in iter(partial(input, 'Please enter value: '), ''): ... ``` +### Next +**Returns next item. If there are no more items it raises exception or returns default if specified.** + = next( [, default]) + +#### Skips first item: +```python +next(, None) +for element in : + ... +``` + Generator --------- From 884babeba43a29c73f4ba872174b2e552b4ea410 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:21:02 +0100 Subject: [PATCH 005/136] Iterator fix --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 11b4bac6a..9fe050937 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,9 @@ for line in iter(partial(input, 'Please enter value: '), ''): ### Next **Returns next item. If there are no more items it raises exception or returns default if specified.** +```python = next( [, default]) +``` #### Skips first item: ```python From bccd41a21c58dec2486f482f2ddf096c768843b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:24:58 +0100 Subject: [PATCH 006/136] Iterator section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9fe050937..c64e30b8c 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ for line in iter(partial(input, 'Please enter value: '), ''): #### Skips first item: ```python -next(, None) +next() for element in : ... ``` From 15d877a6999b0c931265db6d3c7aeec54fdbf997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:40:02 +0100 Subject: [PATCH 007/136] Removed the infamous no_duplicates example --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index c64e30b8c..191837f9e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,6 @@ sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) -no_duplicates = list(dict.fromkeys()) ``` ```python From 2e7e642214cb1bd81f2edb97a19e3454888de2fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:42:51 +0100 Subject: [PATCH 008/136] List --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 191837f9e..f580646d3 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,8 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) -list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) +list_of_chars = list() ``` ```python From a26a5e5cc5350e2a1aeba9c10bba6ad68549bb1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:43:37 +0100 Subject: [PATCH 009/136] List --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f580646d3..f79be8ff5 100644 --- a/README.md +++ b/README.md @@ -33,13 +33,13 @@ List ``` ```python +list_of_chars = list() sum_of_elements = sum() elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) product_of_elems = functools.reduce(lambda out, x: out * x, ) -list_of_chars = list() ``` ```python From 98a3e8df4f5006fdb277a63a4b6c0b24ef374777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 5 Feb 2019 21:46:45 +0100 Subject: [PATCH 010/136] Returned the infamous no_duplicates example, not yet ready --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f79be8ff5..c64e30b8c 100644 --- a/README.md +++ b/README.md @@ -33,13 +33,14 @@ List ``` ```python -list_of_chars = list() sum_of_elements = sum() elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) +list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) +no_duplicates = list(dict.fromkeys()) ``` ```python From 2578864f1d8a562b6184b8b395c0d0f3f9bcf03e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 6 Feb 2019 10:26:14 +0100 Subject: [PATCH 011/136] Added help section --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index c64e30b8c..f8453a8a9 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,15 @@ or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet). ![Monty Python](web/image_888.jpeg) +Help +---- +```python +>>> help() +>>> help() +>>> help() +``` + + Main ---- ```python From 1b6f455a36e16e8488b98a2b34445e13f2a55eed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 6 Feb 2019 10:27:08 +0100 Subject: [PATCH 012/136] Moved help section --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f8453a8a9..e3d78b3d0 100644 --- a/README.md +++ b/README.md @@ -7,20 +7,20 @@ or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet). ![Monty Python](web/image_888.jpeg) -Help +Main ---- ```python ->>> help() ->>> help() ->>> help() +if __name__ == '__main__': + main() ``` -Main +Help ---- ```python -if __name__ == '__main__': - main() +>>> help() +>>> help() +>>> help() ``` From 38eb428fbce43040fa95ff339272b7fac05d884f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 6 Feb 2019 10:29:18 +0100 Subject: [PATCH 013/136] Removed help section --- README.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/README.md b/README.md index e3d78b3d0..c64e30b8c 100644 --- a/README.md +++ b/README.md @@ -15,15 +15,6 @@ if __name__ == '__main__': ``` -Help ----- -```python ->>> help() ->>> help() ->>> help() -``` - - List ---- ```python From b35f4062805fc3f99cbc8d1db2d9481a266f7533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 10 Feb 2019 14:17:22 +0100 Subject: [PATCH 014/136] Added memoryview and pathlib --- README.md | 71 +++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 56 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index c64e30b8c..0fba54ba9 100644 --- a/README.md +++ b/README.md @@ -918,21 +918,6 @@ def write_to_file(filename, text): file.write(text) ``` -### Path -```python -from os import path, listdir - = path.exists() - = path.isfile() - = path.isdir() - = listdir() -``` - -```python ->>> from glob import glob ->>> glob('../*.gif') -['1.gif', 'card.gif'] -``` - ### Command Execution ```python import os @@ -957,6 +942,52 @@ b'.\n..\nfile1.txt\nfile2.txt\n' >>> sys.setrecursionlimit(5000) ``` +### Path +```python +from os import path, listdir + = path.exists() + = path.isfile() + = path.isdir() + = listdir() +``` + +```python +>>> from glob import glob +>>> glob('../*.gif') +['1.gif', 'card.gif'] +``` + + +Pathlib +------- +**This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** + +```python +from pathlib import Path +pwd = Path() + = Path('' [, '', , ...]) + = / '' / '' +``` + +```python + = .iterdir() # Returns all files in a dir. + = .glob('') # Returns all matches. + = .resolve() # Makes path absolute. + = .exists() + = .is_dir() + = .open() +``` + +```python + = str() # Returns path as string. + = .name # Final component. + = .stem # Final component without extension. + = .suffix # Final component's extension. + = .parent # Path without final component. + = .parts # All components as strings. +``` + + JSON ---- ```python @@ -1121,6 +1152,16 @@ from array import array ``` +Memory View +----------- +**Used for accessing the internal data of an object that supports the buffer protocol.** + +```python + = memoryview( / / ) +.release() +``` + + Deque ----- **A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** From fe73d3b7d81dc52d0d657d1b3c5eeafcf87b5a4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 10 Feb 2019 14:26:53 +0100 Subject: [PATCH 015/136] Pathlib --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 0fba54ba9..4f149f5a5 100644 --- a/README.md +++ b/README.md @@ -970,21 +970,21 @@ pwd = Path() ``` ```python - = .iterdir() # Returns all files in a dir. - = .glob('') # Returns all matches. - = .resolve() # Makes path absolute. - = .exists() - = .is_dir() - = .open() + = .iterdir() # Returns all files in a dir. + = .glob('') # Returns all matches. + = .resolve() # Makes path absolute. + = .exists() + = .is_dir() + = .open() ``` ```python - = str() # Returns path as string. - = .name # Final component. - = .stem # Final component without extension. - = .suffix # Final component's extension. - = .parent # Path without final component. - = .parts # All components as strings. + = str() # Returns path as string. + = .name # Final component. + = .stem # Final component without extension. + = .suffix # Final component's extension. + = .parent # Path without final component. + = .parts # All components as strings. ``` From f0045a67a454f6fac586709d01f278b77636483d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 11 Feb 2019 21:39:36 +0100 Subject: [PATCH 016/136] Eval --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4f149f5a5..a35ace7db 100644 --- a/README.md +++ b/README.md @@ -1405,7 +1405,7 @@ import ast from ast import Num, BinOp, UnaryOp import operator as op -legal_operators = {ast.Add: op.add, +LEGAL_OPERATORS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, @@ -1424,9 +1424,9 @@ def eval_node(node): if node_type not in [BinOp, UnaryOp]: raise TypeError(node) operator_type = type(node.op) - if operator_type not in legal_operators: + if operator_type not in LEGAL_OPERATORS: raise TypeError(f'Illegal operator {node.op}') - operator = legal_operators[operator_type] + operator = LEGAL_OPERATORS[operator_type] if node_type == BinOp: left, right = eval_node(node.left), eval_node(node.right) return operator(left, right) From d3f1490ac1f1238fba2a23b7ea2c0eec4de0ca0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 12 Feb 2019 10:49:59 +0100 Subject: [PATCH 017/136] Datetime --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a35ace7db..9b7d4ba0b 100644 --- a/README.md +++ b/README.md @@ -419,12 +419,12 @@ shuffle() Datetime -------- ```python -from datetime import datetime, strptime +from datetime import datetime now = datetime.now() now.month # 3 now.strftime('%Y%m%d') # '20180315' now.strftime('%Y%m%d%H%M%S') # '20180315002834' - = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') + = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') ``` From 0e0c25126a7dfb517c13aa4232eef06e7d7be543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 17 Feb 2019 20:14:18 +0100 Subject: [PATCH 018/136] Iterator --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b7d4ba0b..a018c0df8 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,8 @@ for line in iter(input, ''): #### Same, but prints a message every time: ```python from functools import partial -for line in iter(partial(input, 'Please enter value: '), ''): +promted_in = partial(input, 'Please enter value: ') +for line in iter(promted_in, ''): ... ``` From abc4f9a6c537d97ebe64f5e897ab854ef0fb4efd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 17 Feb 2019 20:15:09 +0100 Subject: [PATCH 019/136] Iterator --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a018c0df8..9b7d4ba0b 100644 --- a/README.md +++ b/README.md @@ -177,8 +177,7 @@ for line in iter(input, ''): #### Same, but prints a message every time: ```python from functools import partial -promted_in = partial(input, 'Please enter value: ') -for line in iter(promted_in, ''): +for line in iter(partial(input, 'Please enter value: '), ''): ... ``` From c54c4c57e961854019d8598098c4c0592dc4c9d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 00:27:25 +0100 Subject: [PATCH 020/136] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b7d4ba0b..16b96d98b 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ creature = Creature() Closure ------- **We have a closure in Python when:** -* **A nested function references a value of its enclosing function and then** +* **Nested function references a value of its enclosing function and then** * **the enclosing function returns the nested function.** ```python From 3504e1e281679e55104435b2c78c187bc2db77fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 00:31:47 +0100 Subject: [PATCH 021/136] Nonlocal --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 16b96d98b..1ddb871e6 100644 --- a/README.md +++ b/README.md @@ -575,7 +575,7 @@ from functools import partial ``` ### Nonlocal -**If variable is assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** ```python def get_counter(): From 4ddf6fae95eb77be94582bcdb4accd971ea3e95f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 00:38:23 +0100 Subject: [PATCH 022/136] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1ddb871e6..c9e71f5df 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ creature = Creature() Closure ------- **We have a closure in Python when:** -* **Nested function references a value of its enclosing function and then** +* **A nested function references a value of its enclosing function and then** * **the enclosing function returns the nested function.** ```python From 1b3ed0b6f5bb6591ffba6dccf0142cc52650532f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 13:54:05 +0100 Subject: [PATCH 023/136] Decorator --- README.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/README.md b/README.md index c9e71f5df..a8e3f6e65 100644 --- a/README.md +++ b/README.md @@ -635,13 +635,6 @@ def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) ``` -```python ->>> [fib(n) for n in range(10)] -[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ->>> fib.cache_info() -CacheInfo(hits=16, misses=10, maxsize=None, currsize=10) -``` - ### Parametrized Decorator ```python from functools import wraps From 64fcd5ef7971807a0f0cbc39fd7e6b25b520d244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 14:06:08 +0100 Subject: [PATCH 024/136] Open function --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8e3f6e65..0dfe67620 100644 --- a/README.md +++ b/README.md @@ -894,8 +894,8 @@ while True: * **`'w+'` - Read and write (truncate).** * **`'r+'` - Read and write from the beginning.** * **`'a+'` - Read and write from the end.** -* **`'b'` - Binary mode.** * **`'t'` - Text mode (default).** +* **`'b'` - Binary mode.** #### Read Text from File: ```python From c678fdbb39f1f3cd480eafcc470684557dc2a896 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:01:40 +0100 Subject: [PATCH 025/136] Open function --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 0dfe67620..ad916cc2d 100644 --- a/README.md +++ b/README.md @@ -897,6 +897,13 @@ while True: * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** +#### Seek: +```python +.seek(0) # Move to start of the file. +.seek(offset) # Move 'offset' chars/bytes from the start. +.seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. +```` + #### Read Text from File: ```python def read_file(filename): From 2b211771bf86911e1c6c66c446f0e1d69595b508 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:43:53 +0100 Subject: [PATCH 026/136] Pathlib --- README.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ad916cc2d..998c8b13f 100644 --- a/README.md +++ b/README.md @@ -964,18 +964,22 @@ Pathlib ```python from pathlib import Path -pwd = Path() - = Path('' [, '', , ...]) - = / '' / '' +pwd = Path() + = Path('' [, '', , ...]) + = / '' / '' ``` ```python - = .iterdir() # Returns all files in a dir. - = .glob('') # Returns all matches. - = .resolve() # Makes path absolute. = .exists() + = .is_file() = .is_dir() - = .open() + = .iterdir() +``` + +```python + = .glob('') # Returns all matches. + = .resolve() # Makes path absolute. + = .open() # Opens file. ``` ```python From a796eaf72483dc77340adaf6673f8f0981a55884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:45:42 +0100 Subject: [PATCH 027/136] Pathlib --- README.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 998c8b13f..8d933f526 100644 --- a/README.md +++ b/README.md @@ -964,31 +964,31 @@ Pathlib ```python from pathlib import Path -pwd = Path() - = Path('' [, '', , ...]) - = / '' / '' +pwd = Path() + = Path('' [, '', , ...]) + = / '' / '' ``` ```python - = .exists() - = .is_file() - = .is_dir() - = .iterdir() + = .exists() + = .is_file() + = .is_dir() + = .iterdir() ``` ```python - = .glob('') # Returns all matches. - = .resolve() # Makes path absolute. - = .open() # Opens file. + = .glob('') # Returns all matches. + = .resolve() # Makes path absolute. + = .open() # Opens file. ``` ```python - = str() # Returns path as string. - = .name # Final component. - = .stem # Final component without extension. - = .suffix # Final component's extension. - = .parent # Path without final component. - = .parts # All components as strings. + = str() # Returns path as string. + = .name # Final component. + = .stem # Final component without extension. + = .suffix # Final component's extension. + = .parent # Path without final component. + = .parts # All components as strings. ``` From 1d8d8c440f1d427ba5ff78bd1d70f722698cb9bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:47:21 +0100 Subject: [PATCH 028/136] Pathlib --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8d933f526..e304ded1d 100644 --- a/README.md +++ b/README.md @@ -978,8 +978,8 @@ pwd = Path() ```python = .glob('') # Returns all matches. - = .resolve() # Makes path absolute. = .open() # Opens file. + = .resolve() # Makes path absolute. ``` ```python From 2d8bfcf61fbcc6859b3747f1d4d18774a890be94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:52:58 +0100 Subject: [PATCH 029/136] Pathlib --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e304ded1d..a4628b860 100644 --- a/README.md +++ b/README.md @@ -977,18 +977,20 @@ pwd = Path() ``` ```python - = .glob('') # Returns all matches. - = .open() # Opens file. - = .resolve() # Makes path absolute. + = .glob('') # Returns all matches. ``` ```python + = .resolve() # Makes path absolute. = str() # Returns path as string. + = .parts # Returns all components as strings. +``` + +```python = .name # Final component. = .stem # Final component without extension. = .suffix # Final component's extension. = .parent # Path without final component. - = .parts # All components as strings. ``` From 7fc697d97dd3522a8d4f3999e78165cd0aaba174 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:54:35 +0100 Subject: [PATCH 030/136] Pathlib --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index a4628b860..3e15623f3 100644 --- a/README.md +++ b/README.md @@ -974,10 +974,7 @@ pwd = Path() = .is_file() = .is_dir() = .iterdir() -``` - -```python - = .glob('') # Returns all matches. + = .glob('') ``` ```python From ae9f5c9b83b008bde3ab2f6ef3f22c57b35b7e73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:56:39 +0100 Subject: [PATCH 031/136] Pathlib --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e15623f3..31c196e50 100644 --- a/README.md +++ b/README.md @@ -978,9 +978,9 @@ pwd = Path() ``` ```python - = .resolve() # Makes path absolute. = str() # Returns path as string. = .parts # Returns all components as strings. + = .resolve() # Makes path absolute. ``` ```python From 04e8bd4ec4b7380681c0a93d81fc0218e30718f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 15:58:10 +0100 Subject: [PATCH 032/136] Pathlib --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 31c196e50..d6fb2d7cb 100644 --- a/README.md +++ b/README.md @@ -978,16 +978,16 @@ pwd = Path() ``` ```python - = str() # Returns path as string. - = .parts # Returns all components as strings. - = .resolve() # Makes path absolute. + = str() # Returns path as string. + = .parts # Returns all components as strings. + = .resolve() # Makes path absolute. ``` ```python - = .name # Final component. - = .stem # Final component without extension. - = .suffix # Final component's extension. - = .parent # Path without final component. + = .name # Final component. + = .stem # Final component without extension. + = .suffix # Final component's extension. + = .parent # Path without final component. ``` From 13a5134e51d8bf857b4e4c704a2fa3ad243de334 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 16:00:07 +0100 Subject: [PATCH 033/136] Pathlib --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d6fb2d7cb..31c196e50 100644 --- a/README.md +++ b/README.md @@ -978,16 +978,16 @@ pwd = Path() ``` ```python - = str() # Returns path as string. - = .parts # Returns all components as strings. - = .resolve() # Makes path absolute. + = str() # Returns path as string. + = .parts # Returns all components as strings. + = .resolve() # Makes path absolute. ``` ```python - = .name # Final component. - = .stem # Final component without extension. - = .suffix # Final component's extension. - = .parent # Path without final component. + = .name # Final component. + = .stem # Final component without extension. + = .suffix # Final component's extension. + = .parent # Path without final component. ``` From 023741ef52c4718deccdf5aa5b8abd57efdb50f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 16:12:57 +0100 Subject: [PATCH 034/136] Bytes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31c196e50..d0bb3a061 100644 --- a/README.md +++ b/README.md @@ -1087,7 +1087,7 @@ Bytes ### Decode ```python - = .decode('utf-8') + = .decode(encoding='utf-8') = int.from_bytes(, byteorder='big|little', signed=False) = .hex() ``` From c1f7c6b914fe71a10891c13a7f34939a4ec03f53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 16:25:40 +0100 Subject: [PATCH 035/136] Product --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d0bb3a061..6bb772b1d 100644 --- a/README.md +++ b/README.md @@ -1238,9 +1238,9 @@ from itertools import * ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] ->>> product('ab', [1, 2]) -[('a', 1), ('a', 2), - ('b', 1), ('b', 2)] +>>> product('ab', '12') +[('a', '1'), ('a', '2'), + ('b', '1'), ('b', '2')] >>> product([0, 1], repeat=3) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), From 44258c23d0005678dd4b81bbd398ecdc3296923e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 19:34:08 +0100 Subject: [PATCH 036/136] Audio --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6bb772b1d..a37c4b7ce 100644 --- a/README.md +++ b/README.md @@ -1624,15 +1624,15 @@ wf.close() import simpleaudio, math, struct from itertools import chain, repeat F = 44100 -S1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,' -S2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,' +P1 = '71♪,69,,71♪,66,,62♪,66,,59♪,,,' +P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) get_hz = lambda n: 8.176 * 2 ** (int(n) / 12) parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125) get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) -samples_f = chain.from_iterable(get_note(n) for n in f'{S1}{S1}{S2}'.split(',')) +samples_f = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) samples_b = b''.join(struct.pack(' Date: Mon, 18 Feb 2019 19:41:12 +0100 Subject: [PATCH 037/136] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a37c4b7ce..3826fdba5 100644 --- a/README.md +++ b/README.md @@ -1777,7 +1777,7 @@ Line # Hits Time Per Hit % Time Line Contents ``` ### Call Graph -#### Generates a PNG image of call graph with highlighted bottlenecks: +#### Generates a PNG image of a call graph with highlighted bottlenecks: ```python # $ pip3 install pycallgraph From 81c51887a8b5f84551fe66d8d1c6699222ec4878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 19:43:59 +0100 Subject: [PATCH 038/136] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3826fdba5..f22455db6 100644 --- a/README.md +++ b/README.md @@ -1793,7 +1793,7 @@ with PyCallGraph(output=drawer): NumPy ----- -**Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.** +**Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.** ```python # $ pip3 install numpy From f404e625994b114f212498b49c15097fce45532f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 19:46:48 +0100 Subject: [PATCH 039/136] Script template --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index f22455db6..6d3d987b4 100644 --- a/README.md +++ b/README.md @@ -1903,8 +1903,7 @@ Basic Script Template from collections import namedtuple from enum import Enum -import re -import sys +import re, sys def main(): From 5f53c58f984f043c6505f3175f6dd043126697ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 19:47:22 +0100 Subject: [PATCH 040/136] Script template --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d3d987b4..f22455db6 100644 --- a/README.md +++ b/README.md @@ -1903,7 +1903,8 @@ Basic Script Template from collections import namedtuple from enum import Enum -import re, sys +import re +import sys def main(): From d991e2eac8068c6813dda4ee23ba951df8896aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 20:02:53 +0100 Subject: [PATCH 041/136] List --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index f22455db6..a7ee3c408 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,9 @@ List ---- ```python = [from_inclusive : to_exclusive : step_size] +``` + +```python .append() .extend() += [] From 25ae22e7a7d335e99a7716ba54fd6e4f9c199483 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 20:04:29 +0100 Subject: [PATCH 042/136] Set --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index a7ee3c408..f11ce450a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,9 @@ Set --- ```python = set() +``` + +```python .add() .update() |= {} From 9a05f192d584c3f80963d3696290ac1912cfcc89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:18:29 +0100 Subject: [PATCH 043/136] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f11ce450a..8c4c998b2 100644 --- a/README.md +++ b/README.md @@ -566,7 +566,7 @@ def get_multiplier(a): ``` * **If multiple nested functions within enclosing function reference the same value, that value gets shared.** -* **To dynamicaly acces functions first free variable use `'.__closure__[0].cell_contents'`.** +* **To dynamically access functions first free variable use: `'.__closure__[0].cell_contents'`.** #### Or: ```python From 47e8e600fce1693df67a04c9eec7af0d1dd56159 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:19:27 +0100 Subject: [PATCH 044/136] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c4c998b2..1a362d8e9 100644 --- a/README.md +++ b/README.md @@ -566,7 +566,7 @@ def get_multiplier(a): ``` * **If multiple nested functions within enclosing function reference the same value, that value gets shared.** -* **To dynamically access functions first free variable use: `'.__closure__[0].cell_contents'`.** +* **To dynamically access function's first free variable use: `'.__closure__[0].cell_contents'`.** #### Or: ```python From 581a1b7dda41aad22f5f55b450c3c8eb9cb26d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:20:59 +0100 Subject: [PATCH 045/136] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a362d8e9..0478be556 100644 --- a/README.md +++ b/README.md @@ -566,7 +566,7 @@ def get_multiplier(a): ``` * **If multiple nested functions within enclosing function reference the same value, that value gets shared.** -* **To dynamically access function's first free variable use: `'.__closure__[0].cell_contents'`.** +* **To dynamically access function's first free variable use `'.__closure__[0].cell_contents'`.** #### Or: ```python From 6641e6d9f6f73aef15d8c69eff9f7c9f9b693537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:29:09 +0100 Subject: [PATCH 046/136] Seek --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0478be556..dcd43eb16 100644 --- a/README.md +++ b/README.md @@ -908,7 +908,7 @@ while True: .seek(0) # Move to start of the file. .seek(offset) # Move 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. -```` +``` #### Read Text from File: ```python From eb0c10f030e8d47521e106c76bb6ebb5696d0c1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:41:28 +0100 Subject: [PATCH 047/136] Path --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dcd43eb16..c775011a1 100644 --- a/README.md +++ b/README.md @@ -889,7 +889,7 @@ while True: **Opens file and returns a corresponding file object.** ```python - = open(, mode='r', encoding=None) + = open('', mode='r', encoding=None) ``` #### Modes: @@ -951,10 +951,10 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ### Path ```python from os import path, listdir - = path.exists() - = path.isfile() - = path.isdir() - = listdir() + = path.exists('') + = path.isfile('') + = path.isdir('') + = listdir('') ``` ```python From d5f3f9f01dec8c69a6d32fe2e8666d9bac4b7e7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:46:22 +0100 Subject: [PATCH 048/136] Pathlib --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c775011a1..a44e64e70 100644 --- a/README.md +++ b/README.md @@ -986,7 +986,7 @@ pwd = Path() ```python = str() # Returns path as string. = .parts # Returns all components as strings. - = .resolve() # Makes path absolute. + = .resolve() # Returns absolute path. ``` ```python From c5fd061fe30388fdd2afbb171c0f1ade74c8fca9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Feb 2019 21:50:59 +0100 Subject: [PATCH 049/136] Pathlib --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a44e64e70..21a8dda99 100644 --- a/README.md +++ b/README.md @@ -986,7 +986,7 @@ pwd = Path() ```python = str() # Returns path as string. = .parts # Returns all components as strings. - = .resolve() # Returns absolute path. + = .resolve() # Returns absolute path without symlinks. ``` ```python From 5b2d188f66c4db3851b365b30aa154e25f93a9ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Feb 2019 14:21:18 +0100 Subject: [PATCH 050/136] Withable --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 21a8dda99..ddde837cc 100644 --- a/README.md +++ b/README.md @@ -758,6 +758,28 @@ class Counter: return self.a ``` +### Withable +```python +class FileReader(): + def __init__(self, filename): + self.filename = filename + def __enter__(self): + self.file = open(self.filename) + return self.file.read() + def __exit__(self, *args): + self.file.close() + print(f'FileReader closed {self.filename!r}') +``` + +```python +>>> with open('test.txt', 'w') as file: +... file.write('Hello World!') +>>> with FileReader('test.txt') as text: +... print(text) +Hello World! +FileReader closed 'test.txt' +``` + ### Copy ```python from copy import copy, deepcopy From 7974d5d2450a08e9cff44c8bb95d3012ac17a961 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Feb 2019 14:45:23 +0100 Subject: [PATCH 051/136] Withable --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index ddde837cc..f18cc7af4 100644 --- a/README.md +++ b/README.md @@ -768,7 +768,6 @@ class FileReader(): return self.file.read() def __exit__(self, *args): self.file.close() - print(f'FileReader closed {self.filename!r}') ``` ```python @@ -777,7 +776,6 @@ class FileReader(): >>> with FileReader('test.txt') as text: ... print(text) Hello World! -FileReader closed 'test.txt' ``` ### Copy From 45ae0d1f3bd8fe8c58ae531feddab56c19e543bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Feb 2019 14:52:47 +0100 Subject: [PATCH 052/136] Callable --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index f18cc7af4..9654ac521 100644 --- a/README.md +++ b/README.md @@ -758,6 +758,12 @@ class Counter: return self.a ``` +```python +>>> c = Counter() +>>> c(), c(), c() +(1, 2, 3) +``` + ### Withable ```python class FileReader(): From ccc4ebc441816ec9ab92243f4f109910a038ba08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Feb 2019 14:53:55 +0100 Subject: [PATCH 053/136] Callable --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9654ac521..9c49849c5 100644 --- a/README.md +++ b/README.md @@ -752,9 +752,9 @@ class MySequence: ```python class Counter: def __init__(self): - self.a = 0 + self.i = 0 def __call__(self): - self.a += 1 + self.i += 1 return self.a ``` From 5cb8a2ad46d544953956a7550dd70d3ccab3574a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Feb 2019 14:54:07 +0100 Subject: [PATCH 054/136] Callable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c49849c5..8981760da 100644 --- a/README.md +++ b/README.md @@ -755,7 +755,7 @@ class Counter: self.i = 0 def __call__(self): self.i += 1 - return self.a + return self.i ``` ```python From fee4178b42d013295215622c72460c383a767ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 20 Feb 2019 00:41:25 +0100 Subject: [PATCH 055/136] Withable --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8981760da..5f458ef80 100644 --- a/README.md +++ b/README.md @@ -766,12 +766,12 @@ class Counter: ### Withable ```python -class FileReader(): +class MyOpen(): def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename) - return self.file.read() + return self.file def __exit__(self, *args): self.file.close() ``` @@ -779,8 +779,8 @@ class FileReader(): ```python >>> with open('test.txt', 'w') as file: ... file.write('Hello World!') ->>> with FileReader('test.txt') as text: -... print(text) +>>> with MyOpen('test.txt') as file: +... print(file.read()) Hello World! ``` From 1c2cf8fd5e92c463cc37bcda6c2ee89dde395439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:24:55 +0100 Subject: [PATCH 056/136] A lot of small changes --- README.md | 153 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 79 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 5f458ef80..580398aa0 100644 --- a/README.md +++ b/README.md @@ -41,16 +41,15 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) -list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) -no_duplicates = list(dict.fromkeys()) +list_of_chars = list() ``` ```python index = .index() # Returns first index of item. .insert(index, ) # Inserts item at index and moves the rest to the right. = .pop([index]) # Removes and returns item at index or from the end. -.remove() # Removes first occurrence of item. +.remove() # Removes first occurrence of item or raises ValueError. .clear() # Removes all items. ``` @@ -64,17 +63,17 @@ Dictionary ``` ```python -value = .get(key, default) # Returns default if key does not exist. -value = .setdefault(key, default) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default=None) # Returns default if key does not exist. +value = .setdefault(key, default=None) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. - = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. +.update() # Or: dict_a = {**dict_a, **dict_b}. + = dict() # Initiates a dict from list of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two lists. + = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. ``` ```python @@ -88,8 +87,8 @@ value = .pop(key) # Removes item from dictionary. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> counter.most_common()[0][0] -'blue' +>>> counter.most_common()[0] +('blue', 3) ``` @@ -121,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable and can be used as a key in dictionary. +#### Is hashable so it can be used as a key in dictionary. ```python = frozenset() ``` @@ -130,10 +129,10 @@ Set Range ----- ```python -range(to_exclusive) -range(from_inclusive, to_exclusive) -range(from_inclusive, to_exclusive, step_size) -range(from_inclusive, to_exclusive, -step_size) + = range(to_exclusive) + = range(from_inclusive, to_exclusive) + = range(from_inclusive, to_exclusive, step_size) + = range(from_inclusive, to_exclusive, -step_size) ``` ```python @@ -153,7 +152,8 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- ```python ->>> Point = collections.namedtuple('Point', 'x y') +>>> from collections import namedtuple +>>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2) Point(x=1, y=2) >>> p[0] @@ -188,7 +188,7 @@ for line in iter(partial(input, 'Please enter value: '), ''): ``` ### Next -**Returns next item. If there are no more items it raises exception or returns default if specified.** +**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.** ```python = next( [, default]) ``` @@ -252,7 +252,7 @@ String = .replace(old_str, new_str) = .startswith() # Pass tuple of strings for multiple options. = .endswith() # Pass tuple of strings for multiple options. - = .index() # Returns first index of a substring. + = .index() # Returns start index of first match. = .isnumeric() # True if str contains only numeric characters. = textwrap.wrap(, width) # Nicely breaks string into lines. ``` @@ -288,7 +288,7 @@ import re * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** * **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** +* **Use `'?'` to make operator non-greedy.** ### Match Object ```python @@ -300,7 +300,7 @@ import re ``` ### Special Sequences -**Use capital letter for negation.** +**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -318,10 +318,10 @@ Format ```python >>> Person = namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) ->>> f'{person.height:10}' -' 187' ->>> '{p.height:10}'.format(p=person) -' 187' +>>> f'{person.height}' +'187' +>>> '{p.height}'.format(p=person) +'187' ``` ### General Options @@ -581,7 +581,7 @@ from functools import partial ``` ### Nonlocal -**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as 'global' or 'nonlocal'.** ```python def get_counter(): @@ -668,7 +668,7 @@ class : def __init__(self, a): self.a = a def __repr__(self): - class_name = type(self).__name__ + class_name = self.__class__.__name__ return f'{class_name}({self.a!r})' def __str__(self): return str(self.a) @@ -870,13 +870,6 @@ KeyboardInterrupt System ------ -### Command Line Arguments -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - ### Print Function ```python print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) @@ -974,7 +967,9 @@ b'.\n..\nfile1.txt\nfile2.txt\n' >>> sys.setrecursionlimit(5000) ``` -### Path + +Path +---- ```python from os import path, listdir = path.exists('') @@ -989,9 +984,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` - -Pathlib -------- +### Pathlib **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** ```python @@ -1023,6 +1016,36 @@ pwd = Path() ``` +Command Line Arguments +---------------------- +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser +desc = 'calculate X to the power of Y' +parser = ArgumentParser(description=desc) +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') +parser.add_argument('x', type=int, help='the base') +parser.add_argument('y', type=int, help='the exponent') +args = parser.parse_args() +answer = args.x ** args.y + +if args.quiet: + print(answer) +elif args.verbose: + print(f'{args.x} to the power {args.y} equals {answer}') +else: + print(f'{args.x}^{args.y} == {answer}') +``` + + JSON ---- ```python @@ -1037,14 +1060,14 @@ from collections import OrderedDict = json.loads(, object_pairs_hook=OrderedDict) ``` -### Read File +### Read Object from JSON File ```python def read_json_file(filename): with open(filename, encoding='utf-8') as file: return json.load(file) ``` -### Write to File +### Write Object to JSON File ```python def write_to_json_file(filename, an_object): with open(filename, 'w', encoding='utf-8') as file: @@ -1079,7 +1102,7 @@ SQLite ------ ```python import sqlite3 -db = sqlite3.connect() +db = sqlite3.connect('') ... db.close() ``` @@ -1114,7 +1137,7 @@ Bytes ```python = .encode(encoding='utf-8') = .to_bytes(length, byteorder='big|little', signed=False) - = bytes.fromhex() + = bytes.fromhex('') ``` ### Decode @@ -1166,7 +1189,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * **`'<'` - little-endian** * **`'>'` - big-endian** -#### Use capital letter for unsigned type. Standard size in brackets: +#### Use capital letter for unsigned type. Standard sizes are in brackets: * **`'x'` - pad byte** * **`'c'` - char (1)** * **`'h'` - short (2)** @@ -1183,7 +1206,7 @@ Array ```python from array import array - = array( [, ]) + = array('' [, ]) ``` @@ -1208,8 +1231,8 @@ from collections import deque ```python .appendleft() -.extendleft() # Collection gets reversed. = .popleft() +.extendleft() # Collection gets reversed. .rotate(n=1) # Rotates elements to the right. ``` @@ -1304,7 +1327,10 @@ from itertools import * >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) [2, 3] +``` +### Group by +```python >>> people = [{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Peter'}] @@ -1367,7 +1393,7 @@ param_names = list(sig.parameters.keys()) **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!).** ```python -type(, , ) + = type(, , ) ``` ```python @@ -1482,7 +1508,7 @@ def eval_node(node): Coroutine --------- -* **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().** +* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** * **Coroutines provide more powerful data routing possibilities than iterators.** * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** @@ -1551,29 +1577,6 @@ pyplot.show() ``` -Argparse --------- -```python -from argparse import ArgumentParser -desc = 'calculate X to the power of Y' -parser = ArgumentParser(description=desc) -group = parser.add_mutually_exclusive_group() -group.add_argument('-v', '--verbose', action='store_true') -group.add_argument('-q', '--quiet', action='store_true') -parser.add_argument('x', type=int, help='the base') -parser.add_argument('y', type=int, help='the exponent') -args = parser.parse_args() -answer = args.x ** args.y - -if args.quiet: - print(answer) -elif args.verbose: - print(f'{args.x} to the power {args.y} equals {answer}') -else: - print(f'{args.x}^{args.y} == {answer}') -``` - - Table ----- #### Prints CSV file as ASCII table: @@ -1641,12 +1644,14 @@ Audio #### Saves a list of floats with values between -1 and 1 to a WAV file: ```python import wave, struct -samples = [struct.pack('] +samples_f = [struct.pack('] +samples_b = b''.join(samples_f) + wf = wave.open('test.wav', 'wb') wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(44100) -wf.writeframes(b''.join(samples)) +wf.writeframes(samples_b) wf.close() ``` From 6c6791ce7d48a1a68ef8a617320c1c14ae232460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:30:46 +0100 Subject: [PATCH 057/136] Pathlib --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 580398aa0..bb8edb19b 100644 --- a/README.md +++ b/README.md @@ -970,6 +970,7 @@ b'.\n..\nfile1.txt\nfile2.txt\n' Path ---- +### Basic ```python from os import path, listdir = path.exists('') @@ -1018,6 +1019,7 @@ pwd = Path() Command Line Arguments ---------------------- +### Basic ```python import sys script_name = sys.argv[0] From e5b2646e9c62ccbad0bbd45e3be46a3394f4896b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:32:59 +0100 Subject: [PATCH 058/136] Pathlib --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bb8edb19b..b056fbcec 100644 --- a/README.md +++ b/README.md @@ -1111,7 +1111,7 @@ db.close() ### Read ```python -cursor = db.execute() +cursor = db.execute('') if cursor: = cursor.fetchone() # First row. = cursor.fetchall() # Remaining rows. @@ -1119,7 +1119,7 @@ if cursor: ### Write ```python -db.execute() +db.execute('') db.commit() ``` From 1f32a89027cdc51719a98d5fa4ad9eb5e16957a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 18:00:37 +0100 Subject: [PATCH 059/136] Argparse --- README.md | 87 +++++++++++++++++++------------------------------------ 1 file changed, 29 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index b056fbcec..33f857ed8 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ sum_of_elements = sum() elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) -flattened_list = list(itertools.chain.from_iterable()) +flatter_list = list(itertools.chain.from_iterable()) product_of_elems = functools.reduce(lambda out, x: out * x, ) list_of_chars = list() ``` @@ -968,6 +968,31 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` +Command Line Arguments +---------------------- +### Basic +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType + = ArgumentParser(description=) +.add_argument('-', '--', action='store_true') # Flag +.add_argument('-', '--', type=) # Option +.add_argument('', type=, nargs=1) # First argument +.add_argument('', type=, nargs='+') # Ramaining arguments + = .parse_args() +value = . +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + Path ---- ### Basic @@ -990,7 +1015,7 @@ from os import path, listdir ```python from pathlib import Path -pwd = Path() +cwd = Path() = Path('' [, '', , ...]) = / '' / '' ``` @@ -1017,37 +1042,6 @@ pwd = Path() ``` -Command Line Arguments ----------------------- -### Basic -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser -desc = 'calculate X to the power of Y' -parser = ArgumentParser(description=desc) -group = parser.add_mutually_exclusive_group() -group.add_argument('-v', '--verbose', action='store_true') -group.add_argument('-q', '--quiet', action='store_true') -parser.add_argument('x', type=int, help='the base') -parser.add_argument('y', type=int, help='the exponent') -args = parser.parse_args() -answer = args.x ** args.y - -if args.quiet: - print(answer) -elif args.verbose: - print(f'{args.x} to the power {args.y} equals {answer}') -else: - print(f'{args.x}^{args.y} == {answer}') -``` - - JSON ---- ```python @@ -1646,8 +1640,8 @@ Audio #### Saves a list of floats with values between -1 and 1 to a WAV file: ```python import wave, struct -samples_f = [struct.pack('] -samples_b = b''.join(samples_f) +samples_l = [struct.pack('] +samples_b = b''.join(samples_l) wf = wave.open('test.wav', 'wb') wf.setnchannels(1) @@ -1677,29 +1671,6 @@ simpleaudio.play_buffer(samples_b, 1, 2, F) ``` -Url ---- -```python -from urllib.parse import quote, quote_plus, unquote, unquote_plus -``` - -### Encode -```python ->>> quote("Can't be in URL!") -'Can%27t%20be%20in%20URL%21' ->>> quote_plus("Can't be in URL!") -'Can%27t+be+in+URL%21' -``` - -### Decode -```python ->>> unquote('Can%27t+be+in+URL%21') -"Can't+be+in+URL!" ->>> unquote_plus('Can%27t+be+in+URL%21') -"Can't be in URL!" -``` - - Scraping -------- ```python From 8ee1ef8d3b8c5a0965917e62013a79d78169a84d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 19:25:41 +0100 Subject: [PATCH 060/136] Splat --- README.md | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 33f857ed8..5cf949549 100644 --- a/README.md +++ b/README.md @@ -434,9 +434,10 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' ``` -Arguments ---------- -**`'*'` is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.** +Splat Operator +-------------- +### Inside Function Call +**`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** ```python args = (1, 2) @@ -449,7 +450,8 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -#### Splat operator can also be used in function declarations: +### Inside Function Declaration +#### Example: ```python def add(*a): return sum(a) @@ -460,7 +462,27 @@ def add(*a): 6 ``` -#### And in few other places: +#### Legal uses: +```python +def f(*args): pass # f(1, 2, 3) +def f(x, *args): pass # f(1, 2, 3) +def f(*args, z): pass # f(1, 2, z=3) +def f(x, *args, z): pass # f(1, 2, z=3) +``` + +```python +def f(**kwargs): pass # f(x=1, y=2, z=3) +def f(x, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +``` + +```python +def f(*args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) +def f(x, *args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) +def f(*args, y, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +def f(x, *args, z, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) +``` + +### Other Uses ```python >>> a = (1, 2, 3) >>> [*a] From 2cf44232abe5a3776a431c9bf6f68b8c9dfa67bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:03:01 +0100 Subject: [PATCH 061/136] Partial --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5cf949549..25c4a1b4f 100644 --- a/README.md +++ b/README.md @@ -590,7 +590,7 @@ def get_multiplier(a): * **If multiple nested functions within enclosing function reference the same value, that value gets shared.** * **To dynamically access function's first free variable use `'.__closure__[0].cell_contents'`.** -#### Or: +### Partial ```python from functools import partial = partial(, [, , ...]) @@ -1072,7 +1072,7 @@ import json = json.loads() ``` -#### To preserve order: +#### To preserve order use: ```python from collections import OrderedDict = json.loads(, object_pairs_hook=OrderedDict) From 5c8518119977592592863e5a0c81d2d91eaca545 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:42:03 +0100 Subject: [PATCH 062/136] Test of external link --- README.md | 3 ++- web/external_link.png | Bin 0 -> 3370 bytes 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 web/external_link.png diff --git a/README.md b/README.md index 25c4a1b4f..6be9e4627 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,8 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic +### Basic External link + ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') diff --git a/web/external_link.png b/web/external_link.png new file mode 100644 index 0000000000000000000000000000000000000000..4d5ee4077282f068e1a9fba02ab07c861518d242 GIT binary patch literal 3370 zcmbtX3se(V8pdH1M@4F9RRp(S?FL(|fH6D@m{_fk?eMA;L9IkFi3d_eQ9+@MgBIFT z1$umt00uao3ThC9iUI;bELsIpj}SzJ#I=Bu1W+IdadP)gu<7a9)9tpKb7#K$&;OkN z|L@$JuY&^C+D>zrW@Tk%yMEp3PpqsEI7O_cT0^Km_s(qyNkK%&M-W%9=KYTYK@c08 zDO0D~Oqw(aD$bt$H+cWUpS86$ilVb-y)hvP=O}7DVPV16)K>VEweORF4OWv7YjpAy zo2l5e=`&{9eVFwxzS<0 z!(=|seNoozgwonLmlN%r$40V_Q+9S`!#lR`W?!hZ1KoS~22}2fuI~t}6tZ25JKGX3 zhcya<+xxY;p^xXB(#ziJz1#gFaq09svg+FF*RF*%3s$z5jjH9L7d>OcgA6*lwY$4J z3i5?M@>e+tKgM5`(lH|2Y9vo7>$uGw$z4u0U{p=eK9|<;QUi@b0 zR&-t8-ss5q2^or#byErzm&!Q+}2dszF*uZI=MgF_F*Rww0PO-=!atH<&< zeJiReY7XfV_mpqxEQ-kH5rmIiV;|ld&{TJM+IK83P zPZOVdC+$hO1Mc;G2QXwj`Fr07Y5vg6&a2?_dUc#15)lI_Z_}CATzsLSf)rA1+bTH>Rkvvbg(w` z77Szy zTDW*2$qE8Qo=M81*?)ntUqE_y4y8#II+Ii}_!q9Eaj+P-?*!_!j>w~!?i_exu-}Fl zpMgTZH4;VII9HfHi&au!N`JtxFM#?{hTR7=47+)pI}GgIsOk|?Q&Ugy<7lVy0XN+1 zGsEcDx+hh8J-t5{dqsD^APJ4Qcg9p*F80XV`c0zzvo zsSJ-FCW62jUzfq#(mYeu!2nG#yAC|9&Fw|sa>rZ9jY`Znp7me@fRZnXlCvg1m%*>3 z{6IP(K=YVgCmSElQPhi){YD17sZ=HE)2EI_(j}Oor4|}kf$Pqb&_Lp^1`1%8L-`X1 zZeLcPH?^S|EuhDo_WO_IDBvQ-feFs9#0~Ca*PSm0XD^*M%#?{)USqwr!EGT4Hh~;G z$20^Aqc2n+amm7D8l&1gFOXuge;Hpthw~jKc3)Q1faYCca)A^auRQnACq7xK`MRgp zY%+mem`@s!YJTho#~7KHS47DLRlw7%yHSRjM)!f!X2+x1W+T_s;ucP8R~;=h z+v)doWTK6!Z8t|@Y?3Gjk6|;Ee*$={42*#7`3HJAa1V6GZ==g7g1@7I0fuT2nt>(y z1^Dp|Xo`sVU1*jt{&pZz9?NZ6Bm)c;$u`3Y3%uTze-|eFnS-#GS|YnV&m7>77WnPn z{GZf>KXVYr8h?pQ@!%K}pyFo>{82t9{Fzg*W+EX>mc-^P@%LKbzvTt;G-iJj30YXS z)IU!iqsqcg&Tihsrb=&wN3()Ly`r1YJJUpP&4xdgbMQrrbFK&x!Ixz!;{O)5)Z%qX z{sbsCE?Y2=lG@g(7nW62J06HAZENiMG!hZ$g{oCRweT9K7+D98KD_X=bmlUu)Whfs zqxLsMG^2MmHBQUog&zrDk1vXLT^xl7ngjy)<`r@|c9N5MibIw5l$NrBR9iw-P`G)T zgctr~6fH_M{W`ui3B2LvcaN#UifScnP1RS}_iMZ@Cp6}u_Uj3a>4MU^{Wjt0KP4nH z@ma6H$QBz0r^35 bGHAQWp^^C=#u-ZHkI4Fu0#;x8ke~c-V6Ak^ literal 0 HcmV?d00001 From c9a2f4ee996c0e1cec1b15d0cbd2defbc86b3b04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:43:30 +0100 Subject: [PATCH 063/136] Undo --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 6be9e4627..94cd212e2 100644 --- a/README.md +++ b/README.md @@ -1467,8 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic External link - +### Basic ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From b2d36e22b3b7e31bfecae0f785637fcafdb26c62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:46:31 +0100 Subject: [PATCH 064/136] Test with link character --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 94cd212e2..0a7865d99 100644 --- a/README.md +++ b/README.md @@ -1465,9 +1465,9 @@ last_el = op.methodcaller('pop')() ``` -Eval +Eval ---- -### Basic +### Basic [🔗](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From b30e304b2533745076d932f8d76bdc1f23c590eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:01 +0100 Subject: [PATCH 065/136] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a7865d99..0c7003068 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [🔗](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From bd3a970db6ee62e307d3dee90668d38913affd80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:28 +0100 Subject: [PATCH 066/136] Test with link character --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c7003068..e054240b6 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,8 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +### Basic +[⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 3162afe5f0b400b31a4e6ebbefbed0d77739c689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:50 +0100 Subject: [PATCH 067/136] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e054240b6..9485321b8 100644 --- a/README.md +++ b/README.md @@ -1468,7 +1468,7 @@ last_el = op.methodcaller('pop')() Eval ---- ### Basic -[⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 71d5d315c110df0bf2051253b1a0560607f03d3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:50:16 +0100 Subject: [PATCH 068/136] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9485321b8..a53f5f4cc 100644 --- a/README.md +++ b/README.md @@ -1468,7 +1468,7 @@ last_el = op.methodcaller('pop')() Eval ---- ### Basic -[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 755cc126ace9d0f184a4287bb6e1b9f51523e0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:50:45 +0100 Subject: [PATCH 069/136] Test with link character --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a53f5f4cc..14ced7ac2 100644 --- a/README.md +++ b/README.md @@ -1467,8 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic -[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 4ae9b39e4adaccb959ef6051a40811245a2734d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:51:43 +0100 Subject: [PATCH 070/136] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 14ced7ac2..5a82b05eb 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic [⬈](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 6aab6d6011692a897fa9c08265660897f16be0fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:57:11 +0100 Subject: [PATCH 071/136] Test with links to docs --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5a82b05eb..bdeceacec 100644 --- a/README.md +++ b/README.md @@ -1446,7 +1446,7 @@ class MyClass(metaclass=MyMetaClass): ``` -Operator +Operator [⬈](https://docs.python.org/3/library/operator.html) -------- ```python from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ @@ -1478,7 +1478,7 @@ Eval ValueError: malformed node or string ``` -### Using Abstract Syntax Trees +### Using Abstract Syntax Trees [⬈](https://docs.python.org/3/library/ast.html#ast.parse) ```python import ast from ast import Num, BinOp, UnaryOp From 1855b66cb84ec047213970327d700e4568f1a7e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 22:06:29 +0100 Subject: [PATCH 072/136] Removed links to docs --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bdeceacec..39aeb5a51 100644 --- a/README.md +++ b/README.md @@ -1446,7 +1446,7 @@ class MyClass(metaclass=MyMetaClass): ``` -Operator [⬈](https://docs.python.org/3/library/operator.html) +Operator -------- ```python from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬈](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') @@ -1478,7 +1478,7 @@ Eval ValueError: malformed node or string ``` -### Using Abstract Syntax Trees [⬈](https://docs.python.org/3/library/ast.html#ast.parse) +### Using Abstract Syntax Trees ```python import ast from ast import Num, BinOp, UnaryOp From 2f602ffe81d3523b2c81b1065c1733de0a17035f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:02:43 +0100 Subject: [PATCH 073/136] Splat --- README.md | 45 +++++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 39aeb5a51..f91bd7ff4 100644 --- a/README.md +++ b/README.md @@ -434,9 +434,23 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' ``` -Splat Operator --------------- +Arguments +--------- ### Inside Function Call +```python +() # f(0, 0) +() # f(x=0, y=0) +(, ) # f(0, y=0) +``` + +### Inside Function Definition +```python +def f() # def f(x, y) +def f() # def f(x=0, y=0) +def f(, ) # def f(x, y=0) +``` + +### Splat operator **`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** ```python @@ -450,8 +464,7 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -### Inside Function Declaration -#### Example: +#### Splat example: ```python def add(*a): return sum(a) @@ -462,24 +475,24 @@ def add(*a): 6 ``` -#### Legal uses: +### Legal Argument Definitions and Calls ```python -def f(*args): pass # f(1, 2, 3) -def f(x, *args): pass # f(1, 2, 3) -def f(*args, z): pass # f(1, 2, z=3) -def f(x, *args, z): pass # f(1, 2, z=3) +def f(*args) # f(1, 2, 3) +def f(x, *args) # f(1, 2, 3) +def f(*args, z) # f(1, 2, z=3) +def f(x, *args, z) # f(1, 2, z=3) ``` ```python -def f(**kwargs): pass # f(x=1, y=2, z=3) -def f(x, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +def f(**kwargs) # f(x=1, y=2, z=3) +def f(x, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) ``` ```python -def f(*args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) -def f(x, *args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) -def f(*args, y, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) -def f(x, *args, z, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) +def f(*args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(x, *args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(*args, y, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(x, *args, z, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) ``` ### Other Uses @@ -1006,7 +1019,7 @@ from argparse import ArgumentParser, FileType .add_argument('-', '--', action='store_true') # Flag .add_argument('-', '--', type=) # Option .add_argument('', type=, nargs=1) # First argument -.add_argument('', type=, nargs='+') # Ramaining arguments +.add_argument('', type=, nargs='+') # Remaining arguments = .parse_args() value = . ``` From 3a1966ea5a0999362ece6f64c2190fc3970d1120 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:55:21 +0100 Subject: [PATCH 074/136] Splat --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f91bd7ff4..b1fa623e2 100644 --- a/README.md +++ b/README.md @@ -450,9 +450,9 @@ def f() # def f(x=0, y=0) def f(, ) # def f(x, y=0) ``` -### Splat operator -**`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** - +Splat Operator +-------------- +### Inside Function Call ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -464,7 +464,8 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -#### Splat example: +### Inside Function Definition +**It combines zero or more positional arguments into tuple.** ```python def add(*a): return sum(a) @@ -475,7 +476,7 @@ def add(*a): 6 ``` -### Legal Argument Definitions and Calls +#### Legal argument combinations and calls: ```python def f(*args) # f(1, 2, 3) def f(x, *args) # f(1, 2, 3) From b4e4c2e87f7da416f36c6f5c33188778134eca04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:55:44 +0100 Subject: [PATCH 075/136] Splat --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b1fa623e2..3ec797d5a 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,7 @@ def f() # def f(x=0, y=0) def f(, ) # def f(x, y=0) ``` + Splat Operator -------------- ### Inside Function Call From 944293ae7cabcb47385dfb8efea8254a8e1e1b46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 02:21:59 +0100 Subject: [PATCH 076/136] Splat --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ec797d5a..8701be02c 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,7 @@ def f(, ) # def f(x, y=0) Splat Operator -------------- ### Inside Function Call +**Splat expands collection into positional arguments, while splatty-splat expands dictionary into keyword arguments.** ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -466,7 +467,7 @@ func(1, 2, x=3, y=4, z=5) ``` ### Inside Function Definition -**It combines zero or more positional arguments into tuple.** +**Splat combines zero or more positional arguments into tuple, while splatty-splat combines zero or more keyword arguments into dictionary.** ```python def add(*a): return sum(a) From 79e0992f85374b645db0b7807405ccf510c14599 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 03:47:28 +0100 Subject: [PATCH 077/136] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8701be02c..3124c0ed4 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,9 @@ value = .setdefault(key, default=None) # Same, but also adds default to ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. - = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. + = dict() # Initiates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two collections. + = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. ``` ```python From a704092ad25957c765d9f7dc10925be16832bffa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 03:56:18 +0100 Subject: [PATCH 078/136] Counter, frozenset --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3124c0ed4..e75020141 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ value = .pop(key) # Removes item from dictionary. ### Counter ```python >>> from collections import Counter ->>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] +>>> colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue'] >>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) >>> counter.most_common()[0] @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable so it can be used as a key in dictionary. +#### Is hashable, meaning it can be used as a key in dictionary. ```python = frozenset() ``` From 2572ebcf5d0437f680add38a1b41dd68626cb09b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 04:46:07 +0100 Subject: [PATCH 079/136] Numbers --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e75020141..e2d08bbc2 100644 --- a/README.md +++ b/README.md @@ -377,8 +377,8 @@ Format * **`'X'` - HEX** -Numbers -------- +Math +---- ### Basic Functions ```python = pow(, ) # Or: ** @@ -412,7 +412,9 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` -### Random + +Random +------ ```python from random import random, randint, choice, shuffle = random() @@ -478,7 +480,7 @@ def add(*a): 6 ``` -#### Legal argument combinations and calls: +#### Legal argument combinations with calls: ```python def f(*args) # f(1, 2, 3) def f(x, *args) # f(1, 2, 3) @@ -1424,7 +1426,7 @@ param_names = list(sig.parameters.keys()) ``` ### Type -**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!).** +**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** ```python = type(, , ) From 87074fcedcf542d1f8fc4f403f7409ea065c281b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 05:15:52 +0100 Subject: [PATCH 080/136] Numbers --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e2d08bbc2..0c9b2c225 100644 --- a/README.md +++ b/README.md @@ -377,8 +377,8 @@ Format * **`'X'` - HEX** -Math ----- +Numbers +------- ### Basic Functions ```python = pow(, ) # Or: ** @@ -412,9 +412,7 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` - -Random ------- +### Random ```python from random import random, randint, choice, shuffle = random() From f71c5319b0c6bc308be4d947a3e8d9374117a704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 05:38:04 +0100 Subject: [PATCH 081/136] Command line arguments --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0c9b2c225..da94875b7 100644 --- a/README.md +++ b/README.md @@ -1018,13 +1018,13 @@ arguments = sys.argv[1:] ### Argparse ```python from argparse import ArgumentParser, FileType - = ArgumentParser(description=) -.add_argument('-', '--', action='store_true') # Flag -.add_argument('-', '--', type=) # Option -.add_argument('', type=, nargs=1) # First argument -.add_argument('', type=, nargs='+') # Remaining arguments - = .parse_args() -value = . +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. ``` * **Use `'help='` for argument description.** From 7269cd91852aee86cf0b03e640ba7c4a6644274b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 06:04:00 +0100 Subject: [PATCH 082/136] System --- README.md | 132 +++++++++++++++++++++++++++++------------------------- 1 file changed, 70 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index da94875b7..da44b286a 100644 --- a/README.md +++ b/README.md @@ -888,7 +888,7 @@ while True: break ``` -#### Raising exception: +### Raising Exception ```python raise ValueError('A very specific message!') ``` @@ -906,16 +906,15 @@ KeyboardInterrupt ``` -System ------- -### Print Function +Print +----- ```python print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for errors.** -#### Pretty print: +### Pretty Print ```python >>> from pprint import pprint >>> pprint(dir()) @@ -924,7 +923,9 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) '__doc__', ...] ``` -### Input Function + +Input +----- * **Reads a line from user input or pipe if present.** * **The trailing newline gets stripped.** * **The prompt string is printed to standard output before reading input.** @@ -942,14 +943,16 @@ while True: break ``` -### Open Function + +Open +---- **Opens file and returns a corresponding file object.** ```python = open('', mode='r', encoding=None) ``` -#### Modes: +### Modes * **`'r'` - Read (default).** * **`'w'` - Write (truncate).** * **`'x'` - Write or fail if the file already exists.** @@ -960,80 +963,30 @@ while True: * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** -#### Seek: +### Seek ```python .seek(0) # Move to start of the file. .seek(offset) # Move 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. ``` -#### Read Text from File: +### Read Text from File ```python def read_file(filename): with open(filename, encoding='utf-8') as file: return file.readlines() ``` -#### Write Text to File: +### Write Text to File ```python def write_to_file(filename, text): with open(filename, 'w', encoding='utf-8') as file: file.write(text) ``` -### Command Execution -```python -import os - = os.popen().read() -``` - -#### Or: -```python ->>> import subprocess ->>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) ->>> a.stdout -b'.\n..\nfile1.txt\nfile2.txt\n' ->>> a.returncode -0 -``` - -### Recursion Limit -```python ->>> import sys ->>> sys.getrecursionlimit() -1000 ->>> sys.setrecursionlimit(5000) -``` - - -Command Line Arguments ----------------------- -### Basic -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser, FileType -p = ArgumentParser(description=) -p.add_argument('-', '--', action='store_true') # Flag -p.add_argument('-', '--', type=) # Option -p.add_argument('', type=, nargs=1) # Argument -p.add_argument('', type=, nargs='+') # Arguments -args = p.parse_args() -value = args. -``` - -* **Use `'help='` for argument description.** -* **Use `'type=FileType()'` for files.** - Path ---- -### Basic ```python from os import path, listdir = path.exists('') @@ -1048,7 +1001,9 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` -### Pathlib + +Pathlib +------- **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** ```python @@ -1080,6 +1035,59 @@ cwd = Path() ``` +Command Line Arguments +---------------------- +### Basic +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + +Command Execution +----------------- +```python +import os + = os.popen().read() +``` + +#### Or: +```python +>>> import subprocess +>>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) +>>> a.stdout +b'.\n..\nfile1.txt\nfile2.txt\n' +>>> a.returncode +0 +``` + + +Recursion Limit +--------------- +```python +>>> import sys +>>> sys.getrecursionlimit() +1000 +>>> sys.setrecursionlimit(5000) +``` + + JSON ---- ```python From 4c9319bea3ea5f087e8d89498b0fe64f4248c28a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 17:48:39 +0100 Subject: [PATCH 083/136] Lambda, Closure --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index da44b286a..dcfcb48fb 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ import re ``` ### Special Sequences -**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.** +**Expressions below hold true for strings that contain only ASCII characters. Use capital letter for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -516,8 +516,8 @@ Inline ------ ### Lambda ```python -lambda: -lambda , : + = lambda: + = lambda , : ``` ### Comprehension @@ -609,7 +609,7 @@ def get_multiplier(a): ### Partial ```python from functools import partial - = partial(, [, , ...]) + = partial( [, , , ...]) ``` ```python @@ -619,7 +619,7 @@ from functools import partial ``` ### Nonlocal -**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as 'global' or 'nonlocal'.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or 'nonlocal'.** ```python def get_counter(): From 6c133b61235e262cb876c7b722eed783c487f136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 20:57:23 +0100 Subject: [PATCH 084/136] Small fixes --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dcfcb48fb..15cb66eaf 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,7 @@ from functools import lru_cache @lru_cache(maxsize=None) def fib(n): - return n if n < 2 else fib(n-1) + fib(n-2) + return n if n < 2 else fib(n-2) + fib(n-1) ``` ### Parametrized Decorator @@ -927,8 +927,8 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Input ----- * **Reads a line from user input or pipe if present.** -* **The trailing newline gets stripped.** -* **The prompt string is printed to standard output before reading input.** +* **Trailing newline gets stripped.** +* **Prompt string is printed to the standard output before reading input.** ```python = input(prompt=None) @@ -958,14 +958,14 @@ Open * **`'x'` - Write or fail if the file already exists.** * **`'a'` - Append.** * **`'w+'` - Read and write (truncate).** -* **`'r+'` - Read and write from the beginning.** +* **`'r+'` - Read and write from the start.** * **`'a+'` - Read and write from the end.** * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** ### Seek ```python -.seek(0) # Move to start of the file. +.seek(0) # Move to the start of the file. .seek(offset) # Move 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. ``` @@ -1274,6 +1274,9 @@ from collections import deque ```python .appendleft() = .popleft() +``` + +```python .extendleft() # Collection gets reversed. .rotate(n=1) # Rotates elements to the right. ``` From af2e851940e185a0f7a1fe295c10de3a87f9b5a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 15:09:31 +0100 Subject: [PATCH 085/136] Small fixes --- README.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 15cb66eaf..d92f3c03b 100644 --- a/README.md +++ b/README.md @@ -1166,7 +1166,7 @@ db.commit() Bytes ----- -**Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.** +**Bytes object is immutable sequence of single bytes. Mutable version is called 'bytearray'.** ```python = b'' @@ -1178,7 +1178,7 @@ Bytes ### Encode ```python = .encode(encoding='utf-8') - = .to_bytes(length, byteorder='big|little', signed=False) + = .to_bytes(, byteorder='big|little', signed=False) = bytes.fromhex('') ``` @@ -1244,7 +1244,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' Array ----- -**List that can only hold elements of predefined type. Available types are listed above.** +**List that can hold only elements of predefined type. Available types are listed above.** ```python from array import array @@ -1264,7 +1264,7 @@ Memory View Deque ----- -**A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** +**Thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** ```python from collections import deque @@ -1349,8 +1349,8 @@ from itertools import * ### Infinite iterators ```python ->>> i = count(5, 2) ->>> next(i), next(i), next(i) +>>> a = count(5, 2) +>>> next(a), next(a), next(a) (5, 7, 9) >>> a = cycle('abc') @@ -1662,7 +1662,7 @@ def get_border(screen): Image ----- -#### Creates PNG image of greyscale gradient: +#### Creates PNG image of rainbow gradient: ```python # $ pip3 install pillow from PIL import Image @@ -1671,9 +1671,10 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img = Image.new('L', (width, height), 'white') -img.putdata(pixels) -img.save('test.png') +img_hsv = Image.new('HSV', (width, height), 'white') +img_hsv.putdata([(int(a), 255, 255) for a in pixels]) +img_rgb = img_hsv.convert(mode='RGB') +img_rgb.save('test.png') ``` ### Modes From c7335d9ee7c4d9a3ba5dde28b8b809fdd3680dca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 18:43:13 +0100 Subject: [PATCH 086/136] Statistics, CSV --- README.md | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d92f3c03b..8efdb6d64 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,11 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` +### Statistics +```python +from statistics import mean, median, variance, pvariance, pstdev +``` + ### Random ```python from random import random, randint, choice, shuffle @@ -1088,6 +1093,28 @@ Recursion Limit ``` +CSV +--- +```python +import csv +``` + +### Read Rows from CSV File +```python +def read_csv_file(filename): + with open(filename, encoding='utf-8') as file: + return csv.reader(file, delimiter=';') +``` + +### Write Rows to CSV File +```python +def write_to_csv_file(filename, rows): + with open(filename, 'w', encoding='utf-8') as file: + writer = csv.writer(file, delimiter=';') + writer.writerows(rows) +``` + + JSON ---- ```python @@ -1366,8 +1393,8 @@ from itertools import * >>> chain([1, 2], range(3, 5)) [1, 2, 3, 4] ->>> compress('abc', [True, 0, 1]) -['a', 'c'] +>>> compress([1, 2, 3, 4], [True, False, 1, 0]) +[1, 3] >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) @@ -1468,8 +1495,7 @@ class MyMetaClass(type): ```python class MyClass(metaclass=MyMetaClass): - def __init__(self): - self.b = 12345 + b = 12345 ``` From aa68b5a04791602311642e02f72f32edd8bba2f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:18:52 +0100 Subject: [PATCH 087/136] Pathlib --- README.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8efdb6d64..f3c566205 100644 --- a/README.md +++ b/README.md @@ -1006,11 +1006,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` - -Pathlib -------- -**This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** - +### Pathlib ```python from pathlib import Path cwd = Path() @@ -1042,7 +1038,6 @@ cwd = Path() Command Line Arguments ---------------------- -### Basic ```python import sys script_name = sys.argv[0] @@ -1072,7 +1067,7 @@ import os = os.popen().read() ``` -#### Or: +### Subprocess ```python >>> import subprocess >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) From 10da42c3a24524f1761bc9f6c60b799c02a84a11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:23:18 +0100 Subject: [PATCH 088/136] Deck --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3c566205..d3afffb2a 100644 --- a/README.md +++ b/README.md @@ -1286,7 +1286,7 @@ Memory View Deque ----- -**Thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** +**Thread-safe list with efficient appends and pops from either side. Pronounced "deck".** ```python from collections import deque From 3fec1cd3210c22a19037ccda9b1335d68f36d185 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:26:55 +0100 Subject: [PATCH 089/136] Iterators --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d3afffb2a..2bf27cae3 100644 --- a/README.md +++ b/README.md @@ -1385,15 +1385,15 @@ from itertools import * ### Iterators ```python ->>> chain([1, 2], range(3, 5)) +>>> chain([1, 2], [3, 4]) [1, 2, 3, 4] >>> compress([1, 2, 3, 4], [True, False, 1, 0]) [1, 3] >>> # islice(, from_inclusive, to_exclusive) ->>> islice([1, 2, 3], 1, None) -[2, 3] +>>> islice([1, 2, 3, 4], 2, None) +[3, 4] ``` ### Group by From c50967eac7952cd6a1bf23bab5b0a2b431337059 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 21:30:35 +0100 Subject: [PATCH 090/136] Arguments --- README.md | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 2bf27cae3..b5af873c6 100644 --- a/README.md +++ b/README.md @@ -949,6 +949,30 @@ while True: ``` +Command Line Arguments +---------------------- +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + Open ---- **Opens file and returns a corresponding file object.** @@ -1036,30 +1060,6 @@ cwd = Path() ``` -Command Line Arguments ----------------------- -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser, FileType -p = ArgumentParser(description=) -p.add_argument('-', '--', action='store_true') # Flag -p.add_argument('-', '--', type=) # Option -p.add_argument('', type=, nargs=1) # Argument -p.add_argument('', type=, nargs='+') # Arguments -args = p.parse_args() -value = args. -``` - -* **Use `'help='` for argument description.** -* **Use `'type=FileType()'` for files.** - - Command Execution ----------------- ```python From 547f8b07b9a72e59bd978354efa2d343429d019e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:20:48 +0100 Subject: [PATCH 091/136] Image --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b5af873c6..1eb967505 100644 --- a/README.md +++ b/README.md @@ -1692,12 +1692,22 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img_hsv = Image.new('HSV', (width, height), 'white') +img_hsv = Image.new('HSV', (width, height)) img_hsv.putdata([(int(a), 255, 255) for a in pixels]) img_rgb = img_hsv.convert(mode='RGB') img_rgb.save('test.png') ``` +#### Adds noise to image: +```python +from random import randint +add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) +img = Image.open('test.png').convert(mode='HSV') +pixels = [(add_noise(h), s, v) for h, s, v in img.getdata()] +img.putdata(pixels) +img.convert(mode='RGB').save('test.png') +``` + ### Modes * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.** * **`'L'` - 8-bit pixels, greyscale.** From fd88d66ab7c6959e0d99e1da19f19e1ec3bc9b82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:22:10 +0100 Subject: [PATCH 092/136] Image --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1eb967505..743a1b8d9 100644 --- a/README.md +++ b/README.md @@ -1683,10 +1683,13 @@ def get_border(screen): Image ----- -#### Creates PNG image of rainbow gradient: ```python # $ pip3 install pillow from PIL import Image +``` + +#### Creates PNG image of rainbow gradient: +```python width = 100 height = 100 size = width * height From d9778749b75503d2bf4082a27bd8862de9431010 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:23:02 +0100 Subject: [PATCH 093/136] Table --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 743a1b8d9..d833a5272 100644 --- a/README.md +++ b/README.md @@ -1648,8 +1648,8 @@ Table #### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate -import csv from tabulate import tabulate +import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') headers = [header.title() for header in next(lines)] From 0b0c276be15301b90b7ecca82ffb68884c15a94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:31:08 +0100 Subject: [PATCH 094/136] Libraries --- README.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index d833a5272..75c908086 100644 --- a/README.md +++ b/README.md @@ -1624,6 +1624,9 @@ Progress Bar ```python # $ pip3 install tqdm from tqdm import tqdm +``` + +```python from time import sleep for i in tqdm([1, 2, 3]): sleep(0.2) @@ -1637,6 +1640,9 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot +``` + +```python pyplot.plot( [, , ...]) pyplot.savefig(, transparent=True) pyplot.show() @@ -1645,10 +1651,13 @@ pyplot.show() Table ----- -#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from tabulate import tabulate +``` + +#### Prints CSV file as ASCII table: +```python import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') @@ -1663,7 +1672,9 @@ Curses ```python # $ pip3 install curses from curses import wrapper +``` +```python def main(): wrapper(draw) @@ -1695,19 +1706,17 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img_hsv = Image.new('HSV', (width, height)) -img_hsv.putdata([(int(a), 255, 255) for a in pixels]) -img_rgb = img_hsv.convert(mode='RGB') -img_rgb.save('test.png') +img = Image.new('HSV', (width, height)) +img.putdata([(int(a), 255, 255) for a in pixels]) +img.convert(mode='RGB').save('test.png') ``` -#### Adds noise to image: +#### Adds noise to an image: ```python from random import randint add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) -img = Image.open('test.png').convert(mode='HSV') -pixels = [(add_noise(h), s, v) for h, s, v in img.getdata()] -img.putdata(pixels) +img = Image.open('test.png').convert(mode='HSV') +img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()]) img.convert(mode='RGB').save('test.png') ``` From a4a27f1a38461b872887d47d4e0893eb73dc887b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:34:41 +0100 Subject: [PATCH 095/136] Libraries --- README.md | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/README.md b/README.md index 75c908086..5bf11b84e 100644 --- a/README.md +++ b/README.md @@ -1624,9 +1624,6 @@ Progress Bar ```python # $ pip3 install tqdm from tqdm import tqdm -``` - -```python from time import sleep for i in tqdm([1, 2, 3]): sleep(0.2) @@ -1640,9 +1637,6 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot -``` - -```python pyplot.plot( [, , ...]) pyplot.savefig(, transparent=True) pyplot.show() @@ -1651,13 +1645,10 @@ pyplot.show() Table ----- +#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from tabulate import tabulate -``` - -#### Prints CSV file as ASCII table: -```python import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') @@ -1672,9 +1663,7 @@ Curses ```python # $ pip3 install curses from curses import wrapper -``` -```python def main(): wrapper(draw) From c3730fabb7f16139c884526324289e89dbdd8693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 02:34:08 +0100 Subject: [PATCH 096/136] Audio --- README.md | 63 +++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5bf11b84e..0e28b7647 100644 --- a/README.md +++ b/README.md @@ -1195,6 +1195,7 @@ Bytes = [] = [] = b''.join() + = list() ``` ### Encode @@ -1232,9 +1233,10 @@ Struct * **Machine’s native type sizes and byte order are used by default.** ```python -from struct import pack, unpack, calcsize +from struct import pack, unpack, iter_unpack, calcsize = pack('', [, , ...]) = unpack('', ) + = iter_unpack('', ) ``` ### Example @@ -1700,7 +1702,7 @@ img.putdata([(int(a), 255, 255) for a in pixels]) img.convert(mode='RGB').save('test.png') ``` -#### Adds noise to an image: +#### Adds noise to PNG image: ```python from random import randint add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) @@ -1719,21 +1721,50 @@ img.convert(mode='RGB').save('test.png') Audio ----- -#### Saves a list of floats with values between -1 and 1 to a WAV file: ```python -import wave, struct -samples_l = [struct.pack('] -samples_b = b''.join(samples_l) +import wave +from struct import pack, iter_unpack +``` + +### Read Frames from WAV File +```python +def read_wav_file(filename): + with wave.open(filename, 'rb') as wf: + frames = wf.readframes(wf.getnframes()) + return [a[0] for a in iter_unpack(' 2 else 0.125) get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) -samples_f = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) -samples_b = b''.join(struct.pack(' Date: Tue, 26 Feb 2019 02:46:05 +0100 Subject: [PATCH 097/136] Libraries --- README.md | 202 +++++++++++++++++++++++++++--------------------------- 1 file changed, 101 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 0e28b7647..0afd11919 100644 --- a/README.md +++ b/README.md @@ -1683,107 +1683,6 @@ def get_border(screen): ``` -Image ------ -```python -# $ pip3 install pillow -from PIL import Image -``` - -#### Creates PNG image of rainbow gradient: -```python -width = 100 -height = 100 -size = width * height -pixels = [255 * i/size for i in range(size)] - -img = Image.new('HSV', (width, height)) -img.putdata([(int(a), 255, 255) for a in pixels]) -img.convert(mode='RGB').save('test.png') -``` - -#### Adds noise to PNG image: -```python -from random import randint -add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) -img = Image.open('test.png').convert(mode='HSV') -img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()]) -img.convert(mode='RGB').save('test.png') -``` - -### Modes -* **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.** -* **`'L'` - 8-bit pixels, greyscale.** -* **`'RGB'` - 3x8-bit pixels, true color.** -* **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.** -* **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.** - - -Audio ------ -```python -import wave -from struct import pack, iter_unpack -``` - -### Read Frames from WAV File -```python -def read_wav_file(filename): - with wave.open(filename, 'rb') as wf: - frames = wf.readframes(wf.getnframes()) - return [a[0] for a in iter_unpack(' 2 else 0.125) -get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) -frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) -frames_b = b''.join(struct.pack(' 2 else 0.125) +get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) +frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) +frames_b = b''.join(struct.pack(' Date: Tue, 26 Feb 2019 02:52:19 +0100 Subject: [PATCH 098/136] Image --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0afd11919..2095606f0 100644 --- a/README.md +++ b/README.md @@ -1982,7 +1982,7 @@ def write_to_wav_file(filename, frames_int): ```python from math import pi, sin sin_f = lambda i: sin(i * 2 * pi * 440 / 44100) -frames_f = (sin_f(a) for a in range(100000)) +frames_f = (sin_f(i) for i in range(100000)) frames_i = (int(a * 30000) for a in frames_f) write_to_wav_file('test.wav', frames_i) ``` From 2632e43cedb0985ab29dc875d037fa4c850c8393 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 02:56:32 +0100 Subject: [PATCH 099/136] Audio --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 2095606f0..c9ace2872 100644 --- a/README.md +++ b/README.md @@ -1981,8 +1981,7 @@ def write_to_wav_file(filename, frames_int): #### Saves a sine wave to a WAV file: ```python from math import pi, sin -sin_f = lambda i: sin(i * 2 * pi * 440 / 44100) -frames_f = (sin_f(i) for i in range(100000)) +frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000)) frames_i = (int(a * 30000) for a in frames_f) write_to_wav_file('test.wav', frames_i) ``` From 7729ac2270e0eed734b545cc503b58e00e1cf698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:00:11 +0100 Subject: [PATCH 100/136] Audio --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index c9ace2872..7b0919f5b 100644 --- a/README.md +++ b/README.md @@ -1990,8 +1990,7 @@ write_to_wav_file('test.wav', frames_i) ```python from random import randint add_noise = lambda value: max(-32768, min(32768, value + randint(-500, 500))) -frames_i = read_wav_file('test.wav') -frames_i = (add_noise(a) for a in frames_i) +frames_i = (add_noise(a) for a in read_wav_file('test.wav')) write_to_wav_file('test.wav', frames_i) ``` From f87b411399a4886d54080e5456c7f35ebb0c48d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:22:08 +0100 Subject: [PATCH 101/136] Splat --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7b0919f5b..6d17de8ee 100644 --- a/README.md +++ b/README.md @@ -485,8 +485,8 @@ def add(*a): #### Legal argument combinations with calls: ```python -def f(*args) # f(1, 2, 3) -def f(x, *args) # f(1, 2, 3) +def f(*args): # f(1, 2, 3) +def f(x, *args): # f(1, 2, 3) def f(*args, z) # f(1, 2, z=3) def f(x, *args, z) # f(1, 2, z=3) ``` From 206381652979521d9f96dad72400a36ce36899be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:23:23 +0100 Subject: [PATCH 102/136] Arguments --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 6d17de8ee..b18b464e7 100644 --- a/README.md +++ b/README.md @@ -450,9 +450,9 @@ Arguments ### Inside Function Definition ```python -def f() # def f(x, y) -def f() # def f(x=0, y=0) -def f(, ) # def f(x, y=0) +def f(): # def f(x, y) +def f(): # def f(x=0, y=0) +def f(, ): # def f(x, y=0) ``` @@ -485,22 +485,22 @@ def add(*a): #### Legal argument combinations with calls: ```python -def f(*args): # f(1, 2, 3) -def f(x, *args): # f(1, 2, 3) -def f(*args, z) # f(1, 2, z=3) -def f(x, *args, z) # f(1, 2, z=3) +def f(*args): # f(1, 2, 3) +def f(x, *args): # f(1, 2, 3) +def f(*args, z): # f(1, 2, z=3) +def f(x, *args, z): # f(1, 2, z=3) ``` ```python -def f(**kwargs) # f(x=1, y=2, z=3) -def f(x, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(**kwargs): # f(x=1, y=2, z=3) +def f(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) ``` ```python -def f(*args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) -def f(x, *args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) -def f(*args, y, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) -def f(x, *args, z, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) +def f(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) ``` ### Other Uses From 1b7112c1a65045c5802c6d53cf87f65b94f4f59e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 12:01:23 +0100 Subject: [PATCH 103/136] Audio --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b18b464e7..be84d18b7 100644 --- a/README.md +++ b/README.md @@ -1968,17 +1968,17 @@ def read_wav_file(filename): ### Write Frames to WAV File ```python -def write_to_wav_file(filename, frames_int): +def write_to_wav_file(filename, frames_int, mono=True): frames_short = (pack(' Date: Tue, 26 Feb 2019 12:20:12 +0100 Subject: [PATCH 104/136] Itertools --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index be84d18b7..3421d127e 100644 --- a/README.md +++ b/README.md @@ -1390,12 +1390,12 @@ from itertools import * >>> chain([1, 2], [3, 4]) [1, 2, 3, 4] ->>> compress([1, 2, 3, 4], [True, False, 1, 0]) -[1, 3] - >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3, 4], 2, None) [3, 4] + +>>> compress([1, 2, 3, 4], [True, False, 1, 0]) +[1, 3] ``` ### Group by From 7b2ec812e5d50f8769011a887bc07d4d2bb7d6bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:04:03 +0100 Subject: [PATCH 105/136] Itertools split --- README.md | 141 +++++++++++++++++++++++++----------------------------- 1 file changed, 64 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 3421d127e..0dcb93280 100644 --- a/README.md +++ b/README.md @@ -206,19 +206,46 @@ Generator **Convenient way to implement the iterator protocol.** ```python -def step(start, step_size): +def count(start, step): while True: yield start - start += step_size + start += step ``` ```python ->>> stepper = step(10, 2) ->>> next(stepper), next(stepper), next(stepper) +>>> counter = count(10, 2) +>>> next(counter), next(counter), next(counter) (10, 12, 14) ``` +Itertools +--------- +* **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!** + +```python +from itertools import islice, count, repeat, cycle, chain +``` + +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) +``` + +```python + = count(start=0, step=1) # Counter. + = repeat( [, times]) # Returns element endlesly or times times. + = cycle() # Repeats the sequence indefinately. +``` + +```python + = chain(, [, ...]) # Empties sequences in order. + = chain.from_iterable() # Empties sequences inside a sequence in order. +``` + + Type ---- ```python @@ -427,6 +454,39 @@ shuffle() ``` +Combinatorics +------------- +* **Every function returns an iterator.** +* **If you want to print the iterator, you need to pass it to the list() function!** + +```python +from itertools import combinations, combinations_with_replacement, permutations, product +``` + +```python +>>> combinations('abc', 2) +[('a', 'b'), ('a', 'c'), ('b', 'c')] + +>>> combinations_with_replacement('abc', 2) +[('a', 'a'), ('a', 'b'), ('a', 'c'), + ('b', 'b'), ('b', 'c'), + ('c', 'c')] + +>>> permutations('abc', 2) +[('a', 'b'), ('a', 'c'), + ('b', 'a'), ('b', 'c'), + ('c', 'a'), ('c', 'b')] + +>>> product('ab', '12') +[('a', '1'), ('a', '2'), + ('b', '1'), ('b', '2')] + +>>> product([0, 1], repeat=3) +[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] +``` + + Datetime -------- ```python @@ -1338,79 +1398,6 @@ Hashlib ``` -Itertools ---------- -* **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!** - -```python -from itertools import * -``` - -### Combinatoric iterators -```python ->>> combinations('abc', 2) -[('a', 'b'), ('a', 'c'), ('b', 'c')] - ->>> combinations_with_replacement('abc', 2) -[('a', 'a'), ('a', 'b'), ('a', 'c'), - ('b', 'b'), ('b', 'c'), - ('c', 'c')] - ->>> permutations('abc', 2) -[('a', 'b'), ('a', 'c'), - ('b', 'a'), ('b', 'c'), - ('c', 'a'), ('c', 'b')] - ->>> product('ab', '12') -[('a', '1'), ('a', '2'), - ('b', '1'), ('b', '2')] - ->>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), - (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] -``` - -### Infinite iterators -```python ->>> a = count(5, 2) ->>> next(a), next(a), next(a) -(5, 7, 9) - ->>> a = cycle('abc') ->>> [next(a) for _ in range(10)] -['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a'] - ->>> repeat(10, 3) -[10, 10, 10] -``` - -### Iterators -```python ->>> chain([1, 2], [3, 4]) -[1, 2, 3, 4] - ->>> # islice(, from_inclusive, to_exclusive) ->>> islice([1, 2, 3, 4], 2, None) -[3, 4] - ->>> compress([1, 2, 3, 4], [True, False, 1, 0]) -[1, 3] -``` - -### Group by -```python ->>> people = [{'id': 1, 'name': 'Bob'}, - {'id': 2, 'name': 'Bob'}, - {'id': 3, 'name': 'Peter'}] ->>> groups = groupby(people, key=lambda a: a['name']) ->>> {name: list(group) for name, group in groups} -{'Bob': [{'id': 1, 'name': 'Bob'}, - {'id': 2, 'name': 'Bob'}], - 'Peter': [{'id': 3, 'name': 'Peter'}]} -``` - - Introspection and Metaprograming -------------------------------- **Inspecting code at runtime and code that generates code. You can:** From 9d549d37be8e2954d101ca9ab309a7af4bd5cf82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:07:14 +0100 Subject: [PATCH 106/136] Itertools --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0dcb93280..ba9887566 100644 --- a/README.md +++ b/README.md @@ -235,14 +235,14 @@ from itertools import islice, count, repeat, cycle, chain ``` ```python - = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlesly or times times. - = cycle() # Repeats the sequence indefinately. + = count(start=0, step=1) # Counter. + = repeat( [, times]) # Returns element endlesly or times times. + = cycle() # Repeats the sequence indefinately. ``` ```python - = chain(, [, ...]) # Empties sequences in order. - = chain.from_iterable() # Empties sequences inside a sequence in order. + = chain(, ) # Empties sequences in order. + = chain.from_iterable() # Empties sequences inside a sequence in order. ``` From 7a73252058130ffb49afb0b3c80b2584408ed924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:09:09 +0100 Subject: [PATCH 107/136] Itertools --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ba9887566..f3de31fee 100644 --- a/README.md +++ b/README.md @@ -236,8 +236,8 @@ from itertools import islice, count, repeat, cycle, chain ```python = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlesly or times times. - = cycle() # Repeats the sequence indefinately. + = repeat( [, times]) # Returns element endlessly or times times. + = cycle() # Repeats the sequence indefinitely. ``` ```python From 1cfcdf644ce52d71a7b472737149c4d503379e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:36:49 +0100 Subject: [PATCH 108/136] Iterator --- README.md | 61 ++++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index f3de31fee..fc4824370 100644 --- a/README.md +++ b/README.md @@ -169,11 +169,37 @@ Point(x=1, y=2) Iterator -------- +* **If you want to print the iterator, you need to pass it to the list() function.** +* **In this cheatsheet `''` can also mean an iterator.** + +```python +from itertools import islice, count, repeat, cycle, chain +``` + ```python = iter() - = iter(, to_exclusive) + = iter(, to_exclusive) # Sequence of return values until 'to_exclusive'. + = next( [, default]) # Raises StopIteration or returns 'default' on end. +``` + +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) ``` +```python + = count(start=0, step=1) # Returns incremented integer endlessly. + = repeat( [, times]) # Returns element endlessly or 'times' times. + = cycle() # Repeats the sequence indefinitely. +``` + +```python + = chain(, ) # Empties collections in order. + = chain.from_iterable() # Empties collections inside a collection in order. +``` + +### Examples #### Reads input until it reaches an empty line: ```python for line in iter(input, ''): @@ -187,12 +213,6 @@ for line in iter(partial(input, 'Please enter value: '), ''): ... ``` -### Next -**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.** -```python - = next( [, default]) -``` - #### Skips first item: ```python next() @@ -219,33 +239,6 @@ def count(start, step): ``` -Itertools ---------- -* **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!** - -```python -from itertools import islice, count, repeat, cycle, chain -``` - -```python - = islice(, to_exclusive) - = islice(, from_inclusive, to_exclusive) - = islice(, from_inclusive, to_exclusive, step_size) -``` - -```python - = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlessly or times times. - = cycle() # Repeats the sequence indefinitely. -``` - -```python - = chain(, ) # Empties sequences in order. - = chain.from_iterable() # Empties sequences inside a sequence in order. -``` - - Type ---- ```python From 1119309c07047656a106673780beddc89f964656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:39:45 +0100 Subject: [PATCH 109/136] Iterator --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fc4824370..86734a25a 100644 --- a/README.md +++ b/README.md @@ -182,12 +182,6 @@ from itertools import islice, count, repeat, cycle, chain = next( [, default]) # Raises StopIteration or returns 'default' on end. ``` -```python - = islice(, to_exclusive) - = islice(, from_inclusive, to_exclusive) - = islice(, from_inclusive, to_exclusive, step_size) -``` - ```python = count(start=0, step=1) # Returns incremented integer endlessly. = repeat( [, times]) # Returns element endlessly or 'times' times. @@ -199,6 +193,12 @@ from itertools import islice, count, repeat, cycle, chain = chain.from_iterable() # Empties collections inside a collection in order. ``` +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) +``` + ### Examples #### Reads input until it reaches an empty line: ```python From 417949b4c707db0d4cd65add2d66d1705175b888 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:43:34 +0100 Subject: [PATCH 110/136] Iterator --- README.md | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/README.md b/README.md index 86734a25a..355c11ed3 100644 --- a/README.md +++ b/README.md @@ -199,27 +199,6 @@ from itertools import islice, count, repeat, cycle, chain = islice(, from_inclusive, to_exclusive, step_size) ``` -### Examples -#### Reads input until it reaches an empty line: -```python -for line in iter(input, ''): - ... -``` - -#### Same, but prints a message every time: -```python -from functools import partial -for line in iter(partial(input, 'Please enter value: '), ''): - ... -``` - -#### Skips first item: -```python -next() -for element in : - ... -``` - Generator --------- From 04f99a98f81764376215ee5f9982998eca390f5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:48:48 +0100 Subject: [PATCH 111/136] Combinatorics --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 355c11ed3..8289fb395 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,14 @@ from itertools import combinations, combinations_with_replacement, permutations, ``` ```python +>>> product([0, 1], repeat=3) +[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] + +>>> product('ab', '12') +[('a', '1'), ('a', '2'), + ('b', '1'), ('b', '2')] + >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] @@ -448,14 +456,6 @@ from itertools import combinations, combinations_with_replacement, permutations, [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] - ->>> product('ab', '12') -[('a', '1'), ('a', '2'), - ('b', '1'), ('b', '2')] - ->>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), - (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` From 136a46e223d31c3d13299f218352a23d241b4bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:15:35 +0100 Subject: [PATCH 112/136] Named tuple --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 8289fb395..c40404278 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,9 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- +* **Tuple is an immutable and hashable list.** +* **Named tuple is a subclass of tuple with named elements.** + ```python >>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') From 687415145ccb75250420a5492c2f26da2dbc65ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:20:41 +0100 Subject: [PATCH 113/136] Set --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c40404278..83a8237c4 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable, meaning it can be used as a key in dictionary. +#### Is hashable, meaning it can be used as a key in dictionary or element in set. ```python = frozenset() ``` From 2d027eb500ad5d974e61f09e3378b1744d31ce31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:23:37 +0100 Subject: [PATCH 114/136] Set --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83a8237c4..b24ff9a2f 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable, meaning it can be used as a key in dictionary or element in set. +#### Is hashable, meaning it can be used as a key in dictionary or as an element in set. ```python = frozenset() ``` From 291eef5290bdb81bae725bc004c246445c711880 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:26:34 +0100 Subject: [PATCH 115/136] Named tuple --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b24ff9a2f..4db6f3547 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- * **Tuple is an immutable and hashable list.** -* **Named tuple is a subclass of tuple with named elements.** +* **Named tuple is its subclass with named elements.** ```python >>> from collections import namedtuple From 6d77f8116568c3d87caf2a95d3b51d4fe9d9c3ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:29:00 +0100 Subject: [PATCH 116/136] Dictionary --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4db6f3547..3909388d3 100644 --- a/README.md +++ b/README.md @@ -63,17 +63,17 @@ Dictionary ``` ```python -value = .get(key, default=None) # Returns default if key does not exist. -value = .setdefault(key, default=None) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default=None) # Returns default if key does not exist. +value = .setdefault(key, default=None) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two collections. - = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. +.update() # Or: dict_a = {**dict_a, **dict_b}. + = dict() # Initiates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two collections. + = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. ``` ```python From ab388b13f1a6605ae80bb2bb03d88b099642ff69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:35:48 +0100 Subject: [PATCH 117/136] Dict --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3909388d3..5f58833bd 100644 --- a/README.md +++ b/README.md @@ -65,15 +65,15 @@ Dictionary ```python value = .get(key, default=None) # Returns default if key does not exist. value = .setdefault(key, default=None) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. + = collections.defaultdict() # Creates a dict with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dict with default value 1. ``` ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two collections. - = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. + = dict() # Inits a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Inits a dict from two collections. + = dict.fromkeys(keys [, value]) # Inits a dict from collection of keys. ``` ```python From 24250c0b6cc9e455931b0dac9dec850a75d78108 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:37:48 +0100 Subject: [PATCH 118/136] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5f58833bd..41d4313b2 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,9 @@ value = .setdefault(key, default=None) # Same, but also adds default to ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Inits a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Inits a dict from two collections. - = dict.fromkeys(keys [, value]) # Inits a dict from collection of keys. + = dict() # Creates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Creates a dict from two collections. + = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys. ``` ```python From a60f8be910333642a9016c43bc64d038266413e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:42:20 +0100 Subject: [PATCH 119/136] Iterator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41d4313b2..94acf6230 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ from itertools import islice, count, repeat, cycle, chain ``` ```python - = count(start=0, step=1) # Returns incremented integer endlessly. + = count(start=0, step=1) # Returns incremented value endlessly. = repeat( [, times]) # Returns element endlessly or 'times' times. = cycle() # Repeats the sequence indefinitely. ``` From 142183f258b29353b36fb01b10e9a13ea8a83ab0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:46:56 +0100 Subject: [PATCH 120/136] Combinatorics --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 94acf6230..689b2abf0 100644 --- a/README.md +++ b/README.md @@ -435,7 +435,7 @@ Combinatorics * **If you want to print the iterator, you need to pass it to the list() function!** ```python -from itertools import combinations, combinations_with_replacement, permutations, product +from itertools import product, combinations, combinations_with_replacement, permutations ``` ```python From f76948068a781a91556a66bf8502e06687c3f687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:49:15 +0100 Subject: [PATCH 121/136] Partial --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 689b2abf0..975f2003e 100644 --- a/README.md +++ b/README.md @@ -649,7 +649,7 @@ def get_multiplier(a): ### Partial ```python from functools import partial - = partial( [, , , ...]) + = partial( [, , , ...]) ``` ```python From 28b5ad2958aea8954c5f723ab2be9af91ffece35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:56:24 +0100 Subject: [PATCH 122/136] Bytes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 975f2003e..6dfb4518d 100644 --- a/README.md +++ b/README.md @@ -1229,8 +1229,8 @@ Bytes = b'' = [] = [] - = b''.join() = list() + = b''.join() ``` ### Encode From ab9e750aad2a52b4fb57d5359bf887fb2bcf3997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:58:19 +0100 Subject: [PATCH 123/136] Struct --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6dfb4518d..f8826260c 100644 --- a/README.md +++ b/README.md @@ -1269,9 +1269,9 @@ Struct ```python from struct import pack, unpack, iter_unpack, calcsize - = pack('', [, , ...]) - = unpack('', ) - = iter_unpack('', ) + = pack('', [, , ...]) + = unpack('', ) + = iter_unpack('', ) ``` ### Example From 0fa17890fc7309378c0b8db77eb65e0f2d385347 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:05:57 +0100 Subject: [PATCH 124/136] Attributes --- README.md | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index f8826260c..319f830dd 100644 --- a/README.md +++ b/README.md @@ -1391,25 +1391,10 @@ Introspection and Metaprograming ### Attributes ```python -class Z: - def __init__(self): - self.a = 'abcde' - self.b = 12345 -``` - -```python ->>> z = Z() - ->>> vars(z) -{'a': 'abcde', 'b': 12345} - ->>> getattr(z, 'a') -'abcde' - ->>> hasattr(z, 'c') -False - ->>> setattr(z, 'c', 10) + = vars() + = hasattr(, '') +value = getattr(, '') +setattr(, '', value) ``` ### Parameters From 64f1f82d5f2a87d2948c524d0980409c3f891574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:15:42 +0100 Subject: [PATCH 125/136] Metaclass --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 319f830dd..e84aa071f 100644 --- a/README.md +++ b/README.md @@ -1442,6 +1442,11 @@ class MyClass(metaclass=MyMetaClass): b = 12345 ``` +```python +>>> MyClass.a, MyClass.b +('abcde', 12345) +``` + Operator -------- From be02c4923d5ff5a6899b09d1b640dac36d040283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:19:39 +0100 Subject: [PATCH 126/136] Introspection --- README.md | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e84aa071f..97186bb30 100644 --- a/README.md +++ b/README.md @@ -1373,15 +1373,8 @@ Hashlib ``` -Introspection and Metaprograming --------------------------------- -**Inspecting code at runtime and code that generates code. You can:** -* **Look at the attributes** -* **Set new attributes** -* **Create functions dynamically** -* **Traverse the parent classes** -* **Change values in the class** - +Introspection +------------- ### Variables ```python = dir() # Names of in-scope variables. @@ -1405,6 +1398,9 @@ no_of_params = len(sig.parameters) param_names = list(sig.parameters.keys()) ``` + +Metaprograming +-------------- ### Type **Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** From 0f9fb0d947355b9ab7763eccf4b72f47682db7a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:21:11 +0100 Subject: [PATCH 127/136] Metaprograming --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 97186bb30..629cf1cce 100644 --- a/README.md +++ b/README.md @@ -1401,6 +1401,8 @@ param_names = list(sig.parameters.keys()) Metaprograming -------------- +**Code that generates code.** + ### Type **Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** From e8abd0baa9c2ab2279e0f957176ed8d3eace052d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:22:43 +0100 Subject: [PATCH 128/136] Introspection --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 629cf1cce..ebaaab8e7 100644 --- a/README.md +++ b/README.md @@ -1375,6 +1375,8 @@ Hashlib Introspection ------------- +**Inspecting code at runtime.** + ### Variables ```python = dir() # Names of in-scope variables. From ceb5a2e186a981b972436f360a2b044c1bf8f35a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 18:44:37 +0100 Subject: [PATCH 129/136] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ebaaab8e7..a77dffd3e 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ Format ``` ```python ->>> Person = namedtuple('Person', 'name height') +>>> Person = collections.namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) >>> f'{person.height}' '187' From 9d03a3d57e1ee6ceab346853955d1fc902e11b7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 18:58:13 +0100 Subject: [PATCH 130/136] Map --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a77dffd3e..5c9596b6a 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ for i in range(10): ``` ### Map, Filter, Reduce -```python +```python3 from functools import reduce = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) From 70abe77ad27f9bbbe1b778e9046fb0cf27e9aa79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 19:00:42 +0100 Subject: [PATCH 131/136] Map --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c9596b6a..a77dffd3e 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ for i in range(10): ``` ### Map, Filter, Reduce -```python3 +```python from functools import reduce = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) From 92dc1cf028532af9c0fbe7d4db2c85391a15ab26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Mar 2019 04:03:42 +0100 Subject: [PATCH 132/136] String --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a77dffd3e..af08aa877 100644 --- a/README.md +++ b/README.md @@ -240,8 +240,8 @@ from numbers import Number, Integral, Real, Rational, Complex String ------ ```python - = .strip() # Strips all whitespace characters from both ends. - = .strip('') # Strips all passed characters from both ends. + = .strip() # Strips all whitespace characters from both ends. + = .strip('') # Strips all passed characters from both ends. ``` ```python @@ -251,12 +251,15 @@ String ``` ```python - = .replace(old_str, new_str) - = .startswith() # Pass tuple of strings for multiple options. - = .endswith() # Pass tuple of strings for multiple options. - = .index() # Returns start index of first match. - = .isnumeric() # True if str contains only numeric characters. - = textwrap.wrap(, width) # Nicely breaks string into lines. + = .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times. + = .startswith() # Pass tuple of strings for multiple options. + = .endswith() # Pass tuple of strings for multiple options. + = .index() # Returns start index of first match. +``` + +```python + = .isnumeric() # True if str contains only numeric characters. + = textwrap.wrap(, width) # Nicely breaks string into lines. ``` ### Char From 8deedd39709498fdfe205799b6507fc1f5a0a983 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Mar 2019 02:50:59 +0100 Subject: [PATCH 133/136] Minor fixes --- README.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index af08aa877..e455dd559 100644 --- a/README.md +++ b/README.md @@ -131,8 +131,7 @@ Range ```python = range(to_exclusive) = range(from_inclusive, to_exclusive) - = range(from_inclusive, to_exclusive, step_size) - = range(from_inclusive, to_exclusive, -step_size) + = range(from_inclusive, to_exclusive, ±step_size) ``` ```python @@ -172,11 +171,10 @@ Point(x=1, y=2) Iterator -------- -* **If you want to print the iterator, you need to pass it to the list() function.** -* **In this cheatsheet `''` can also mean an iterator.** +**In this cheatsheet `''` can also mean an iterator.** ```python -from itertools import islice, count, repeat, cycle, chain +from itertools import count, repeat, cycle, chain, islice ``` ```python @@ -228,7 +226,7 @@ Type ``` ```python -from numbers import Number, Integral, Real, Rational, Complex +from numbers import Integral, Rational, Real, Complex, Number = isinstance(, Number) ``` @@ -388,7 +386,8 @@ Numbers ```python = pow(, ) # Or: ** = abs() - = round( [, ndigits]) + = round() + = round(, ±ndigits) ``` ### Constants From 1884b059050ab3f1fbca17a5b8553134ff407a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Mar 2019 23:57:15 +0100 Subject: [PATCH 134/136] Small updates --- README.md | 75 +++++++++++++++++++++---------------------------------- 1 file changed, 28 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index e455dd559..c49d27a20 100644 --- a/README.md +++ b/README.md @@ -390,32 +390,14 @@ Numbers = round(, ±ndigits) ``` -### Constants +### Math ```python from math import e, pi -``` - -### Trigonometry -```python from math import cos, acos, sin, asin, tan, atan, degrees, radians -``` - -### Logarithm -```python from math import log, log10, log2 - = log( [, base]) # Base e, if not specified. -``` - -### Infinity, nan -```python from math import inf, nan, isinf, isnan ``` -#### Or: -```python -float('inf'), float('nan') -``` - ### Statistics ```python from statistics import mean, median, variance, pvariance, pstdev @@ -444,19 +426,27 @@ from itertools import product, combinations, combinations_with_replacement, perm >>> product([0, 1], repeat=3) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] +``` +```python >>> product('ab', '12') [('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')] +``` +```python >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] +``` +```python >>> combinations_with_replacement('abc', 2) [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')] +``` +```python >>> permutations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), @@ -469,9 +459,9 @@ Datetime ```python from datetime import datetime now = datetime.now() -now.month # 3 -now.strftime('%Y%m%d') # '20180315' -now.strftime('%Y%m%d%H%M%S') # '20180315002834' +now.month # 3 +now.strftime('%Y%m%d') # '20180315' +now.strftime('%Y%m%d%H%M%S') # '20180315002834' = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') ``` @@ -520,7 +510,7 @@ def add(*a): 6 ``` -#### Legal argument combinations with calls: +#### Legal argument combinations: ```python def f(*args): # f(1, 2, 3) def f(x, *args): # f(1, 2, 3) @@ -542,15 +532,14 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python ->>> a = (1, 2, 3) ->>> [*a] -[1, 2, 3] + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python ->>> head, *body, tail = [1, 2, 3, 4] ->>> body -[2, 3] +head, *body, tail = ``` @@ -566,8 +555,8 @@ Inline ```python = [i+1 for i in range(10)] # [1, 2, ..., 10] = {i for i in range(10) if i > 5} # {6, 7, 8, 9} - = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} = (i+5 for i in range(10)) # (5, 6, ..., 14) + = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} ``` ```python @@ -665,11 +654,11 @@ from functools import partial ```python def get_counter(): - a = 0 + i = 0 def out(): - nonlocal a - a += 1 - return a + nonlocal i + i += 1 + return i return out ``` @@ -721,6 +710,8 @@ def fib(n): return n if n < 2 else fib(n-2) + fib(n-1) ``` +* **Recursion depth is limited to 1000 by default. To increase it use `'sys.setrecursionlimit()'`.** + ### Parametrized Decorator ```python from functools import wraps @@ -839,8 +830,8 @@ class Counter: ``` ```python ->>> c = Counter() ->>> c(), c(), c() +>>> counter = Counter() +>>> counter(), counter(), counter() (1, 2, 3) ``` @@ -1115,16 +1106,6 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` -Recursion Limit ---------------- -```python ->>> import sys ->>> sys.getrecursionlimit() -1000 ->>> sys.setrecursionlimit(5000) -``` - - CSV --- ```python @@ -1633,7 +1614,7 @@ def get_border(screen): from collections import namedtuple P = namedtuple('P', 'x y') height, width = screen.getmaxyx() - return P(width - 1, height - 1) + return P(width-1, height-1) ``` From 370b5ca66821f8fc2a99a67a44e72b417648eae9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 3 Mar 2019 12:43:51 +0100 Subject: [PATCH 135/136] Few changes --- README.md | 57 +++++++++++++++++++++++-------------------------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c49d27a20..a8817f61d 100644 --- a/README.md +++ b/README.md @@ -1347,15 +1347,6 @@ lock.release() ``` -Hashlib -------- -```python ->>> import hashlib ->>> hashlib.md5(.encode()).hexdigest() -'33d0eba106da4d3ebca17fcd3f4c3d77' -``` - - Introspection ------------- **Inspecting code at runtime.** @@ -1389,7 +1380,7 @@ Metaprograming **Code that generates code.** ### Type -**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** +**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class.** ```python = type(, , ) @@ -1434,17 +1425,17 @@ class MyClass(metaclass=MyMetaClass): Operator -------- ```python -from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ - eq, ne, lt, le, gt, ge, \ - not_, and_, or_, \ - itemgetter, attrgetter, methodcaller +from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs +from operator import eq, ne, lt, le, gt, ge +from operator import not_, and_, or_ +from operator import itemgetter, attrgetter, methodcaller ``` ```python import operator as op -product_of_elems = functools.reduce(op.mul, ) -sorted_by_second = sorted(, key=op.itemgetter(1)) -sorted_by_both = sorted(, key=op.itemgetter(1, 0)) +product_of_elems = functools.reduce(op.mul, ) +sorted_by_second = sorted(, key=op.itemgetter(1)) +sorted_by_both = sorted(, key=op.itemgetter(1, 0)) LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_}) last_el = op.methodcaller('pop')() ``` @@ -1459,7 +1450,7 @@ Eval 3 >>> literal_eval('[1, 2, 3]') [1, 2, 3] ->>> ast.literal_eval('abs(1)') +>>> literal_eval('abs(1)') ValueError: malformed node or string ``` @@ -1469,13 +1460,13 @@ import ast from ast import Num, BinOp, UnaryOp import operator as op -LEGAL_OPERATORS = {ast.Add: op.add, - ast.Sub: op.sub, - ast.Mult: op.mul, - ast.Div: op.truediv, - ast.Pow: op.pow, - ast.BitXor: op.xor, - ast.USub: op.neg} +LEGAL_OPERATORS = {ast.Add: op.add, # + + ast.Sub: op.sub, # - + ast.Mult: op.mul, # * + ast.Div: op.truediv, # / + ast.Pow: op.pow, # ** + ast.BitXor: op.xor, # ^ + ast.USub: op.neg} # - def evaluate(expression): root = ast.parse(expression, mode='eval') @@ -1679,7 +1670,7 @@ def odds_handler(sport): ```python # $ pip3 install requests >>> import requests ->>> url = 'http://localhost:8080/odds/football' +>>> url = 'http://localhost:8080/odds/football' >>> data = {'team': 'arsenal f.c.'} >>> response = requests.post(url, data=data) >>> response.json() @@ -1771,12 +1762,12 @@ import numpy as np ``` ```python - = .sum() -indexes = .argmin() + = .sum(axis=None) +indexes = .argmin(axis=None) ``` * **Shape is a tuple of dimension sizes.** -* **Axis is an index of dimension that gets collapsed.** +* **Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.** ### Indexing ```bash @@ -1806,7 +1797,7 @@ left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) ``` -#### 1. If array shapes differ, left-pad the smaller shape with ones: +#### 1. If array shapes differ in length, left-pad the smaller shape with ones: ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! @@ -1931,7 +1922,7 @@ write_to_wav_file('test.wav', frames_i) #### Plays Popcorn: ```python -# pip3 install simpleaudio +# $ pip3 install simpleaudio import simpleaudio, math, struct from itertools import chain, repeat F = 44100 @@ -1940,8 +1931,8 @@ P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) -get_hz = lambda n: 8.176 * 2 ** (int(n) / 12) -parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125) +get_hz = lambda key: 8.176 * 2 ** (int(key) / 12) +parse_n = lambda note: (get_hz(note[:2]), 0.25 if '♪' in note else 0.125) get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) frames_b = b''.join(struct.pack(' Date: Tue, 5 Mar 2019 19:36:34 +0100 Subject: [PATCH 136/136] Json, Numpy --- README.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a8817f61d..98d33fb3c 100644 --- a/README.md +++ b/README.md @@ -1136,12 +1136,6 @@ import json = json.loads() ``` -#### To preserve order use: -```python -from collections import OrderedDict - = json.loads(, object_pairs_hook=OrderedDict) -``` - ### Read Object from JSON File ```python def read_json_file(filename): @@ -1762,8 +1756,8 @@ import numpy as np ``` ```python - = .sum(axis=None) -indexes = .argmin(axis=None) + = .sum(axis) +indexes = .argmin(axis) ``` * **Shape is a tuple of dimension sizes.**