Browse Source

Update

pull/1/head
Jure Šorn 7 years ago
parent
commit
891b905a5b
1 changed files with 135 additions and 147 deletions
  1. 282
      README.md

282
README.md

@ -18,11 +18,7 @@ List
<list>.reverse() <list>.reverse()
sum(<list>) sum(<list>)
sorted_by_second = sorted(<list>, key=lambda tup: tup[1]) sorted_by_second = sorted(<list>, key=lambda tup: tup[1])
``` [item for sublist in <list> for item in sublist] # Flattens List
#### Flatten List
```python
[item for sublist in <list> for item in sublist]
``` ```
Dictionary Dictionary
@ -33,16 +29,8 @@ Dictionary
<dict>.setdefault(key, default) <dict>.setdefault(key, default)
<dict>.update(<dict>) <dict>.update(<dict>)
collections.defaultdict(<type>) collections.defaultdict(<type>)
``` dict(zip(keys, values)) # Initiates a dict from two lists
{k: v for k, v in <dict>.iteritems() if k in <list>} # Filters a dict by keys
#### Initiates dict from two lists
```python
dict(zip(keys, values))
```
#### Filters by keys
```python
{k: v for k, v in <dict>.iteritems() if k in keys}
``` ```
#### Counter #### Counter
@ -68,32 +56,31 @@ Set
Range Range
----- -----
```python ```python
range(<to exclusive>) range(to_exclusive)
range(<from inclusive>, <to exclusive>) range(from_inclusive, to_exclusive)
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward range(from_inclusive, to_exclusive, step_size) # Negative step for backward
``` ```
Enumerate Enumerate
--------- ---------
```python ```python
for i, <el> in enumerate(<list>, [start]) for i, <el> in enumerate(<collection> [, i_start])
``` ```
Named Tuples Named Tuple
------------ -----------
```python ```python
>>> TestResults = collections.namedtuple('TestResults', ['filed', 'attempted']) >>> TestResults = collections.namedtuple('TestResults', ['filed', 'attempted'])
>>> TestResults(1, 2) >>> TestResults(1, 2)
TestResults(filed=1, attempted=2) TestResults(filed=1, attempted=2)
``` ```
Iterator Iterator
-------- --------
#### Reads input until it reaches empty line. #### Reads input until it reaches empty line
```python ```python
for line in iter(input, ''): for line in iter(input, ''):
print(line) pass
``` ```
Use partial from functools if function needs arguments. Use partial from functools if function needs arguments.
@ -101,13 +88,26 @@ Use partial from functools if function needs arguments.
```python ```python
next(<iter>) next(<iter>)
for element in <iter>: for element in <iter>:
... pass
```
Generator
---------
```python
def step(start, step):
while True:
yield start
start += step
stepper = step(10, 2)
next(stepper) # -> 10 (, 12, 14, ...)
``` ```
Type Type
---- ----
```python ```python
type(<el>) is int/str/set/list type(<el>) # is int/str/set/list/...
``` ```
```python ```python
import numbers import numbers
@ -118,7 +118,7 @@ isinstance(<el>, numbers.Number)
String String
------ ------
```python ```python
str.replace(<text>, <old>, <new>) str.replace(text, old, new)
<str>.isnumeric() <str>.isnumeric()
<str>.split() <str>.split()
<str>.strip() <str>.strip()
@ -127,14 +127,14 @@ str.replace(<text>, <old>, <new>)
### Print ### Print
```python ```python
print(<el>, <el>, end='', sep='', file=<file>) print(<el> [, <el>, end='', sep='', file=<file>])
``` ```
### Regex ### Regex
```python ```python
import re import re
re.sub(<regex>, <new>, <text>) re.sub(<regex>, new, text)
re.search(<regex>, <text>) re.search(<regex>, text)
``` ```
### Format ### Format
@ -143,13 +143,13 @@ re.search(<regex>, <text>)
``` ```
```python ```python
{:<min width>} -> '<el> ' {:min_width} # -> '<el> '
{:><min width>} -> ' <el>' {:>min_width} # -> ' <el>'
{:^<min width>} -> ' <el> ' {:^min_width} # -> ' <el> '
{:_<min width>} -> '<el>____' {:_min_width} # -> '<el>____'
{:.<max width>} -> '<e>' {:.max_width} # -> '<e>'
{:<max widht>.<min width>} -> ' <e>' {:max_widht.min_width} # -> ' <e>'
{:<max width>.<no of decimals>f} -> ' 3.14' {:max_width.no_of_decimalsf} # -> ' 3.14'
``` ```
```python ```python
@ -161,7 +161,7 @@ re.search(<regex>, <text>)
### Text Wrap ### Text Wrap
```python ```python
import textwrap import textwrap
textwrap.wrap(<text>, <width>) textwrap.wrap(text, width)
``` ```
@ -170,7 +170,7 @@ Random
```python ```python
import random import random
random.random() random.random()
random.randint(<from inclusive>, <to inclusive>) random.randint(from_inclusive, to_inclusive)
random.shuffle(<list>) random.shuffle(<list>)
``` ```
@ -194,35 +194,36 @@ Arguments
```python ```python
args = (1, 2) args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5} kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs) func(*args, **kwargs) # Is same as
# same as
func(1, 2, x=3, y=4, z=5) func(1, 2, x=3, y=4, z=5)
``` ```
* is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call. "*" is the "splat" operator, that takes a list as input, and expands it into
actual positional arguments in the function call.
So if uniqueCrossTabs was [ [ 1, 2 ], [ 3, 4 ] ], then itertools.chain(*uniqueCrossTabs) is the same as saying itertools.chain([ 1, 2 ], [ 3, 4 ])
Inline Inline
------ ------
### Lambda ### Lambda
```python ```python
lambda <arg1>, <arg2>: <return value> lambda <argument1>, <argument2>: <return value>
lambda: <return value> lambda: <return value>
``` ```
### Comprehension ### Comprehension
```python ```python
[i+1 for i in range(10)] [i+1 for i in range(10)] # 1, 2, ..., 10
[i for i in range(10) if i>5] [i for i in range(10) if i>5] # 6, 7, ..., 9
{i: i*2 for i in range(10)} - dictionary {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
(x+5 for x in range(0, 10)) - generator (x+5 for x in range(0, 10)) # -> Generator
``` ```
```python ```python
[i+j for i in range(10) for j in range(10)] [i+j for i in range(10) for j in range(10)]
# Same as: ```
Is same as:
```
out = []
for i in range(10): for i in range(10):
for j in range(10): for j in range(10):
out.append(i+j) out.append(i+j)
@ -230,14 +231,14 @@ for i in range(10):
### Map, Filter, Reduce ### Map, Filter, Reduce
```python ```python
map(lambda x: x+1, range(10)) map(lambda x: x+1, range(10)) # 1, 2, ..., 10
filter(lambda x: x>5, range(10)) filter(lambda x: x>5, range(10)) # 6, 7, ..., 9
functools.reduce(combining_function, list_of_inputs) functools.reduce(combining_function, list_of_inputs)
``` ```
### Any, All ### Any, All
```python ```python
any(a[1] for a in aaa) any(el[1] for el in <collection>) # -> Boolean
``` ```
### If - Else ### If - Else
@ -248,18 +249,18 @@ expression_if_true if condition else expression_if_false
Closure Closure
------- -------
```python ```python
def mult_clos(x): def multiply_closure(x):
def wrapped(y): def wrapped(y):
return x * y return x * y
return wrapped return wrapped
mul_by_3 = mult_clos(3) multiply_by_3 = multiply_closure(3)
``` ```
#### or #### or
```python ```python
from functools import partial from functools import partial
partial(<function>, <parameter>) partial(<function>, <argument>)
``` ```
Decorator Decorator
@ -267,7 +268,7 @@ Decorator
```python ```python
@closure_name @closure_name
def function_that_gets_passed_to_closure(): def function_that_gets_passed_to_closure():
... pass
``` ```
#### Debugger example #### Debugger example
@ -275,7 +276,7 @@ def function_that_gets_passed_to_closure():
from functools import wraps from functools import wraps
def debug(func): def debug(func):
@wraps(func) # Nedded for metadata copying (func name, etc) @wraps(func) # Needed for metadata copying (func name, ...)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
print(func.__name__) print(func.__name__)
return func(*args, **kwargs) return func(*args, **kwargs)
@ -287,26 +288,12 @@ def add(x, y):
``` ```
Generator
---------
```python
def step(start, step):
while True:
yield start
start += step
stepper = step(10, 2)
next(stepper)
```
Class Class
----- -----
### Class
```python ```python
class <name>: class <name>:
def __init__(self, <arg>): def __init__(self, a):
self.a = <arg> self.a = a
def __repr__(self): def __repr__(self):
return str({'a': self.a}) return str({'a': self.a})
def __str__(self): def __str__(self):
@ -316,17 +303,21 @@ class <name>:
### Enum ### Enum
```python ```python
import enum import enum
class <enum-name>(enum.Enum): class <enum_name>(enum.Enum):
<name> = <value> # or enum.auto() <name> = <value> # Or enum.auto() for automatic indexing.
```
<enum-name>.<name> == <enum> ```python
<enum-name>(value) == <enum> <enum_name>.<name> # == <enum>
<enum>.name == <name> <enum_name>(value) # == <enum>
<enum>.value == <value> <enum>.name # == <name>
<enum>.value # == <value>
```
```python
Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon']) Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
list(<enum-name>) == [<enum1>, <enum2>, ...] list(<enum_name>) # == [<enum1>, <enum2>, ...]
random.choice(list(<enum-name>)) == random <enum> random.choice(list(<enum_name>)) # == random <enum>
``` ```
### Copy ### Copy
@ -348,19 +339,19 @@ sys.argv
### Read File ### Read File
```python ```python
with open(<filename>, encoding='utf-8') as file: with open(file_name, encoding='utf-8') as file:
return file.readlines() return file.readlines()
``` ```
```python ```python
def get_file_contents(file_name): def get_file_contents(file_name):
with open(file_name, encoding='utf-8') as f: with open(file_name, encoding='utf-8') as file:
return f.readlines() return file.readlines()
``` ```
### Write to File ### Write to File
```python ```python
with open(<filename>, 'w', enconding='utf-8') as file: with open(file_name, 'w', enconding='utf-8') as file:
file.write(<text>) file.write(text)
``` ```
### Execute Command ### Execute Command
@ -371,10 +362,10 @@ os.popen(<command>).read()
### Input ### Input
```python ```python
filename = input('Enter a file name: ') file_name = input('Enter a file name: ')
``` ```
Print lines until EOF ### Print lines until EOF
```python ```python
while True: while True:
try: try:
@ -391,13 +382,13 @@ import json
### Read File ### Read File
```python ```python
with open(<filename>, encoding='utf-8') as file: with open(file_name, encoding='utf-8') as file:
return json.load(file) return json.load(file)
``` ```
### Write to File ### Write to File
```python ```python
with open(<filename>, 'w', enconding='utf-8') as file: with open(file_name, 'w', enconding='utf-8') as file:
file.write(json.dumps(<object>)) file.write(json.dumps(<object>))
``` ```
@ -405,7 +396,7 @@ SQLite
------ ------
```python ```python
import sqlite3 import sqlite3
db = sqlite3.connect(<filename>) db = sqlite3.connect(file_name)
``` ```
### Read ### Read
@ -455,8 +446,8 @@ lock.release()
Itertools Itertools
--------- ---------
Every function returns an generator and can accept any collection. Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to list()
All examples should be passed to list() to get the output. function.
```python ```python
from itertools import * from itertools import *
@ -464,7 +455,7 @@ from itertools import *
### Chain ### Chain
```python ```python
>>> chain([1,2], range(3,5)) >>> chain([1, 2], range(3, 5))
[1, 2, 3, 4] [1, 2, 3, 4]
``` ```
@ -482,7 +473,7 @@ from itertools import *
### Product ### Product
```python ```python
>>> list(product('ab', [1,2])) >>> list(product('ab', [1, 2]))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)] [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
``` ```
@ -530,7 +521,13 @@ Filter, map and zip functions that return generators instead of iterators
Introspection and Metaprograming Introspection and Metaprograming
-------------------------------- --------------------------------
#### Inspecting code at runtime and code that generates code. #### 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
```python ```python
>>> class B: >>> class B:
@ -540,70 +537,57 @@ Introspection and Metaprograming
>>> b = B() >>> b = B()
``` ```
### Getattr #### Getattr
```python ```python
>>> getattr(b, 'a') >>> getattr(b, 'a')
'sdfsd' 'sdfsd'
``` ```
same as Is the same as
```python ```python
B.__getattribute__(b, 'a') B.__getattribute__(b, 'a')
``` ```
### Hasattr #### Hasattr
```python ```python
>>> hasattr(b, 'c') >>> hasattr(b, 'c')
False False
``` ```
### Setattr #### Setattr
```python ```python
>>> setattr(b, 'c', 10) >>> setattr(b, 'c', 10)
``` ```
Type ### Type
----
Type is the root class. If only passed the object it returns it's type. Type is the root class. If only passed the object it returns it's type.
Otherwise it creates new class (and not the instance!). Otherwise it creates new class (and not the instance!).
```python ```python
type(class_name, parents[tuple], attributes[dict]) type(class_name, parents<tuple>, attributes<dict>)
``` ```
```python ```python
BB = type('B', (), {'a': 'sdfsd', 'b': 123324} >>> BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
b = BB() >>> b = BB()
``` ```
### MetaClass
MetaClass #### Classes that create classes.
---------
#### Classes that creates classes.
```python ```python
def my_meta_class(name, parents, attrs): def my_meta_class(name, parents, attrs):
... do stuff # do stuff
return type(name, parents, attrs) return type(name, parents, attrs)
``` ```
or or
```python ```python
class MyMetaClass(type): class MyMetaClass(type):
def __new__(klass, name, parents, attrs): def __new__(klass, name, parents, attrs):
... do stuff # do stuff
return type.__new__(klass, name, parents, attrs) return type.__new__(klass, name, parents, attrs)
``` ```
### Metaclass Attr
Do Stuff
--------
* Look at the attributes
* Set new attributes
* Create functions dynamically
* Traverse the parent classes
* Change values in the class
Metaclass Attr
--------------
When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type. When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined, and eventually comes to type.
```python ```python
class BlaBla: class BlaBla:
@ -617,34 +601,35 @@ Eval
import ast import ast
import operator as op import operator as op
# supported operators # Supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, 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.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg} ast.USub: op.neg}
def eval_expr(expr): def eval_expr(expr):
"""
>>> eval_expr('2^6')
4
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
"""
print(expr) print(expr)
return eval_(ast.parse(expr, mode='eval').body) return eval_(ast.parse(expr, mode='eval').body)
def eval_(node): def eval_(node):
if isinstance(node, ast.Num): # <number> if isinstance(node, ast.Num): # <number>
return node.n return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right> elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right)) return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand)) return operators[type(node.op)](eval_(node.operand))
else: else:
raise TypeError(node) raise TypeError(node)
``` ```
```
>>> eval_expr('2^6')
4
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0
```
Libraries Libraries
========= =========
@ -653,9 +638,9 @@ Plot
---- ----
```python ```python
import matplotlib import matplotlib
matplotlib.pyplot.plot(<data>, ...) matplotlib.pyplot.plot(<data> [, <data>])
matplotlib.pyplot.show() matplotlib.pyplot.show()
matplotlib.pyplot.savefig(<filename>) matplotlib.pyplot.savefig(filename)
``` ```
Web Web
@ -701,14 +686,18 @@ Profile
import timeit import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
``` ```
#### Generates a PNG image of call graph and highlights the bottlenecks.
```python ```python
import pycallgraph import pycallgraph
graph = pycallgraph.output.GraphvizOutput() graph = pycallgraph.output.GraphvizOutput()
graph.output_file = "{}-{}.png".format("profile", graph.output_file = get_file_name()
get_current_datetime_string())
with pycallgraph.PyCallGraph(output=graph): with pycallgraph.PyCallGraph(output=graph):
<code> <code_to_be_profiled>
```
#### Utility code for unique PNG filenames.
```python
def get_file_name():
return "{}-{}.png".format("profile", get_current_datetime_string())
def get_current_datetime_string(): def get_current_datetime_string():
now = datetime.datetime.now() now = datetime.datetime.now()
@ -722,10 +711,9 @@ Audio
----- -----
#### Saves list of floats of size 0 to 1 to a WAV file. #### Saves list of floats of size 0 to 1 to a WAV file.
```python ```python
import wave import wave, struct
import struct
frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>] frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
wf = wave.open(<filename>, 'wb') wf = wave.open(file_name, 'wb')
wf.setnchannels(1) wf.setnchannels(1)
wf.setsampwidth(4) wf.setsampwidth(4)
wf.setframerate(44100) wf.setframerate(44100)

|||||||
100:0
Loading…
Cancel
Save