diff --git a/CONDENSED.md b/CONDENSED.md index 08422b0..8f7a80b 100644 --- a/CONDENSED.md +++ b/CONDENSED.md @@ -1,5 +1,5 @@ -Python and Libraries Cheatsheet -=============================== +Minimal Python Cheatsheet +========================= Main ---- @@ -8,16 +8,17 @@ if __name__ == '__main__': main() ``` -Range ------ +Ranges +------ ```python range(, , ) # Negative step for backward. +[::] # Negative step for backward. +random.randint(, ) ``` List ---- ```python -[::] ``` Dictionary @@ -110,7 +111,6 @@ Random ``` import random random.random() -random.randint(, ) random.shuffle() ``` diff --git a/LIBRARIES.md b/LIBRARIES.md index ed5aeb7..3b761ab 100644 --- a/LIBRARIES.md +++ b/LIBRARIES.md @@ -48,11 +48,16 @@ def draw(screen): Profile ------- +``` +import timeit +timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) +``` + ``` import pycallgraph graph = pycallgraph.output.GraphvizOutput() graph.output_file = -whith pycallgraph.PyCallGraph(output=graph): +with pycallgraph.PyCallGraph(output=graph): ``` diff --git a/README.md b/README.md index 0aa4b32..933d0d5 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,6 @@ if __name__ == '__main__': main() ``` -Range ------ -``` -range() -range(, ) -range(, , ) # Negative step for backward -``` List ---- @@ -24,6 +17,7 @@ List .sort() .reverse() sum() +sorted_by_second = sorted(, key=lambda tup: tup[1]) ``` Dictionary @@ -31,6 +25,7 @@ Dictionary .items() .get(, ) .setdefault(, ) +.update() ``` Set @@ -44,6 +39,14 @@ Set .difference() ``` +Range +----- +``` +range() +range(, ) +range(, , ) # Negative step for backward +``` + Enumerate --------- ``` @@ -51,7 +54,6 @@ for i, in enumerate() ``` - Type ---- ``` @@ -63,12 +65,14 @@ isinstance(, numbers.Number) ``` - String ------ ``` str.replace(, , ) .isnumeric() +.split() +.strip() +''.join() ``` ### Print @@ -130,24 +134,65 @@ now.strftime('%Y%m%d%H%M%S') ``` - - - Inline ------ -### For +### Lambda +``` +lambda , : +lambda: +``` + +### Comprehension ``` [i+1 for i in range(10)] -[i+1 for i in range(10) if i > 5] +[i for i in range(10) if i>5] [i+j for i in range(10) for j in range(10)] +{i: i*2 for i in range(10)} +(x+5 for x in range(0, 10)) - generator! ``` -### Lambda +### Map, Filter, Reduce ``` -lambda , : -lambda: +A. map(lambda x: x+1, range(10)) +B. filter(lambda x: x>5, range(10)) +functools.reduce(combining_function, list_of_inputs) +``` + + +Closure +------- +``` +def mult_clos(x): + def wrapped(y): + return x * y + return wrapped + +mul_by_3 = mult_clos(3) +``` + + +Decorator +--------- +``` +@closure_name +def function_that_gets_passed_to_closure(): + ... ``` + +Generator +--------- +``` +def step(start, step): + while True: + yield start + start += step + +stepper = step(10, 2) +next(stepper) +``` + + Class ----- ### Class @@ -204,6 +249,11 @@ import os os.popen().read() ``` +### Input +``` +filename = input('Enter a file name: ') +``` + JSON ---- @@ -268,18 +318,148 @@ lock.release() ``` +Itertools +--------- +Every function returns an generator and can accept any collection. +All examples should be passed to list() to get the output. + +``` +from itertools import * +``` + +### Chain +``` +>>> chain([1,2], range(3,5)) +[1, 2, 3, 4] +``` + +### Combinations +``` +>>> combinations("abc", 2) +[('a', 'b'), ('a', 'c'), ('b', 'c')] +``` +### Permutations +``` +>>> permutations("abc", 2) +[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] +``` +### Compress +``` +>>> compress("abc", [True, 0, 23]) +['a', 'c'] +``` +### Count +``` +>>> a = count(5, 2) +>>> next(a), next(a) +(5, 7) +``` +### Cycle +``` +>>> a = cycle("abc") +>>> [next(a) for _ in range(10)] +['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a'] +``` +### Groupby +``` +>>> {k: list(v) for k, v in groupby("aabbbc")} +{'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']} +``` +``` +>>> a = [{"id": 1, "name": "bob"}, {"id": 2, "name": "bob"}, {"id": 3, "name": "peter"}] +>>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])} +{'bob': [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'bob'}], 'peter': [{'id': 3, 'name': 'peter'}]} +``` +### Product +``` +>>> list(product('ab', [1,2])) +[('a', 1), ('a', 2), ('b', 1), ('b', 2)] +``` +### ifilter/imap/izip +Filter, map and zip functions that return generators instead of iterators +Introspection and Metaprograming +-------------------------------- +Inspecting code at runetime and code that generates code. +``` +>>> class B: +... def __init__(self): +... self.a= 'sdfsd' +... self.b = 123324 +>>> b = B() +``` +### Getattr +``` +>>> getattr(b, 'a') +'sdfsd' +``` + +### Hasattr +``` +>>> hasattr(b, 'c') +False +``` + +### Setattr +``` +>>> setattr(b, 'c', 10) +``` + +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!). +``` +type(class_name, parents[tuple], attributes[dict]) +``` + +``` +BB = type('B', (), {'a': 'sdfsd', 'b': 123324} +b = BB() +``` + +MetaClass +--------- +Classes that creates classes. +``` +def my_meta_class(name, parents, attrs): + ... do stuff + return type(name, parents, attrs) +``` +or +``` +class MyMetaClass(type): + def __new__(klass, name, parents, attrs): + ... 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 +-------------- +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. +``` +class BlaBla: + __metaclass__ = Bla +```