Skip to content

Commit 21574a9

Browse files
committed
Merge
2 parents b758cfa + 720b1e2 commit 21574a9

File tree

4 files changed

+272
-119
lines changed

4 files changed

+272
-119
lines changed

README.md

Lines changed: 102 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Comprehensive Python Cheatsheet
88

99
Contents
1010
--------
11-
**   ** **1. Collections:** ** ** **[`List`](#list)**__,__ **[`Dict`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Namedtuple`](#named-tuple)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__
11+
**   ** **1. Collections:** ** ** **[`List`](#list)**__,__ **[`Dict`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__
1212
**   ** **2. Types:** **          ** **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regex`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__
1313
**   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exceptions`](#exceptions)**__.__
1414
**   ** **4. System:** **        ** **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#path)**__,__ **[`Command_Execution`](#command-execution)**__.__
@@ -55,7 +55,8 @@ list_of_chars = list(<str>)
5555
```
5656

5757
```python
58-
index = <list>.index(<el>) # Returns first index of item or raises ValueError.
58+
<bool> = <el> in <collection> # For dictionary it checks if key exists.
59+
index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
5960
<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
6061
<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
6162
<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
@@ -126,13 +127,42 @@ Set
126127
<set>.discard(<el>) # Doesn't raise an error.
127128
```
128129

129-
### Frozenset
130-
#### Is hashable, meaning it can be used as a key in a dictionary or as an element in a set.
130+
### Frozen Set
131+
* **Is immutable and hashable.**
132+
* **That means it can be used as a key in a dictionary or as an element in a set.**
131133
```python
132134
<frozenset> = frozenset(<collection>)
133135
```
134136

135137

138+
Tuple
139+
-----
140+
**Tuple is an immutable and hashable list.**
141+
```python
142+
<tuple> = ()
143+
<tuple> = (<el>, )
144+
<tuple> = (<el_1>, <el_2>, ...)
145+
```
146+
147+
### Named Tuple
148+
**Tuple's subclass with named elements.**
149+
150+
```python
151+
>>> from collections import namedtuple
152+
>>> Point = namedtuple('Point', 'x y')
153+
>>> p = Point(1, y=2)
154+
Point(x=1, y=2)
155+
>>> p[0]
156+
1
157+
>>> p.x
158+
1
159+
>>> getattr(p, 'y')
160+
2
161+
>>> p._fields # Or: Point._fields
162+
('x', 'y')
163+
```
164+
165+
136166
Range
137167
-----
138168
```python
@@ -155,27 +185,6 @@ for i, el in enumerate(<collection> [, i_start]):
155185
```
156186

157187

158-
Named Tuple
159-
-----------
160-
* **Tuple is an immutable and hashable list.**
161-
* **Named tuple is its subclass with named elements.**
162-
163-
```python
164-
>>> from collections import namedtuple
165-
>>> Point = namedtuple('Point', 'x y')
166-
>>> p = Point(1, y=2)
167-
Point(x=1, y=2)
168-
>>> p[0]
169-
1
170-
>>> p.x
171-
1
172-
>>> getattr(p, 'y')
173-
2
174-
>>> p._fields # Or: Point._fields
175-
('x', 'y')
176-
```
177-
178-
179188
Iterator
180189
--------
181190
```python
@@ -250,15 +259,36 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType
250259
**An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**
251260

252261
```python
253-
from numbers import Integral, Rational, Real, Complex, Number
254-
from collections.abc import Sequence, Collection, Iterable
262+
>>> from collections.abc import Sequence, Collection, Iterable
263+
>>> isinstance([1, 2, 3], Iterable)
264+
True
265+
```
266+
267+
```text
268+
+------------------+----------+------------+----------+
269+
| | Sequence | Collection | Iterable |
270+
+------------------+----------+------------+----------+
271+
| list, range, str | yes | yes | yes |
272+
| dict, set | | yes | yes |
273+
| iter | | | yes |
274+
+------------------+----------+------------+----------+
255275
```
256276

257277
```python
278+
>>> from numbers import Integral, Rational, Real, Complex, Number
258279
>>> isinstance(123, Number)
259280
True
260-
>>> isinstance([1, 2, 3], Iterable)
261-
True
281+
```
282+
283+
```text
284+
+--------------------+----------+----------+------+---------+--------+
285+
| | Integral | Rational | Real | Complex | Number |
286+
+--------------------+----------+----------+------+---------+--------+
287+
| int | yes | yes | yes | yes | yes |
288+
| fractions.Fraction | | yes | yes | yes | yes |
289+
| float | | | yes | yes | yes |
290+
| complex | | | | yes | yes |
291+
+--------------------+----------+----------+------+---------+--------+
262292
```
263293

264294

@@ -408,18 +438,17 @@ Format
408438

409439
Numbers
410440
-------
411-
* **Int, float and complex are the only number types.**
412-
* **I use `<num>` to mean any of the above and `<real>` for either int or float.**
413-
414441
```python
415-
<int> = int(<float/str/bool>) # Or: math.floor(<float>)
416-
<float> = float(<int/str/bool>)
417-
<complex> = complex(real=0, imag=0) # Or: <real> + <real>j
442+
<int> = int(<float/str/bool>) # Or: math.floor(<float>)
443+
<float> = float(<int/str/bool>)
444+
<complex> = complex(real=0, imag=0) # Or: <real> + <real>j
445+
<Fraction> = fractions.Fraction(numerator=0, denominator=1)
418446
```
447+
* **`'int(<str>)'` and `'float(<str>)'` raise ValueError on malformed strings.**
419448

420449
### Basic Functions
421450
```python
422-
<num> = pow(<num>, <num>) # Or: <num> ** <num>
451+
<num> = pow(<num>, <num>) # Or: <num> ** <num>
423452
<real> = abs(<num>)
424453
<int> = round(<real>)
425454
<real> = round(<real>, ±ndigits)
@@ -1027,6 +1056,31 @@ class MyCollection:
10271056
yield el
10281057
```
10291058

1059+
```python
1060+
>>> from collections.abc import Sequence, Collection, Iterable
1061+
>>> a = MyCollection([1, 2, 3])
1062+
>>> isinstance(a, Sequence), isinstance(a, Collection), isinstance(a, Iterable)
1063+
(False, True, True)
1064+
```
1065+
1066+
### Iterator
1067+
```python
1068+
class Counter:
1069+
def __init__(self):
1070+
self.i = 0
1071+
def __next__(self):
1072+
self.i += 1
1073+
return self.i
1074+
def __iter__(self):
1075+
return self
1076+
```
1077+
1078+
```python
1079+
>>> counter = Counter()
1080+
>>> next(counter), next(counter), next(counter)
1081+
(1, 2, 3)
1082+
```
1083+
10301084
### Callable
10311085
```python
10321086
class Counter:
@@ -1858,33 +1912,19 @@ retention=<int>|<datetime.timedelta>|<str>
18581912

18591913
Scraping
18601914
--------
1915+
#### Scrapes and prints Python's URL and version number from Wikipedia:
18611916
```python
18621917
# $ pip3 install requests beautifulsoup4
1863-
>>> import requests
1864-
>>> from bs4 import BeautifulSoup
1865-
>>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
1866-
>>> page = requests.get(url)
1867-
>>> doc = BeautifulSoup(page.text, 'html.parser')
1868-
>>> table = doc.find('table', class_='infobox vevent')
1869-
>>> rows = table.find_all('tr')
1870-
>>> link = rows[11].find('a')['href']
1871-
>>> ver = rows[6].find('div').text.split()[0]
1872-
>>> link, ver
1873-
('https://www.python.org/', '3.7.2')
1874-
```
1875-
1876-
### Selenium
1877-
**Library for scraping dynamically generated web content.**
1878-
1879-
```python
1880-
# $ brew cask install chromedriver
1881-
# $ pip3 install selenium
1882-
>>> from selenium import webdriver
1883-
>>> driver = webdriver.Chrome()
1884-
>>> driver.get(url)
1885-
>>> xpath = '//*[@id="mw-content-text"]/div/table[1]/tbody/tr[7]/td/div'
1886-
>>> driver.find_element_by_xpath(xpath).text.split()[0]
1887-
'3.7.2'
1918+
import requests
1919+
from bs4 import BeautifulSoup
1920+
url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
1921+
page = requests.get(url)
1922+
doc = BeautifulSoup(page.text, 'html.parser')
1923+
table = doc.find('table', class_='infobox vevent')
1924+
rows = table.find_all('tr')
1925+
link = rows[11].find('a')['href']
1926+
ver = rows[6].find('div').text.split()[0]
1927+
print(link, ver)
18881928
```
18891929

18901930

@@ -1996,7 +2036,7 @@ from datetime import datetime
19962036
time_str = datetime.now().strftime('%Y%m%d%H%M%S')
19972037
filename = f'profile-{time_str}.png'
19982038
drawer = output.GraphvizOutput(output_file=filename)
1999-
with PyCallGraph(output=drawer):
2039+
with PyCallGraph(drawer):
20002040
<code_to_be_profiled>
20012041
```
20022042

0 commit comments

Comments
 (0)