Browse Source

Update

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

Loading…
Cancel
Save