Skip to content

Commit 68dd21b

Browse files
committed
A lot of small changes
1 parent f74e5cc commit 68dd21b

File tree

1 file changed

+79
-74
lines changed

1 file changed

+79
-74
lines changed

README.md

Lines changed: 79 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,15 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
4141
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
4242
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
4343
flattened_list = list(itertools.chain.from_iterable(<list>))
44-
list_of_chars = list(<str>)
4544
product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
46-
no_duplicates = list(dict.fromkeys(<list>))
45+
list_of_chars = list(<str>)
4746
```
4847

4948
```python
5049
index = <list>.index(<el>) # Returns first index of item.
5150
<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
5251
<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
53-
<list>.remove(<el>) # Removes first occurrence of item.
52+
<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
5453
<list>.clear() # Removes all items.
5554
```
5655

@@ -64,17 +63,17 @@ Dictionary
6463
```
6564

6665
```python
67-
value = <dict>.get(key, default) # Returns default if key does not exist.
68-
value = <dict>.setdefault(key, default) # Same, but also adds default to dict.
69-
<dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
70-
<dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
66+
value = <dict>.get(key, default=None) # Returns default if key does not exist.
67+
value = <dict>.setdefault(key, default=None) # Same, but also adds default to dict.
68+
<dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
69+
<dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
7170
```
7271

7372
```python
74-
<dict>.update(<dict>) # Or: dict_a = {**dict_a, **dict_b}.
75-
<dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
76-
<dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
77-
<dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
73+
<dict>.update(<dict>) # Or: dict_a = {**dict_a, **dict_b}.
74+
<dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
75+
<dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
76+
<dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
7877
```
7978

8079
```python
@@ -88,8 +87,8 @@ value = <dict>.pop(key) # Removes item from dictionary.
8887
>>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
8988
>>> counter = Counter(colors)
9089
Counter({'blue': 3, 'red': 2, 'yellow': 1})
91-
>>> counter.most_common()[0][0]
92-
'blue'
90+
>>> counter.most_common()[0]
91+
('blue', 3)
9392
```
9493

9594

@@ -121,7 +120,7 @@ Set
121120
```
122121

123122
### Frozenset
124-
#### Is hashable and can be used as a key in dictionary.
123+
#### Is hashable so it can be used as a key in dictionary.
125124
```python
126125
<frozenset> = frozenset(<collection>)
127126
```
@@ -130,10 +129,10 @@ Set
130129
Range
131130
-----
132131
```python
133-
range(to_exclusive)
134-
range(from_inclusive, to_exclusive)
135-
range(from_inclusive, to_exclusive, step_size)
136-
range(from_inclusive, to_exclusive, -step_size)
132+
<range> = range(to_exclusive)
133+
<range> = range(from_inclusive, to_exclusive)
134+
<range> = range(from_inclusive, to_exclusive, step_size)
135+
<range> = range(from_inclusive, to_exclusive, -step_size)
137136
```
138137

139138
```python
@@ -153,7 +152,8 @@ for i, el in enumerate(<collection> [, i_start]):
153152
Named Tuple
154153
-----------
155154
```python
156-
>>> Point = collections.namedtuple('Point', 'x y')
155+
>>> from collections import namedtuple
156+
>>> Point = namedtuple('Point', 'x y')
157157
>>> p = Point(1, y=2)
158158
Point(x=1, y=2)
159159
>>> p[0]
@@ -188,7 +188,7 @@ for line in iter(partial(input, 'Please enter value: '), ''):
188188
```
189189

190190
### Next
191-
**Returns next item. If there are no more items it raises exception or returns default if specified.**
191+
**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.**
192192
```python
193193
<el> = next(<iter> [, default])
194194
```
@@ -252,7 +252,7 @@ String
252252
<str> = <str>.replace(old_str, new_str)
253253
<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
254254
<bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
255-
<int> = <str>.index(<sub_str>) # Returns first index of a substring.
255+
<int> = <str>.index(<sub_str>) # Returns start index of first match.
256256
<bool> = <str>.isnumeric() # True if str contains only numeric characters.
257257
<list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
258258
```
@@ -288,7 +288,7 @@ import re
288288
* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.**
289289
* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.**
290290
* **Use `r'\1'` or `'\\\\1'` for backreference.**
291-
* **Use `'?'` to make operators non-greedy.**
291+
* **Use `'?'` to make operator non-greedy.**
292292

293293
### Match Object
294294
```python
@@ -300,7 +300,7 @@ import re
300300
```
301301

302302
### Special Sequences
303-
**Use capital letter for negation.**
303+
**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.**
304304
```python
305305
'\d' == '[0-9]' # Digit
306306
'\s' == '[ \t\n\r\f\v]' # Whitespace
@@ -318,10 +318,10 @@ Format
318318
```python
319319
>>> Person = namedtuple('Person', 'name height')
320320
>>> person = Person('Jean-Luc', 187)
321-
>>> f'{person.height:10}'
322-
' 187'
323-
>>> '{p.height:10}'.format(p=person)
324-
' 187'
321+
>>> f'{person.height}'
322+
'187'
323+
>>> '{p.height}'.format(p=person)
324+
'187'
325325
```
326326

327327
### General Options
@@ -581,7 +581,7 @@ from functools import partial
581581
```
582582

583583
### Nonlocal
584-
**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.**
584+
**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'.**
585585

586586
```python
587587
def get_counter():
@@ -668,7 +668,7 @@ class <name>:
668668
def __init__(self, a):
669669
self.a = a
670670
def __repr__(self):
671-
class_name = type(self).__name__
671+
class_name = self.__class__.__name__
672672
return f'{class_name}({self.a!r})'
673673
def __str__(self):
674674
return str(self.a)
@@ -870,13 +870,6 @@ KeyboardInterrupt
870870

871871
System
872872
------
873-
### Command Line Arguments
874-
```python
875-
import sys
876-
script_name = sys.argv[0]
877-
arguments = sys.argv[1:]
878-
```
879-
880873
### Print Function
881874
```python
882875
print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
@@ -974,7 +967,9 @@ b'.\n..\nfile1.txt\nfile2.txt\n'
974967
>>> sys.setrecursionlimit(5000)
975968
```
976969

977-
### Path
970+
971+
Path
972+
----
978973
```python
979974
from os import path, listdir
980975
<bool> = path.exists('<path>')
@@ -989,9 +984,7 @@ from os import path, listdir
989984
['1.gif', 'card.gif']
990985
```
991986

992-
993-
Pathlib
994-
-------
987+
### Pathlib
995988
**This module offers classes representing filesystem paths with semantics appropriate for different operating systems.**
996989

997990
```python
@@ -1023,6 +1016,36 @@ pwd = Path()
10231016
```
10241017

10251018

1019+
Command Line Arguments
1020+
----------------------
1021+
```python
1022+
import sys
1023+
script_name = sys.argv[0]
1024+
arguments = sys.argv[1:]
1025+
```
1026+
1027+
### Argparse
1028+
```python
1029+
from argparse import ArgumentParser
1030+
desc = 'calculate X to the power of Y'
1031+
parser = ArgumentParser(description=desc)
1032+
group = parser.add_mutually_exclusive_group()
1033+
group.add_argument('-v', '--verbose', action='store_true')
1034+
group.add_argument('-q', '--quiet', action='store_true')
1035+
parser.add_argument('x', type=int, help='the base')
1036+
parser.add_argument('y', type=int, help='the exponent')
1037+
args = parser.parse_args()
1038+
answer = args.x ** args.y
1039+
1040+
if args.quiet:
1041+
print(answer)
1042+
elif args.verbose:
1043+
print(f'{args.x} to the power {args.y} equals {answer}')
1044+
else:
1045+
print(f'{args.x}^{args.y} == {answer}')
1046+
```
1047+
1048+
10261049
JSON
10271050
----
10281051
```python
@@ -1037,14 +1060,14 @@ from collections import OrderedDict
10371060
<object> = json.loads(<str>, object_pairs_hook=OrderedDict)
10381061
```
10391062

1040-
### Read File
1063+
### Read Object from JSON File
10411064
```python
10421065
def read_json_file(filename):
10431066
with open(filename, encoding='utf-8') as file:
10441067
return json.load(file)
10451068
```
10461069

1047-
### Write to File
1070+
### Write Object to JSON File
10481071
```python
10491072
def write_to_json_file(filename, an_object):
10501073
with open(filename, 'w', encoding='utf-8') as file:
@@ -1079,7 +1102,7 @@ SQLite
10791102
------
10801103
```python
10811104
import sqlite3
1082-
db = sqlite3.connect(<filename>)
1105+
db = sqlite3.connect('<path>')
10831106
...
10841107
db.close()
10851108
```
@@ -1114,7 +1137,7 @@ Bytes
11141137
```python
11151138
<bytes> = <str>.encode(encoding='utf-8')
11161139
<bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
1117-
<bytes> = bytes.fromhex(<hex>)
1140+
<bytes> = bytes.fromhex('<hex>')
11181141
```
11191142

11201143
### Decode
@@ -1166,7 +1189,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
11661189
* **`'<'` - little-endian**
11671190
* **`'>'` - big-endian**
11681191

1169-
#### Use capital letter for unsigned type. Standard size in brackets:
1192+
#### Use capital letter for unsigned type. Standard sizes are in brackets:
11701193
* **`'x'` - pad byte**
11711194
* **`'c'` - char (1)**
11721195
* **`'h'` - short (2)**
@@ -1183,7 +1206,7 @@ Array
11831206

11841207
```python
11851208
from array import array
1186-
<array> = array(<typecode> [, <collection>])
1209+
<array> = array('<typecode>' [, <collection>])
11871210
```
11881211

11891212

@@ -1208,8 +1231,8 @@ from collections import deque
12081231

12091232
```python
12101233
<deque>.appendleft(<el>)
1211-
<deque>.extendleft(<collection>) # Collection gets reversed.
12121234
<el> = <deque>.popleft()
1235+
<deque>.extendleft(<collection>) # Collection gets reversed.
12131236
<deque>.rotate(n=1) # Rotates elements to the right.
12141237
```
12151238

@@ -1304,7 +1327,10 @@ from itertools import *
13041327
>>> # islice(<collection>, from_inclusive, to_exclusive)
13051328
>>> islice([1, 2, 3], 1, None)
13061329
[2, 3]
1330+
```
13071331

1332+
### Group by
1333+
```python
13081334
>>> people = [{'id': 1, 'name': 'Bob'},
13091335
{'id': 2, 'name': 'Bob'},
13101336
{'id': 3, 'name': 'Peter'}]
@@ -1367,7 +1393,7 @@ param_names = list(sig.parameters.keys())
13671393
**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!).**
13681394

13691395
```python
1370-
type(<class_name>, <parents_tuple>, <attributes_dict>)
1396+
<class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
13711397
```
13721398

13731399
```python
@@ -1482,7 +1508,7 @@ def eval_node(node):
14821508

14831509
Coroutine
14841510
---------
1485-
* **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
1511+
* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().**
14861512
* **Coroutines provide more powerful data routing possibilities than iterators.**
14871513
* **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
14881514

@@ -1551,29 +1577,6 @@ pyplot.show()
15511577
```
15521578

15531579

1554-
Argparse
1555-
--------
1556-
```python
1557-
from argparse import ArgumentParser
1558-
desc = 'calculate X to the power of Y'
1559-
parser = ArgumentParser(description=desc)
1560-
group = parser.add_mutually_exclusive_group()
1561-
group.add_argument('-v', '--verbose', action='store_true')
1562-
group.add_argument('-q', '--quiet', action='store_true')
1563-
parser.add_argument('x', type=int, help='the base')
1564-
parser.add_argument('y', type=int, help='the exponent')
1565-
args = parser.parse_args()
1566-
answer = args.x ** args.y
1567-
1568-
if args.quiet:
1569-
print(answer)
1570-
elif args.verbose:
1571-
print(f'{args.x} to the power {args.y} equals {answer}')
1572-
else:
1573-
print(f'{args.x}^{args.y} == {answer}')
1574-
```
1575-
1576-
15771580
Table
15781581
-----
15791582
#### Prints CSV file as ASCII table:
@@ -1641,12 +1644,14 @@ Audio
16411644
#### Saves a list of floats with values between -1 and 1 to a WAV file:
16421645
```python
16431646
import wave, struct
1644-
samples = [struct.pack('<h', int(a * 30000)) for a in <list>]
1647+
samples_f = [struct.pack('<h', int(a * 30000)) for a in <list>]
1648+
samples_b = b''.join(samples_f)
1649+
16451650
wf = wave.open('test.wav', 'wb')
16461651
wf.setnchannels(1)
16471652
wf.setsampwidth(2)
16481653
wf.setframerate(44100)
1649-
wf.writeframes(b''.join(samples))
1654+
wf.writeframes(samples_b)
16501655
wf.close()
16511656
```
16521657

0 commit comments

Comments
 (0)