Browse Source

Update

pull/1/head
Jure Šorn 7 years ago
parent
commit
69ad545b4d
3 changed files with 209 additions and 24 deletions
  1. 12
      CONDENSED.md
  2. 7
      LIBRARIES.md
  3. 214
      README.md

12
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(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward.
<list>[<from inclusive>:<to exclusive>:<step size>] # Negative step for backward.
random.randint(<from inclusive>, <to inclusive>)
```
List
----
```python
<list>[<inclusive from>:<exclusive to>:<step size>]
```
Dictionary
@ -110,7 +111,6 @@ Random
```
import random
random.random()
random.randint(<from inclusive>, <to inclusive>)
random.shuffle(<list>)
```

7
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 = <filename>
whith pycallgraph.PyCallGraph(output=graph):
with pycallgraph.PyCallGraph(output=graph):
<code>
```

214
README.md

@ -8,13 +8,6 @@ if __name__ == '__main__':
main()
```
Range
-----
```
range(<to exclusive>)
range(<from inclusive>, <to exclusive>)
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
```
List
----
@ -24,6 +17,7 @@ List
<list>.sort()
<list>.reverse()
sum(<list>)
sorted_by_second = sorted(<list>, key=lambda tup: tup[1])
```
Dictionary
@ -31,6 +25,7 @@ Dictionary
<dict>.items()
<dict>.get(<key>, <default>)
<dict>.setdefault(<key>, <default>)
<dict>.update(<dict>)
```
Set
@ -44,6 +39,14 @@ Set
<set>.difference(<set>)
```
Range
-----
```
range(<to exclusive>)
range(<from inclusive>, <to exclusive>)
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
```
Enumerate
---------
```
@ -51,7 +54,6 @@ for i, <el> in enumerate(<list>)
```
Type
----
```
@ -63,12 +65,14 @@ isinstance(<el>, numbers.Number)
```
String
------
```
str.replace(<text>, <old>, <new>)
<str>.isnumeric()
<str>.split()
<str>.strip()
'<str>'.join(<list>)
```
### Print
@ -130,24 +134,65 @@ now.strftime('%Y%m%d%H%M%S')
```
Inline
------
### For
### Lambda
```
lambda <arg1>, <arg2>: <return value>
lambda: <return value>
```
### 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 <arg1>, <arg2>: <return value>
lambda: <return value>
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(<command>).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
```

Loading…
Cancel
Save